{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "order-edit",
  "title": "Order Edit",
  "author": "Zubeyr <https://zubeyr.dev>",
  "description": "A CRM record edit page: a clickable stage path, editable line items with a product picker, custom items, price and quantity edits and restore, live totals with balance due or refund, a schema-driven record form, a review of unsaved changes, undo/redo and a floating Cancel and Save toolbar. Pass your own sections, values, items and catalog to reuse it for deals, quotes or invoices.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://tomei.zubeyr.dev/ui/r/sidebar.json",
    "https://tomei.zubeyr.dev/ui/r/button.json",
    "https://tomei.zubeyr.dev/ui/r/badge.json",
    "https://tomei.zubeyr.dev/ui/r/record-form.json",
    "https://tomei.zubeyr.dev/ui/r/use-history.json",
    "https://tomei.zubeyr.dev/ui/r/toast.json",
    "https://tomei.zubeyr.dev/ui/r/popover.json"
  ],
  "files": [
    {
      "path": "registry/dashboard/pages/order-edit/order-edit.tsx",
      "content": "'use client'\n\nimport { useEffect, useMemo, useState } from 'react'\nimport {\n  BarChart3,\n  ChevronDown,\n  ChevronUp,\n  Globe,\n  Home,\n  Package,\n  Redo2,\n  ShoppingBag,\n  Undo2,\n  Users,\n  X,\n} from 'lucide-react'\nimport { useForm } from 'react-hook-form'\n\nimport { cn } from '@/lib/utils'\nimport { Badge } from '@/registry/dashboard/components/badge/badge'\nimport { Button } from '@/registry/dashboard/components/button/button'\nimport { ToggleField } from '@/registry/dashboard/components/record-form/controls'\nimport {\n  RecordForm,\n  recordFormResolver,\n  visibleFields,\n  type FormLayout,\n  type FormSection,\n  type FormValues,\n  ChangeList,\n  normalizeOptions,\n} from '@/registry/dashboard/components/record-form/record-form'\nimport {\n  Sidebar,\n  SidebarContent,\n  SidebarFooter,\n  SidebarGroup,\n  SidebarHeader,\n  SidebarItem,\n} from '@/registry/dashboard/components/sidebar/sidebar'\nimport { toast, Toaster } from '@/registry/dashboard/components/toast/toast'\nimport { useHistory } from '@/registry/dashboard/components/use-history/use-history'\n\nimport { diffRecord } from './changes'\nimport * as demo from './data'\nimport { LineItemEditor, type EditItem, type Product } from './line-item-editor'\nimport { StagePath } from './stage-path'\nimport { computeTotals, TotalsCard } from './totals'\n\ntype Snapshot = { values: FormValues; items: EditItem[] }\n\nexport type OrderEditProps = {\n  title?: string\n  subtitle?: string\n  sections?: FormSection[]\n  values?: FormValues\n  items?: EditItem[]\n  catalog?: Product[]\n  stageField?: string\n  fields?: { discount?: string; shipping?: string; code?: string }\n  badges?: { label: string; tone?: React.ComponentProps<typeof Badge>['tone'] }[]\n  formLayout?: FormLayout\n  paid?: number\n  taxRate?: number\n  formatOptions?: Intl.NumberFormatOptions\n}\n\nconst num = (value: unknown) =>\n  typeof value === 'number' ? value : typeof value === 'string' ? Number(value) || 0 : 0\n\nexport function OrderEdit({\n  title = 'Order #1078',\n  subtitle = 'Placed Oct 29, 2026 via Online Store',\n  sections = demo.sections,\n  values: initialValues = demo.values,\n  items: initialItems = demo.items,\n  catalog = demo.catalog,\n  stageField = 'stage',\n  fields = demo.totalFields,\n  badges = demo.badges,\n  formLayout = 'accordion',\n  paid = 394.49,\n  taxRate = 0.08875,\n  formatOptions = { style: 'currency', currency: 'USD' },\n}: OrderEditProps) {\n  const initial = useMemo(\n    () => ({ values: initialValues, items: initialItems }),\n    [initialValues, initialItems],\n  )\n  const history = useHistory<Snapshot>(initial, { hotkeys: true })\n  const { values, items } = history.value\n  const [saved, setSaved] = useState<Snapshot>(initial)\n  const [itemsError, setItemsError] = useState('')\n  const [notify, setNotify] = useState(true)\n  const [justSaved, setJustSaved] = useState(false)\n\n  const money = useMemo(() => new Intl.NumberFormat('en-US', formatOptions), [formatOptions])\n  const changes = diffRecord(sections, saved, history.value)\n  const dirty = changes.length > 0\n\n  const stageDef = sections.flatMap((s) => s.fields).find((f) => f.name === stageField)\n  const stageOptions = stageDef?.options && normalizeOptions(stageDef.options).map((o) => o.value)\n  const totalsOf = (s: Snapshot) => {\n    const shown = new Set(visibleFields(sections, s.values).map((f) => f.name))\n    const read = (name?: string) => (name && shown.has(name) ? num(s.values[name]) : 0)\n    return computeTotals(s.items, read(fields.discount), read(fields.shipping), taxRate)\n  }\n  const totals = totalsOf(history.value)\n  const count = items.reduce((sum, i) => sum + i.quantity, 0)\n\n  const form = useForm<FormValues>({\n    values,\n    resetOptions: { keepErrors: true, keepIsSubmitted: true },\n    resolver: recordFormResolver({ sections }),\n  })\n  const { set } = history\n  useEffect(\n    () =>\n      form.subscribe({\n        formState: { values: true },\n        callback: ({ values: next, name, type }) => {\n          if (name && type === 'change')\n            set((s) => ({ ...s, values: { ...next } }), { merge: name })\n        },\n      }),\n    [form, set],\n  )\n\n  const setValue = (name: string, value: FormValues[string]) =>\n    set((s) => ({ ...s, values: { ...s.values, [name]: value } }), { merge: name })\n\n  const cancel = () => {\n    history.reset(saved)\n    form.clearErrors()\n    setItemsError('')\n  }\n\n  const checkItems = () => {\n    const error = items.some((i) => !i.name.trim()) ? 'Every item needs a name' : ''\n    setItemsError(error)\n    return !error\n  }\n\n  const save = form.handleSubmit(() => {\n    if (!checkItems()) return\n    setSaved(history.value)\n    history.reset()\n    setJustSaved(true)\n    setTimeout(() => setJustSaved(false), 1500)\n    toast.success(`${title} updated`, {\n      description: notify ? 'The customer was emailed an updated invoice.' : undefined,\n    })\n  }, checkItems)\n\n  return (\n    <div className=\"flex h-svh overflow-hidden bg-sidebar text-foreground\">\n      <Sidebar className=\"border-r-0 max-lg:hidden\">\n        <SidebarHeader\n          logo={<span className=\"size-8 rounded-lg bg-sidebar-primary-foreground\" />}\n          title=\"Tomei\"\n          subtitle=\"Store admin\"\n        />\n        <SidebarContent>\n          <SidebarGroup>\n            <SidebarItem icon={<Home />}>Home</SidebarItem>\n            <SidebarItem icon={<ShoppingBag />} count={12} active>\n              Orders\n            </SidebarItem>\n            <SidebarItem icon={<Package />}>Products</SidebarItem>\n            <SidebarItem icon={<Users />}>Customers</SidebarItem>\n            <SidebarItem icon={<BarChart3 />}>Analytics</SidebarItem>\n          </SidebarGroup>\n        </SidebarContent>\n        <SidebarFooter>\n          <SidebarItem icon={<Globe />}>Online store</SidebarItem>\n        </SidebarFooter>\n      </Sidebar>\n\n      <main className=\"min-w-0 flex-1 overflow-y-auto bg-card lg:my-2 lg:mr-2 lg:rounded-2xl lg:border\">\n        <header className=\"sticky top-0 z-20 grid grid-cols-[1fr_auto_1fr] items-center gap-3 bg-card/90 px-4 py-3 backdrop-blur\">\n          <div className=\"flex min-w-0 items-center gap-2 text-sm\">\n            <ShoppingBag className=\"size-4 shrink-0 text-muted-foreground\" />\n            <span className=\"truncate font-medium\">Edit {title.toLowerCase()}</span>\n            {dirty && (\n              <span className=\"text-amber-600 max-md:hidden dark:text-amber-400\">\n                · {changes.length} unsaved\n              </span>\n            )}\n          </div>\n\n          <div\n            role=\"toolbar\"\n            aria-label=\"Edit actions\"\n            className=\"flex items-center gap-1 rounded-xl bg-primary p-1 text-primary-foreground shadow-lg\"\n          >\n            <button\n              type=\"button\"\n              disabled={!dirty}\n              onClick={cancel}\n              className=\"h-7 rounded-lg px-3 text-sm font-medium hover:bg-primary-foreground/10 disabled:opacity-40 disabled:hover:bg-transparent\"\n            >\n              Cancel\n            </button>\n            <button\n              type=\"button\"\n              disabled={!dirty}\n              onClick={save}\n              className={cn(\n                'h-7 rounded-lg bg-primary-foreground px-3 text-sm font-medium text-primary disabled:opacity-50',\n                justSaved && 'disabled:opacity-100',\n              )}\n            >\n              {justSaved ? 'Saved ✓' : 'Save'}\n            </button>\n          </div>\n\n          <div className=\"flex justify-end gap-1.5\">\n            <Button\n              size=\"icon\"\n              variant=\"ghost\"\n              aria-label=\"Undo\"\n              title=\"Undo (Ctrl+Z)\"\n              disabled={!history.canUndo}\n              onClick={history.undo}\n            >\n              <Undo2 />\n            </Button>\n            <Button\n              size=\"icon\"\n              variant=\"ghost\"\n              aria-label=\"Redo\"\n              title=\"Redo (Ctrl+Shift+Z)\"\n              disabled={!history.canRedo}\n              onClick={history.redo}\n            >\n              <Redo2 />\n            </Button>\n            <Button size=\"icon\" aria-label=\"Previous record\" className=\"max-sm:hidden\">\n              <ChevronUp />\n            </Button>\n            <Button size=\"icon\" aria-label=\"Next record\" className=\"max-sm:hidden\">\n              <ChevronDown />\n            </Button>\n            <Button size=\"icon\" variant=\"ghost\" aria-label=\"Close\">\n              <X />\n            </Button>\n          </div>\n        </header>\n\n        <div className=\"mx-auto flex max-w-[1200px] flex-col gap-8 px-6 pt-4 pb-16\">\n          <div className=\"flex flex-col gap-4\">\n            <div className=\"flex flex-col gap-1.5\">\n              <div className=\"flex flex-wrap items-center gap-2\">\n                <h1 className=\"text-2xl font-semibold tracking-tight\">{title}</h1>\n                {badges.map((b) => (\n                  <Badge\n                    key={b.label}\n                    tone={b.tone}\n                    indicator={!b.tone || b.tone === 'neutral' ? 'dot' : 'ring'}\n                  >\n                    {b.label}\n                  </Badge>\n                ))}\n              </div>\n              <p className=\"text-sm text-muted-foreground\">{subtitle}</p>\n            </div>\n            {stageOptions && (\n              <StagePath\n                stages={stageOptions}\n                value={String(values[stageField] ?? '')}\n                onChange={(stage) => setValue(stageField, stage)}\n              />\n            )}\n          </div>\n\n          <div className=\"grid gap-10 lg:grid-cols-[minmax(0,1fr)_26rem]\">\n            <div className=\"flex min-w-0 flex-col gap-8\">\n              <div className=\"flex flex-col gap-2\">\n                <LineItemEditor\n                  items={items}\n                  original={saved.items}\n                  catalog={catalog}\n                  money={money}\n                  onChange={(next, merge) =>\n                    history.set((s) => ({ ...s, items: next }), merge ? { merge } : undefined)\n                  }\n                />\n                {itemsError && <p className=\"text-sm text-destructive\">{itemsError}</p>}\n              </div>\n\n              <TotalsCard\n                totals={totals}\n                before={totalsOf(saved)}\n                count={count}\n                paid={paid}\n                taxRate={taxRate}\n                discountLabel={fields.code ? String(values[fields.code] ?? '') : undefined}\n                money={money}\n              >\n                <ToggleField\n                  id=\"notify\"\n                  value={notify}\n                  label=\"Email the customer an updated invoice on save\"\n                  onChange={setNotify}\n                />\n              </TotalsCard>\n\n              <ChangeList changes={changes} />\n            </div>\n\n            <RecordForm form={form} layout={formLayout} sections={sections} warnOnLeave={false} />\n          </div>\n        </div>\n      </main>\n      <Toaster />\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/order-edit.tsx"
    },
    {
      "path": "registry/dashboard/pages/order-edit/changes.tsx",
      "content": "import {\n  diffValues,\n  type Change,\n  type FieldTypeMap,\n  type FormSection,\n  type FormValues,\n} from '@/registry/dashboard/components/record-form/schema'\n\nimport type { EditItem } from './line-item-editor'\n\nexport function diffRecord(\n  sections: FormSection[],\n  before: { values: FormValues; items: EditItem[] },\n  after: { values: FormValues; items: EditItem[] },\n  fieldTypes: FieldTypeMap = {},\n): Change[] {\n  const changes = diffValues(sections, before.values, after.values, fieldTypes)\n\n  for (const item of after.items) {\n    const old = before.items.find((i) => i.id === item.id)\n    const name = item.name || 'Custom item'\n    if (!old)\n      changes.push({\n        id: item.id,\n        label: name,\n        from: 'Not on order',\n        to: `Added × ${item.quantity}`,\n      })\n    else {\n      if (old.quantity !== item.quantity)\n        changes.push({\n          id: `${item.id}-qty`,\n          label: `${name} quantity`,\n          from: `${old.quantity}`,\n          to: `${item.quantity}`,\n        })\n      if (old.price !== item.price)\n        changes.push({\n          id: `${item.id}-price`,\n          label: `${name} price`,\n          from: old.price.toFixed(2),\n          to: item.price.toFixed(2),\n        })\n    }\n  }\n  for (const old of before.items) {\n    if (!after.items.some((i) => i.id === old.id))\n      changes.push({ id: old.id, label: old.name, from: `× ${old.quantity}`, to: 'Removed' })\n  }\n\n  return changes\n}\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/changes.tsx"
    },
    {
      "path": "registry/dashboard/pages/order-edit/data.tsx",
      "content": "import { CreditCard, FileText, MapPin, ShoppingBag, User } from 'lucide-react'\n\nimport type {\n  FormSection,\n  FormValues,\n} from '@/registry/dashboard/components/record-form/record-form'\n\nimport type { EditItem, Product } from './line-item-editor'\n\nexport const sections: FormSection[] = [\n  {\n    id: 'order',\n    title: 'Order details',\n    icon: <ShoppingBag />,\n    columns: 2,\n    defaultOpen: true,\n    fields: [\n      {\n        name: 'stage',\n        label: 'Stage',\n        type: 'select',\n        required: true,\n        options: ['Draft', 'Confirmed', 'Invoiced', 'Paid', 'Fulfilled'],\n      },\n      {\n        name: 'owner',\n        label: 'Owner',\n        type: 'select',\n        options: ['Sam Rivera', 'Alex Chen', 'Priya Nair', 'Unassigned'],\n      },\n      { name: 'priority', label: 'Priority', type: 'radio', options: ['Low', 'Normal', 'High'] },\n      {\n        name: 'due',\n        label: 'Delivery date',\n        type: 'date',\n        min: 'today',\n        messages: { min: 'Delivery can’t be in the past' },\n      },\n      {\n        name: 'source',\n        label: 'Source',\n        type: 'select',\n        options: ['Online store', 'Phone', 'Email', 'Sales rep', 'Wholesale portal'],\n      },\n      {\n        name: 'po',\n        label: 'PO number',\n        type: 'text',\n        pattern: '^PO-\\\\d{4,}$',\n        placeholder: 'PO-1234',\n        messages: { pattern: 'Use the format PO-1234', required: 'Wholesale orders need a PO' },\n        requiredWhen: { field: 'source', is: 'Wholesale portal' },\n      },\n      {\n        name: 'tags',\n        label: 'Tags',\n        type: 'multiselect',\n        creatable: true,\n        options: ['VIP', 'Wholesale', 'Gift', 'Rush'],\n        span: 2,\n      },\n      {\n        name: 'giftMessage',\n        label: 'Gift message',\n        type: 'textarea',\n        maxLength: 200,\n        span: 2,\n        visibleWhen: { field: 'tags', is: 'Gift' },\n      },\n    ],\n  },\n  {\n    id: 'customer',\n    title: 'Customer',\n    icon: <User />,\n    columns: 2,\n    defaultOpen: true,\n    fields: [\n      { name: 'name', label: 'Full name', type: 'text', required: true },\n      { name: 'company', label: 'Company', type: 'text' },\n      { name: 'email', label: 'Email', type: 'email', required: true },\n      { name: 'phone', label: 'Phone', type: 'phone' },\n    ],\n  },\n  {\n    id: 'shipping',\n    title: 'Shipping address',\n    icon: <MapPin />,\n    columns: 2,\n    fields: [\n      { name: 'address', label: 'Address', type: 'text', span: 2 },\n      { name: 'city', label: 'City', type: 'text' },\n      { name: 'region', label: 'State / region', type: 'text' },\n      { name: 'postal', label: 'Postal code', type: 'text' },\n      {\n        name: 'country',\n        label: 'Country',\n        type: 'select',\n        options: ['United States', 'Canada', 'United Kingdom', 'Germany', 'Ethiopia'],\n      },\n    ],\n  },\n  {\n    id: 'pricing',\n    title: 'Pricing',\n    icon: <CreditCard />,\n    columns: 2,\n    fields: [\n      { name: 'code', label: 'Discount code', type: 'text' },\n      {\n        name: 'discount',\n        label: 'Discount (%)',\n        type: 'number',\n        min: 0,\n        max: 100,\n        visibleWhen: { field: 'code', filled: true },\n      },\n      {\n        name: 'method',\n        label: 'Shipping method',\n        type: 'select',\n        options: ['Standard', 'Express', 'Overnight', 'Local pickup'],\n      },\n      {\n        name: 'shipping',\n        label: 'Shipping cost',\n        type: 'currency',\n        min: 0,\n        visibleWhen: { field: 'method', not: 'Local pickup' },\n      },\n    ],\n  },\n  {\n    id: 'notes',\n    title: 'Notes',\n    icon: <FileText />,\n    fields: [\n      {\n        name: 'note',\n        label: 'Internal note',\n        type: 'textarea',\n        hint: 'Only your team can see this',\n      },\n    ],\n  },\n]\n\nexport const values: FormValues = {\n  stage: 'Confirmed',\n  owner: 'Sam Rivera',\n  priority: 'Normal',\n  due: '',\n  source: 'Online store',\n  po: '',\n  tags: ['VIP'],\n  name: 'Jordan Ellis',\n  company: '',\n  email: 'jordan@example.com',\n  phone: '+1 718 555 0142',\n  address: '184 Kent Ave',\n  city: 'Brooklyn',\n  region: 'NY',\n  postal: '11249',\n  country: 'United States',\n  code: 'WELCOME10',\n  discount: '10',\n  method: 'Express',\n  shipping: '4.99',\n  note: '',\n  giftMessage: '',\n}\n\nexport const totalFields = { discount: 'discount', shipping: 'shipping', code: 'code' }\n\nexport const badges: { label: string; tone?: 'neutral' | 'warning' }[] = [\n  { label: 'Paid' },\n  { label: 'Unfulfilled', tone: 'warning' },\n]\n\nexport const items: EditItem[] = [\n  {\n    id: 'sneakers',\n    name: 'Canvas Sneakers',\n    variant: '10.5 US',\n    price: 235,\n    quantity: 1,\n    color: '#d6cfc4',\n  },\n  {\n    id: 'shirt',\n    name: 'Button-down Shirt',\n    variant: 'Blue / XL',\n    price: 65,\n    quantity: 2,\n    color: '#3b4a6b',\n  },\n  {\n    id: 'beanie',\n    name: 'Knit Beanie',\n    variant: 'One size',\n    price: 32.5,\n    quantity: 1,\n    color: '#6b7a4f',\n  },\n]\n\nexport const catalog: Product[] = [\n  ...items.map(({ id, name, variant, price, color }) => ({ id, name, variant, price, color })),\n  { id: 'tote', name: 'Canvas Tote', variant: 'Natural', price: 28, color: '#e8dcc2' },\n  { id: 'socks', name: 'Wool Socks', variant: '3 pack', price: 24, color: '#8a5a44' },\n  { id: 'jacket', name: 'Chore Jacket', variant: 'Olive / L', price: 189, color: '#55613d' },\n  { id: 'cap', name: 'Six-panel Cap', variant: 'Navy', price: 38, color: '#1f2a44' },\n]\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/data.tsx"
    },
    {
      "path": "registry/dashboard/pages/order-edit/line-item-editor.tsx",
      "content": "'use client'\n\nimport { useState } from 'react'\nimport { Minus, Plus, Search, Trash2, Undo2 } from 'lucide-react'\n\nimport { Badge } from '@/registry/dashboard/components/badge/badge'\nimport { Button } from '@/registry/dashboard/components/button/button'\nimport { Input } from '@/registry/dashboard/components/input/input'\nimport { Popover } from '@/registry/dashboard/components/popover/popover'\n\nexport type EditItem = {\n  id: string\n  name: string\n  variant?: string\n  color?: string\n  price: number\n  quantity: number\n}\n\nexport type Product = Omit<EditItem, 'quantity'>\n\ntype LineItemEditorProps = {\n  items: EditItem[]\n  original: EditItem[]\n  catalog: Product[]\n  money: Intl.NumberFormat\n  onChange: (items: EditItem[], merge?: string) => void\n}\n\nfunction Swatch({ color }: { color?: string }) {\n  return (\n    <span\n      className=\"block size-11 shrink-0 rounded-lg bg-muted\"\n      style={color ? { background: color } : undefined}\n    />\n  )\n}\n\nfunction PriceInput({\n  value,\n  label,\n  onCommit,\n}: {\n  value: number\n  label: string\n  onCommit: (value: number) => void\n}) {\n  const [draft, setDraft] = useState<string | null>(null)\n  const commit = () => {\n    if (draft === null) return\n    const next = Number(draft)\n    if (!Number.isNaN(next) && next >= 0) onCommit(Math.round(next * 100) / 100)\n    setDraft(null)\n  }\n\n  return (\n    <Input\n      aria-label={label}\n      inputMode=\"decimal\"\n      leading=\"$\"\n      value={draft ?? value.toFixed(2)}\n      onChange={(e) => setDraft(e.target.value)}\n      onBlur={commit}\n      onKeyDown={(e) => e.key === 'Enter' && commit()}\n      className=\"w-24\"\n    />\n  )\n}\n\nfunction Stepper({\n  value,\n  label,\n  onChange,\n}: {\n  value: number\n  label: string\n  onChange: (value: number) => void\n}) {\n  return (\n    <div\n      role=\"group\"\n      aria-label={label}\n      className=\"flex h-8 items-center rounded-lg border border-input bg-card\"\n    >\n      <button\n        type=\"button\"\n        aria-label=\"Decrease\"\n        disabled={value <= 1}\n        onClick={() => onChange(value - 1)}\n        className=\"flex h-full w-7 items-center justify-center text-muted-foreground hover:text-foreground disabled:opacity-40\"\n      >\n        <Minus className=\"size-3\" />\n      </button>\n      <span className=\"w-6 text-center text-sm tabular-nums\">{value}</span>\n      <button\n        type=\"button\"\n        aria-label=\"Increase\"\n        onClick={() => onChange(value + 1)}\n        className=\"flex h-full w-7 items-center justify-center text-muted-foreground hover:text-foreground\"\n      >\n        <Plus className=\"size-3\" />\n      </button>\n    </div>\n  )\n}\n\nexport function LineItemEditor({ items, original, catalog, money, onChange }: LineItemEditorProps) {\n  const [query, setQuery] = useState('')\n  const removed = original.filter((o) => !items.some((i) => i.id === o.id))\n  const shown = catalog.filter((p) =>\n    `${p.name} ${p.variant ?? ''}`.toLowerCase().includes(query.toLowerCase()),\n  )\n\n  const patch = (id: string, change: Partial<EditItem>, merge?: string) =>\n    onChange(\n      items.map((i) => (i.id === id ? { ...i, ...change } : i)),\n      merge,\n    )\n\n  const add = (product: Product) => {\n    const existing = items.find((i) => i.id === product.id)\n    if (existing) return patch(product.id, { quantity: existing.quantity + 1 })\n    const before = original.find((o) => o.id === product.id)\n    onChange([...items, before ?? { ...product, quantity: 1 }])\n  }\n\n  const addCustom = () =>\n    onChange([\n      ...items,\n      { id: `custom-${Date.now().toString(36)}`, name: '', price: 0, quantity: 1 },\n    ])\n\n  const status = (item: EditItem) => {\n    const before = original.find((o) => o.id === item.id)\n    if (!before) return <Badge tone=\"success\">New</Badge>\n    if (before.quantity !== item.quantity || before.price !== item.price)\n      return <Badge tone=\"attention\">Edited</Badge>\n    return null\n  }\n\n  return (\n    <section className=\"flex flex-col gap-3\">\n      <div className=\"flex flex-wrap items-center justify-between gap-2\">\n        <h2 className=\"text-base font-semibold\">Line items</h2>\n        <div className=\"flex items-center gap-2\">\n          <Button variant=\"ghost\" onClick={addCustom}>\n            Custom item\n          </Button>\n          <div>\n            <Popover\n              align=\"end\"\n              className=\"w-72\"\n              trigger={({ open, toggle }) => (\n                <Button aria-expanded={open} onClick={toggle}>\n                  <Plus /> Add product\n                </Button>\n              )}\n            >\n              {(close) => (\n                <>\n                  <Input\n                    autoFocus\n                    leading={<Search />}\n                    value={query}\n                    onChange={(e) => setQuery(e.target.value)}\n                    placeholder=\"Search products\"\n                    aria-label=\"Search products\"\n                    className=\"mb-1\"\n                  />\n                  <ul className=\"max-h-64 overflow-y-auto\">\n                    {shown.map((p) => (\n                      <li key={p.id}>\n                        <button\n                          type=\"button\"\n                          onClick={() => {\n                            add(p)\n                            setQuery('')\n                            close()\n                          }}\n                          className=\"flex w-full items-center gap-3 rounded-lg p-1.5 text-left hover:bg-muted\"\n                        >\n                          <span\n                            className=\"size-8 shrink-0 rounded-md bg-muted\"\n                            style={p.color ? { background: p.color } : undefined}\n                          />\n                          <span className=\"flex min-w-0 flex-1 flex-col\">\n                            <span className=\"truncate text-sm\">{p.name}</span>\n                            {p.variant && (\n                              <span className=\"text-xs text-muted-foreground\">{p.variant}</span>\n                            )}\n                          </span>\n                          <span className=\"text-sm text-muted-foreground tabular-nums\">\n                            {money.format(p.price)}\n                          </span>\n                        </button>\n                      </li>\n                    ))}\n                    {!shown.length && (\n                      <li className=\"px-2 py-4 text-center text-sm text-muted-foreground\">\n                        No products match\n                      </li>\n                    )}\n                  </ul>\n                </>\n              )}\n            </Popover>\n          </div>\n        </div>\n      </div>\n\n      <div className=\"rounded-xl bg-card shadow-(--shadow-card)\">\n        <ul className=\"divide-y px-4\">\n          {items.map((item) => (\n            <li\n              key={item.id}\n              className=\"grid grid-cols-[auto_1fr_auto] items-center gap-x-4 gap-y-2 py-3 sm:grid-cols-[auto_1fr_auto_auto_5.5rem_auto]\"\n            >\n              <Swatch color={item.color} />\n              <span className=\"flex min-w-0 flex-col items-start gap-1.5\">\n                {item.id.startsWith('custom-') ? (\n                  <Input\n                    aria-label=\"Item name\"\n                    autoFocus={!item.name}\n                    placeholder=\"Item name\"\n                    value={item.name}\n                    onChange={(e) => patch(item.id, { name: e.target.value }, `name-${item.id}`)}\n                  />\n                ) : (\n                  <span className=\"truncate text-sm font-medium\">{item.name}</span>\n                )}\n                <span className=\"flex items-center gap-1.5\">\n                  {item.variant && (\n                    <span className=\"rounded-md bg-muted px-1.5 py-0.5 text-xs\">\n                      {item.variant}\n                    </span>\n                  )}\n                  {status(item)}\n                </span>\n              </span>\n              <div className=\"col-span-2 col-start-2 flex items-center gap-3 max-sm:order-last sm:contents\">\n                <PriceInput\n                  label={`Price of ${item.name || 'item'}`}\n                  value={item.price}\n                  onCommit={(price) => patch(item.id, { price })}\n                />\n                <Stepper\n                  label={`Quantity of ${item.name || 'item'}`}\n                  value={item.quantity}\n                  onChange={(quantity) => patch(item.id, { quantity })}\n                />\n                <span className=\"ml-auto text-right text-sm tabular-nums sm:ml-0\">\n                  {money.format(item.price * item.quantity)}\n                </span>\n              </div>\n              <Button\n                variant=\"ghost\"\n                size=\"icon\"\n                aria-label={`Remove ${item.name || 'item'}`}\n                onClick={() => onChange(items.filter((i) => i.id !== item.id))}\n              >\n                <Trash2 />\n              </Button>\n            </li>\n          ))}\n\n          {removed.map((item) => (\n            <li\n              key={item.id}\n              className=\"grid grid-cols-[auto_1fr_auto] items-center gap-4 py-3 text-muted-foreground\"\n            >\n              <span className=\"opacity-40\">\n                <Swatch color={item.color} />\n              </span>\n              <span className=\"flex min-w-0 flex-col items-start gap-1.5\">\n                <span className=\"truncate text-sm line-through\">{item.name}</span>\n                <Badge tone=\"critical\">Removed</Badge>\n              </span>\n              <Button size=\"sm\" onClick={() => onChange([...items, item])}>\n                <Undo2 /> Restore\n              </Button>\n            </li>\n          ))}\n\n          {!items.length && !removed.length && (\n            <li className=\"py-8 text-center text-sm text-muted-foreground\">\n              No items yet. Add a product to get started.\n            </li>\n          )}\n        </ul>\n      </div>\n    </section>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/line-item-editor.tsx"
    },
    {
      "path": "registry/dashboard/pages/order-edit/stage-path.tsx",
      "content": "'use client'\n\nimport { Check } from 'lucide-react'\n\nimport { cn } from '@/lib/utils'\n\ntype StagePathProps = {\n  stages: string[]\n  value: string\n  onChange: (stage: string) => void\n  className?: string\n}\n\nexport function StagePath({ stages, value, onChange, className }: StagePathProps) {\n  const current = stages.indexOf(value)\n\n  return (\n    <ol\n      aria-label=\"Stage\"\n      className={cn('flex gap-1 overflow-x-auto rounded-xl bg-muted p-1', className)}\n    >\n      {stages.map((stage, i) => {\n        const done = i < current\n        const active = i === current\n        return (\n          <li key={stage} className=\"min-w-24 flex-1\">\n            <button\n              type=\"button\"\n              aria-current={active ? 'step' : undefined}\n              onClick={() => onChange(stage)}\n              className={cn(\n                'flex h-8 w-full items-center justify-center gap-1.5 rounded-lg px-3 text-sm font-medium whitespace-nowrap transition-colors',\n                active && 'bg-primary text-primary-foreground shadow-(--shadow-button-primary)',\n                done && 'bg-card text-foreground shadow-(--shadow-button)',\n                !active && !done && 'text-muted-foreground hover:bg-card/60 hover:text-foreground',\n              )}\n            >\n              {done && <Check className=\"size-3.5\" />}\n              {stage}\n            </button>\n          </li>\n        )\n      })}\n    </ol>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/stage-path.tsx"
    },
    {
      "path": "registry/dashboard/pages/order-edit/totals.tsx",
      "content": "import { cn } from '@/lib/utils'\n\nexport type Totals = {\n  subtotal: number\n  discount: number\n  shipping: number\n  tax: number\n  total: number\n}\n\ntype TotalsCardProps = {\n  totals: Totals\n  before: Totals\n  count: number\n  paid: number\n  discountLabel?: string\n  taxRate: number\n  money: Intl.NumberFormat\n  children?: React.ReactNode\n}\n\nexport function computeTotals(\n  items: { price: number; quantity: number }[],\n  discountPct: number,\n  shipping: number,\n  taxRate: number,\n): Totals {\n  const subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0)\n  const discount = (subtotal * Math.min(100, Math.max(0, discountPct || 0))) / 100\n  const ship = Math.max(0, shipping || 0)\n  const tax = (subtotal - discount) * taxRate\n  return { subtotal, discount, shipping: ship, tax, total: subtotal - discount + ship + tax }\n}\n\nfunction Row({\n  label,\n  detail,\n  value,\n  was,\n  strong,\n}: {\n  label: React.ReactNode\n  detail?: React.ReactNode\n  value: string\n  was?: string\n  strong?: boolean\n}) {\n  return (\n    <div\n      className={cn(\n        'grid grid-cols-[1fr_auto_7rem] items-baseline gap-4 py-2 text-sm',\n        strong && 'font-semibold',\n      )}\n    >\n      <span>{label}</span>\n      <span className=\"text-right text-muted-foreground\">{detail}</span>\n      <span className=\"flex flex-col items-end tabular-nums\">\n        {value}\n        {was && was !== value && (\n          <span className=\"text-xs font-normal text-muted-foreground line-through\">{was}</span>\n        )}\n      </span>\n    </div>\n  )\n}\n\nexport function TotalsCard({\n  totals,\n  before,\n  count,\n  paid,\n  discountLabel,\n  taxRate,\n  money,\n  children,\n}: TotalsCardProps) {\n  const f = (n: number) => money.format(n)\n  const balance = Math.round((totals.total - paid) * 100) / 100\n\n  return (\n    <section className=\"flex flex-col gap-3\">\n      <h2 className=\"text-base font-semibold\">Payment</h2>\n      <div className=\"rounded-xl bg-muted\">\n        <div className=\"rounded-xl bg-card px-4 py-2 shadow-(--shadow-card)\">\n          <Row\n            label=\"Subtotal\"\n            detail={`${count} item${count === 1 ? '' : 's'}`}\n            value={f(totals.subtotal)}\n            was={f(before.subtotal)}\n          />\n          {totals.discount > 0 && (\n            <Row\n              label=\"Discount\"\n              detail={discountLabel}\n              value={`−${f(totals.discount)}`}\n              was={before.discount ? `−${f(before.discount)}` : undefined}\n            />\n          )}\n          <Row label=\"Shipping\" value={f(totals.shipping)} was={f(before.shipping)} />\n          <Row\n            label=\"Tax\"\n            detail={`${Math.round(taxRate * 1000) / 10}%`}\n            value={f(totals.tax)}\n            was={f(before.tax)}\n          />\n          <div className=\"mt-1 border-t pt-1\">\n            <Row label=\"Total\" value={f(totals.total)} was={f(before.total)} strong />\n          </div>\n        </div>\n        <div className=\"px-4 py-2\">\n          <Row label=\"Paid by customer\" value={f(paid)} />\n          <Row\n            strong\n            label={balance > 0 ? 'Amount to collect' : balance < 0 ? 'Refund owed' : 'Balance'}\n            value={f(Math.abs(balance))}\n          />\n          {children && <div className=\"border-t py-3\">{children}</div>}\n        </div>\n      </div>\n    </section>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/dashboard/order-edit/totals.tsx"
    }
  ],
  "meta": {
    "scenario": "dashboard",
    "kind": "pages"
  },
  "categories": [
    "dashboard",
    "forms",
    "crm"
  ],
  "type": "registry:block"
}