{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sparkline-stat",
  "title": "Sparkline Stat",
  "description": "A KPI card with a sparkline: the number counts to its new value, a change badge says how far it moved, range tabs swap the series with a redraw, and scrubbing the chart turns the headline into that point's value.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/sparkline-stat/sparkline-stat.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, animate, 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 SparklinePeriod {\n  label: string;\n  data: number[];\n  /** One label per point, shown while scrubbing (e.g. dates). */\n  labels?: string[];\n}\n\nexport interface SparklineStatProps {\n  label?: string;\n  /** Points for a single series. Use periods for switchable ranges instead. */\n  data?: number[];\n  labels?: string[];\n  /** Switchable ranges (7D / 30D / 90D ...), shown as tabs. */\n  periods?: SparklinePeriod[];\n  defaultPeriod?: number;\n  format?: \"number\" | \"currency\" | \"percent\" | \"compact\";\n  currency?: string;\n  decimals?: number;\n  locale?: string;\n  /** Text after the change, e.g. \"vs last week\". Defaults to the period. */\n  deltaLabel?: string;\n  /** For metrics where going down is good (churn, latency): flips which direction is highlighted. */\n  invertDelta?: boolean;\n  variant?: \"line\" | \"area\";\n  chartHeight?: number;\n  /** Scrub the chart to read any point; the headline follows. */\n  interactive?: boolean;\n  theme?: \"dark\" | \"light\";\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.55)\", faint: \"rgba(245,244,241,0.16)\", panel: \"#0E0E0E\", border: \"rgba(255,255,255,0.1)\", borderHover: \"rgba(255,255,255,0.2)\", tab: \"rgba(255,255,255,0.08)\", line: \"#F5F4F1\", down: \"#FF7A6B\", badge: \"rgba(255,255,255,0.07)\", downBadge: \"rgba(255,122,107,0.12)\", focus: \"rgba(245,244,241,0.85)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.55)\", faint: \"rgba(10,10,10,0.14)\", panel: \"#FFFFFF\", border: \"rgba(10,10,10,0.12)\", borderHover: \"rgba(10,10,10,0.24)\", tab: \"rgba(10,10,10,0.06)\", line: \"#0A0A0A\", down: \"#E5484D\", badge: \"rgba(10,10,10,0.05)\", downBadge: \"rgba(229,72,77,0.1)\", focus: \"rgba(10,10,10,0.85)\" },\n};\n\n// Deterministic demo series (no Math.random, so server and client agree).\nfunction series(n: number, start: number, drift: number, wobble: number, seed: number) {\n  return Array.from({ length: n }, (_, i) => Math.round(start + drift * i + Math.sin(i * 0.9 + seed) * wobble + Math.sin(i * 0.37 + seed * 2) * wobble * 0.6));\n}\n\nconst DEFAULT_PERIODS: SparklinePeriod[] = [\n  { label: \"7D\", data: series(7, 11800, 190, 260, 1), labels: [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"] },\n  { label: \"30D\", data: series(30, 9800, 95, 520, 2), labels: Array.from({ length: 30 }, (_, i) => `Day ${i + 1}`) },\n  { label: \"90D\", data: series(45, 14200, -40, 900, 3), labels: Array.from({ length: 45 }, (_, i) => `Week ${Math.floor(i / 3.5) + 1}`) },\n];\n\n// A smooth line through the points that never overshoots between them (monotone cubic).\nfunction smoothPath(pts: [number, number][]) {\n  if (pts.length < 2) return \"\";\n  const n = pts.length;\n  const dx = pts.slice(1).map((p, i) => p[0] - pts[i][0]);\n  const m = pts.slice(1).map((p, i) => (p[1] - pts[i][1]) / dx[i]);\n  const t = pts.map((_, i) => (i === 0 ? m[0] : i === n - 1 ? m[n - 2] : m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2));\n  for (let i = 0; i < n - 1; i++) {\n    if (m[i] === 0) {\n      t[i] = 0;\n      t[i + 1] = 0;\n      continue;\n    }\n    const a = t[i] / m[i];\n    const b = t[i + 1] / m[i];\n    const h = a * a + b * b;\n    if (h > 9) {\n      const k = 3 / Math.sqrt(h);\n      t[i] = k * a * m[i];\n      t[i + 1] = k * b * m[i];\n    }\n  }\n  let d = `M${pts[0][0]},${pts[0][1]}`;\n  for (let i = 0; i < n - 1; i++) {\n    const h = dx[i] / 3;\n    d += ` C${pts[i][0] + h},${pts[i][1] + t[i] * h} ${pts[i + 1][0] - h},${pts[i + 1][1] - t[i + 1] * h} ${pts[i + 1][0]},${pts[i + 1][1]}`;\n  }\n  return d;\n}\n\nexport function SparklineStat({\n  label = \"Revenue\",\n  data,\n  labels,\n  periods,\n  defaultPeriod = 0,\n  format = \"currency\",\n  currency = \"USD\",\n  decimals,\n  locale = \"en-US\",\n  deltaLabel,\n  invertDelta = false,\n  variant = \"area\",\n  chartHeight = 72,\n  interactive = true,\n  theme = \"dark\",\n  className,\n}: SparklineStatProps) {\n  const p = PALETTES[theme];\n  const uid = React.useId().replace(/:/g, \"\");\n  const reduce = Boolean(useReducedMotion());\n  const ranges: SparklinePeriod[] = periods ?? (data ? [{ label: deltaLabel ?? \"\", data, labels }] : DEFAULT_PERIODS);\n  const [period, setPeriod] = React.useState(Math.min(defaultPeriod, ranges.length - 1));\n  const [hover, setHover] = React.useState<number | null>(null);\n  const chartRef = React.useRef<HTMLDivElement>(null);\n  const [w, setW] = React.useState(0);\n\n  const range = ranges[period];\n  const pts = range.data;\n  const lastIdx = pts.length - 1;\n  const shownIdx = hover ?? lastIdx;\n  const target = pts[shownIdx] ?? 0;\n\n  const fmt = React.useMemo(() => {\n    const opts: Intl.NumberFormatOptions =\n      format === \"currency\" ? { style: \"currency\", currency, maximumFractionDigits: decimals ?? 0 } : format === \"percent\" ? { style: \"percent\", maximumFractionDigits: decimals ?? 1 } : format === \"compact\" ? { notation: \"compact\", maximumFractionDigits: decimals ?? 1 } : { maximumFractionDigits: decimals ?? 0 };\n    return new Intl.NumberFormat(locale, opts);\n  }, [format, currency, decimals, locale]);\n\n  // The headline counts to a new value when the range changes, but follows the pointer instantly.\n  const [display, setDisplay] = React.useState(target);\n  const displayRef = React.useRef(target);\n  React.useEffect(() => {\n    if (hover !== null || reduce) return;\n    const controls = animate(displayRef.current, target, {\n      duration: 0.7,\n      ease: [0.22, 1, 0.36, 1],\n      onUpdate: (v) => {\n        displayRef.current = v;\n        setDisplay(v);\n      },\n    });\n    return () => controls.stop();\n  }, [target, hover, reduce]);\n  const shown = hover !== null || reduce ? target : display;\n\n  React.useLayoutEffect(() => {\n    const el = chartRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => setW(el.clientWidth));\n    ro.observe(el);\n    setW(el.clientWidth);\n    return () => ro.disconnect();\n  }, []);\n\n  const first = pts[0] ?? 0;\n  const change = first ? (target - first) / Math.abs(first) : 0;\n  const good = invertDelta ? change <= 0 : change >= 0;\n  const min = Math.min(...pts);\n  const max = Math.max(...pts);\n  const pad = 4;\n  const H = chartHeight;\n  const xy = (i: number): [number, number] => [pts.length > 1 ? (i / lastIdx) * w : w / 2, pad + (max === min ? (H - pad * 2) / 2 : (1 - (pts[i] - min) / (max - min)) * (H - pad * 2))];\n  const coords = w ? pts.map((_, i) => xy(i)) : [];\n  const line = smoothPath(coords);\n  const area = line ? `${line} L${w},${H} L0,${H} Z` : \"\";\n  const dot = coords[shownIdx];\n\n  const scrub = (clientX: number) => {\n    const el = chartRef.current;\n    if (!el || !interactive || pts.length < 2) return;\n    const r = el.getBoundingClientRect();\n    const i = Math.round(Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * lastIdx);\n    displayRef.current = pts[i];\n    setHover(i);\n  };\n\n  const onKey = (e: React.KeyboardEvent) => {\n    if (!interactive) return;\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault();\n      const i = Math.max(0, Math.min(lastIdx, (hover ?? lastIdx) + (e.key === \"ArrowLeft\" ? -1 : 1)));\n      displayRef.current = pts[i];\n      setHover(i);\n    } else if (e.key === \"Escape\") setHover(null);\n  };\n\n  const pointLabel = range.labels?.[shownIdx];\n\n  return (\n    <div className={cn(\"flex w-full flex-col\", className)} style={{ gap: 14, padding: 18, borderRadius: 18, background: p.panel, border: `1px solid ${p.border}`, fontFamily: \"Inter, sans-serif\", color: p.text }}>\n      <div className=\"flex items-start justify-between\" style={{ gap: 12 }}>\n        <div className=\"flex min-w-0 flex-col\" style={{ gap: 6 }}>\n          <span className=\"truncate text-[13px] font-medium\" style={{ color: p.muted }}>\n            {label}\n            {hover !== null && pointLabel ? ` · ${pointLabel}` : null}\n          </span>\n          <span className=\"text-[30px] leading-none font-semibold tracking-[-0.03em] tabular-nums\" aria-live=\"polite\">\n            {fmt.format(format === \"percent\" ? shown : Math.round(shown * 10 ** (decimals ?? 0)) / 10 ** (decimals ?? 0))}\n          </span>\n          <span className=\"flex items-center text-[12.5px]\" style={{ gap: 6 }}>\n            <span className=\"inline-flex items-center rounded-full font-semibold tabular-nums\" style={{ gap: 3, padding: \"2px 7px\", background: good ? p.badge : p.downBadge, color: good ? p.text : p.down }}>\n              <svg width=\"9\" height=\"9\" viewBox=\"0 0 10 10\" aria-hidden=\"true\" style={{ transform: change < 0 ? \"rotate(180deg)\" : undefined }}>\n                <path d=\"M5 1.5 9 8H1Z\" fill=\"currentColor\" />\n              </svg>\n              {Math.abs(change * 100).toFixed(1)}%\n            </span>\n            <span style={{ color: p.muted }}>{deltaLabel ?? (hover !== null ? \"since start\" : `over ${range.label}`)}</span>\n          </span>\n        </div>\n        {ranges.length > 1 && (\n          <div className=\"flex shrink-0 rounded-lg\" style={{ padding: 2, gap: 2, background: p.tab }} role=\"tablist\" aria-label=\"Range\">\n            {ranges.map((r, i) => (\n              <button\n                key={r.label}\n                type=\"button\"\n                role=\"tab\"\n                aria-selected={i === period}\n                onClick={() => {\n                  setHover(null);\n                  setPeriod(i);\n                }}\n                className=\"relative cursor-pointer rounded-md border-none bg-transparent text-[12px] font-semibold outline-none focus-visible:ring-2\"\n                style={{ height: 26, padding: \"0 9px\", color: i === period ? p.text : p.muted, [\"--tw-ring-color\" as string]: p.focus }}\n              >\n                {i === period && <motion.span layoutId={`${uid}-tab`} className=\"absolute inset-0 rounded-md\" style={{ background: p.panel, boxShadow: `0 0 0 1px ${p.border}` }} transition={{ type: \"spring\", stiffness: 500, damping: 38 }} />}\n                <span className=\"relative\">{r.label}</span>\n              </button>\n            ))}\n          </div>\n        )}\n      </div>\n\n      <div\n        ref={chartRef}\n        className=\"relative w-full outline-none focus-visible:ring-2\"\n        style={{ height: H, touchAction: \"pan-y\", cursor: interactive ? \"crosshair\" : undefined, borderRadius: 8, [\"--tw-ring-color\" as string]: p.focus }}\n        tabIndex={interactive ? 0 : -1}\n        role={interactive ? \"slider\" : \"img\"}\n        aria-label={`${label} over ${range.label || \"the period\"}`}\n        aria-valuemin={interactive ? 0 : undefined}\n        aria-valuemax={interactive ? lastIdx : undefined}\n        aria-valuenow={interactive ? shownIdx : undefined}\n        aria-valuetext={interactive ? `${pointLabel ?? `Point ${shownIdx + 1}`}: ${fmt.format(target)}` : undefined}\n        onPointerMove={(e) => scrub(e.clientX)}\n        onPointerDown={(e) => scrub(e.clientX)}\n        onPointerLeave={() => setHover(null)}\n        onKeyDown={onKey}\n        onBlur={() => setHover(null)}\n      >\n        {w > 0 && (\n          <svg width={w} height={H} viewBox={`0 0 ${w} ${H}`} className=\"block overflow-visible\" aria-hidden=\"true\">\n            <defs>\n              <linearGradient id={`${uid}-fill`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor={p.line} stopOpacity={0.22} />\n                <stop offset=\"100%\" stopColor={p.line} stopOpacity={0} />\n              </linearGradient>\n            </defs>\n            {variant === \"area\" && <motion.path key={`a-${period}`} d={area} fill={`url(#${uid}-fill)`} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: reduce ? 0 : 0.6, delay: reduce ? 0 : 0.25 }} />}\n            <motion.path key={`l-${period}`} d={line} fill=\"none\" stroke={p.line} strokeWidth={1.75} strokeLinecap=\"round\" strokeLinejoin=\"round\" initial={{ pathLength: reduce ? 1 : 0 }} animate={{ pathLength: 1 }} transition={{ duration: reduce ? 0 : 0.9, ease: [0.22, 1, 0.36, 1] }} />\n            {hover !== null && dot && <line x1={dot[0]} x2={dot[0]} y1={0} y2={H} stroke={p.faint} strokeWidth={1} strokeDasharray=\"3 3\" />}\n            {dot && (\n              <g transform={`translate(${dot[0]} ${dot[1]})`}>\n                {hover === null && !reduce && <motion.circle r={4} fill={p.line} initial={{ scale: 1, opacity: 0.5 }} animate={{ scale: 2.6, opacity: 0 }} transition={{ duration: 1.6, repeat: Infinity, ease: \"easeOut\", delay: 0.9 }} />}\n                <circle r={3.5} fill={p.panel} stroke={p.line} strokeWidth={2} />\n              </g>\n            )}\n          </svg>\n        )}\n      </div>\n    </div>\n  );\n}\n\nexport default SparklineStat;\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}