{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "quota",
  "type": "registry:ui",
  "title": "Quota",
  "description": "A context-window / credits meter card: rolling digit headline over one segmented bar that splits usage by category, each slice springing to its width independently. Past the warn threshold the leading edge breathes an amber glow; past critical the headline turns amber and a note fades in. Optional cost line and reset countdown.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/ai/quota/quota.tsx",
      "type": "registry:ui",
      "target": "components/crucible/quota.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, motion, useInView } from \"motion/react\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\n\n/** One category of consumed usage, drawn as a slice of the segmented bar. */\nexport interface QuotaSegment {\n  /** Category name shown in the legend, e.g. \"System\", \"Tools\", \"Messages\". Also the React key — keep unique. */\n  label: string;\n  /** Units consumed by this category (same unit as `limit`). Negative values clamp to 0. */\n  value: number;\n  /** Slice + swatch color. Defaults to a tint of `accentColor` that fades with each successive segment. */\n  color?: string;\n}\n\n/** Number style for the headline and legend values. */\nexport type QuotaFormat = \"compact\" | \"full\" | ((value: number) => string);\n\nexport interface QuotaProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  /**\n   * Consumed usage by category, left to right. Used = the sum of all values;\n   * the remainder up to `limit` is shown as an automatic \"Free\" entry.\n   * Pass new arrays to update — each slice springs to its new width independently.\n   */\n  segments: QuotaSegment[];\n  /** Capacity the meter reads full at (e.g. a 200k-token context window). */\n  limit: number;\n  /** Unit noun appended to the headline and aria text. @default \"tokens\" */\n  unit?: string;\n  /** \"compact\" → 84.2k, \"full\" → 84,200, or a custom formatter. @default \"compact\" */\n  format?: QuotaFormat;\n  /** Fraction of `limit` (0–1) past which the bar's leading edge pulses with an accent→amber glow. @default 0.8 */\n  warnAt?: number;\n  /** Fraction of `limit` (0–1) past which the headline turns amber and `note` fades in. @default 0.95 */\n  critAt?: number;\n  /** Optional cost line. A number renders as \"$0.42 this session\"; a string renders verbatim. */\n  cost?: number | string;\n  /** When the quota resets (Date or epoch ms). Renders \"Resets in 2h 14m\", computed after mount (hydration-safe). */\n  resetAt?: Date | number;\n  /** Text of the critical-threshold note. @default \"Compacting soon\" */\n  note?: string;\n  /** Card heading. @default \"Context window\" */\n  label?: string;\n  /** Legend label for the unused remainder; pass `null` to hide that entry. @default \"Free\" */\n  freeLabel?: string | null;\n  /** The single accent hue: focus/edge glow and the default segment tints. @default \"#a78bfa\" (ion violet) */\n  accentColor?: string;\n  /** Warning/critical hue used by the glow tail, headline and note. @default \"#fbbf24\" */\n  warnColor?: string;\n}\n\nconst DEFAULT_ACCENT = \"#a78bfa\";\nconst DEFAULT_WARN = \"#fbbf24\";\nconst HEADLINE_COLOR = \"#fafafa\";\n/** Successive segment tints: % of accent mixed into a graphite base. */\nconst TINT_STEPS = [100, 68, 44, 28, 18];\nconst SPRING = { type: \"spring\", stiffness: 140, damping: 22, mass: 0.9 } as const;\nconst REDUCED_FADE = { duration: 0.15, ease: \"easeOut\" } as const;\nconst INSTANT = { duration: 0 } as const;\n\nfunction trimZero(s: string): string {\n  return s.endsWith(\".0\") ? s.slice(0, -2) : s;\n}\n\nfunction formatCompact(n: number): string {\n  const a = Math.abs(n);\n  if (a < 1000) return String(Math.round(n));\n  if (a < 1_000_000) return `${trimZero((n / 1000).toFixed(1))}k`;\n  if (a < 1_000_000_000) return `${trimZero((n / 1_000_000).toFixed(1))}M`;\n  return `${trimZero((n / 1_000_000_000).toFixed(1))}B`;\n}\n\n/** Fixed locale so server and client render identical strings. */\nconst FULL = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 0 });\n\nfunction resolveFormat(format: QuotaFormat): (n: number) => string {\n  if (typeof format === \"function\") return format;\n  return format === \"full\" ? (n) => FULL.format(n) : formatCompact;\n}\n\nfunction formatRemaining(ms: number): string {\n  if (ms <= 0) return \"Resetting now\";\n  const totalMin = Math.floor(ms / 60_000);\n  if (totalMin < 1) return \"Resets in <1m\";\n  const d = Math.floor(totalMin / 1440);\n  const h = Math.floor((totalMin % 1440) / 60);\n  const m = totalMin % 60;\n  if (d > 0) return `Resets in ${d}d ${h}h`;\n  if (h > 0) return `Resets in ${h}h ${m}m`;\n  return `Resets in ${m}m`;\n}\n\nfunction tint(accent: string, index: number): string {\n  const pct = TINT_STEPS[Math.min(index, TINT_STEPS.length - 1)];\n  return pct === 100 ? accent : `color-mix(in oklab, ${accent} ${pct}%, #3f3f46)`;\n}\n\n/**\n * Rolling text: each digit is a 0–9 drum that slides to its value; other\n * characters are static. The real string sits underneath as transparent,\n * selectable text so copy/paste and layout use the true value.\n */\nfunction RollText({ text, reducedMotion }: { text: string; reducedMotion: boolean }) {\n  const chars = text.split(\"\");\n  return (\n    <span className=\"relative inline-block whitespace-nowrap tabular-nums leading-none\">\n      <span className=\"text-transparent\">{text}</span>\n      <span aria-hidden className=\"pointer-events-none absolute inset-0 flex select-none\">\n        {chars.map((ch, i) => {\n          // Key from the right so a growing number keeps its ones/tens drums stable.\n          const key = chars.length - i;\n          const digit = ch >= \"0\" && ch <= \"9\" ? Number(ch) : -1;\n          if (digit < 0) {\n            return (\n              <span key={`c${key}`} className=\"inline-block\">\n                {ch}\n              </span>\n            );\n          }\n          return (\n            <span key={`d${key}`} className=\"relative inline-block h-[1em] w-[1ch] overflow-hidden\">\n              <motion.span\n                className=\"absolute left-0 top-0 flex flex-col\"\n                initial={false}\n                animate={{ y: `${-digit * 10}%` }}\n                transition={reducedMotion ? INSTANT : { type: \"spring\", stiffness: 380, damping: 36 }}\n              >\n                {Array.from({ length: 10 }, (_, n) => (\n                  <span key={n} className=\"block h-[1em] leading-none\">\n                    {n}\n                  </span>\n                ))}\n              </motion.span>\n            </span>\n          );\n        })}\n      </span>\n    </span>\n  );\n}\n\n/**\n * Quota — a context-window / credits meter card. The headline (used / limit)\n * rolls on digit drums, and a single segmented bar splits usage by category,\n * each slice with its own tint of one accent. On scroll-in the slices grow\n * from the left on a staggered spring; on updates each slice springs to its\n * new width independently. Past `warnAt` the bar's leading edge breathes an\n * accent→amber glow; past `critAt` the headline turns amber and a note fades\n * in. Optional cost line and a hydration-safe reset countdown. The bar is a\n * real `role=\"meter\"` with full aria value text; reduced motion renders the\n * settled state with short opacity fades and no glow pulse.\n */\nexport function Quota({\n  segments,\n  limit,\n  unit = \"tokens\",\n  format = \"compact\",\n  warnAt = 0.8,\n  critAt = 0.95,\n  cost,\n  resetAt,\n  note = \"Compacting soon\",\n  label = \"Context window\",\n  freeLabel = \"Free\",\n  accentColor = DEFAULT_ACCENT,\n  warnColor = DEFAULT_WARN,\n  className,\n  style,\n  ...props\n}: QuotaProps) {\n  const reducedMotion = useReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const fmt = React.useMemo(() => resolveFormat(format), [format]);\n\n  const safeLimit = limit > 0 ? limit : 1;\n  const parts = segments.map((s, i) => ({\n    label: s.label,\n    value: Math.max(0, s.value),\n    color: s.color ?? tint(accentColor, i),\n  }));\n  const used = parts.reduce((sum, p) => sum + p.value, 0);\n  const ratio = Math.min(used / safeLimit, 1);\n  const free = Math.max(safeLimit - used, 0);\n  const isWarn = ratio >= warnAt;\n  const isCrit = ratio >= critAt;\n\n  // ---- Reveal: grow from the left once in view, staggered, then go live. ----\n  const inView = useInView(rootRef, { once: true, amount: 0.3 });\n  const visible = useInView(rootRef, { amount: 0 });\n  const armed = inView || reducedMotion;\n  const [staggerDone, setStaggerDone] = React.useState(false);\n  React.useEffect(() => {\n    if (!armed || staggerDone) return;\n    const id = window.setTimeout(() => setStaggerDone(true), 900);\n    return () => window.clearTimeout(id);\n  }, [armed, staggerDone]);\n\n  // ---- Reset countdown: only computed after mount so SSR markup is stable. ----\n  const resetMs = resetAt === undefined ? undefined : typeof resetAt === \"number\" ? resetAt : resetAt.getTime();\n  const [now, setNow] = React.useState<number | null>(null);\n  React.useEffect(() => {\n    if (resetMs === undefined) return;\n    setNow(Date.now());\n    const id = window.setInterval(() => setNow(Date.now()), 15_000);\n    return () => window.clearInterval(id);\n  }, [resetMs]);\n\n  const shownUsed = armed ? used : 0;\n  const shownPct = armed ? Math.round(ratio * 100) : 0;\n  const widthTransition = (i: number) =>\n    reducedMotion ? INSTANT : { ...SPRING, delay: staggerDone ? 0 : i * 0.08 };\n  const edgeDelay = staggerDone ? 0 : Math.max(parts.length - 1, 0) * 0.08;\n\n  const valueText = `${Math.round(ratio * 100)} percent used, ${FULL.format(used)} of ${FULL.format(safeLimit)} ${unit}`;\n  const costText = cost === undefined ? null : typeof cost === \"number\" ? `$${cost.toFixed(2)} this session` : cost;\n  const resetText = resetMs !== undefined && now !== null ? formatRemaining(resetMs - now) : null;\n  const pulseOn = isWarn && armed && !reducedMotion && visible;\n  const fade = reducedMotion ? REDUCED_FADE : { duration: 0.35, ease: \"easeOut\" as const };\n\n  return (\n    <div\n      ref={rootRef}\n      data-crucible=\"quota\"\n      className={cn(\n        \"relative w-full max-w-sm overflow-hidden rounded-2xl border border-white/10 bg-neutral-950/90 p-5 text-neutral-200 shadow-[0_1px_0_0_rgba(255,255,255,0.04)_inset,0_24px_48px_-24px_rgba(0,0,0,0.8)]\",\n        className\n      )}\n      style={style}\n      {...props}\n    >\n      {/* Faint accent wash in the top corner — the card's only ornament. */}\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute -right-16 -top-16 h-40 w-40 rounded-full opacity-[0.12] blur-3xl\"\n        style={{ background: accentColor }}\n      />\n\n      <div className=\"relative flex min-h-5 items-center justify-between gap-3\">\n        <span className=\"text-[11px] font-medium uppercase tracking-[0.16em] text-neutral-400\">{label}</span>\n        <AnimatePresence initial={false}>\n          {isCrit && armed && note ? (\n            <motion.span\n              key=\"note\"\n              role=\"status\"\n              className=\"inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium\"\n              style={{\n                color: warnColor,\n                borderColor: `color-mix(in oklab, ${warnColor} 30%, transparent)`,\n                background: `color-mix(in oklab, ${warnColor} 8%, transparent)`,\n              }}\n              initial={reducedMotion ? { opacity: 0 } : { opacity: 0, y: -4 }}\n              animate={{ opacity: 1, y: 0 }}\n              exit={reducedMotion ? { opacity: 0 } : { opacity: 0, y: -4 }}\n              transition={fade}\n            >\n              <span aria-hidden className=\"h-1.5 w-1.5 rounded-full\" style={{ background: warnColor }} />\n              {note}\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </div>\n\n      <div className=\"relative mt-3 flex items-end justify-between gap-4\">\n        <p className=\"flex items-baseline gap-1.5\">\n          <motion.span\n            className=\"text-3xl font-semibold tracking-tight\"\n            initial={false}\n            animate={{ color: isCrit && armed ? warnColor : HEADLINE_COLOR }}\n            transition={reducedMotion ? REDUCED_FADE : { duration: 0.4 }}\n          >\n            <RollText text={fmt(shownUsed)} reducedMotion={reducedMotion} />\n          </motion.span>\n          <span className=\"text-sm text-neutral-500\">\n            / {fmt(safeLimit)} {unit}\n          </span>\n        </p>\n        <span className=\"pb-0.5 text-sm font-medium text-neutral-300\">\n          <RollText text={`${shownPct}%`} reducedMotion={reducedMotion} />\n        </span>\n      </div>\n\n      {/* Segmented bar */}\n      <div className=\"relative mt-4\">\n        <div\n          role=\"meter\"\n          aria-label={`${label} usage`}\n          aria-valuemin={0}\n          aria-valuemax={safeLimit}\n          aria-valuenow={Math.min(used, safeLimit)}\n          aria-valuetext={valueText}\n          className=\"relative flex h-2.5 w-full overflow-hidden rounded-full bg-white/[0.06]\"\n        >\n          {parts.map((p, i) => {\n            const pct = armed ? (Math.min(p.value, safeLimit) / safeLimit) * 100 : 0;\n            return (\n              <motion.div\n                key={p.label}\n                className=\"relative h-full shrink-0\"\n                initial={false}\n                animate={{ width: `${pct}%` }}\n                transition={widthTransition(i)}\n              >\n                {/* 2px seam lives inside the slice so widths always sum to the true ratio. */}\n                <span\n                  aria-hidden\n                  className=\"absolute inset-y-0 left-0 right-[2px]\"\n                  style={{ background: p.color }}\n                />\n              </motion.div>\n            );\n          })}\n        </div>\n\n        {/* Leading-edge glow: accent→warn tail that breathes past warnAt. */}\n        <motion.div\n          aria-hidden\n          className=\"pointer-events-none absolute top-1/2 h-5 w-14 -translate-y-1/2\"\n          style={{ marginLeft: \"-3.5rem\" }}\n          initial={false}\n          animate={{ left: `${armed ? ratio * 100 : 0}%` }}\n          transition={reducedMotion ? INSTANT : { ...SPRING, delay: edgeDelay }}\n        >\n          <motion.div\n            className=\"h-full w-full rounded-full blur-md\"\n            style={{ background: `linear-gradient(90deg, transparent, ${accentColor} 55%, ${warnColor})` }}\n            initial={false}\n            animate={\n              pulseOn\n                ? { opacity: [0.35, 0.9, 0.35] }\n                : { opacity: isWarn && armed ? (reducedMotion ? 0.5 : 0.35) : 0 }\n            }\n            transition={\n              pulseOn ? { duration: 1.8, repeat: Infinity, ease: \"easeInOut\" } : reducedMotion ? REDUCED_FADE : { duration: 0.4 }\n            }\n          />\n        </motion.div>\n      </div>\n\n      {/* Legend */}\n      <ul className=\"relative mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-xs\">\n        {parts.map((p) => (\n          <li key={p.label} className=\"flex items-center gap-2\">\n            <span aria-hidden className=\"h-2 w-2 shrink-0 rounded-[3px]\" style={{ background: p.color }} />\n            <span className=\"truncate text-neutral-400\">{p.label}</span>\n            <span className=\"ml-auto tabular-nums text-neutral-200\">{fmt(p.value)}</span>\n          </li>\n        ))}\n        {freeLabel !== null ? (\n          <li className=\"flex items-center gap-2\">\n            <span aria-hidden className=\"h-2 w-2 shrink-0 rounded-[3px] border border-white/15 bg-white/[0.06]\" />\n            <span className=\"truncate text-neutral-500\">{freeLabel}</span>\n            <span className=\"ml-auto tabular-nums text-neutral-400\">{fmt(free)}</span>\n          </li>\n        ) : null}\n      </ul>\n\n      {costText !== null || resetMs !== undefined ? (\n        <div className=\"relative mt-4 flex min-h-4 items-center justify-between gap-3 border-t border-white/[0.08] pt-3 text-[11px] text-neutral-500\">\n          <span className=\"tabular-nums\">{costText}</span>\n          <motion.span\n            className=\"tabular-nums\"\n            initial={false}\n            animate={{ opacity: resetText ? 1 : 0 }}\n            transition={reducedMotion ? REDUCED_FADE : { duration: 0.3 }}\n          >\n            {resetText ?? \" \"}\n          </motion.span>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ]
}