{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"stats-carousel","type":"registry:ui","title":"Stats Carousel","description":"A carousel of KPI cards whose numbers count up and sparklines draw in as each one slides to center.","dependencies":[],"registryDependencies":[],"files":[{"path":"registry/ui/stats-carousel.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, type KeyboardEvent } from \"react\";\n\nexport interface StatItem {\n  label: string;\n  value: number;\n  prefix?: string;\n  suffix?: string;\n  decimals?: number;\n  /** Change vs. previous period, in %. */\n  delta?: number;\n  /** Set when a drop is good news (churn, latency). */\n  invert?: boolean;\n  /** Sparkline points, any scale. */\n  data: number[];\n  /** Small caption under the chart, e.g. \"vs. last 30 days\". */\n  caption?: string;\n}\n\nexport interface StatsCarouselProps {\n  stats: StatItem[];\n  /** Advance automatically. Pauses on hover and focus. */\n  autoPlay?: boolean;\n  /** Ms between slides. */\n  interval?: number;\n  /** Ms for the count-up and sparkline draw. */\n  duration?: number;\n  /** Card width in px. */\n  cardWidth?: number;\n  /** Px between cards. */\n  gap?: number;\n  /** Accent for metrics moving the right way. */\n  positiveColor?: string;\n  /** Accent for metrics moving the wrong way. */\n  negativeColor?: string;\n  className?: string;\n}\n\nconst W = 240;\nconst H = 64;\n\nfunction sparkPath(data: number[]) {\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const span = max - min || 1;\n  const pts = data.map((d, i) => [(i / Math.max(1, data.length - 1)) * W, H - 4 - ((d - min) / span) * (H - 8)]);\n  // Smooth with midpoint quadratic curves.\n  let line = `M${pts[0][0]},${pts[0][1]}`;\n  for (let i = 1; i < pts.length; i++) {\n    const [px, py] = pts[i - 1];\n    const [x, y] = pts[i];\n    line += ` Q${px},${py} ${(px + x) / 2},${(py + y) / 2}`;\n  }\n  const [lx, ly] = pts[pts.length - 1];\n  line += ` T${lx},${ly}`;\n  return { line, area: `${line} L${W},${H} L0,${H} Z`, end: [lx, ly] as const };\n}\n\nconst fmt = (n: number, decimals: number) =>\n  n.toLocaleString(\"en-US\", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });\n\nfunction StatCard({\n  stat,\n  active,\n  duration,\n  color,\n  index,\n  total,\n}: {\n  stat: StatItem;\n  active: boolean;\n  duration: number;\n  color: string;\n  index: number;\n  total: number;\n}) {\n  const num = useRef<HTMLSpanElement>(null);\n  const gid = useId().replace(/:/g, \"\");\n  const { line, area, end } = sparkPath(stat.data.length > 1 ? stat.data : [0, 0]);\n  const decimals = stat.decimals ?? 0;\n  const up = (stat.delta ?? 0) >= 0;\n\n  useEffect(() => {\n    const el = num.current;\n    if (!el || !active) return;\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n      el.textContent = fmt(stat.value, decimals);\n      return;\n    }\n    let raf = 0;\n    const t0 = performance.now();\n    const tick = (now: number) => {\n      const p = Math.min((now - t0) / duration, 1);\n      el.textContent = fmt(stat.value * (1 - Math.pow(1 - p, 4)), decimals);\n      if (p < 1) raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [active, stat.value, decimals, duration]);\n\n  const draw = active ? `stroke-dashoffset ${duration}ms cubic-bezier(.3,.7,.2,1) 120ms` : \"stroke-dashoffset .3s\";\n\n  return (\n    <div\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      aria-label={`${index + 1} of ${total}: ${stat.label}`}\n      aria-hidden={!active}\n      className=\"relative flex h-full flex-col overflow-hidden rounded-2xl border border-border bg-card p-5 shadow-xl\"\n    >\n      <div className=\"flex items-start justify-between gap-3\">\n        <p className=\"text-sm font-medium text-muted-foreground\">{stat.label}</p>\n        {stat.delta !== undefined && (\n          <span\n            className=\"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold tabular-nums\"\n            style={{ color, background: `color-mix(in oklab, ${color} 14%, transparent)` }}\n          >\n            <svg viewBox=\"0 0 10 10\" className=\"size-2.5\" style={{ transform: up ? undefined : \"rotate(180deg)\" }} aria-hidden>\n              <path d=\"M5 1.5 9 7.5H1z\" fill=\"currentColor\" />\n            </svg>\n            {Math.abs(stat.delta).toFixed(1)}%\n          </span>\n        )}\n      </div>\n      <p className=\"mt-2 text-4xl font-semibold tracking-tight text-foreground\" style={{ fontVariantNumeric: \"tabular-nums\" }}>\n        {stat.prefix}\n        <span ref={num}>{fmt(stat.value, decimals)}</span>\n        {stat.suffix && <span className=\"ml-0.5 text-2xl text-muted-foreground\">{stat.suffix}</span>}\n      </p>\n      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio=\"none\" className=\"mt-auto h-16 w-full overflow-visible pt-4\" aria-hidden>\n        <defs>\n          <linearGradient id={`${gid}-fill`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n            <stop offset=\"0\" stopColor={color} stopOpacity=\".28\" />\n            <stop offset=\"1\" stopColor={color} stopOpacity=\"0\" />\n          </linearGradient>\n        </defs>\n        <path\n          d={area}\n          fill={`url(#${gid}-fill)`}\n          style={{ opacity: active ? 1 : 0, transition: `opacity ${active ? duration : 300}ms ease ${active ? duration * 0.4 : 0}ms` }}\n        />\n        <path\n          d={line}\n          fill=\"none\"\n          stroke={color}\n          strokeWidth={2}\n          strokeLinecap=\"round\"\n          vectorEffect=\"non-scaling-stroke\"\n          pathLength={1}\n          strokeDasharray=\"1 1\"\n          style={{ strokeDashoffset: active ? 0 : 1, transition: draw }}\n        />\n        <circle\n          cx={end[0]}\n          cy={end[1]}\n          r={3.5}\n          fill={color}\n          style={{\n            opacity: active ? 1 : 0,\n            transition: `opacity .3s ease ${active ? duration + 80 : 0}ms`,\n            filter: `drop-shadow(0 0 6px ${color})`,\n          }}\n        />\n      </svg>\n      {stat.caption && <p className=\"mt-2 text-xs text-muted-foreground\">{stat.caption}</p>}\n    </div>\n  );\n}\n\nexport function StatsCarousel({\n  stats,\n  autoPlay = true,\n  interval = 3200,\n  duration = 1400,\n  cardWidth = 280,\n  gap = 20,\n  positiveColor = \"#a3e635\",\n  negativeColor = \"#fb7185\",\n  className,\n}: StatsCarouselProps) {\n  const [index, setIndex] = useState(0);\n  const [paused, setPaused] = useState(false);\n  const n = stats.length;\n  const current = n ? ((index % n) + n) % n : 0;\n  const go = (i: number) => setIndex(((i % n) + n) % n);\n\n  useEffect(() => {\n    if (!autoPlay || paused || n < 2) return;\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n    const id = window.setTimeout(() => setIndex((i) => (i + 1) % n), interval);\n    return () => window.clearTimeout(id);\n  }, [autoPlay, paused, interval, n, current]);\n\n  const onKey = (e: KeyboardEvent) => {\n    if (e.key === \"ArrowRight\") go(current + 1);\n    else if (e.key === \"ArrowLeft\") go(current - 1);\n    else return;\n    e.preventDefault();\n  };\n\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label=\"Key metrics\"\n      className={`relative w-full select-none ${className ?? \"\"}`}\n      onPointerEnter={() => setPaused(true)}\n      onPointerLeave={() => setPaused(false)}\n      onFocus={() => setPaused(true)}\n      onBlur={(e) => !e.currentTarget.contains(e.relatedTarget) && setPaused(false)}\n      onKeyDown={onKey}\n    >\n      <div\n        className=\"overflow-hidden py-6\"\n        style={{\n          maskImage: \"linear-gradient(90deg, transparent, #000 18%, #000 82%, transparent)\",\n          WebkitMaskImage: \"linear-gradient(90deg, transparent, #000 18%, #000 82%, transparent)\",\n        }}\n      >\n        <div aria-live={autoPlay && !paused ? \"off\" : \"polite\"} className=\"relative\" style={{ height: 212 }}>\n          {stats.map((s, i) => {\n            const active = i === current;\n            const good = (s.delta ?? 0) >= 0 !== !!s.invert;\n            // Signed circular distance from the current card, so both sides stay filled and the loop is seamless.\n            let off = (((i - current) % n) + n) % n;\n            if (off > n / 2) off -= n;\n            const far = Math.abs(off) > 2;\n            return (\n              <div\n                key={s.label + i}\n                onClick={() => !active && go(i)}\n                className=\"absolute left-1/2 top-0 motion-reduce:!transition-none\"\n                style={{\n                  width: cardWidth,\n                  height: 212,\n                  marginLeft: -cardWidth / 2,\n                  zIndex: 10 - Math.abs(off),\n                  visibility: far ? \"hidden\" : undefined,\n                  opacity: far ? 0 : active ? 1 : 0.4,\n                  transform: `translateX(${off * (cardWidth + gap)}px) scale(${active ? 1 : 0.9})`,\n                  filter: active ? \"none\" : \"saturate(.4)\",\n                  // Far cards jump instantly (they are off-stage), so nothing visibly slides across the row.\n                  transition: far ? \"opacity .3s, visibility .3s\" : \"opacity .6s, transform .7s cubic-bezier(.65,0,.2,1), filter .6s\",\n                  cursor: active ? \"default\" : \"pointer\",\n                }}\n              >\n                <StatCard stat={s} active={active} duration={duration} color={good ? positiveColor : negativeColor} index={i} total={n} />\n              </div>\n            );\n          })}\n        </div>\n      </div>\n\n      <div className=\"mt-2 flex items-center justify-center gap-4\">\n        <button\n          type=\"button\"\n          aria-label=\"Previous metric\"\n          onClick={() => go(current - 1)}\n          className=\"grid size-9 place-items-center rounded-full border border-border bg-card text-foreground transition hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n        >\n          <svg viewBox=\"0 0 24 24\" className=\"size-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth={2} aria-hidden>\n            <path d=\"m15 18-6-6 6-6\" />\n          </svg>\n        </button>\n        <div className=\"flex items-center gap-1.5\">\n          {stats.map((s, i) => (\n            <button\n              key={s.label + i}\n              type=\"button\"\n              aria-label={`Show ${s.label}`}\n              aria-current={i === current}\n              onClick={() => go(i)}\n              className=\"h-1.5 rounded-full bg-foreground/20 transition-all duration-500 hover:bg-foreground/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring aria-[current=true]:bg-foreground\"\n              style={{ width: i === current ? 22 : 6 }}\n            />\n          ))}\n        </div>\n        <button\n          type=\"button\"\n          aria-label=\"Next metric\"\n          onClick={() => go(current + 1)}\n          className=\"grid size-9 place-items-center rounded-full border border-border bg-card text-foreground transition hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n        >\n          <svg viewBox=\"0 0 24 24\" className=\"size-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth={2} aria-hidden>\n            <path d=\"m9 18 6-6-6-6\" />\n          </svg>\n        </button>\n      </div>\n    </section>\n  );\n}\n"}]}