# Purchase Dialog

The confirm step of any purchase. It shows the item, a quantity stepper for bundles, the total, and "Balance 1,250 → 1,130" for each in-game currency. If the wallet falls short, Buy is disabled and the dialog says "Need 70 more Coins" with an optional Get more button. onConfirm can return a Promise: the button spins, then a success view pops up (or the error appears with a retry). Free items say Claim; real-money prices are shown as given.

Docs: https://cozy-ui.solo.engineer/docs/components/purchase-dialog/

Install: `npx shadcn@latest add @cozy/purchase-dialog`

### Usage

```tsx
import { PurchaseDialog } from "@/components/ui/purchase-dialog"

<PurchaseDialog
  open={open}
  onOpenChange={setOpen}
  item={{ id: "rice", name: "Rice seeds", icon: <Grain />, price: { currency: "coin", amount: 20 }, quantity: 10 }}
  wallet={wallet}
  maxQuantity={5}
  onConfirm={async (item, qty) => { await api.buy(item.id, qty) }}
  onGetMore={(currency, missing) => openCoinShop(missing)}
/>
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| open / defaultOpen / onOpenChange | `boolean / boolean / (open) => void` | `false` | Open state. It never asks to close while a purchase is pending. |
| item | `PurchaseItem<T>` | – | { id, name, label?, icon?, description?, price, rarity?, quantity?, data? }. `price` is a Price or a list of Prices. `quantity` is the units per purchase (a bundle of 10 shows "×10"). `label` is the plain-text name used in the success message. |
| wallet / currencies | `Wallet / Record<string, Currency>` | `none / DEFAULT_CURRENCIES` | With a wallet the dialog shows balances and blocks Buy when it cannot pay. Without one it never blocks. |
| maxQuantity / quantity / defaultQuantity / onQuantityChange | `number / number / number / (n) => void` | `1 / 1` | The stepper shows when maxQuantity is above 1. Quantity is the number of purchases, not units. Shift+click steps by 10, and so does holding a button on touch. Real-money prices always buy 1. |
| onConfirm | `(item, quantity) => void \| Promise` | – | Called when the player confirms. Return a Promise for the busy state, then success; a rejection shows its message and a Try again button. Return nothing to go straight to success. Charge the player here: the component charges nothing. |
| status / error | `"idle" \| "pending" \| "success" \| "error" / ReactNode` | `from onConfirm` | Drive the state yourself, e.g. from a server response. |
| onDone | `() => void` | – | Called when the success view closes. |
| onGetMore | `(currencyId, missing) => void` | – | Shows a "Get more Coins" button next to each missing amount. |
| realMoneyNote | `ReactNode` | – | Shown under the total for real-money prices, e.g. "Charged by the App Store". |
| renderDetails / trigger / rarities | `fn / ReactNode / Record<string, RarityConfig>` | – | Content under the item, an element that opens the dialog, and your own rarity set. |
| labels | `Partial<PurchaseDialogLabels>` | `English` | title, claimTitle, description, confirm, claim, cancel, retry, quantity, decrease, increase, units, total, free, balance, need, getMore, pending, successTitle, success, claimed, close, error. Placeholders: {quantity} {name} {amount} {currency} {units}. |

PurchaseDialog never charges anything. A price like `{ real: "$4.99" }` is only text: call your store SDK (App Store, Google Play, Stripe) from `onConfirm`, and reject the Promise if it fails.

While pending, the close button, Escape, outside click and Cancel are disabled so a payment cannot be abandoned half way. The success view is an `aria-live` region; errors use `role="alert"`.

The dialog opens fresh (idle, default quantity) each time. Validate the purchase again on your server: the wallet check here is only for the button.

### Example

```tsx
import * as React from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { CurrencyBar } from "@/components/ui/currency-bar";
import { PurchaseDialog, type PurchaseItem } from "@/components/ui/purchase-dialog";
import { isCurrencyPrice } from "@/components/ui/economy-core";
import { CURRENCIES, SHOP_ITEMS, START_WALLET, type ShopData } from "./economy-data";

export default function Demo() {
  const [wallet, setWallet] = React.useState(START_WALLET);
  const [item, setItem] = React.useState<PurchaseItem<ShopData>>(SHOP_ITEMS[0]);
  const [open, setOpen] = React.useState(false);
  const show = (it: PurchaseItem<ShopData>) => { setItem(it); setOpen(true); };

  // Your game charges here (or calls the store SDK for real money), then returns a Promise.
  const confirm = (it: PurchaseItem<ShopData>, qty: number) =>
    new Promise<void>((resolve) => setTimeout(() => {
      setWallet((w) => {
        const next = { ...w };
        for (const p of Array.isArray(it.price) ? it.price : [it.price]) if (isCurrencyPrice(p)) next[p.currency] -= p.amount * qty;
        for (const [id, n] of Object.entries(it.data?.grant ?? {})) next[id] = (next[id] ?? 0) + n * qty;
        return next;
      });
      resolve();
    }, 800));

  return (
    <div className="flex w-full flex-col items-center gap-6">
      <CurrencyBar wallet={wallet} currencies={CURRENCIES} />
      <div className="flex flex-wrap justify-center gap-3">
        {SHOP_ITEMS.map((it) => (
          <Button key={it.id} variant="outline" size="sm" onClick={() => show(it)}>{it.label ?? (typeof it.name === "string" ? it.name : it.id)}</Button>
        ))}
      </div>
      <PurchaseDialog
        open={open}
        onOpenChange={setOpen}
        item={item}
        wallet={wallet}
        currencies={CURRENCIES}
        maxQuantity={item.quantity ? 5 : 1}
        onConfirm={confirm}
        onGetMore={(id, missing) => { setWallet((w) => ({ ...w, [id]: w[id] + missing })); toast(`Added ${missing} ${CURRENCIES[id].label} (pretend you bought them)`); }}
        realMoneyNote="Charged by the App Store. This demo charges nothing."
      />
    </div>
  );
}
```

### Source (components/ui/purchase-dialog.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "./button";
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "./dialog";
import {
  DEFAULT_CURRENCIES, canAfford, formatAmount, isCurrencyPrice, isRealPrice, PriceTag,
  type Currency, type Price, type Wallet,
} from "./economy-core";
import { GameIcon, RarityBadge, rarityStyle, type Rarity, type RarityConfig } from "./game-core";

/* The confirm step of any purchase. Shows the item, a quantity stepper, the
   total, the balance before and after, and what is missing when the wallet
   falls short. onConfirm may return a Promise: the dialog shows a busy state,
   then a success view, or the error with a retry. It never charges anything
   itself: real-money prices are shown as text and your game calls its store
   or payment SDK from onConfirm. */

/** Something that can be bought. */
export type PurchaseItem<T = unknown> = {
  /** Stable id. */
  id: string;
  /** Display name. */
  name: React.ReactNode;
  /** Plain-text name for the success message and screen readers. Falls back to `name` when it is a string, else `id`. */
  label?: string;
  /** A React node (SVG, sprite) or an image URL. */
  icon?: React.ReactNode;
  /** Short text under the name. */
  description?: React.ReactNode;
  /** The price, a list of prices (e.g. 50 coins + 2 gems), `{ real: "$4.99" }` or `"free"`. */
  price: Price | Price[];
  /** Rarity edge and badge. */
  rarity?: Rarity;
  /** Units you get per purchase, e.g. 10 for a bundle of 10 seeds. Shown as "×10". Default 1. */
  quantity?: number;
  /** Your own object; comes back in `onConfirm`. */
  data?: T;
};

/** Where the purchase is. "idle" shows the question, "pending" a busy button, "success" the result, "error" the message and a retry. */
export type PurchaseStatus = "idle" | "pending" | "success" | "error";

/** Strings used by PurchaseDialog. `{quantity}`, `{name}`, `{amount}`, `{currency}` and `{units}` are replaced. */
export type PurchaseDialogLabels = {
  /** Dialog title. Default "Buy item?". */
  title: string;
  /** Dialog title for free items. Default "Claim item?". */
  claimTitle: string;
  /** Screen reader description when the item has none. Default "Check the price, then confirm.". */
  description: string;
  /** Confirm button. Default "Buy". */
  confirm: string;
  /** Confirm button for free items. Default "Claim". */
  claim: string;
  /** Cancel button. Default "Cancel". */
  cancel: string;
  /** Confirm button after an error. Default "Try again". */
  retry: string;
  /** Quantity row label. Default "Quantity". */
  quantity: string;
  /** Stepper button names. Default "Fewer" and "More". */
  decrease: string;
  increase: string;
  /** Pill on bundles. Default "×{units}". */
  units: string;
  /** Total row label. Default "Total". */
  total: string;
  /** Free price. Default "Free". */
  free: string;
  /** Before the wallet amount, e.g. "Balance 1,250 → 1,130". Default "Balance". */
  balance: string;
  /** Shortfall text. Default "Need {amount} more {currency}". */
  need: string;
  /** The Get more button. Default "Get more". */
  getMore: string;
  /** Busy text for screen readers. Default "Processing…". */
  pending: string;
  /** Title of the success view. Default "Done!". */
  successTitle: string;
  /** Success message. Default "Bought {quantity}× {name}". */
  success: string;
  /** Success message for free items. Default "Claimed {quantity}× {name}". */
  claimed: string;
  /** Close button of the success view. Default "Close". */
  close: string;
  /** Shown when onConfirm rejects without a message. Default "Something went wrong. Please try again.". */
  error: string;
};

const DEFAULT_LABELS: PurchaseDialogLabels = {
  title: "Buy item?",
  claimTitle: "Claim item?",
  description: "Check the price, then confirm.",
  confirm: "Buy",
  claim: "Claim",
  cancel: "Cancel",
  retry: "Try again",
  quantity: "Quantity",
  decrease: "Fewer",
  increase: "More",
  units: "×{units}",
  total: "Total",
  free: "Free",
  balance: "Balance",
  need: "Need {amount} more {currency}",
  getMore: "Get more",
  pending: "Processing…",
  successTitle: "Done!",
  success: "Bought {quantity}× {name}",
  claimed: "Claimed {quantity}× {name}",
  close: "Close",
  error: "Something went wrong. Please try again.",
};

const fill = (tpl: string, vars: Record<string, string | number>) => tpl.replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ""));

type PurchaseDialogProps<T = unknown> = {
  /** Open state. Controlled. */
  open?: boolean;
  /** Initial open state when uncontrolled. Default false. */
  defaultOpen?: boolean;
  /** Called when the dialog asks to open or close. It never asks to close while a purchase is pending. */
  onOpenChange?: (open: boolean) => void;
  /** What is being bought. */
  item: PurchaseItem<T>;
  /** What the player has. Enables balances and the "not enough" state. Without it the dialog cannot tell and never blocks the button. */
  wallet?: Wallet;
  /** Currency definitions by id. Default `DEFAULT_CURRENCIES`. */
  currencies?: Record<string, Currency>;
  /** Most purchases at once; the stepper shows when above 1. Ignored (1) for real-money prices. Default 1. */
  maxQuantity?: number;
  /** Purchases chosen (not units). Controlled. */
  quantity?: number;
  /** Initial quantity when uncontrolled. Default 1. */
  defaultQuantity?: number;
  /** Called when the stepper changes. */
  onQuantityChange?: (quantity: number) => void;
  /** Called on confirm with the item and the number of purchases. Return a Promise to show busy, then success or error (a rejected Error's message is shown). Nothing is charged by this component: do it here. */
  onConfirm?: (item: PurchaseItem<T>, quantity: number) => void | Promise<unknown>;
  /** Drive the state yourself: "idle", "pending", "success" or "error". Default: follows the Promise from `onConfirm`. */
  status?: PurchaseStatus;
  /** Message for the "error" state. Default: the rejection message. */
  error?: React.ReactNode;
  /** Called when the success view closes (Close button, X, Escape or outside click). */
  onDone?: () => void;
  /** Shows a "Get more" button next to each missing amount. Gets the currency id and how much is missing. */
  onGetMore?: (currencyId: string, missing: number) => void;
  /** Shown under the total for real-money prices, e.g. "Charged by the App Store". */
  realMoneyNote?: React.ReactNode;
  /** Extra content under the item, e.g. stats or a comparison. */
  renderDetails?: (item: PurchaseItem<T>) => React.ReactNode;
  /** Optional element that opens the dialog (rendered with `asChild`). */
  trigger?: React.ReactNode;
  /** Rarity colours and names. Default `DEFAULT_RARITIES`. */
  rarities?: Record<string, RarityConfig>;
  /** Override any built-in string (for translation). */
  labels?: Partial<PurchaseDialogLabels>;
  className?: string;
};

function useControllable<V>(value: V | undefined, defaultValue: V, onChange?: (v: V) => void) {
  const [inner, setInner] = React.useState(defaultValue);
  const controlled = value !== undefined;
  const current = controlled ? (value as V) : inner;
  const set = React.useCallback((next: V) => {
    if (!controlled) setInner(next);
    onChange?.(next);
  }, [controlled, onChange]);
  return [current, set] as const;
}

const scalePrice = (p: Price, q: number): Price => {
  if (!isCurrencyPrice(p)) return p;
  return { ...p, amount: p.amount * q, was: p.was != null ? p.was * q : undefined };
};

function itemText(item: PurchaseItem<unknown>) {
  return item.label ?? (typeof item.name === "string" ? item.name : item.id);
}

/** The confirm step of a purchase: item, quantity, total, balance before and after, "need more", busy, success and error states. Charges nothing itself. */
function PurchaseDialog<T = unknown>({
  open: openProp, defaultOpen = false, onOpenChange, item, wallet, currencies = DEFAULT_CURRENCIES,
  maxQuantity = 1, quantity: quantityProp, defaultQuantity = 1, onQuantityChange, onConfirm,
  status: statusProp, error: errorProp, onDone, onGetMore, realMoneyNote, renderDetails, trigger, rarities, labels: labelsProp, className,
}: PurchaseDialogProps<T>) {
  const labels = { ...DEFAULT_LABELS, ...labelsProp };
  const [open, setOpenState] = useControllable(openProp, defaultOpen, onOpenChange);
  const prices = Array.isArray(item.price) ? item.price : [item.price];
  const hasReal = prices.some(isRealPrice);
  const allFree = prices.every((p) => p === "free");
  const max = hasReal ? 1 : Math.max(1, Math.floor(maxQuantity));
  const clamp = (n: number) => Math.min(max, Math.max(1, Math.round(n) || 1));
  const [qRaw, setQ] = useControllable(quantityProp, defaultQuantity, onQuantityChange);
  const quantity = clamp(qRaw);

  const [innerStatus, setInnerStatus] = React.useState<PurchaseStatus>("idle");
  const [innerError, setInnerError] = React.useState<React.ReactNode>(null);
  const status = statusProp ?? innerStatus;
  const errorNode = errorProp ?? innerError;
  const alive = React.useRef(true);
  const run = React.useRef(0);
  React.useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);

  // start every opening from a clean idle state
  const wasOpen = React.useRef(open);
  React.useEffect(() => {
    if (open && !wasOpen.current) {
      run.current++;
      setInnerStatus("idle");
      setInnerError(null);
      if (quantityProp === undefined) setQ(clamp(defaultQuantity));
    }
    wasOpen.current = open;
  }); // eslint-disable-line react-hooks/exhaustive-deps

  // totals
  const totals = prices.map((p) => scalePrice(p, quantity));
  const need: Record<string, number> = {};
  for (const p of totals) if (isCurrencyPrice(p)) need[p.currency] = (need[p.currency] ?? 0) + p.amount;
  const currencyIds = Object.keys(need);
  const covered = wallet ? canAfford(totals, wallet) : true;
  const busy = status === "pending";
  const done = status === "success";
  const free = allFree;
  const units = (item.quantity ?? 1) > 1 ? item.quantity : undefined;
  const name = itemText(item as PurchaseItem<unknown>);

  const handleOpenChange = (next: boolean) => {
    if (!next && busy) return;
    if (!next && done) onDone?.();
    setOpenState(next);
  };

  const confirm = async () => {
    if (!covered || busy) return;
    const my = ++run.current;
    let result: void | Promise<unknown>;
    try {
      result = onConfirm?.(item, quantity);
    } catch (e) {
      setInnerError(e instanceof Error && e.message ? e.message : labels.error);
      setInnerStatus("error");
      return;
    }
    if (result && typeof (result as Promise<unknown>).then === "function") {
      setInnerStatus("pending");
      try {
        await result;
        if (alive.current && run.current === my) setInnerStatus("success");
      } catch (e) {
        if (alive.current && run.current === my) {
          setInnerError(e instanceof Error && e.message ? e.message : labels.error);
          setInnerStatus("error");
        }
      }
    } else {
      setInnerStatus("success");
    }
  };

  const step = (dir: 1 | -1, e: React.MouseEvent) => setQ(clamp(quantity + dir * (e.shiftKey ? 10 : 1)));
  const longPress = useLongPress((dir) => setQ(clamp(quantity + dir * 10)));

  const title = done ? labels.successTitle : free ? labels.claimTitle : labels.title;
  const successText = fill(free ? labels.claimed : labels.success, { quantity, name });
  const confirmLabel = status === "error" ? labels.retry : free ? labels.claim : labels.confirm;

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
      <DialogContent
        data-slot="purchase-dialog"
        data-status={status}
        showCloseButton={!busy}
        className={cn("cz-purchase", className)}
        onInteractOutside={(e) => { if (busy) e.preventDefault(); }}
        onEscapeKeyDown={(e) => { if (busy) e.preventDefault(); }}
      >
        <div className="cz-purchase__head">
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription className={cn(!item.description && "cz-sr-only")}>{item.description ?? labels.description}</DialogDescription>
        </div>

        <div className="cz-purchase__live" aria-live="polite" aria-atomic="true">
          {done && (
            <div className="cz-purchase__success">
              <span className="cz-purchase__pop" style={rarityStyle(item.rarity, rarities)}><GameIcon icon={item.icon} alt="" /></span>
              <p className="cz-purchase__success-text">{successText}</p>
            </div>
          )}
        </div>

        {!done && (
          <>
            <div className="cz-purchase__item" style={rarityStyle(item.rarity, rarities)} data-rarity={item.rarity}>
              <span className="cz-purchase__icon"><GameIcon icon={item.icon} alt="" /></span>
              <span className="cz-purchase__info">
                <span className="cz-purchase__name">{item.name}{units && <span className="cz-purchase__units">{fill(labels.units, { units })}</span>}</span>
                {item.rarity && <RarityBadge rarity={item.rarity} rarities={rarities} />}
              </span>
            </div>

            {renderDetails?.(item)}

            {max > 1 && (
              <div className="cz-purchase__row" role="group" aria-label={labels.quantity}>
                <span className="cz-purchase__row-label" aria-hidden>{labels.quantity}</span>
                <span className="cz-purchase__stepper">
                  <Button variant="outline" size="icon-sm" aria-label={labels.decrease} disabled={busy || quantity <= 1} onClick={(e) => step(-1, e)} {...longPress(-1)}>
                    <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden><path d="M3 8h10" stroke="currentColor" strokeWidth="3" strokeLinecap="round" /></svg>
                  </Button>
                  <output className="cz-purchase__qty" aria-live="polite">{quantity}</output>
                  <Button variant="outline" size="icon-sm" aria-label={labels.increase} disabled={busy || quantity >= max} onClick={(e) => step(1, e)} {...longPress(1)}>
                    <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden><path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="3" strokeLinecap="round" /></svg>
                  </Button>
                </span>
              </div>
            )}

            <div className="cz-purchase__row cz-purchase__total" data-free={free || undefined}>
              <span className="cz-purchase__row-label">{labels.total}</span>
              <span className="cz-purchase__prices">
                {free ? <span className="cz-purchase__free">{labels.free}</span> : totals.filter((p) => p !== "free").map((p, i) => (
                  <PriceTag key={i} price={p} currencies={currencies} wallet={wallet} size="lg" />
                ))}
              </span>
            </div>
            {hasReal && realMoneyNote != null && <p className="cz-purchase__note">{realMoneyNote}</p>}

            {wallet && currencyIds.length > 0 && (
              <ul className="cz-purchase__balances">
                {currencyIds.map((id) => {
                  const cur = currencies[id] ?? { label: id };
                  const have = wallet[id] ?? 0;
                  const lacking = need[id] - have;
                  return (
                    <li key={id} className="cz-purchase__balance" data-short={lacking > 0 || undefined}>
                      <span className="cz-purchase__cur">
                        <span className="cz-purchase__cur-icon" aria-hidden><GameIcon icon={cur.icon} alt="" /></span>
                        {cur.label}
                      </span>
                      <span className="cz-purchase__amounts">
                        {labels.balance} <b>{formatAmount(have)}</b>
                        {lacking <= 0 && <> <span aria-hidden>{"→"}</span><span className="cz-sr-only"> to </span> <b data-after>{formatAmount(have - need[id])}</b></>}
                      </span>
                      {lacking > 0 && (
                        <span className="cz-purchase__need">
                          <span role="status">{fill(labels.need, { amount: formatAmount(lacking), currency: cur.label })}</span>
                          {onGetMore && (
                            <Button variant="reward" size="sm" aria-label={`${labels.getMore} ${cur.label}`} onClick={() => onGetMore(id, lacking)}>{labels.getMore}</Button>
                          )}
                        </span>
                      )}
                    </li>
                  );
                })}
              </ul>
            )}

            {status === "error" && (
              <p className="cz-purchase__error" role="alert">{errorNode ?? labels.error}</p>
            )}
          </>
        )}

        <div className="cz-purchase__actions">
          {done ? (
            <Button variant="success" onClick={() => handleOpenChange(false)}>{labels.close}</Button>
          ) : (
            <>
              <Button variant="outline" disabled={busy} onClick={() => handleOpenChange(false)}>{labels.cancel}</Button>
              <Button variant={free ? "reward" : "success"} loading={busy} disabled={!covered} onClick={confirm}>
                {confirmLabel}
                {busy && <span className="cz-sr-only"> {labels.pending}</span>}
              </Button>
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

/** Holding a stepper button for 500 ms steps by 10 once (click is then ignored). */
function useLongPress(onLong: (dir: 1 | -1) => void) {
  const timer = React.useRef(0);
  const fired = React.useRef(false);
  const cb = React.useRef(onLong);
  cb.current = onLong;
  React.useEffect(() => () => window.clearTimeout(timer.current), []);
  return (dir: 1 | -1) => ({
    onPointerDown: (e: React.PointerEvent) => {
      if (e.pointerType === "mouse") return; // mouse users have Shift+click
      fired.current = false;
      timer.current = window.setTimeout(() => { fired.current = true; cb.current(dir); }, 500);
    },
    onPointerUp: () => window.clearTimeout(timer.current),
    onPointerLeave: () => window.clearTimeout(timer.current),
    onPointerCancel: () => window.clearTimeout(timer.current),
    onClickCapture: (e: React.MouseEvent) => { if (fired.current) { fired.current = false; e.stopPropagation(); e.preventDefault(); } },
    onContextMenu: (e: React.MouseEvent) => { if (fired.current) e.preventDefault(); },
  });
}

export { PurchaseDialog };
export type { PurchaseDialogProps };
```

npm: `import { PurchaseDialog } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
