{
  "name": "ai-checkout",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: AI Checkout\n * @version: 1.1.0\n * @date: 2026-10-31\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { Check, Coffee, Lock, Minus, Plus } from \"lucide-react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface CheckoutItem {\n  title: string;\n  subtitle: string;\n  /** Price of one, in cents. */\n  unitPrice: number;\n  quantity: number;\n  /** Most you can order in one go. */\n  maxQuantity?: number;\n  icon?: ReactNode;\n}\n\nexport interface CheckoutDetails {\n  merchant: string;\n  item: CheckoutItem;\n  /** Tax rate, e.g. 0.08. */\n  taxRate: number;\n  currency?: string;\n  /** Last four digits of the saved card. */\n  cardLast4: string;\n  /** e.g. \"Arrives in 2 days\". */\n  delivery: string;\n}\n\nexport interface AICheckoutProps {\n  /** The user's message, drawn as a bubble. Only the demo draws one by default. */\n  prompt?: string;\n  /** What the assistant says before the order. */\n  message?: string;\n  /** What it says once paid. */\n  confirmation?: string;\n  /** The order, usually a tool's output. Leave it out for the demo. */\n  checkout?: CheckoutDetails;\n  /**\n   * Charges the card for this many items, with the total in cents. Resolve\n   * with an order number for the receipt. Throw and the order comes back with\n   * the error's message under it, so they can try again. The demo waits a\n   * moment and resolves.\n   */\n  onPay?: (quantity: number, total: number) => Promise<string>;\n  /** Called when they change how many. */\n  onQuantityChange?: (quantity: number) => void;\n  className?: string;\n}\n\ntype Status = \"review\" | \"paying\" | \"paid\" | \"receipt\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\nconst NON_NUMBER = /[^0-9.]/g;\nconst ROLL = {\n  enter: (dir: number) => ({\n    y: `${60 * dir}%`,\n    opacity: 0,\n    filter: \"blur(2px)\",\n  }),\n  exit: (dir: number) => ({\n    y: `${-60 * dir}%`,\n    opacity: 0,\n    filter: \"blur(2px)\",\n  }),\n};\nconst MORPH = { type: \"spring\", stiffness: 420, damping: 36 } as const;\n\nconst DEMO: CheckoutDetails = {\n  merchant: \"Northside Roasters\",\n  item: {\n    title: \"Ethiopia Guji\",\n    subtitle: \"Whole bean, 250 g\",\n    unitPrice: 1900,\n    quantity: 2,\n    maxQuantity: 6,\n  },\n  taxRate: 0.08,\n  cardLast4: \"4242\",\n  delivery: \"Arrives in 2 days\",\n};\n\nconst demoPay = () =>\n  new Promise<string>((resolve) => setTimeout(() => resolve(\"7F2K\"), 1500));\n\nconst DEMO_TEXT = {\n  prompt: \"Reorder the coffee beans I got last month\",\n  message: \"Same as October, two bags of Ethiopia Guji. Want me to place it?\",\n  confirmation: \"Done. I’ll tell you when it ships.\",\n};\n\n/** The chat text around the card: the demo's only when it's the demo. */\nfunction shownText(\n  text: Pick<AICheckoutProps, \"prompt\" | \"message\" | \"confirmation\">,\n  isDemo: boolean\n) {\n  if (!isDemo) {\n    return text;\n  }\n  return {\n    prompt: text.prompt ?? DEMO_TEXT.prompt,\n    message: text.message ?? DEMO_TEXT.message,\n    confirmation: text.confirmation ?? DEMO_TEXT.confirmation,\n  };\n}\n\nconst reason = (error: unknown) =>\n  error instanceof Error && error.message\n    ? error.message\n    : \"The payment didn’t go through. Try again.\";\n\nexport default function AICheckout({\n  prompt,\n  message,\n  confirmation,\n  checkout: checkoutProp,\n  onPay = demoPay,\n  onQuantityChange,\n  className,\n}: AICheckoutProps) {\n  const checkout = checkoutProp ?? DEMO;\n  const shown = shownText(\n    { prompt, message, confirmation },\n    checkoutProp === undefined\n  );\n  const { item } = checkout;\n  const [status, setStatus] = useState<Status>(\"review\");\n  const [quantity, setQuantity] = useState(item.quantity);\n  const [orderId, setOrderId] = useState(\"\");\n  const [error, setError] = useState<string>();\n\n  const subtotal = item.unitPrice * quantity;\n  const tax = Math.round(subtotal * checkout.taxRate);\n  const total = subtotal + tax;\n  const money = (cents: number) =>\n    new Intl.NumberFormat(\"en-US\", {\n      style: \"currency\",\n      currency: checkout.currency ?? \"USD\",\n    }).format(cents / 100);\n\n  // Holds the drawn check for a beat, then folds into the receipt.\n  useEffect(() => {\n    if (status !== \"paid\") {\n      return;\n    }\n    const t = setTimeout(() => setStatus(\"receipt\"), 900);\n    return () => clearTimeout(t);\n  }, [status]);\n\n  const pay = async () => {\n    setStatus(\"paying\");\n    setError(undefined);\n    try {\n      setOrderId(await onPay(quantity, total));\n      setStatus(\"paid\");\n    } catch (e) {\n      setError(reason(e));\n      setStatus(\"review\");\n    }\n  };\n\n  const changeQuantity = (n: number) => {\n    setQuantity(n);\n    setError(undefined);\n    onQuantityChange?.(n);\n  };\n\n  const locked = status !== \"review\";\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\"flex w-full max-w-md flex-col gap-4\", className)}\n        data-state={error && status === \"review\" ? \"error\" : status}\n      >\n        {shown.prompt ? (\n          <p className=\"max-w-[85%] self-end rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-[14px] text-zinc-800 leading-snug dark:bg-zinc-800 dark:text-zinc-100\">\n            {shown.prompt}\n          </p>\n        ) : null}\n        {shown.message ? (\n          <p className=\"text-[15px] text-zinc-800 leading-7 dark:text-zinc-200\">\n            {shown.message}\n          </p>\n        ) : null}\n\n        <AutoHeight className=\"rounded-[22px] bg-black/[0.04] dark:bg-white/[0.06]\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {status === \"receipt\" ? (\n              <motion.div\n                animate={{ opacity: 1, filter: \"blur(0px)\" }}\n                initial={{ opacity: 0, filter: \"blur(4px)\" }}\n                key=\"receipt\"\n                transition={{ duration: 0.35, ease: EASE_OUT, delay: 0.1 }}\n              >\n                <Receipt\n                  delivery={checkout.delivery}\n                  merchant={checkout.merchant}\n                  orderId={orderId}\n                  total={money(total)}\n                />\n              </motion.div>\n            ) : (\n              <motion.div\n                exit={{ opacity: 0, filter: \"blur(4px)\" }}\n                key=\"order\"\n                transition={{ duration: 0.2 }}\n              >\n                <div className=\"flex h-8 items-center justify-between px-3 text-[12px] text-zinc-500 dark:text-zinc-400\">\n                  <span className=\"font-medium text-zinc-700 dark:text-zinc-300\">\n                    {checkout.merchant}\n                  </span>\n                  <span className=\"flex items-center gap-1\">\n                    <Lock aria-hidden=\"true\" className=\"size-3\" />\n                    Secure checkout\n                  </span>\n                </div>\n\n                <div className=\"rounded-[18px] bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] ring-1 ring-black/[0.06] dark:bg-zinc-900 dark:ring-white/[0.08]\">\n                  <div className=\"flex items-center gap-3 p-3.5\">\n                    <span className=\"flex size-11 shrink-0 items-center justify-center rounded-xl bg-[#6f4e37] text-[#f3e6d8]\">\n                      {item.icon ?? <Coffee className=\"size-5\" />}\n                    </span>\n                    <div className=\"min-w-0 flex-1\">\n                      <p className=\"truncate font-medium text-[14px] text-zinc-900 dark:text-zinc-100\">\n                        {item.title}\n                      </p>\n                      <p className=\"mt-0.5 truncate text-[12.5px] text-zinc-500 dark:text-zinc-400\">\n                        {money(item.unitPrice)} · {item.subtitle}\n                      </p>\n                    </div>\n                    <Stepper\n                      disabled={locked}\n                      max={item.maxQuantity ?? 9}\n                      onChange={changeQuantity}\n                      value={quantity}\n                    />\n                  </div>\n\n                  <dl className=\"mx-3.5 space-y-1 border-black/[0.08] border-t border-dashed py-3 text-[13px] dark:border-white/10\">\n                    <Line label=\"Subtotal\" value={money(subtotal)} />\n                    <Line label=\"Shipping\" value=\"Free\" />\n                    <Line label=\"Tax\" value={money(tax)} />\n                  </dl>\n                  <div className=\"flex items-baseline justify-between border-black/[0.06] border-t px-3.5 py-3 dark:border-white/[0.08]\">\n                    <span className=\"font-medium text-[14px] text-zinc-900 dark:text-zinc-100\">\n                      Total\n                    </span>\n                    <Rolling\n                      className=\"font-semibold text-[17px] text-zinc-900 tracking-tight dark:text-zinc-100\"\n                      value={money(total)}\n                    />\n                  </div>\n                </div>\n\n                <div className=\"flex items-center gap-3 py-1 pr-1 pl-3\">\n                  <span className=\"flex min-w-0 flex-1 items-center gap-2 text-[12.5px] text-zinc-600 dark:text-zinc-300\">\n                    <CardChip />\n                    <span className=\"whitespace-nowrap tabular-nums tracking-wide\">\n                      •••• {checkout.cardLast4}\n                    </span>\n                    <span className=\"hidden truncate text-zinc-400 sm:inline dark:text-zinc-500\">\n                      · {checkout.delivery}\n                    </span>\n                  </span>\n                  <PayButton\n                    label={`Pay ${money(total)}`}\n                    onPay={pay}\n                    status={status}\n                  />\n                </div>\n                <AnimatePresence initial={false}>\n                  {error ? (\n                    <motion.p\n                      animate={{ height: \"auto\", opacity: 1 }}\n                      className=\"overflow-hidden px-3 text-[12.5px] text-rose-600 dark:text-rose-400\"\n                      exit={{ height: 0, opacity: 0 }}\n                      initial={{ height: 0, opacity: 0 }}\n                      key=\"error\"\n                      transition={{ duration: 0.2, ease: EASE_OUT }}\n                    >\n                      <span className=\"block pb-2\">{error}</span>\n                    </motion.p>\n                  ) : null}\n                </AnimatePresence>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </AutoHeight>\n\n        <AnimatePresence>\n          {status === \"receipt\" && shown.confirmation ? (\n            <motion.p\n              animate={{ opacity: 1, filter: \"blur(0px)\", y: 0 }}\n              className=\"text-[15px] text-zinc-800 leading-7 dark:text-zinc-200\"\n              initial={{ opacity: 0, filter: \"blur(4px)\", y: 4 }}\n              transition={{ duration: 0.4, ease: EASE_OUT, delay: 0.4 }}\n            >\n              {shown.confirmation}\n            </motion.p>\n          ) : null}\n        </AnimatePresence>\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {status === \"paying\" ? \"Processing payment\" : \"\"}\n          {status === \"paid\" || status === \"receipt\" ? \"Payment complete\" : \"\"}\n          {error ?? \"\"}\n        </p>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction Line({ label, value }: { label: string; value: string }) {\n  return (\n    <div className=\"flex justify-between\">\n      <dt className=\"text-zinc-500 dark:text-zinc-400\">{label}</dt>\n      <dd className=\"text-zinc-700 tabular-nums dark:text-zinc-300\">\n        <Rolling value={value} />\n      </dd>\n    </div>\n  );\n}\n\n/** Text that rolls when it changes: up when the number grows, down when it shrinks. */\nfunction Rolling({ value, className }: { value: string; className?: string }) {\n  const amount = Number.parseFloat(value.replace(NON_NUMBER, \"\")) || 0;\n  const last = useRef(amount);\n  const dir = amount < last.current ? -1 : 1;\n  useEffect(() => {\n    last.current = amount;\n  }, [amount]);\n\n  return (\n    <span\n      className={cn(\n        \"relative inline-flex overflow-hidden tabular-nums\",\n        className\n      )}\n    >\n      <AnimatePresence custom={dir} initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ y: 0, opacity: 1, filter: \"blur(0px)\" }}\n          custom={dir}\n          exit=\"exit\"\n          initial=\"enter\"\n          key={value}\n          transition={{ duration: 0.22, ease: EASE_OUT }}\n          variants={ROLL}\n        >\n          {value}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction Stepper({\n  value,\n  max,\n  disabled,\n  onChange,\n}: {\n  value: number;\n  max: number;\n  disabled: boolean;\n  onChange: (n: number) => void;\n}) {\n  const button =\n    \"flex size-7 items-center justify-center rounded-full text-zinc-600 outline-hidden transition-colors duration-100 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:ring-2 focus-visible:ring-zinc-400/50 disabled:pointer-events-none disabled:opacity-30 dark:text-zinc-300 dark:hover:bg-white/[0.08] dark:hover:text-white active:bg-zinc-200 dark:active:bg-white/[0.13]\";\n  return (\n    <div className=\"flex items-center rounded-full p-0.5 ring-1 ring-black/[0.08] dark:ring-white/10\">\n      <button\n        aria-label=\"One fewer\"\n        className={button}\n        disabled={disabled || value <= 1}\n        onClick={() => onChange(value - 1)}\n        type=\"button\"\n      >\n        <Minus className=\"size-3.5\" />\n      </button>\n      <Rolling\n        className=\"w-5 justify-center font-medium text-[13px] text-zinc-900 dark:text-zinc-100\"\n        value={String(value)}\n      />\n      <button\n        aria-label=\"One more\"\n        className={button}\n        disabled={disabled || value >= max}\n        onClick={() => onChange(value + 1)}\n        type=\"button\"\n      >\n        <Plus className=\"size-3.5\" />\n      </button>\n    </div>\n  );\n}\n\n/** A small card face, so the saved method reads at a glance. */\nfunction CardChip() {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"relative flex h-[18px] w-[27px] shrink-0 items-end justify-end overflow-hidden rounded-[4px] bg-[#1a1f71] px-[3px] pb-[2px]\"\n    >\n      <span className=\"absolute top-[4px] left-[3px] h-[5px] w-[7px] rounded-[1.5px] bg-[#d9b56b]\" />\n      <span className=\"font-black text-[6.5px] text-white italic leading-none tracking-tight\">\n        VISA\n      </span>\n    </span>\n  );\n}\n\n/**\n * Pay folds into a ring while the charge runs, then fills green and draws\n * its check.\n */\nfunction PayButton({\n  status,\n  label,\n  onPay,\n}: {\n  status: Status;\n  label: string;\n  onPay: () => void;\n}) {\n  const round = status !== \"review\";\n  const paid = status === \"paid\" || status === \"receipt\";\n  let name = label;\n  if (round) {\n    name = paid ? \"Paid\" : \"Paying\";\n  }\n\n  return (\n    <motion.button\n      aria-label={name}\n      className={cn(\n        \"relative flex h-10 shrink-0 items-center justify-center overflow-hidden font-medium text-[14px] outline-hidden transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-zinc-400/60 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-zinc-900\",\n        round ? \"w-10\" : \"px-4\",\n        paid\n          ? \"bg-emerald-600 text-white dark:bg-emerald-500\"\n          : \"bg-zinc-900 text-white hover:bg-zinc-800 active:bg-zinc-700 dark:bg-white dark:text-zinc-900 dark:active:bg-zinc-300 dark:hover:bg-zinc-200\"\n      )}\n      disabled={round}\n      layout\n      onClick={onPay}\n      style={{ borderRadius: 999 }}\n      transition={{ layout: MORPH }}\n      type=\"button\"\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        {status === \"review\" && (\n          <motion.span\n            animate={{ opacity: 1 }}\n            className=\"whitespace-nowrap tabular-nums\"\n            exit={{ opacity: 0, transition: { duration: 0.08 } }}\n            initial={{ opacity: 0 }}\n            key=\"label\"\n            layout=\"position\"\n          >\n            {label}\n          </motion.span>\n        )}\n        {status === \"paying\" && (\n          <motion.svg\n            animate={{ opacity: 1, rotate: 360 }}\n            aria-hidden=\"true\"\n            className=\"size-5\"\n            exit={{ opacity: 0 }}\n            fill=\"none\"\n            initial={{ opacity: 0 }}\n            key=\"ring\"\n            transition={{\n              opacity: { duration: 0.15, delay: 0.12 },\n              rotate: {\n                duration: 0.6,\n                ease: \"linear\",\n                repeat: Number.POSITIVE_INFINITY,\n              },\n            }}\n            viewBox=\"0 0 20 20\"\n          >\n            <circle\n              cx=\"10\"\n              cy=\"10\"\n              opacity=\"0.25\"\n              r=\"8\"\n              stroke=\"currentColor\"\n              strokeWidth=\"2\"\n            />\n            <path\n              d=\"M10 2a8 8 0 0 1 8 8\"\n              stroke=\"currentColor\"\n              strokeLinecap=\"round\"\n              strokeWidth=\"2\"\n            />\n          </motion.svg>\n        )}\n        {paid && (\n          <motion.svg\n            aria-hidden=\"true\"\n            className=\"size-5\"\n            fill=\"none\"\n            key=\"check\"\n            viewBox=\"0 0 20 20\"\n          >\n            <motion.path\n              animate={{ pathLength: 1 }}\n              d=\"M5 10.5l3.2 3.2L15 6.8\"\n              initial={{ pathLength: 0 }}\n              stroke=\"currentColor\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              strokeWidth=\"2.2\"\n              transition={{ duration: 0.35, ease: EASE_OUT, delay: 0.1 }}\n            />\n          </motion.svg>\n        )}\n      </AnimatePresence>\n    </motion.button>\n  );\n}\n\nfunction Receipt({\n  total,\n  merchant,\n  orderId,\n  delivery,\n}: {\n  total: string;\n  merchant: string;\n  orderId: string;\n  delivery: string;\n}) {\n  return (\n    <div className=\"flex items-center gap-3 rounded-[18px] bg-white px-3.5 py-3 ring-1 ring-black/[0.06] dark:bg-zinc-900 dark:ring-white/[0.08]\">\n      <span className=\"flex size-8 shrink-0 items-center justify-center rounded-full bg-emerald-600/10 text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400\">\n        <Check aria-hidden=\"true\" className=\"size-4\" strokeWidth={2.5} />\n      </span>\n      <div className=\"min-w-0 flex-1\">\n        <p className=\"truncate text-[13.5px] text-zinc-900 dark:text-zinc-100\">\n          <span className=\"font-medium tabular-nums\">Paid {total}</span>\n          <span className=\"text-zinc-500 dark:text-zinc-400\">\n            {\" \"}\n            to {merchant}\n          </span>\n        </p>\n        <p className=\"mt-0.5 truncate text-[12px] text-zinc-500 dark:text-zinc-400\">\n          {delivery}\n        </p>\n      </div>\n      <span className=\"shrink-0 rounded-md bg-zinc-100 px-1.5 py-0.5 font-mono text-[11px] text-zinc-600 dark:bg-white/[0.07] dark:text-zinc-300\">\n        #{orderId}\n      </span>\n    </div>\n  );\n}\n\n/** Eases the frame to its content's height when the content swaps. */\nfunction AutoHeight({\n  className,\n  children,\n}: {\n  className?: string;\n  children: ReactNode;\n}) {\n  const innerRef = useRef<HTMLDivElement>(null);\n  const [height, setHeight] = useState<number | \"auto\">(\"auto\");\n\n  useEffect(() => {\n    const inner = innerRef.current;\n    if (!inner) {\n      return;\n    }\n    const observer = new ResizeObserver(() => setHeight(inner.offsetHeight));\n    observer.observe(inner);\n    return () => observer.disconnect();\n  }, []);\n\n  return (\n    <motion.div\n      animate={{ height }}\n      className={cn(\"overflow-hidden\", className)}\n      initial={false}\n      transition={{ duration: 0.3, ease: EASE_DRAWER }}\n    >\n      <div className=\"p-1\" ref={innerRef}>\n        {children}\n      </div>\n    </motion.div>\n  );\n}\n",
      "path": "/components/kokonutui/ai-checkout.tsx",
      "target": "components/kokonutui/ai-checkout.tsx"
    }
  ]
}