{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-07",
  "title": "Billing",
  "description": "The plan with its status, renewal and a chooser whose highlight travels, meters that turn amber near their limit as runs come in, invoices that download, a drawn card that Update card replaces, and Cancel subscription that confirms in place and turns the plan into Cancels on 30 Nov with Resume beside it.",
  "dependencies": [
    "@base-ui/react",
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/label.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/table.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/wash.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/settings/settings-07/index.tsx",
      "content": "'use client';\n\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport {\n  USAGE_RESETS_ON,\n  WORKSPACE_NAME,\n  type Invoice,\n  type PlanId,\n} from './data';\nimport { DOLLARS, Invoices } from './invoices';\nimport { PaymentMethod } from './payment-method';\nimport { PlanCard } from './plan-card';\nimport {\n  DOWNLOAD_MS,\n  DOWNLOADED_MS,\n  firstCardErrorOf,\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SAVE_CARD_MS,\n  SCRIPT,\n  SWITCH_MS,\n} from './session';\nimport { SettingsFrame, SettingsSection } from './settings-frame';\nimport { UsageMeters } from './usage-meters';\n\n/** The address of a saved file lives long enough for the browser to start the download. */\nconst RELEASE_FILE_AFTER_MS = 1000;\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\n/** The file a person saves: the invoice in words, marked as a sample. */\nfunction invoiceTextOf(invoice: Invoice) {\n  const total = DOLLARS.format(invoice.amount);\n  const lines = [\n    WORKSPACE_NAME,\n    `Invoice ${invoice.id}, ${invoice.date}`,\n    '',\n    ...invoice.lines,\n    '',\n    `Total: ${total}`,\n    `Status: ${invoice.status}`,\n    '',\n    'A sample invoice from a component preview. Illustrative figures.',\n  ];\n  return lines.join('\\n');\n}\n\nexport default function Settings07() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const { schedule, clearAll } = useTimeouts();\n  const message = spokenUnless(isAutoplaying, state.spoken);\n  const canReplay = isFinished && !isAutoplaying;\n\n  function focusLater(selector: string) {\n    requestAnimationFrame(() => {\n      const target = ref.current?.querySelector<HTMLElement>(selector);\n      target?.focus();\n    });\n  }\n\n  function toggleChooser() {\n    const wasOpen = state.isChoosingPlan;\n    act({ type: 'chooserToggled' });\n    if (wasOpen) {\n      focusLater('[data-change-plan]');\n      return;\n    }\n    focusLater(`[data-plan=\"${state.planId}\"]`);\n  }\n\n  function pickPlan(planId: PlanId) {\n    act({ type: 'planPicked', planId });\n  }\n\n  function finishSwitch() {\n    act({ type: 'planSwitched' });\n    focusLater('[data-change-plan]');\n  }\n\n  function switchPlan() {\n    const after = reducer(state, { type: 'switchPressed' });\n    act({ type: 'switchPressed' });\n    if (after.isSwitchingPlan) {\n      schedule(finishSwitch, SWITCH_MS);\n    }\n  }\n\n  function askCancel() {\n    act({ type: 'cancelAsked' });\n    focusLater('[data-keep-plan]');\n  }\n\n  function keepPlan() {\n    act({ type: 'cancelKept' });\n    focusLater('[data-plan-end]');\n  }\n\n  function confirmCancel() {\n    act({ type: 'cancelConfirmed' });\n    focusLater('[data-plan-end]');\n  }\n\n  function resume() {\n    act({ type: 'resumed' });\n  }\n\n  function toggleCard() {\n    const wasOpen = state.isEditingCard;\n    act({ type: 'cardEditToggled' });\n    if (wasOpen) {\n      focusLater('[data-update-card]');\n      return;\n    }\n    focusLater('[data-card-field=\"number\"]');\n  }\n\n  function finishCardSave() {\n    act({ type: 'cardSaved' });\n    focusLater('[data-update-card]');\n  }\n\n  function saveCard() {\n    const after = reducer(state, { type: 'cardSavePressed' });\n    act({ type: 'cardSavePressed' });\n    if (after.isSavingCard) {\n      schedule(finishCardSave, SAVE_CARD_MS);\n      return;\n    }\n    const field = firstCardErrorOf(after.cardErrors);\n    if (field) {\n      focusLater(`[data-card-field=\"${field}\"]`);\n    }\n  }\n\n  /** Nothing calls a network: the invoice is written in the page and handed to the browser. */\n  function saveFile(invoice: Invoice) {\n    const text = invoiceTextOf(invoice);\n    const blob = new Blob([text], { type: 'text/plain' });\n    const address = URL.createObjectURL(blob);\n    const link = document.createElement('a');\n    link.href = address;\n    link.download = `${invoice.id}.txt`;\n    link.click();\n    schedule(() => URL.revokeObjectURL(address), RELEASE_FILE_AFTER_MS);\n  }\n\n  function download(invoice: Invoice) {\n    const id = invoice.id;\n    const readyAgainAfter = DOWNLOAD_MS + DOWNLOADED_MS;\n    act({ type: 'downloadStarted', id });\n    schedule(() => {\n      act({ type: 'downloadDone', id });\n      saveFile(invoice);\n    }, DOWNLOAD_MS);\n    schedule(() => act({ type: 'downloadFaded', id }), readyAgainAfter);\n  }\n\n  /** A change on its way belongs to the round it was asked for in. */\n  function replay() {\n    clearAll();\n    restart();\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <SettingsFrame\n        ref={ref}\n        title='Billing'\n        line={`The plan of ${WORKSPACE_NAME}, what it used this month, its invoices and the card that pays them.`}\n        aside={\n          <ReplayButton isShown={canReplay} onReplay={replay} label='Replay' />\n        }\n      >\n        <SettingsSection title='Plan'>\n          <PlanCard\n            state={state}\n            pressed={pressed}\n            onToggleChooser={toggleChooser}\n            onPick={pickPlan}\n            onSwitch={switchPlan}\n            onAskCancel={askCancel}\n            onKeep={keepPlan}\n            onConfirmCancel={confirmCancel}\n            onResume={resume}\n          />\n        </SettingsSection>\n        <SettingsSection\n          title='Usage this month'\n          line={\n            <span className='flex flex-wrap items-center gap-x-1.5 gap-y-1'>\n              {`Resets on ${USAGE_RESETS_ON}`}\n              <Badge variant='secondary'>Illustrative</Badge>\n            </span>\n          }\n        >\n          <UsageMeters planId={state.planId} used={state.used} />\n        </SettingsSection>\n        <SettingsSection\n          title='Invoices'\n          line='Sent to billing@tidewell.example'\n        >\n          <Invoices\n            downloads={state.downloads}\n            pressed={pressed}\n            onDownload={download}\n          />\n        </SettingsSection>\n        <SettingsSection title='Payment method'>\n          <PaymentMethod\n            state={state}\n            onAction={act}\n            onToggle={toggleCard}\n            onSave={saveCard}\n          />\n        </SettingsSection>\n        <LiveRegion message={message} />\n      </SettingsFrame>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/plan-card.tsx",
      "content": "'use client';\n\nimport { Radio as RadioPrimitive } from '@base-ui/react/radio';\nimport { RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group';\nimport { motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  pressedQuietOf,\n  pressedSolidOf,\n} from '@/registry/ndeko/lib/demonstration';\nimport { springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { Wash } from '@/registry/ndeko/ui/wash';\n\nimport {\n  PLANS,\n  RENEWAL_DATE,\n  RENEWAL_DAY,\n  type Plan,\n  type PlanId,\n} from './data';\nimport { isTooSmall, planOf, type BillingState } from './session';\nimport { SURFACE } from './settings-frame';\n\nexport const WHOLE_DOLLARS: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  maximumFractionDigits: 0,\n};\n\nconst DOLLARS = new Intl.NumberFormat('en-US', WHOLE_DOLLARS);\n\ntype PlanStatus = {\n  key: string;\n  label: string;\n  variant: 'success' | 'warning';\n};\n\nfunction statusOf(state: BillingState): PlanStatus {\n  if (state.isCancelling) {\n    return {\n      key: 'cancelling',\n      label: `Cancels on ${RENEWAL_DAY}`,\n      variant: 'warning',\n    };\n  }\n  return { key: 'active', label: 'Active', variant: 'success' };\n}\n\nfunction renewalLineOf(state: BillingState, plan: Plan) {\n  const isFree = plan.price === 0;\n  if (isFree) {\n    return `${plan.seats} seats, free, nothing to renew`;\n  }\n  if (state.isCancelling) {\n    return `Ends on ${RENEWAL_DATE}, then moves to Starter. Nothing more is charged`;\n  }\n  return `${plan.seats} seats · Renews on ${RENEWAL_DATE}`;\n}\n\nfunction priceLineOf(plan: Plan) {\n  if (plan.price === 0) {\n    return 'Free';\n  }\n  return `${DOLLARS.format(plan.price)} a month`;\n}\n\nfunction switchLabelsOf(picked: Plan): Record<MorphState, string> {\n  return {\n    idle: `Switch to ${picked.name}`,\n    busy: 'Switching',\n    done: 'Switched',\n  };\n}\n\nfunction switchStateOf(isSwitching: boolean): MorphState {\n  if (isSwitching) {\n    return 'busy';\n  }\n  return 'idle';\n}\n\nfunction tooSmallLineOf(seatsUsed: number) {\n  return `${seatsUsed} seats in use`;\n}\n\ntype PlanChooserProps = {\n  state: BillingState;\n  onPick: (planId: PlanId) => void;\n  onSwitch: () => void;\n  onClose: () => void;\n};\n\n/** One highlight travels to the plan picked; a plan too small for the team stays in place, dimmed. */\nfunction PlanChooser({ state, onPick, onSwitch, onClose }: PlanChooserProps) {\n  const thumbId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const travel = springOf(shouldReduceMotion);\n  const picked = planOf(state.pickedPlanId);\n  const isSamePlan = state.pickedPlanId === state.planId;\n  const seatsUsed = state.used.seats;\n\n  function pick(value: unknown) {\n    const plan = PLANS.find((candidate) => candidate.id === value);\n    if (plan) {\n      onPick(plan.id);\n    }\n  }\n\n  function closeOnEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key !== 'Escape') {\n      return;\n    }\n    event.preventDefault();\n    onClose();\n  }\n\n  return (\n    <div\n      onKeyDown={closeOnEscape}\n      className='bg-card/70 dark:bg-foreground/[0.03] flex flex-col gap-3 rounded-lg p-2'\n    >\n      <RadioGroupPrimitive\n        value={state.pickedPlanId}\n        onValueChange={pick}\n        aria-label='Plans'\n        className='flex flex-col gap-1'\n      >\n        {PLANS.map((plan) => {\n          const isPicked = plan.id === state.pickedPlanId;\n          const isCurrent = plan.id === state.planId;\n          const isBlocked = isTooSmall(plan.id, seatsUsed);\n          return (\n            <RadioPrimitive.Root\n              key={plan.id}\n              value={plan.id}\n              disabled={isBlocked}\n              data-plan={plan.id}\n              className='focus-visible:ring-ring/25 relative flex w-full cursor-pointer items-center gap-3 rounded-md px-3 py-2.5 text-start outline-none focus-visible:ring-[3px] data-disabled:cursor-not-allowed data-disabled:opacity-50'\n            >\n              {isPicked && (\n                <motion.span\n                  aria-hidden='true'\n                  layoutId={thumbId}\n                  transition={travel}\n                  className='bg-primary/[0.07] hairline-ring ring-primary/30 absolute inset-0 rounded-md'\n                />\n              )}\n              <span className='relative flex min-w-0 flex-1 flex-col gap-0.5'>\n                <span className='flex flex-wrap items-center gap-x-2 gap-y-1 text-[13px] font-medium'>\n                  {plan.name}\n                  {isCurrent && <Badge variant='secondary'>Current</Badge>}\n                </span>\n                <span className='text-muted-foreground text-xs text-pretty'>\n                  {isBlocked && tooSmallLineOf(seatsUsed)}\n                  {!isBlocked && `${plan.seats} seats. ${plan.line}`}\n                </span>\n              </span>\n              <span className='relative shrink-0 text-[13px] tabular-nums'>\n                {priceLineOf(plan)}\n              </span>\n            </RadioPrimitive.Root>\n          );\n        })}\n      </RadioGroupPrimitive>\n      <div className='flex flex-wrap items-center justify-end gap-2 px-1 pb-1'>\n        <Button type='button' variant='ghost' size='sm' onClick={onClose}>\n          Close\n        </Button>\n        <MorphButton\n          type='button'\n          size='sm'\n          state={switchStateOf(state.isSwitchingPlan)}\n          labels={switchLabelsOf(picked)}\n          disabled={isSamePlan}\n          onClick={onSwitch}\n        />\n      </div>\n    </div>\n  );\n}\n\ntype CancelConfirmProps = {\n  planName: string;\n  pressed: string | null;\n  onKeep: () => void;\n  onConfirm: () => void;\n};\n\nfunction CancelConfirm({\n  planName,\n  pressed,\n  onKeep,\n  onConfirm,\n}: CancelConfirmProps) {\n  function keepOnEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key !== 'Escape') {\n      return;\n    }\n    event.preventDefault();\n    onKeep();\n  }\n\n  return (\n    <div\n      role='group'\n      aria-label={`Cancel the ${planName} plan`}\n      onKeyDown={keepOnEscape}\n      className='bg-destructive/[0.06] flex flex-col gap-3 rounded-lg p-3'\n    >\n      <p className='text-[13px] text-pretty'>\n        <span className='font-medium'>{`Cancel the ${planName} plan?`}</span>{' '}\n        {`It stays active until ${RENEWAL_DATE}, then the workspace moves to Starter and keeps 5 seats.`}\n      </p>\n      <div className='flex flex-wrap justify-end gap-2'>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          data-keep-plan\n          onClick={onKeep}\n        >\n          Keep the plan\n        </Button>\n        <Button\n          type='button'\n          variant='destructive'\n          size='sm'\n          onClick={onConfirm}\n          className={pressedSolidOf(pressed === 'confirm-cancel')}\n        >\n          Cancel subscription\n        </Button>\n      </div>\n    </div>\n  );\n}\n\nfunction endLabelOf(isCancelling: boolean) {\n  if (isCancelling) {\n    return 'Resume subscription';\n  }\n  return 'Cancel subscription';\n}\n\n/** Only Cancel opens something: Resume acts at once. */\nfunction endExpandedOf(isCancelling: boolean, isConfirming: boolean) {\n  if (isCancelling) {\n    return undefined;\n  }\n  return isConfirming;\n}\n\n/** Cancelling is quiet until it is pending; Resume is then the action the card asks for. */\nfunction endLookOf(isCancelling: boolean, pressed: string | null) {\n  if (isCancelling) {\n    return cn('text-primary-ink', pressedQuietOf(pressed === 'resume'));\n  }\n  return cn('text-destructive-ink', pressedQuietOf(pressed === 'cancel'));\n}\n\ntype PlanCardProps = {\n  state: BillingState;\n  pressed: string | null;\n  onToggleChooser: () => void;\n  onPick: (planId: PlanId) => void;\n  onSwitch: () => void;\n  onAskCancel: () => void;\n  onKeep: () => void;\n  onConfirmCancel: () => void;\n  onResume: () => void;\n};\n\n/** The one featured surface of the page, so it wears the wash. */\nexport function PlanCard({\n  state,\n  pressed,\n  onToggleChooser,\n  onPick,\n  onSwitch,\n  onAskCancel,\n  onKeep,\n  onConfirmCancel,\n  onResume,\n}: PlanCardProps) {\n  const titleId = useId();\n  const plan = planOf(state.planId);\n  const status = statusOf(state);\n  const renewalLine = renewalLineOf(state, plan);\n  const isPaid = plan.price > 0;\n  const endLabel = endLabelOf(state.isCancelling);\n\n  function pressEnd() {\n    if (state.isCancelling) {\n      onResume();\n      return;\n    }\n    onAskCancel();\n  }\n\n  return (\n    <section\n      aria-labelledby={titleId}\n      className={cn(\n        SURFACE,\n        'relative isolate flex flex-col gap-4 p-4 @xl:p-5'\n      )}\n    >\n      <Wash />\n      <div className='flex flex-wrap items-start gap-x-4 gap-y-3'>\n        <div className='flex min-w-0 flex-1 basis-56 flex-col gap-1.5'>\n          <div className='flex flex-wrap items-center gap-2'>\n            <h3 id={titleId} className='flex text-sm font-medium'>\n              <Swap swapKey={plan.name}>{`${plan.name} plan`}</Swap>\n            </h3>\n            <Badge variant={status.variant}>\n              <AnimatedSize as='span' axis='width' contentClassName='flex'>\n                <Swap swapKey={status.key}>{status.label}</Swap>\n              </AnimatedSize>\n            </Badge>\n          </div>\n          <p className='flex items-baseline gap-1.5'>\n            <MotionNumber\n              value={plan.price}\n              format={WHOLE_DOLLARS}\n              className='text-2xl leading-8 font-semibold'\n            />\n            <span className='text-muted-foreground text-xs'>a month</span>\n          </p>\n          <p className='text-muted-foreground flex text-xs text-pretty'>\n            <Swap swapKey={renewalLine}>{renewalLine}</Swap>\n          </p>\n        </div>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          data-change-plan\n          aria-expanded={state.isChoosingPlan}\n          onClick={onToggleChooser}\n        >\n          Change plan\n        </Button>\n      </div>\n      <Fold open={state.isChoosingPlan}>\n        <PlanChooser\n          state={state}\n          onPick={onPick}\n          onSwitch={onSwitch}\n          onClose={onToggleChooser}\n        />\n      </Fold>\n      {isPaid && (\n        <div className='flex flex-col gap-3'>\n          <div className='flex flex-wrap items-center justify-between gap-x-4 gap-y-2'>\n            <p className='text-muted-foreground text-xs'>\n              Prices are illustrative\n            </p>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              data-plan-end\n              aria-expanded={endExpandedOf(\n                state.isCancelling,\n                state.isConfirmingCancel\n              )}\n              onClick={pressEnd}\n              className={endLookOf(state.isCancelling, pressed)}\n            >\n              <AnimatedSize as='span' axis='width' contentClassName='flex'>\n                <Swap swapKey={endLabel}>{endLabel}</Swap>\n              </AnimatedSize>\n            </Button>\n          </div>\n          <Fold open={state.isConfirmingCancel}>\n            <CancelConfirm\n              planName={plan.name}\n              pressed={pressed}\n              onKeep={onKeep}\n              onConfirm={onConfirmCancel}\n            />\n          </Fold>\n        </div>\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/plan-card.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/usage-meters.tsx",
      "content": "import { MotionNumber } from '@/components/core/motion-number';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport {\n  METERS,\n  NEAR_LIMIT_SHARE,\n  type Meter,\n  type MeterId,\n  type PlanId,\n} from './data';\nimport { SURFACE } from './settings-frame';\n\ntype Tone = 'calm' | 'near' | 'over';\n\nconst FILL_TONE: Record<Tone, string> = {\n  calm: 'bg-primary',\n  near: 'bg-warning',\n  over: 'bg-warning',\n};\n\nconst NOTE_TONE: Record<Tone, string> = {\n  calm: 'text-muted-foreground',\n  near: 'text-warning-foreground',\n  over: 'text-warning-foreground',\n};\n\nfunction toneOf(used: number, included: number): Tone {\n  const share = used / included;\n  if (share > 1) {\n    return 'over';\n  }\n  if (share >= NEAR_LIMIT_SHARE) {\n    return 'near';\n  }\n  return 'calm';\n}\n\nfunction formatOf(decimals: number): Intl.NumberFormatOptions {\n  return {\n    minimumFractionDigits: decimals,\n    maximumFractionDigits: decimals,\n  };\n}\n\nfunction quantityOf(value: number, decimals: number) {\n  const options = formatOf(decimals);\n  const formatter = new Intl.NumberFormat('en-US', options);\n  return formatter.format(value);\n}\n\nfunction noteOf(meter: Meter, used: number, included: number, tone: Tone) {\n  if (tone === 'over') {\n    const extra = used - included;\n    const over = quantityOf(extra, meter.decimals);\n    return `${over} ${meter.unit} over the plan`;\n  }\n  const remaining = included - used;\n  const left = quantityOf(remaining, meter.decimals);\n  if (tone === 'near') {\n    return `Near the limit: ${left} ${meter.unit} left`;\n  }\n  return `${left} ${meter.unit} left`;\n}\n\n/** The bar stops at its end: what goes past the plan is said in words under it. */\nfunction fillStyleOf(used: number, included: number) {\n  const ratio = used / included;\n  const share = Math.min(ratio, 1);\n  return { transform: `scaleX(${share})` };\n}\n\ntype MeterRowProps = {\n  meter: Meter;\n  used: number;\n  included: number;\n};\n\nfunction MeterRow({ meter, used, included }: MeterRowProps) {\n  const tone = toneOf(used, included);\n  const note = noteOf(meter, used, included, tone);\n  const includedText = quantityOf(included, 0);\n  const usedText = quantityOf(used, meter.decimals);\n  const valueNow = Math.min(used, included);\n\n  return (\n    <li className='flex flex-col gap-2'>\n      <p className='flex flex-wrap items-baseline justify-between gap-x-3'>\n        <span className='text-[13px] font-medium'>{meter.label}</span>\n        <span className='text-[13px] tabular-nums'>\n          <MotionNumber value={used} format={formatOf(meter.decimals)} />\n          <span className='text-muted-foreground'>\n            {` of ${includedText} ${meter.unit}`}\n          </span>\n        </span>\n      </p>\n      <div\n        role='meter'\n        aria-label={meter.label}\n        aria-valuemin={0}\n        aria-valuemax={included}\n        aria-valuenow={valueNow}\n        aria-valuetext={`${usedText} of ${includedText} ${meter.unit}`}\n        className='bg-foreground/10 h-1.5 overflow-hidden rounded-full'\n      >\n        <span\n          style={fillStyleOf(used, included)}\n          className={cn(\n            'block h-full origin-left rounded-full transition-[transform,background-color] duration-500 ease-(--ease-out-strong) rtl:origin-right',\n            FILL_TONE[tone]\n          )}\n        />\n      </div>\n      <p className={cn('flex text-xs tabular-nums', NOTE_TONE[tone])}>\n        <Swap swapKey={tone}>{note}</Swap>\n      </p>\n    </li>\n  );\n}\n\ntype UsageMetersProps = {\n  planId: PlanId;\n  used: Record<MeterId, number>;\n};\n\n/** What the plan includes follows the plan: a change of plan moves every bar. */\nexport function UsageMeters({ planId, used }: UsageMetersProps) {\n  return (\n    <ul className={cn(SURFACE, 'flex flex-col gap-5 p-4 @xl:p-5')}>\n      {METERS.map((meter) => (\n        <MeterRow\n          key={meter.id}\n          meter={meter}\n          used={used[meter.id]}\n          included={meter.included[planId]}\n        />\n      ))}\n    </ul>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/usage-meters.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/invoices.tsx",
      "content": "'use client';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { DownloadIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from '@/registry/ndeko/ui/table';\n\nimport { INVOICES, type Invoice, type InvoiceStatus } from './data';\nimport type { DownloadStatus } from './session';\nimport { SURFACE } from './settings-frame';\n\nexport const DOLLARS = new Intl.NumberFormat('en-US', {\n  style: 'currency',\n  currency: 'USD',\n});\n\nconst DOWNLOAD_LABELS: Record<MorphState, string> = {\n  idle: 'Download',\n  busy: 'Preparing',\n  done: 'Downloaded',\n};\n\nconst MORPH_OF: Record<DownloadStatus, MorphState> = {\n  idle: 'idle',\n  busy: 'busy',\n  done: 'done',\n};\n\nconst STATUS_LABEL: Record<InvoiceStatus, string> = {\n  paid: 'Paid',\n  refunded: 'Refunded',\n};\n\nconst STATUS_VARIANT: Record<InvoiceStatus, 'success' | 'secondary'> = {\n  paid: 'success',\n  refunded: 'secondary',\n};\n\n/** The name follows the state of the button, so it always holds the words it shows. */\nfunction downloadLabelOf(status: DownloadStatus, invoiceId: string) {\n  const words = DOWNLOAD_LABELS[MORPH_OF[status]];\n  return `${words} ${invoiceId}`;\n}\n\ntype InvoicesProps = {\n  downloads: Record<string, DownloadStatus>;\n  pressed: string | null;\n  onDownload: (invoice: Invoice) => void;\n};\n\n/** A wide table scrolls inside its own frame on a phone, never the page. */\nexport function Invoices({ downloads, pressed, onDownload }: InvoicesProps) {\n  return (\n    <div className={cn(SURFACE, 'overflow-hidden')}>\n      <Table className='min-w-[30rem]'>\n        <TableHeader>\n          <TableRow className='hover:bg-transparent'>\n            <TableHead className='ps-4'>Date</TableHead>\n            <TableHead>Invoice</TableHead>\n            <TableHead className='text-end'>Amount</TableHead>\n            <TableHead>Status</TableHead>\n            <TableHead className='pe-4 text-end'>\n              <span className='sr-only'>Download</span>\n            </TableHead>\n          </TableRow>\n        </TableHeader>\n        <TableBody>\n          {INVOICES.map((invoice) => {\n            const status = downloads[invoice.id] ?? 'idle';\n            return (\n              <TableRow key={invoice.id}>\n                <TableCell className='ps-4 whitespace-nowrap'>\n                  {invoice.date}\n                </TableCell>\n                <TableCell className='font-mono text-xs'>\n                  {invoice.id}\n                </TableCell>\n                <TableCell className='text-end tabular-nums'>\n                  {DOLLARS.format(invoice.amount)}\n                </TableCell>\n                <TableCell>\n                  <Badge variant={STATUS_VARIANT[invoice.status]}>\n                    {STATUS_LABEL[invoice.status]}\n                  </Badge>\n                </TableCell>\n                <TableCell className='pe-2 text-end'>\n                  <MorphButton\n                    type='button'\n                    variant='ghost'\n                    size='sm'\n                    state={MORPH_OF[status]}\n                    labels={DOWNLOAD_LABELS}\n                    idleIcon={<DownloadIcon />}\n                    aria-label={downloadLabelOf(status, invoice.id)}\n                    onClick={() => onDownload(invoice)}\n                    className={cn(\n                      'text-muted-foreground',\n                      pressedQuietOf(pressed === `download-${invoice.id}`)\n                    )}\n                  />\n                </TableCell>\n              </TableRow>\n            );\n          })}\n        </TableBody>\n      </Table>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/invoices.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/payment-method.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { BrandLogo } from '@/registry/ndeko/lib/brand-logos';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Label } from '@/registry/ndeko/ui/label';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\n\nimport { CARD_BRAND_NAME, type Card } from './data';\nimport type {\n  BillingAction,\n  BillingState,\n  CardErrors,\n  CardField,\n} from './session';\nimport { describedByOf, ErrorLine, SURFACE } from './settings-frame';\n\nconst SAVE_LABELS: Record<MorphState, string> = {\n  idle: 'Save card',\n  busy: 'Checking',\n  done: 'Saved',\n};\n\nfunction saveStateOf(isSaving: boolean): MorphState {\n  if (isSaving) {\n    return 'busy';\n  }\n  return 'idle';\n}\n\n/** A card face drawn with the page's own materials: the network's mark, a chip, the last digits. */\nfunction CardFace({ card }: { card: Card }) {\n  return (\n    <div\n      aria-hidden='true'\n      className='bg-card hairline-ring ring-border dark:bg-foreground/[0.06] relative flex aspect-[86/54] w-40 shrink-0 flex-col justify-between rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.06),0_4px_12px_-4px_rgb(0_0_0/0.08)]'\n    >\n      <div className='flex items-start justify-between'>\n        <span className='keycap-3d h-5 w-7 rounded-[5px]' />\n        <Swap swapKey={card.brand}>\n          <BrandLogo brand={card.brand} className='size-7' />\n        </Swap>\n      </div>\n      <div className='flex items-end justify-between gap-2 font-mono text-[11px] tabular-nums'>\n        <span className='flex items-center gap-1'>\n          <span className='text-muted-foreground'>••••</span>\n          <Swap swapKey={card.last4}>{card.last4}</Swap>\n        </span>\n        <Swap swapKey={card.expiry} className='text-muted-foreground'>\n          {card.expiry}\n        </Swap>\n      </div>\n    </div>\n  );\n}\n\ntype CardInputProps = {\n  field: CardField;\n  label: string;\n  value: string;\n  errors: CardErrors;\n  attempts: number;\n  placeholder: string;\n  autoComplete: string;\n  maxLength: number;\n  isLocked: boolean;\n  onAction: (action: BillingAction) => void;\n};\n\nfunction CardInput({\n  field,\n  label,\n  value,\n  errors,\n  attempts,\n  placeholder,\n  autoComplete,\n  maxLength,\n  isLocked,\n  onAction,\n}: CardInputProps) {\n  const inputId = useId();\n  const errorId = useId();\n  const error = errors[field] ?? null;\n  const hasError = error !== null;\n\n  return (\n    <div className='flex min-w-0 flex-col gap-1.5'>\n      <Label htmlFor={inputId}>{label}</Label>\n      <Input\n        id={inputId}\n        data-card-field={field}\n        value={value}\n        inputMode='numeric'\n        autoComplete={autoComplete}\n        placeholder={placeholder}\n        maxLength={maxLength}\n        spellCheck={false}\n        readOnly={isLocked}\n        aria-invalid={hasError}\n        aria-describedby={describedByOf(hasError, errorId)}\n        onChange={(event) =>\n          onAction({ type: 'cardTyped', field, value: event.target.value })\n        }\n        className='font-mono'\n      />\n      <ErrorLine id={errorId} error={error} attempts={attempts} />\n    </div>\n  );\n}\n\ntype CardFormProps = {\n  state: BillingState;\n  onAction: (action: BillingAction) => void;\n  onSave: () => void;\n  onClose: () => void;\n};\n\nfunction CardForm({ state, onAction, onSave, onClose }: CardFormProps) {\n  const draft = state.cardDraft;\n  const isSaving = state.isSavingCard;\n  const shared = {\n    errors: state.cardErrors,\n    attempts: state.cardAttempts,\n    isLocked: isSaving,\n    onAction,\n  };\n\n  function submit(event: React.FormEvent<HTMLFormElement>) {\n    event.preventDefault();\n    onSave();\n  }\n\n  function closeOnEscape(event: React.KeyboardEvent<HTMLFormElement>) {\n    if (event.key !== 'Escape') {\n      return;\n    }\n    event.preventDefault();\n    onClose();\n  }\n\n  return (\n    <form\n      noValidate\n      onSubmit={submit}\n      onKeyDown={closeOnEscape}\n      className='bg-foreground/[0.03] flex flex-col gap-3 rounded-lg p-3'\n    >\n      <div className='grid gap-3 @lg:grid-cols-[minmax(0,1fr)_6.5rem_6rem]'>\n        <CardInput\n          field='number'\n          label='Card number'\n          value={draft.number}\n          placeholder='1234 1234 1234 1234'\n          autoComplete='cc-number'\n          maxLength={23}\n          {...shared}\n        />\n        <CardInput\n          field='expiry'\n          label='Expiry'\n          value={draft.expiry}\n          placeholder='MM/YY'\n          autoComplete='cc-exp'\n          maxLength={7}\n          {...shared}\n        />\n        <CardInput\n          field='cvc'\n          label='Security code'\n          value={draft.cvc}\n          placeholder='123'\n          autoComplete='cc-csc'\n          maxLength={4}\n          {...shared}\n        />\n      </div>\n      <div className='flex flex-wrap items-center justify-between gap-x-4 gap-y-2'>\n        <p className='text-muted-foreground min-w-0 flex-1 basis-48 text-xs text-pretty'>\n          A sample form: what you type never leaves this page\n        </p>\n        <div className='flex gap-2'>\n          <Button\n            type='button'\n            variant='ghost'\n            size='sm'\n            disabled={isSaving}\n            onClick={onClose}\n          >\n            Close\n          </Button>\n          <MorphButton\n            type='submit'\n            size='sm'\n            state={saveStateOf(isSaving)}\n            labels={SAVE_LABELS}\n          />\n        </div>\n      </div>\n    </form>\n  );\n}\n\ntype PaymentMethodProps = {\n  state: BillingState;\n  onAction: (action: BillingAction) => void;\n  onToggle: () => void;\n  onSave: () => void;\n};\n\nexport function PaymentMethod({\n  state,\n  onAction,\n  onToggle,\n  onSave,\n}: PaymentMethodProps) {\n  const card = state.card;\n  const summary = `${CARD_BRAND_NAME[card.brand]} ending in ${card.last4}`;\n  const expiryLine = `Expires ${card.expiry}. Pays every invoice of the workspace`;\n\n  return (\n    <div className={cn(SURFACE, 'flex flex-col gap-4 p-4 @xl:p-5')}>\n      <div className='flex flex-wrap items-center gap-4'>\n        <CardFace card={card} />\n        <div className='flex min-w-0 flex-1 basis-40 flex-col gap-0.5'>\n          <p className='flex text-[13px] font-medium'>\n            <Swap swapKey={summary}>{summary}</Swap>\n          </p>\n          <p className='text-muted-foreground text-xs text-pretty'>\n            {expiryLine}\n          </p>\n        </div>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          data-update-card\n          aria-expanded={state.isEditingCard}\n          disabled={state.isSavingCard}\n          onClick={onToggle}\n        >\n          Update card\n        </Button>\n      </div>\n      <Fold open={state.isEditingCard}>\n        <CardForm\n          state={state}\n          onAction={onAction}\n          onSave={onSave}\n          onClose={onToggle}\n        />\n      </Fold>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/payment-method.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/settings-frame.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { rowPresenceOf, SPRING } from '@/registry/ndeko/lib/motion-presets';\n\nexport const SURFACE =\n  'bg-card hairline-ring ring-border rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-foreground/[0.03]';\n\nconst NUDGE = { initial: { x: 4 }, animate: { x: 0 } };\n\nconst STILL = { initial: false, animate: { x: 0 } };\n\nfunction nudgeOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return STILL;\n  }\n  return NUDGE;\n}\n\nexport function describedByOf(hasError: boolean, errorId: string) {\n  if (hasError) {\n    return errorId;\n  }\n  return undefined;\n}\n\ntype SettingsFrameProps = {\n  ref?: React.Ref<HTMLDivElement>;\n  title: string;\n  line: string;\n  /** Sits beside the title: the Replay of the demonstration. */\n  aside?: React.ReactNode;\n  children: React.ReactNode;\n};\n\n/** A settings page that follows its own width: one column, the title above, the sections under it. */\nexport function SettingsFrame({\n  ref,\n  title,\n  line,\n  aside,\n  children,\n}: SettingsFrameProps) {\n  return (\n    <div\n      ref={ref}\n      className='bg-background text-foreground @container min-h-dvh w-full'\n    >\n      <div className='mx-auto flex w-full max-w-3xl flex-col gap-8 px-4 py-8 @2xl:px-6 @2xl:py-10'>\n        <header className='flex flex-wrap items-start gap-x-3 gap-y-2'>\n          <div className='flex min-w-0 flex-1 basis-64 flex-col gap-1'>\n            <h1 className='text-2xl font-semibold text-balance @xl:text-3xl'>\n              {title}\n            </h1>\n            <p className='text-muted-foreground text-[13px] text-pretty'>\n              {line}\n            </p>\n          </div>\n          {aside}\n        </header>\n        {children}\n      </div>\n    </div>\n  );\n}\n\ntype SettingsSectionProps = {\n  title: string;\n  line?: React.ReactNode;\n  action?: React.ReactNode;\n  children: React.ReactNode;\n};\n\nexport function SettingsSection({\n  title,\n  line,\n  action,\n  children,\n}: SettingsSectionProps) {\n  const headingId = useId();\n\n  return (\n    <section aria-labelledby={headingId} className='flex flex-col gap-3'>\n      <div className='flex flex-wrap items-end justify-between gap-x-3 gap-y-2'>\n        <div className='flex min-w-0 flex-col gap-0.5'>\n          <h2 id={headingId} className='text-sm font-medium'>\n            {title}\n          </h2>\n          {line && (\n            <p className='text-muted-foreground text-xs text-pretty'>{line}</p>\n          )}\n        </div>\n        {action}\n      </div>\n      {children}\n    </section>\n  );\n}\n\ntype ErrorLineProps = {\n  /** The field points to it with `aria-describedby` while it shows. */\n  id: string;\n  error: string | null;\n  /** A new refusal of the same entry nudges the line again. */\n  attempts: number;\n};\n\n/** A refusal grows in under its field, nudges 4px, and folds away once the person types again. */\nexport function ErrorLine({ id, error, attempts }: ErrorLineProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = rowPresenceOf(shouldReduceMotion);\n  const nudge = nudgeOf(shouldReduceMotion);\n\n  return (\n    <AnimatePresence initial={false}>\n      {error && (\n        <motion.div key='error' className='overflow-hidden' {...presence}>\n          <motion.p\n            key={attempts}\n            id={id}\n            className='text-destructive-ink pt-0.5 text-xs text-pretty'\n            transition={SPRING}\n            {...nudge}\n          >\n            {error}\n          </motion.p>\n        </motion.div>\n      )}\n    </AnimatePresence>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/settings-frame.tsx"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\n\nimport {\n  CARD,\n  CARD_BRAND_NAME,\n  METERS,\n  PLANS,\n  RENEWAL_DATE,\n  type Card,\n  type CardBrand,\n  type MeterId,\n  type PlanId,\n} from './data';\n\nexport type DownloadStatus = 'idle' | 'busy' | 'done';\n\nexport type CardField = 'number' | 'expiry' | 'cvc';\n\nexport type CardDraft = Record<CardField, string>;\n\nexport type CardErrors = Partial<Record<CardField, string>>;\n\nexport type BillingState = {\n  planId: PlanId;\n  /** The plan ends with its term instead of renewing. */\n  isCancelling: boolean;\n  isConfirmingCancel: boolean;\n  isChoosingPlan: boolean;\n  pickedPlanId: PlanId;\n  isSwitchingPlan: boolean;\n  used: Record<MeterId, number>;\n  card: Card;\n  isEditingCard: boolean;\n  cardDraft: CardDraft;\n  cardErrors: CardErrors;\n  /** Counts the refused saves, so a message that comes back nudges again. */\n  cardAttempts: number;\n  isSavingCard: boolean;\n  downloads: Record<string, DownloadStatus>;\n  spoken: string;\n};\n\nexport type BillingAction =\n  | { type: 'chooserToggled' }\n  | { type: 'planPicked'; planId: PlanId }\n  | { type: 'switchPressed' }\n  | { type: 'planSwitched' }\n  | { type: 'cancelAsked' }\n  | { type: 'cancelKept' }\n  | { type: 'cancelConfirmed' }\n  | { type: 'resumed' }\n  | { type: 'usageAdded'; id: MeterId; amount: number }\n  | { type: 'cardEditToggled' }\n  | { type: 'cardTyped'; field: CardField; value: string }\n  | { type: 'cardSavePressed' }\n  | { type: 'cardSaved' }\n  | { type: 'downloadStarted'; id: string }\n  | { type: 'downloadDone'; id: string }\n  | { type: 'downloadFaded'; id: string };\n\ntype Step = SessionStep<BillingState, BillingAction>;\n\n/** How long a change of plan takes to apply. */\nexport const SWITCH_MS = 900;\n\n/** How long a new card takes to be checked. */\nexport const SAVE_CARD_MS = 900;\n\n/** How long an invoice takes to be prepared. */\nexport const DOWNLOAD_MS = 700;\n\n/** How long Downloaded stays before the button is ready again. */\nexport const DOWNLOADED_MS = 1600;\n\nconst EMPTY_DRAFT: CardDraft = { number: '', expiry: '', cvc: '' };\n\nconst FIELD_ORDER: CardField[] = ['number', 'expiry', 'cvc'];\n\n/** The month the sample lives in: a card that ends before it has expired. */\nconst THIS_YEAR = 26;\n\nconst THIS_MONTH = 11;\n\nfunction usedOf() {\n  const used: Record<MeterId, number> = { seats: 0, storage: 0, runs: 0 };\n  for (const meter of METERS) {\n    used[meter.id] = meter.used;\n  }\n  return used;\n}\n\nexport const INITIAL: BillingState = {\n  planId: 'team',\n  isCancelling: false,\n  isConfirmingCancel: false,\n  isChoosingPlan: false,\n  pickedPlanId: 'team',\n  isSwitchingPlan: false,\n  used: usedOf(),\n  card: CARD,\n  isEditingCard: false,\n  cardDraft: EMPTY_DRAFT,\n  cardErrors: {},\n  cardAttempts: 0,\n  isSavingCard: false,\n  downloads: {},\n  spoken: '',\n};\n\nexport function planOf(planId: PlanId) {\n  const plan = PLANS.find((candidate) => candidate.id === planId);\n  return plan ?? PLANS[0];\n}\n\n/** A plan with fewer seats than the people already in the workspace cannot be picked. */\nexport function isTooSmall(planId: PlanId, seatsUsed: number) {\n  return planOf(planId).seats < seatsUsed;\n}\n\nfunction chooserToggled(state: BillingState): BillingState {\n  if (state.isSwitchingPlan) {\n    return state;\n  }\n  return {\n    ...state,\n    isChoosingPlan: !state.isChoosingPlan,\n    pickedPlanId: state.planId,\n    isConfirmingCancel: false,\n  };\n}\n\nfunction planPicked(state: BillingState, planId: PlanId): BillingState {\n  const isBlocked = isTooSmall(planId, state.used.seats);\n  if (isBlocked) {\n    return state;\n  }\n  return { ...state, pickedPlanId: planId };\n}\n\nfunction switchPressed(state: BillingState): BillingState {\n  const isSamePlan = state.pickedPlanId === state.planId;\n  if (isSamePlan) {\n    return state;\n  }\n  const name = planOf(state.pickedPlanId).name;\n  return {\n    ...state,\n    isSwitchingPlan: true,\n    spoken: `Switching to the ${name} plan`,\n  };\n}\n\n/** Picking a plan also answers a pending cancellation: the new plan renews. */\nfunction planSwitched(state: BillingState): BillingState {\n  if (!state.isSwitchingPlan) {\n    return state;\n  }\n  const name = planOf(state.pickedPlanId).name;\n  return {\n    ...state,\n    planId: state.pickedPlanId,\n    isSwitchingPlan: false,\n    isChoosingPlan: false,\n    isCancelling: false,\n    spoken: `You are on the ${name} plan from now on`,\n  };\n}\n\nfunction cancelAsked(state: BillingState): BillingState {\n  const isPaid = planOf(state.planId).price > 0;\n  const canCancel = isPaid && !state.isCancelling;\n  if (!canCancel) {\n    return state;\n  }\n  return {\n    ...state,\n    isConfirmingCancel: true,\n    isChoosingPlan: false,\n    spoken: 'Confirm below to cancel the subscription',\n  };\n}\n\nfunction cancelConfirmed(state: BillingState): BillingState {\n  if (!state.isConfirmingCancel) {\n    return state;\n  }\n  const name = planOf(state.planId).name;\n  return {\n    ...state,\n    isCancelling: true,\n    isConfirmingCancel: false,\n    spoken: `${name} plan cancelled. It stays active until ${RENEWAL_DATE}`,\n  };\n}\n\nfunction resumed(state: BillingState): BillingState {\n  if (!state.isCancelling) {\n    return state;\n  }\n  const name = planOf(state.planId).name;\n  return {\n    ...state,\n    isCancelling: false,\n    spoken: `${name} plan resumed. It renews on ${RENEWAL_DATE}`,\n  };\n}\n\nfunction usageAdded(\n  state: BillingState,\n  id: MeterId,\n  amount: number\n): BillingState {\n  const used = { ...state.used, [id]: state.used[id] + amount };\n  return { ...state, used };\n}\n\nfunction cardEditToggled(state: BillingState): BillingState {\n  if (state.isSavingCard) {\n    return state;\n  }\n  return {\n    ...state,\n    isEditingCard: !state.isEditingCard,\n    cardDraft: EMPTY_DRAFT,\n    cardErrors: {},\n  };\n}\n\nfunction cardTyped(\n  state: BillingState,\n  field: CardField,\n  value: string\n): BillingState {\n  const cardDraft = { ...state.cardDraft, [field]: value };\n  const cardErrors = { ...state.cardErrors };\n  delete cardErrors[field];\n  return { ...state, cardDraft, cardErrors };\n}\n\nexport function digitsOf(value: string) {\n  return value.replace(/\\D/g, '');\n}\n\nfunction isAmexStart(digits: string) {\n  const isThirtyFour = digits.startsWith('34');\n  const isThirtySeven = digits.startsWith('37');\n  return isThirtyFour || isThirtySeven;\n}\n\nexport function brandOf(digits: string): CardBrand | null {\n  if (digits.startsWith('4')) {\n    return 'visa';\n  }\n  if (/^(5[1-5]|2[2-7])/.test(digits)) {\n    return 'mastercard';\n  }\n  if (isAmexStart(digits)) {\n    return 'americanexpress';\n  }\n  return null;\n}\n\nfunction numberLengthOf(brand: CardBrand) {\n  if (brand === 'americanexpress') {\n    return 15;\n  }\n  return 16;\n}\n\nfunction codeLengthOf(brand: CardBrand | null) {\n  if (brand === 'americanexpress') {\n    return 4;\n  }\n  return 3;\n}\n\nfunction numberProblemOf(digits: string, brand: CardBrand | null) {\n  if (digits === '') {\n    return 'Enter the card number';\n  }\n  if (!brand) {\n    return 'Use a Visa, Mastercard or American Express card';\n  }\n  const length = numberLengthOf(brand);\n  if (digits.length !== length) {\n    return `Enter the ${length} digits on the front of the card`;\n  }\n  return null;\n}\n\nfunction hasEnded(month: number, year: number) {\n  const isPastYear = year < THIS_YEAR;\n  const isPastMonth = year === THIS_YEAR && month < THIS_MONTH;\n  return isPastYear || isPastMonth;\n}\n\nfunction expiryProblemOf(expiry: string) {\n  const trimmed = expiry.trim();\n  const match = trimmed.match(/^(\\d{2})\\s*\\/\\s*(\\d{2})$/);\n  if (!match) {\n    return 'Enter the date as MM/YY';\n  }\n  const month = Number(match[1]);\n  const year = Number(match[2]);\n  const isMonth = month >= 1 && month <= 12;\n  if (!isMonth) {\n    return 'Enter a month from 01 to 12';\n  }\n  if (hasEnded(month, year)) {\n    return 'This card has expired';\n  }\n  return null;\n}\n\nfunction codeProblemOf(code: string, brand: CardBrand | null) {\n  const length = codeLengthOf(brand);\n  const digits = digitsOf(code);\n  const trimmed = code.trim();\n  const isOnlyDigits = trimmed === digits;\n  const isRightLength = digits.length === length;\n  const isComplete = isRightLength && isOnlyDigits;\n  if (isComplete) {\n    return null;\n  }\n  return `Enter the ${length} digits of the security code`;\n}\n\nexport function cardErrorsOf(draft: CardDraft): CardErrors {\n  const digits = digitsOf(draft.number);\n  const brand = brandOf(digits);\n  const errors: CardErrors = {};\n  const numberProblem = numberProblemOf(digits, brand);\n  const expiryProblem = expiryProblemOf(draft.expiry);\n  const codeProblem = codeProblemOf(draft.cvc, brand);\n  if (numberProblem) {\n    errors.number = numberProblem;\n  }\n  if (expiryProblem) {\n    errors.expiry = expiryProblem;\n  }\n  if (codeProblem) {\n    errors.cvc = codeProblem;\n  }\n  return errors;\n}\n\nexport function firstCardErrorOf(errors: CardErrors) {\n  const field = FIELD_ORDER.find((candidate) => Boolean(errors[candidate]));\n  return field ?? null;\n}\n\nfunction cardSavePressed(state: BillingState): BillingState {\n  const isOpen = state.isEditingCard && !state.isSavingCard;\n  if (!isOpen) {\n    return state;\n  }\n  const errors = cardErrorsOf(state.cardDraft);\n  const first = firstCardErrorOf(errors);\n  if (first) {\n    return {\n      ...state,\n      cardErrors: errors,\n      cardAttempts: state.cardAttempts + 1,\n      spoken: errors[first] ?? '',\n    };\n  }\n  return { ...state, isSavingCard: true, spoken: 'Checking the card' };\n}\n\n/** 08 / 28 is kept as 08/28. */\nfunction compactExpiryOf(expiry: string) {\n  const trimmed = expiry.trim();\n  return trimmed.replace(/\\s/g, '');\n}\n\nfunction cardSaved(state: BillingState): BillingState {\n  if (!state.isSavingCard) {\n    return state;\n  }\n  const digits = digitsOf(state.cardDraft.number);\n  const brand = brandOf(digits) ?? 'visa';\n  const card: Card = {\n    ...state.card,\n    brand,\n    last4: digits.slice(-4),\n    expiry: compactExpiryOf(state.cardDraft.expiry),\n  };\n  return {\n    ...state,\n    card,\n    isSavingCard: false,\n    isEditingCard: false,\n    cardDraft: EMPTY_DRAFT,\n    spoken: `${CARD_BRAND_NAME[brand]} ending in ${card.last4} saved. It pays the next invoice`,\n  };\n}\n\nfunction withDownload(\n  state: BillingState,\n  id: string,\n  from: DownloadStatus,\n  to: DownloadStatus\n): BillingState {\n  const current = state.downloads[id] ?? 'idle';\n  if (current !== from) {\n    return state;\n  }\n  const downloads = { ...state.downloads, [id]: to };\n  return { ...state, downloads };\n}\n\nexport function reducer(\n  state: BillingState,\n  action: BillingAction\n): BillingState {\n  switch (action.type) {\n    case 'chooserToggled':\n      return chooserToggled(state);\n    case 'planPicked':\n      return planPicked(state, action.planId);\n    case 'switchPressed':\n      return switchPressed(state);\n    case 'planSwitched':\n      return planSwitched(state);\n    case 'cancelAsked':\n      return cancelAsked(state);\n    case 'cancelKept':\n      return { ...state, isConfirmingCancel: false, spoken: '' };\n    case 'cancelConfirmed':\n      return cancelConfirmed(state);\n    case 'resumed':\n      return resumed(state);\n    case 'usageAdded':\n      return usageAdded(state, action.id, action.amount);\n    case 'cardEditToggled':\n      return cardEditToggled(state);\n    case 'cardTyped':\n      return cardTyped(state, action.field, action.value);\n    case 'cardSavePressed':\n      return cardSavePressed(state);\n    case 'cardSaved':\n      return cardSaved(state);\n    case 'downloadStarted':\n      return withDownload(state, action.id, 'idle', 'busy');\n    case 'downloadDone':\n      return withDownload(state, action.id, 'busy', 'done');\n    case 'downloadFaded':\n      return withDownload(state, action.id, 'done', 'idle');\n  }\n}\n\nconst SHOWN_INVOICE = 'TW-2611';\n\n/**\n * Automations keep running while the page is open, an invoice is downloaded, then the\n * subscription is cancelled in place. That is where the page rests under reduced motion: the plan\n * reads Cancels on 30 Nov, with Resume beside it, and the runs meter has turned amber.\n */\nconst BEFORE_RESUME: Step[] = [\n  { after: 1400, action: { type: 'usageAdded', id: 'runs', amount: 90 } },\n  {\n    after: 1100,\n    by: 'demo',\n    press: `download-${SHOWN_INVOICE}`,\n    action: { type: 'downloadStarted', id: SHOWN_INVOICE },\n  },\n  {\n    after: DOWNLOAD_MS,\n    action: { type: 'downloadDone', id: SHOWN_INVOICE },\n  },\n  {\n    after: DOWNLOADED_MS,\n    action: { type: 'downloadFaded', id: SHOWN_INVOICE },\n  },\n  { after: 500, action: { type: 'usageAdded', id: 'runs', amount: 120 } },\n  { after: 1400, by: 'demo', press: 'cancel', action: { type: 'cancelAsked' } },\n  {\n    after: 2000,\n    by: 'demo',\n    press: 'confirm-cancel',\n    action: { type: 'cancelConfirmed' },\n  },\n];\n\nexport const SCRIPT: Step[] = [\n  ...BEFORE_RESUME,\n  { after: 2600, by: 'demo', press: 'resume', action: { type: 'resumed' } },\n];\n\nfunction endOf(steps: Step[]) {\n  let state = INITIAL;\n  for (const step of steps) {\n    state = reducer(state, step.action);\n  }\n  return state;\n}\n\nexport const RESTING: BillingState = { ...endOf(BEFORE_RESUME), spoken: '' };\n\nexport const LOOP_AFTER_MS = 3000;\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/settings/settings-07/data.ts",
      "content": "export type PlanId = 'starter' | 'team' | 'business';\n\nexport type Plan = {\n  id: PlanId;\n  name: string;\n  /** Dollars a month. */\n  price: number;\n  seats: number;\n  line: string;\n};\n\nexport type MeterId = 'seats' | 'storage' | 'runs';\n\nexport type Meter = {\n  id: MeterId;\n  label: string;\n  used: number;\n  /** What the plan includes, so the meters follow a change of plan. */\n  included: Record<PlanId, number>;\n  unit: string;\n  decimals: number;\n};\n\nexport type CardBrand = 'visa' | 'mastercard' | 'americanexpress';\n\nexport type Card = {\n  brand: CardBrand;\n  last4: string;\n  expiry: string;\n  holder: string;\n};\n\nexport type InvoiceStatus = 'paid' | 'refunded';\n\nexport type Invoice = {\n  id: string;\n  date: string;\n  /** Dollars. */\n  amount: number;\n  status: InvoiceStatus;\n  lines: string[];\n};\n\nexport const WORKSPACE_NAME = 'Tidewell Studio';\n\nexport const RENEWAL_DATE = '30 Nov 2026';\n\nexport const RENEWAL_DAY = '30 Nov';\n\nexport const USAGE_RESETS_ON = '1 Dec';\n\n/** From this share of what the plan includes, a meter turns to the warning pair. */\nexport const NEAR_LIMIT_SHARE = 0.8;\n\nexport const PLANS: Plan[] = [\n  {\n    id: 'starter',\n    name: 'Starter',\n    price: 0,\n    seats: 5,\n    line: 'For a small team trying things out',\n  },\n  {\n    id: 'team',\n    name: 'Team',\n    price: 96,\n    seats: 20,\n    line: 'Reports, automations and the desktop app',\n  },\n  {\n    id: 'business',\n    name: 'Business',\n    price: 240,\n    seats: 60,\n    line: 'Everything in Team, with sign-in rules and audit logs',\n  },\n];\n\nexport const METERS: Meter[] = [\n  {\n    id: 'seats',\n    label: 'Seats',\n    used: 18,\n    included: { starter: 5, team: 20, business: 60 },\n    unit: 'seats',\n    decimals: 0,\n  },\n  {\n    id: 'storage',\n    label: 'File storage',\n    used: 61.4,\n    included: { starter: 10, team: 100, business: 500 },\n    unit: 'GB',\n    decimals: 1,\n  },\n  {\n    id: 'runs',\n    label: 'Automation runs',\n    used: 7860,\n    included: { starter: 500, team: 10000, business: 50000 },\n    unit: 'runs',\n    decimals: 0,\n  },\n];\n\nexport const CARD: Card = {\n  brand: 'visa',\n  last4: '1881',\n  expiry: '08/28',\n  holder: 'Dana Whitfield',\n};\n\nexport const CARD_BRAND_NAME: Record<CardBrand, string> = {\n  visa: 'Visa',\n  mastercard: 'Mastercard',\n  americanexpress: 'American Express',\n};\n\nexport const INVOICES: Invoice[] = [\n  {\n    id: 'TW-2611',\n    date: '1 Nov 2026',\n    amount: 96,\n    status: 'paid',\n    lines: ['Team plan, November 2026: $96.00'],\n  },\n  {\n    id: 'TW-2610',\n    date: '1 Oct 2026',\n    amount: 96,\n    status: 'paid',\n    lines: ['Team plan, October 2026: $96.00'],\n  },\n  {\n    id: 'TW-2609',\n    date: '1 Sep 2026',\n    amount: 105.6,\n    status: 'paid',\n    lines: [\n      'Team plan, September 2026: $96.00',\n      'Automation runs over the plan: $9.60',\n    ],\n  },\n  {\n    id: 'TW-2608',\n    date: '1 Aug 2026',\n    amount: 96,\n    status: 'refunded',\n    lines: ['Team plan, August 2026: $96.00', 'Refunded on 4 Aug 2026'],\n  },\n];\n",
      "type": "registry:component",
      "target": "components/blocks/settings-07/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "settings"
  ],
  "type": "registry:block"
}