{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stat-card",
  "title": "Stat Card",
  "description": "A dashboard metric card with an animated count-up value, an auto-derived good/bad trend badge, an optional icon and a drawn-in sparkline.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/stat-card/stat-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, animate, useMotionValue, useMotionValueEvent } 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 type StatCardSize = \"sm\" | \"md\" | \"lg\";\nexport type StatCardTrend = \"up\" | \"down\" | \"neutral\";\n\nexport interface StatCardProps {\n  label: string;\n  value: number;\n  /** Used to auto-compute a percentage delta when `delta` isn't given directly. */\n  previousValue?: number;\n  /** Percentage change; overrides one derived from previousValue. */\n  delta?: number;\n  deltaLabel?: string;\n  /** Overrides the up/down/neutral arrow direction the sign of delta would otherwise imply. */\n  trend?: StatCardTrend;\n  /** Whether an \"up\" trend is the good outcome (revenue) or the bad one (error rate, latency, disk usage). */\n  goodDirection?: \"up\" | \"down\";\n  icon?: React.ReactNode;\n  prefix?: string;\n  suffix?: string;\n  formatValue?: (value: number) => string;\n  /** A handful of recent values, oldest first, rendered as a small drawn-in line. */\n  sparkline?: number[];\n  /** \"sharp\" connects points with straight segments; \"smooth\" runs a curve through them. */\n  sparklineStyle?: \"sharp\" | \"smooth\";\n  animateValue?: boolean;\n  size?: StatCardSize;\n  theme?: \"dark\" | \"light\";\n  accentColor?: string;\n  width?: number | string;\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { bg: \"#0E0E0E\", border: \"rgba(255,255,255,0.09)\", text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.55)\", faint: \"rgba(245,244,241,0.3)\", iconBg: \"rgba(255,255,255,0.06)\", good: \"#87FFE3\", bad: \"#FF7A6B\", neutralBadge: \"rgba(245,244,241,0.08)\", tooltipBg: \"#1A1A1C\", tooltipBorder: \"rgba(255,255,255,0.12)\", crosshair: \"rgba(245,244,241,0.35)\" },\n  light: { bg: \"#FFFFFF\", border: \"rgba(10,10,10,0.1)\", text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.55)\", faint: \"rgba(10,10,10,0.3)\", iconBg: \"rgba(10,10,10,0.05)\", good: \"#0F9F7F\", bad: \"#E5484D\", neutralBadge: \"rgba(10,10,10,0.06)\", tooltipBg: \"#FFFFFF\", tooltipBorder: \"rgba(10,10,10,0.1)\", crosshair: \"rgba(10,10,10,0.3)\" },\n};\n\nconst SIZES: Record<StatCardSize, { pad: number; radius: number; label: number; value: number; icon: number; gap: number; sparkH: number }> = {\n  sm: { pad: 16, radius: 14, label: 12, value: 22, icon: 30, gap: 8, sparkH: 28 },\n  md: { pad: 20, radius: 16, label: 12.5, value: 28, icon: 36, gap: 10, sparkH: 36 },\n  lg: { pad: 24, radius: 18, label: 13.5, value: 34, icon: 42, gap: 12, sparkH: 44 },\n};\n\ntype Size = (typeof SIZES)[\"md\"];\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nfunction TrendArrow({ trend, size }: { trend: StatCardTrend; size: number }) {\n  if (trend === \"neutral\") {\n    return (\n      <svg width={size} height={size} viewBox=\"0 0 12 12\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" aria-hidden=\"true\">\n        <path d=\"M2.5 6h7\" />\n      </svg>\n    );\n  }\n  return (\n    <svg width={size} height={size} viewBox=\"0 0 12 12\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" style={{ transform: trend === \"down\" ? \"rotate(180deg)\" : undefined }}>\n      <path d=\"M6 9.5V2.3M2.8 5.3L6 2L9.2 5.3\" />\n    </svg>\n  );\n}\n\ntype Point = readonly [number, number];\n\n/** Monotone cubic Hermite interpolation (Fritsch-Carlson), converted to\n * cubic Beziers. A plain Catmull-Rom curve can overshoot past a point's\n * own value on a sharp direction change — e.g. the last point in a chart\n * that's flat and then spikes up would get a curve that bulges *above*\n * that final point, pushing it outside the sparkline's own drawable area\n * and into a clipped-looking sliver above the card. This construction is\n * mathematically guaranteed not to overshoot between any two consecutive\n * points, which is why charting libraries (D3, Recharts) use it for\n * exactly this \"smooth line through real data\" case. */\nfunction smoothPath(points: Point[]): string {\n  const n = points.length;\n  if (n < 3) return points.map(([x, y], i) => `${i === 0 ? \"M\" : \"L\"}${x.toFixed(2)},${y.toFixed(2)}`).join(\" \");\n\n  const dx: number[] = [];\n  const secant: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    dx[i] = points[i + 1][0] - points[i][0];\n    secant[i] = dx[i] === 0 ? 0 : (points[i + 1][1] - points[i][1]) / dx[i];\n  }\n\n  const tangent: number[] = new Array(n);\n  tangent[0] = secant[0];\n  tangent[n - 1] = secant[n - 2];\n  for (let i = 1; i < n - 1; i++) {\n    tangent[i] = secant[i - 1] === 0 || secant[i] === 0 || secant[i - 1] < 0 !== secant[i] < 0 ? 0 : (secant[i - 1] + secant[i]) / 2;\n  }\n  for (let i = 0; i < n - 1; i++) {\n    if (secant[i] === 0) {\n      tangent[i] = 0;\n      tangent[i + 1] = 0;\n      continue;\n    }\n    const a = tangent[i] / secant[i];\n    const b = tangent[i + 1] / secant[i];\n    const s = a * a + b * b;\n    if (s > 9) {\n      const tau = 3 / Math.sqrt(s);\n      tangent[i] = tau * a * secant[i];\n      tangent[i + 1] = tau * b * secant[i];\n    }\n  }\n\n  let d = `M${points[0][0].toFixed(2)},${points[0][1].toFixed(2)}`;\n  for (let i = 0; i < n - 1; i++) {\n    const [x0, y0] = points[i];\n    const [x1, y1] = points[i + 1];\n    const h = dx[i];\n    const c1x = x0 + h / 3;\n    const c1y = y0 + (tangent[i] * h) / 3;\n    const c2x = x1 - h / 3;\n    const c2y = y1 - (tangent[i + 1] * h) / 3;\n    d += ` C${c1x.toFixed(2)},${c1y.toFixed(2)} ${c2x.toFixed(2)},${c2y.toFixed(2)} ${x1.toFixed(2)},${y1.toFixed(2)}`;\n  }\n  return d;\n}\n\nfunction sharpPath(points: Point[]): string {\n  return points.map(([x, y], i) => `${i === 0 ? \"M\" : \"L\"}${x.toFixed(2)},${y.toFixed(2)}`).join(\" \");\n}\n\nfunction formatSparkPoint(v: number, prefix?: string, suffix?: string, formatValue?: (v: number) => string) {\n  if (formatValue) return formatValue(v);\n  const decimals = Number.isInteger(v) ? 0 : 2;\n  return `${prefix ?? \"\"}${v.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })}${suffix ?? \"\"}`;\n}\n\ninterface SparklineProps {\n  data: number[];\n  s: Size;\n  p: Palette;\n  color: string;\n  style: \"sharp\" | \"smooth\";\n  prefix?: string;\n  suffix?: string;\n  formatValue?: (v: number) => string;\n  label: string;\n}\n\nfunction Sparkline({ data, s, p, color, style, prefix, suffix, formatValue, label }: SparklineProps) {\n  const width = 100;\n  const height = s.sparkH;\n  const pad = 4;\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const range = max - min || 1;\n  const toPoints = (values: number[]): Point[] =>\n    values.map((v, i) => [\n      values.length === 1 ? width / 2 : (i / (values.length - 1)) * (width - pad * 2) + pad,\n      height - pad - ((v - min) / range) * (height - pad * 2),\n    ]);\n  const points = toPoints(data);\n  const linePath = style === \"smooth\" ? smoothPath(points) : sharpPath(points);\n  const last = points[points.length - 1];\n  const areaPath = `${linePath} L${last[0].toFixed(2)},${height} L${points[0][0].toFixed(2)},${height} Z`;\n  const gradId = React.useId();\n  const glowId = React.useId();\n  const clipId = React.useId();\n\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [entered, setEntered] = React.useState(false);\n  const containerRef = React.useRef<HTMLDivElement>(null);\n  const interactive = data.length > 1;\n\n  const nearestIndex = (clientX: number) => {\n    const el = containerRef.current;\n    if (!el) return 0;\n    const rect = el.getBoundingClientRect();\n    const x = ((clientX - rect.left) / rect.width) * width;\n    let best = 0;\n    let bestDist = Infinity;\n    points.forEach((pt, i) => {\n      const d = Math.abs(pt[0] - x);\n      if (d < bestDist) {\n        bestDist = d;\n        best = i;\n      }\n    });\n    return best;\n  };\n\n  const summary = `${label} trend from ${formatSparkPoint(data[0], prefix, suffix, formatValue)} to ${formatSparkPoint(data[data.length - 1], prefix, suffix, formatValue)}, peak ${formatSparkPoint(max, prefix, suffix, formatValue)}`;\n\n  return (\n    <div\n      ref={containerRef}\n      role={interactive ? \"img\" : undefined}\n      aria-label={interactive ? summary : undefined}\n      tabIndex={interactive ? 0 : undefined}\n      className=\"relative outline-none focus-visible:ring-2 rounded-lg\"\n      style={{ height, cursor: interactive ? \"crosshair\" : undefined, [\"--tw-ring-color\" as string]: color }}\n      onMouseMove={interactive ? (e) => setHover(nearestIndex(e.clientX)) : undefined}\n      onMouseLeave={interactive ? () => setHover(null) : undefined}\n      onFocus={interactive ? () => setHover((h) => h ?? points.length - 1) : undefined}\n      onBlur={interactive ? () => setHover(null) : undefined}\n      onKeyDown={\n        interactive\n          ? (e) => {\n              if (e.key === \"ArrowRight\") {\n                e.preventDefault();\n                setHover((h) => Math.min(points.length - 1, (h ?? -1) + 1));\n              } else if (e.key === \"ArrowLeft\") {\n                e.preventDefault();\n                setHover((h) => Math.max(0, (h ?? points.length) - 1));\n              } else if (e.key === \"Home\") {\n                e.preventDefault();\n                setHover(0);\n              } else if (e.key === \"End\") {\n                e.preventDefault();\n                setHover(points.length - 1);\n              } else if (e.key === \"Escape\") {\n                setHover(null);\n              }\n            }\n          : undefined\n      }\n    >\n      <svg width=\"100%\" height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio=\"none\" aria-hidden=\"true\" style={{ overflow: \"visible\", display: \"block\" }}>\n        <defs>\n          <linearGradient id={gradId} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n            <stop offset=\"0%\" stopColor={color} stopOpacity=\"0.38\" />\n            <stop offset=\"55%\" stopColor={color} stopOpacity=\"0.1\" />\n            <stop offset=\"100%\" stopColor={color} stopOpacity=\"0\" />\n          </linearGradient>\n          <filter id={glowId} x=\"-30%\" y=\"-60%\" width=\"160%\" height=\"220%\">\n            <feGaussianBlur stdDeviation=\"1.4\" result=\"blur\" />\n            <feMerge>\n              <feMergeNode in=\"blur\" />\n              <feMergeNode in=\"SourceGraphic\" />\n            </feMerge>\n          </filter>\n          {/* The line draws in by widening this clip. Animating pathLength instead breaks here: with\n           * vector-effect=\"non-scaling-stroke\" on a horizontally stretched viewBox, Chrome measures\n           * the dash in screen pixels, so the stroke stopped partway across. */}\n          <clipPath id={clipId}>\n            <motion.rect x={-4} y={-height} height={height * 3} initial={{ width: 0 }} animate={{ width: width + 8 }} transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }} />\n          </clipPath>\n        </defs>\n        <motion.path d={areaPath} fill={`url(#${gradId})`} stroke=\"none\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5, delay: 0.15 }} />\n        <motion.path\n          d={linePath}\n          fill=\"none\"\n          stroke={color}\n          strokeWidth=\"2\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          clipPath={`url(#${clipId})`}\n          vectorEffect=\"non-scaling-stroke\"\n          filter={`url(#${glowId})`}\n        />\n        {hover !== null && (\n          <line x1={points[hover][0]} x2={points[hover][0]} y1={points[hover][1]} y2={height} stroke={p.crosshair} strokeWidth=\"0.6\" strokeDasharray=\"1.5 2\" />\n        )}\n        {/* Kept mounted (never swapped out) so the spring pop-in only ever\n         * plays once, on first mount — toggling it off and back on via\n         * hover would otherwise restart that same entrance transition,\n         * including its 0.75s delay, every time the pointer leaves. */}\n        <motion.circle\n          cx={last[0]}\n          cy={last[1]}\n          r=\"2.6\"\n          fill={color}\n          initial={{ scale: 0, opacity: 0 }}\n          animate={{ scale: 1, opacity: hover === null ? 1 : 0 }}\n          transition={entered ? { duration: 0.15 } : { delay: 0.75, duration: 0.25, ease: \"backOut\" }}\n          onAnimationComplete={() => setEntered(true)}\n          style={{ transformOrigin: `${last[0]}px ${last[1]}px` }}\n        />\n        <motion.circle\n          cx={last[0]}\n          cy={last[1]}\n          r=\"2.6\"\n          fill=\"none\"\n          stroke={color}\n          strokeWidth=\"1.4\"\n          initial={{ opacity: 0 }}\n          animate={hover === null ? { scale: [1, 2.6], opacity: [0.6, 0] } : { opacity: 0 }}\n          transition={hover === null ? { delay: entered ? 0 : 0.9, duration: 1.6, repeat: Infinity, ease: \"easeOut\" } : { duration: 0.15 }}\n          style={{ transformOrigin: `${last[0]}px ${last[1]}px` }}\n        />\n        {hover !== null && <circle cx={points[hover][0]} cy={points[hover][1]} r=\"2.8\" fill={p.tooltipBg} stroke={color} strokeWidth=\"1.6\" />}\n      </svg>\n\n      {hover !== null && (\n        <div\n          role=\"status\"\n          className=\"pointer-events-none absolute whitespace-nowrap rounded-lg font-semibold\"\n          style={{\n            left: `${(points[hover][0] / width) * 100}%`,\n            top: Math.max(0, (points[hover][1] / height) * height - 34),\n            transform: \"translateX(-50%)\",\n            background: p.tooltipBg,\n            border: `1px solid ${p.tooltipBorder}`,\n            color: p.text,\n            fontSize: s.label - 2,\n            padding: \"4px 7px\",\n            boxShadow: \"0 8px 22px rgba(0,0,0,0.28)\",\n            zIndex: 2,\n          }}\n        >\n          {formatSparkPoint(data[hover], prefix, suffix, formatValue)}\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport function StatCard({\n  label,\n  value,\n  previousValue,\n  delta,\n  deltaLabel,\n  trend,\n  goodDirection = \"up\",\n  icon,\n  prefix,\n  suffix,\n  formatValue,\n  sparkline,\n  sparklineStyle = \"smooth\",\n  animateValue = true,\n  size = \"md\",\n  theme = \"dark\",\n  accentColor,\n  width = 260,\n  className,\n}: StatCardProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const uid = React.useId();\n\n  const resolvedDelta = delta ?? (previousValue !== undefined && previousValue !== 0 ? ((value - previousValue) / Math.abs(previousValue)) * 100 : undefined);\n  const resolvedTrend: StatCardTrend = trend ?? (resolvedDelta === undefined || Math.abs(resolvedDelta) < 0.05 ? \"neutral\" : resolvedDelta > 0 ? \"up\" : \"down\");\n  const isGood = resolvedTrend === \"neutral\" ? null : (resolvedTrend === \"up\") === (goodDirection === \"up\");\n  const trendColor = resolvedTrend === \"neutral\" ? p.muted : isGood ? p.good : p.bad;\n\n  const mv = useMotionValue(0);\n  const [shown, setShown] = React.useState(animateValue ? 0 : value);\n  useMotionValueEvent(mv, \"change\", (v) => setShown(v));\n  React.useEffect(() => {\n    if (!animateValue) {\n      // mv.jump sets the motion value immediately (no animation) but still\n      // fires the \"change\" subscription above, which is what actually\n      // updates `shown` — calling setShown directly here instead would be\n      // a same-render setState-in-effect, exactly what the \"external\n      // system\" pattern (subscribe, let its callback setState) exists to\n      // avoid.\n      mv.jump(value);\n      return;\n    }\n    const controls = animate(mv, value, { duration: 0.9, ease: [0.16, 1, 0.3, 1] });\n    return () => controls.stop();\n  }, [value, animateValue, mv]);\n\n  const decimals = Number.isInteger(value) ? 0 : 2;\n  const text = formatValue ? formatValue(shown) : `${prefix ?? \"\"}${shown.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })}${suffix ?? \"\"}`;\n\n  const sparkColor = accentColor ?? (resolvedTrend === \"neutral\" ? p.muted : trendColor);\n\n  return (\n    <div\n      className={cn(\"flex flex-col\", className)}\n      style={{ width, maxWidth: \"100%\", padding: s.pad, borderRadius: s.radius, background: p.bg, border: `1px solid ${p.border}`, fontFamily: \"Inter, sans-serif\", gap: s.gap }}\n    >\n      <div className=\"flex items-center\" style={{ gap: 10 }}>\n        {icon && (\n          <span className=\"flex shrink-0 items-center justify-center\" style={{ width: s.icon, height: s.icon, borderRadius: Math.round(s.icon * 0.32), background: p.iconBg, color: accentColor ?? sparkColor }}>\n            {icon}\n          </span>\n        )}\n        <span id={`${uid}-label`} className=\"font-medium\" style={{ color: p.muted, fontSize: s.label, lineHeight: 1.4 }}>\n          {label}\n        </span>\n      </div>\n\n      <span aria-labelledby={`${uid}-label`} className=\"font-semibold tabular-nums tracking-[-0.02em]\" style={{ color: p.text, fontSize: s.value, lineHeight: 1.1 }}>\n        {text}\n      </span>\n\n      {(resolvedDelta !== undefined || deltaLabel) && (\n        <div className=\"flex items-center\" style={{ gap: 6 }}>\n          {resolvedDelta !== undefined && (\n            <span className=\"inline-flex items-center font-semibold tabular-nums\" style={{ gap: 3, color: trendColor, fontSize: s.label - 0.5 }}>\n              <TrendArrow trend={resolvedTrend} size={s.label - 3} />\n              {Math.abs(resolvedDelta).toFixed(Math.abs(resolvedDelta) < 10 ? 1 : 0)}%\n            </span>\n          )}\n          {deltaLabel && (\n            <span style={{ color: p.faint, fontSize: s.label - 0.5 }}>{deltaLabel}</span>\n          )}\n        </div>\n      )}\n\n      {sparkline && sparkline.length > 1 && (\n        <div style={{ marginTop: sparkline ? 2 : 0 }}>\n          <Sparkline data={sparkline} s={s} p={p} color={sparkColor} style={sparklineStyle} prefix={prefix} suffix={suffix} formatValue={formatValue} label={label} />\n        </div>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}