{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "usage-chart",
  "title": "Usage Chart Block",
  "description": "A usage panel for metered plans: daily stacked bars by source with a daily budget line, a cumulative view with the plan limit and a dashed projection to cycle end, used / projected / overage figures, a status line that names the day you will pass your limit, hover breakdowns and legend toggles.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/usage-chart/usage-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface UsageSeries {\n  id: string;\n  label: string;\n  color: string;\n  /** One value per day so far this cycle. */\n  values: number[];\n}\n\nexport interface UsageMetric {\n  id: string;\n  label: string;\n  unit: string;\n  /** Plan limit for the whole cycle. */\n  limit: number;\n  /** Price per unit above the limit. */\n  overagePrice?: number;\n  series: UsageSeries[];\n}\n\nexport interface UsageChartProps {\n  title?: string;\n  metrics?: UsageMetric[];\n  /** First day of the billing cycle, YYYY-MM-DD. */\n  cycleStart?: string;\n  /** Days in the cycle. */\n  cycleDays?: number;\n  currency?: string;\n  theme?: \"dark\" | \"light\";\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { bg: \"#0A0A0A\", text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.62)\", faint: \"rgba(245,244,241,0.36)\", card: \"#121212\", border: \"rgba(255,255,255,0.09)\", chip: \"rgba(255,255,255,0.06)\", grid: \"rgba(255,255,255,0.06)\", ghost: \"rgba(255,255,255,0.05)\", on: \"#F5F4F1\", onText: \"#0A0A0A\", amber: \"#FBBF24\", red: \"#F87171\", green: \"#4ADE80\", tip: \"#1C1C1C\", ring: \"rgba(245,244,241,0.6)\" },\n  light: { bg: \"#FAFAF8\", text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.62)\", faint: \"rgba(10,10,10,0.4)\", card: \"#FFFFFF\", border: \"rgba(10,10,10,0.09)\", chip: \"rgba(10,10,10,0.05)\", grid: \"rgba(10,10,10,0.06)\", ghost: \"rgba(10,10,10,0.04)\", on: \"#0A0A0A\", onText: \"#FAFAF8\", amber: \"#B45309\", red: \"#DC2626\", green: \"#15803D\", tip: \"#FFFFFF\", ring: \"rgba(10,10,10,0.5)\" },\n};\n\nfunction rng(seed: number) {\n  let s = seed;\n  return () => {\n    s = (s * 16807) % 2147483647;\n    return (s - 1) / 2147483646;\n  };\n}\nconst gen = (seed: number, n: number, base: number, growth: number, weekendDip = 0.35) => {\n  const r = rng(seed);\n  return Array.from({ length: n }, (_, i) => {\n    const weekday = (i + 6) % 7;\n    const dip = weekday >= 5 ? 1 - weekendDip : 1;\n    return Math.round(base * (1 + growth * (i / n)) * dip * (0.85 + r() * 0.3));\n  });\n};\nconst DAYS_SO_FAR = 22;\nconst DEFAULT_METRICS: UsageMetric[] = [\n  {\n    id: \"requests\",\n    label: \"API requests\",\n    unit: \"requests\",\n    limit: 5_000_000,\n    overagePrice: 0.00002,\n    series: [\n      { id: \"search\", label: \"/search\", color: \"#FB923C\", values: gen(11, DAYS_SO_FAR, 92_000, 0.5) },\n      { id: \"events\", label: \"/events\", color: \"#60A5FA\", values: gen(23, DAYS_SO_FAR, 64_000, 0.35) },\n      { id: \"users\", label: \"/users\", color: \"#A78BFA\", values: gen(37, DAYS_SO_FAR, 30_000, 0.2) },\n      { id: \"other\", label: \"Other\", color: \"#6B7280\", values: gen(41, DAYS_SO_FAR, 14_000, 0.1) },\n    ],\n  },\n  {\n    id: \"compute\",\n    label: \"Compute\",\n    unit: \"hours\",\n    limit: 1_200,\n    overagePrice: 0.12,\n    series: [\n      { id: \"workers\", label: \"Workers\", color: \"#2DD4BF\", values: gen(5, DAYS_SO_FAR, 24, 0.1, 0.1) },\n      { id: \"jobs\", label: \"Scheduled jobs\", color: \"#F472B6\", values: gen(9, DAYS_SO_FAR, 12, 0.05, 0.05) },\n      { id: \"preview\", label: \"Preview builds\", color: \"#FBBF24\", values: gen(15, DAYS_SO_FAR, 8, 0.2, 0.6) },\n    ],\n  },\n  {\n    id: \"bandwidth\",\n    label: \"Bandwidth\",\n    unit: \"GB\",\n    limit: 1_000,\n    overagePrice: 0.08,\n    series: [\n      { id: \"cdn\", label: \"CDN\", color: \"#4ADE80\", values: gen(3, DAYS_SO_FAR, 22, 0.15) },\n      { id: \"api\", label: \"API responses\", color: \"#93C5FD\", values: gen(7, DAYS_SO_FAR, 6, 0.1) },\n    ],\n  },\n];\n\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nfunction dayLabel(start: string, offset: number) {\n  const [y, m, d] = start.split(\"-\").map(Number);\n  const dt = new Date(Date.UTC(y, m - 1, d) + offset * 864e5);\n  return `${dt.getUTCDate()} ${MONTHS[dt.getUTCMonth()]}`;\n}\nfunction compact(n: number) {\n  if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 2)}M`;\n  if (n >= 1e3) return `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k`;\n  return n.toLocaleString(\"en-US\", { maximumFractionDigits: 1 });\n}\n\nexport function UsageChart({ title = \"Usage\", metrics = DEFAULT_METRICS, cycleStart = \"2026-10-10\", cycleDays = 31, currency = \"$\", theme = \"dark\", className }: UsageChartProps) {\n  const p = PALETTES[theme];\n  const reduce = !!useReducedMotion();\n  const uid = React.useId();\n  const [metricId, setMetricId] = React.useState(metrics[0].id);\n  const [hidden, setHidden] = React.useState<string[]>([]);\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [view, setView] = React.useState<\"daily\" | \"cumulative\">(\"daily\");\n\n  const metric = metrics.find((m) => m.id === metricId) ?? metrics[0];\n  const visible = metric.series.filter((s) => !hidden.includes(s.id));\n  const days = metric.series[0]?.values.length ?? 0;\n  const totals = Array.from({ length: days }, (_, i) => metric.series.reduce((s, x) => s + x.values[i], 0));\n  const used = totals.reduce((a, b) => a + b, 0);\n  const recent = totals.slice(-7);\n  const avg = recent.reduce((a, b) => a + b, 0) / Math.max(1, recent.length);\n  const projected = used + avg * (cycleDays - days);\n  const overDay = (() => {\n    let run = used;\n    if (run >= metric.limit) return days - 1;\n    for (let d = days; d < cycleDays; d++) {\n      run += avg;\n      if (run >= metric.limit) return d;\n    }\n    return null;\n  })();\n  const overage = Math.max(0, projected - metric.limit) * (metric.overagePrice ?? 0);\n  const pctUsed = (used / metric.limit) * 100;\n  const status = overDay !== null ? \"over\" : projected > metric.limit * 0.85 ? \"close\" : \"ok\";\n\n  // Chart geometry\n  const W = 720;\n  const H = 220;\n  const slot = W / cycleDays;\n  const barW = Math.max(4, slot * 0.62);\n  const cumulative = view === \"cumulative\";\n  const cum: number[] = [];\n  totals.forEach((t, i) => cum.push((cum[i - 1] ?? 0) + t));\n  const visTotals = Array.from({ length: days }, (_, i) => visible.reduce((s, x) => s + x.values[i], 0));\n  const maxDaily = Math.max(...totals, avg) * 1.15;\n  const maxY = cumulative ? Math.max(metric.limit, projected) * 1.08 : maxDaily;\n  const y = (v: number) => H - (v / maxY) * H;\n  const limitY = y(metric.limit);\n  const projLine = cumulative ? `M${(days - 0.5) * slot},${y(used)} L${(cycleDays - 0.5) * slot},${y(projected)}` : \"\";\n  const cumLine = cum.map((v, i) => `${i ? \"L\" : \"M\"}${(i + 0.5) * slot},${y(v)}`).join(\" \");\n\n  const move = (e: React.PointerEvent<SVGSVGElement>) => {\n    const r = e.currentTarget.getBoundingClientRect();\n    const i = Math.floor(((e.clientX - r.left) / r.width) * cycleDays);\n    setHover(i >= 0 && i < days ? i : null);\n  };\n\n  const ring = { [\"--tw-ring-color\" as string]: p.ring, [\"--tw-ring-offset-color\" as string]: p.card } as React.CSSProperties;\n  const focus = \"outline-none focus-visible:ring-2 focus-visible:ring-offset-2\";\n  const statusColor = status === \"over\" ? p.red : status === \"close\" ? p.amber : p.green;\n\n  return (\n    <section className={cn(\"@container w-full\", className)} style={{ background: p.bg, color: p.text }}>\n      <div className=\"mx-auto max-w-5xl px-4 py-10 @[640px]:px-6 @[640px]:py-14\">\n        <div className=\"rounded-2xl border p-5 @[640px]:p-6\" style={{ background: p.card, borderColor: p.border }}>\n          <div className=\"flex flex-wrap items-start justify-between gap-4\">\n            <div>\n              <h2 className=\"m-0 text-[18px] font-semibold tracking-[-0.01em]\">{title}</h2>\n              <p className=\"m-0 mt-0.5 text-[12.5px]\" style={{ color: p.faint }}>\n                Cycle {dayLabel(cycleStart, 0)} – {dayLabel(cycleStart, cycleDays - 1)} · day {days} of {cycleDays}\n              </p>\n            </div>\n            <div className=\"flex flex-wrap gap-2\">\n              <div role=\"radiogroup\" aria-label=\"Metric\" className=\"flex rounded-lg border p-0.5\" style={{ borderColor: p.border }}>\n                {metrics.map((m) => (\n                  <button\n                    key={m.id}\n                    type=\"button\"\n                    role=\"radio\"\n                    aria-checked={metricId === m.id}\n                    onClick={() => {\n                      setMetricId(m.id);\n                      setHidden([]);\n                    }}\n                    className={cn(\"relative h-7 cursor-pointer rounded-md border-0 bg-transparent px-2.5 text-[12.5px]\", focus)}\n                    style={{ color: metricId === m.id ? p.text : p.faint, ...ring }}\n                  >\n                    {metricId === m.id && <motion.span layoutId={`${uid}-metric`} className=\"absolute inset-0 rounded-md\" style={{ background: p.chip }} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 38 }} />}\n                    <span className=\"relative\">{m.label}</span>\n                  </button>\n                ))}\n              </div>\n              <div role=\"radiogroup\" aria-label=\"Chart view\" className=\"flex rounded-lg border p-0.5\" style={{ borderColor: p.border }}>\n                {([\"daily\", \"cumulative\"] as const).map((v) => (\n                  <button key={v} type=\"button\" role=\"radio\" aria-checked={view === v} onClick={() => setView(v)} className={cn(\"relative h-7 cursor-pointer rounded-md border-0 bg-transparent px-2.5 text-[12.5px] capitalize\", focus)} style={{ color: view === v ? p.text : p.faint, ...ring }}>\n                    {view === v && <motion.span layoutId={`${uid}-view`} className=\"absolute inset-0 rounded-md\" style={{ background: p.chip }} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 38 }} />}\n                    <span className=\"relative\">{v}</span>\n                  </button>\n                ))}\n              </div>\n            </div>\n          </div>\n\n          {/* Summary */}\n          <div className=\"mt-5 grid gap-4 @[640px]:grid-cols-[1.3fr_1fr_1fr]\">\n            <div>\n              <p className=\"m-0 text-[12px]\" style={{ color: p.faint }}>\n                Used this cycle\n              </p>\n              <p className=\"m-0 mt-1 text-[26px] leading-none font-semibold tracking-[-0.02em] tabular-nums\">\n                {compact(used)} <span className=\"text-[13px] font-normal tracking-normal\" style={{ color: p.faint }}>/ {compact(metric.limit)} {metric.unit}</span>\n              </p>\n              <div className=\"mt-2.5 h-1.5 overflow-hidden rounded-full\" style={{ background: p.chip }} role=\"progressbar\" aria-label={`${metric.label} used`} aria-valuenow={Math.round(pctUsed)} aria-valuemin={0} aria-valuemax={100}>\n                <motion.div className=\"h-full rounded-full\" style={{ background: statusColor }} initial={false} animate={{ width: `${Math.min(100, pctUsed)}%` }} transition={{ duration: reduce ? 0 : 0.6 }} />\n              </div>\n            </div>\n            <div>\n              <p className=\"m-0 text-[12px]\" style={{ color: p.faint }}>\n                Projected by cycle end\n              </p>\n              <p className=\"m-0 mt-1 text-[18px] font-semibold tabular-nums\" style={{ color: status === \"ok\" ? p.text : statusColor }}>\n                {compact(projected)} <span className=\"text-[12px] font-normal\" style={{ color: p.faint }}>{Math.round((projected / metric.limit) * 100)}%</span>\n              </p>\n            </div>\n            <div>\n              <p className=\"m-0 text-[12px]\" style={{ color: p.faint }}>\n                Estimated overage\n              </p>\n              <p className=\"m-0 mt-1 text-[18px] font-semibold tabular-nums\" style={{ color: overage ? statusColor : p.text }}>\n                {currency}\n                {overage.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}\n              </p>\n            </div>\n          </div>\n\n          <AnimatePresence initial={false} mode=\"wait\">\n            <motion.p key={`${metric.id}-${status}`} initial={reduce ? false : { opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={reduce ? undefined : { opacity: 0 }} className=\"m-0 mt-4 flex items-center gap-2 rounded-lg px-3 py-2 text-[12.5px]\" style={{ background: p.chip, color: status === \"ok\" ? p.muted : statusColor }} role=\"status\">\n              <span className=\"h-1.5 w-1.5 shrink-0 rounded-full\" style={{ background: statusColor }} aria-hidden=\"true\" />\n              {status === \"over\" ? `At the current pace you will pass your limit on ${dayLabel(cycleStart, overDay ?? 0)}.` : status === \"close\" ? \"You are on track to use most of your limit this cycle.\" : \"Comfortably within your plan limit.\"}\n            </motion.p>\n          </AnimatePresence>\n\n          {/* Chart */}\n          <div className=\"relative mt-5\">\n            <svg viewBox={`0 0 ${W} ${H}`} className=\"block h-[220px] w-full overflow-visible\" preserveAspectRatio=\"none\" onPointerMove={move} onPointerLeave={() => setHover(null)} role=\"img\" aria-label={`${metric.label}: ${compact(used)} of ${compact(metric.limit)} ${metric.unit} used, projected ${compact(projected)}.`}>\n              {[0.25, 0.5, 0.75, 1].map((g) => (\n                <line key={g} x1=\"0\" x2={W} y1={H * (1 - g)} y2={H * (1 - g)} stroke={p.grid} vectorEffect=\"non-scaling-stroke\" />\n              ))}\n              {/* future slots */}\n              {Array.from({ length: cycleDays - days }, (_, k) => (\n                <rect key={k} x={(days + k) * slot + (slot - barW) / 2} y={cumulative ? H : y(avg)} width={barW} height={cumulative ? 0 : H - y(avg)} rx=\"2\" fill={p.ghost} />\n              ))}\n              {!cumulative &&\n                Array.from({ length: days }, (_, i) => {\n                  let acc = 0;\n                  return (\n                    <g key={i} opacity={hover === null || hover === i ? 1 : 0.45}>\n                      {visible.map((s) => {\n                        const v = s.values[i];\n                        const yTop = y(acc + v);\n                        const h = H - y(v);\n                        acc += v;\n                        return <motion.rect key={s.id} x={i * slot + (slot - barW) / 2} width={barW} rx=\"1.5\" fill={s.color} initial={false} animate={{ y: yTop, height: Math.max(0, h) }} transition={{ duration: reduce ? 0 : 0.45, delay: reduce ? 0 : i * 0.008 }} />;\n                      })}\n                    </g>\n                  );\n                })}\n              {cumulative && (\n                <>\n                  <path d={`${cumLine} L${(days - 0.5) * slot},${H} L${0.5 * slot},${H} Z`} fill={p.chip} />\n                  <motion.path key={metric.id} d={cumLine} fill=\"none\" stroke={p.text} strokeWidth=\"2\" vectorEffect=\"non-scaling-stroke\" initial={reduce ? false : { opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: reduce ? 0 : 0.4 }} />\n                  <path d={projLine} fill=\"none\" stroke={statusColor} strokeWidth=\"2\" strokeDasharray=\"5 5\" vectorEffect=\"non-scaling-stroke\" />\n                </>\n              )}\n              {(cumulative || metric.limit / cycleDays < maxY) && (\n                <g>\n                  <line x1=\"0\" x2={W} y1={cumulative ? limitY : y(metric.limit / cycleDays)} y2={cumulative ? limitY : y(metric.limit / cycleDays)} stroke={p.red} strokeWidth=\"1.25\" strokeDasharray=\"3 4\" vectorEffect=\"non-scaling-stroke\" />\n                </g>\n              )}\n              {hover !== null && <rect x={hover * slot} y=\"0\" width={slot} height={H} fill={p.ghost} />}\n            </svg>\n            <span className=\"pointer-events-none absolute right-0 -translate-y-full pb-0.5 text-[11px]\" style={{ top: `${((cumulative ? limitY : y(metric.limit / cycleDays)) / H) * 100}%`, color: p.red }}>\n              {cumulative ? `Limit ${compact(metric.limit)}` : `Daily budget ${compact(metric.limit / cycleDays)}`}\n            </span>\n            <AnimatePresence>\n              {hover !== null && (\n                <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.1 }} className=\"pointer-events-none absolute top-0 z-10 w-48 rounded-xl border p-3 text-[12px] shadow-xl\" style={{ left: `clamp(0px, calc(${((hover + 0.5) / cycleDays) * 100}% - 96px), calc(100% - 192px))`, background: p.tip, borderColor: p.border }}>\n                  <p className=\"m-0 mb-1.5 font-medium\">{dayLabel(cycleStart, hover)}</p>\n                  {cumulative ? (\n                    <p className=\"m-0 flex justify-between tabular-nums\">\n                      <span style={{ color: p.muted }}>Total so far</span>\n                      {compact(cum[hover])}\n                    </p>\n                  ) : (\n                    <>\n                      {visible.map((s) => (\n                        <p key={s.id} className=\"m-0 flex items-center justify-between gap-2 py-0.5 tabular-nums\">\n                          <span className=\"flex items-center gap-1.5\" style={{ color: p.muted }}>\n                            <span className=\"h-2 w-2 rounded-sm\" style={{ background: s.color }} />\n                            {s.label}\n                          </span>\n                          {compact(s.values[hover])}\n                        </p>\n                      ))}\n                      <p className=\"m-0 mt-1 flex justify-between border-t pt-1.5 font-medium tabular-nums\" style={{ borderColor: p.border }}>\n                        <span>Total</span>\n                        {compact(visTotals[hover])}\n                      </p>\n                    </>\n                  )}\n                </motion.div>\n              )}\n            </AnimatePresence>\n            <div className=\"mt-2 flex justify-between text-[11px] tabular-nums\" style={{ color: p.faint }}>\n              <span>{dayLabel(cycleStart, 0)}</span>\n              <span>Today · {dayLabel(cycleStart, days - 1)}</span>\n              <span>{dayLabel(cycleStart, cycleDays - 1)}</span>\n            </div>\n          </div>\n\n          {/* Legend */}\n          <ul className=\"m-0 mt-4 flex list-none flex-wrap gap-2 p-0\" aria-label=\"Series\">\n            {metric.series.map((s) => {\n              const on = !hidden.includes(s.id);\n              const share = (s.values.reduce((a, b) => a + b, 0) / used) * 100;\n              return (\n                <li key={s.id}>\n                  <button type=\"button\" aria-pressed={on} disabled={cumulative || (on && visible.length === 1)} onClick={() => setHidden((h) => (on ? [...h, s.id] : h.filter((x) => x !== s.id)))} className={cn(\"flex h-8 cursor-pointer items-center gap-2 rounded-full border px-3 text-[12.5px] disabled:cursor-default\", focus)} style={{ borderColor: p.border, background: on ? p.chip : \"transparent\", color: on ? p.text : p.faint, ...ring }}>\n                    <span className=\"h-2.5 w-2.5 rounded-sm\" style={{ background: on ? s.color : \"transparent\", border: `1.5px solid ${s.color}` }} aria-hidden=\"true\" />\n                    {s.label}\n                    <span className=\"tabular-nums\" style={{ color: p.faint }}>\n                      {share.toFixed(0)}%\n                    </span>\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n        </div>\n      </div>\n    </section>\n  );\n}\n\nexport default UsageChart;\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}