{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sparkline-table",
  "title": "Sparkline Table",
  "description": "A product table with a tiny trend chart in every row: 30-day sparklines coloured by direction, hover for any day's value, revenue with share bars, week-over-week change pills and sortable columns.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/sparkline-table/sparkline-table.tsx",
      "content": "\"use client\";\n\nimport * as React from \"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 TableTheme = \"dark\" | \"light\";\n\nexport interface SparklineRow {\n  name: string;\n  category?: string;\n  price: number;\n  /** Daily values for the trend, oldest first (e.g. units sold per day). */\n  series: number[];\n}\n\nexport interface SparklineTableProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: TableTheme;\n  title?: string;\n  subtitle?: string;\n  rows?: SparklineRow[];\n  /** Label of the last day in the series; earlier days count back from it. */\n  endLabel?: string;\n  currency?: string;\n}\n\ntype SortKey = \"name\" | \"price\" | \"units\" | \"revenue\" | \"change\";\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    faint: \"rgba(255,255,255,0.38)\",\n    head: \"rgba(255,255,255,0.03)\",\n    hover: \"rgba(255,255,255,0.025)\",\n    chip: \"rgba(255,255,255,0.06)\",\n    track: \"rgba(255,255,255,0.07)\",\n    bar: \"#8FB8FF\",\n    up: \"#2EE6A8\",\n    down: \"#FF6B78\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.08)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    faint: \"rgba(17,19,23,0.4)\",\n    head: \"rgba(17,19,23,0.025)\",\n    hover: \"rgba(17,19,23,0.02)\",\n    chip: \"rgba(17,19,23,0.05)\",\n    track: \"rgba(17,19,23,0.07)\",\n    bar: \"#3B6FD8\",\n    up: \"#0E9F6E\",\n    down: \"#E5484D\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n  },\n};\n\n// Deterministic sample: 30 days of units for eight products, each with its own trend.\nfunction sampleRows(): SparklineRow[] {\n  let seed = 21;\n  const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;\n  const items: [string, string, number, number, number][] = [\n    [\"Field Jacket\", \"Outerwear\", 240, 38, 0.9],\n    [\"Merino Crew\", \"Knitwear\", 95, 64, 0.35],\n    [\"Canvas Tote\", \"Bags\", 68, 52, -0.4],\n    [\"Wool Overshirt\", \"Shirts\", 180, 26, 1.1],\n    [\"Leather Belt\", \"Accessories\", 75, 41, 0.05],\n    [\"Down Vest\", \"Outerwear\", 210, 22, -0.8],\n    [\"Linen Shirt\", \"Shirts\", 110, 47, -0.15],\n    [\"Rib Socks\", \"Accessories\", 24, 120, 0.6],\n  ];\n  return items.map(([name, category, price, base, trend]) => ({\n    name,\n    category,\n    price,\n    series: Array.from({ length: 30 }, (_, i) =>\n      Math.max(\n        1,\n        Math.round(\n          base * (1 + (trend * (i - 15)) / 30) +\n            Math.sin(i * 0.9 + base) * base * 0.12 +\n            (rnd() - 0.5) * base * 0.25,\n        ),\n      ),\n    ),\n  }));\n}\n\nconst DEFAULT_ROWS = sampleRows();\nconst MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Sparkline({\n  values,\n  color,\n  w,\n  h,\n  gradId,\n  labelFor,\n  pal,\n  unit,\n}: {\n  values: number[];\n  color: string;\n  w: number;\n  h: number;\n  gradId: string;\n  labelFor: (i: number) => string;\n  pal: (typeof PALETTES)[\"dark\"];\n  unit: string;\n}) {\n  const [hover, setHover] = React.useState<number | null>(null);\n  const lo = Math.min(...values);\n  const hi = Math.max(...values);\n  const x = (i: number) => 2 + (i / Math.max(1, values.length - 1)) * (w - 4);\n  const y = (v: number) =>\n    3 + (1 - (v - lo) / Math.max(1e-9, hi - lo)) * (h - 6);\n  const line = values\n    .map((v, i) => `${i ? \"L\" : \"M\"}${x(i).toFixed(1)},${y(v).toFixed(1)}`)\n    .join(\"\");\n  const at = hover ?? values.length - 1;\n  return (\n    <span className=\"relative inline-block\" style={{ width: w, height: h }}>\n      <svg\n        width={w}\n        height={h}\n        className=\"block overflow-visible\"\n        role=\"img\"\n        aria-label={`Trend from ${values[0]} to ${values[values.length - 1]} ${unit}, low ${lo}, high ${hi}`}\n        onPointerMove={(e) => {\n          const r = e.currentTarget.getBoundingClientRect();\n          setHover(\n            Math.max(\n              0,\n              Math.min(\n                values.length - 1,\n                Math.round(\n                  ((e.clientX - r.left - 2) / (w - 4)) * (values.length - 1),\n                ),\n              ),\n            ),\n          );\n        }}\n        onPointerLeave={() => setHover(null)}\n      >\n        <defs>\n          <linearGradient id={gradId} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n            <stop offset=\"0%\" stopColor={color} stopOpacity={0.3} />\n            <stop offset=\"100%\" stopColor={color} stopOpacity={0} />\n          </linearGradient>\n        </defs>\n        <path\n          d={`${line}L${x(values.length - 1)},${h}L${x(0)},${h}Z`}\n          fill={`url(#${gradId})`}\n        />\n        <path\n          d={line}\n          fill=\"none\"\n          stroke={color}\n          strokeWidth={1.6}\n          strokeLinejoin=\"round\"\n          strokeLinecap=\"round\"\n        />\n        {hover !== null && (\n          <line\n            x1={x(at)}\n            x2={x(at)}\n            y1={0}\n            y2={h}\n            stroke={pal.sub}\n            strokeDasharray=\"2 2\"\n          />\n        )}\n        <circle\n          cx={x(at)}\n          cy={y(values[at])}\n          r={2.6}\n          fill={color}\n          stroke={pal.card}\n          strokeWidth={1.5}\n        />\n      </svg>\n      {hover !== null && (\n        <span\n          className=\"pointer-events-none absolute bottom-full z-10 mb-1.5 -translate-x-1/2 rounded-md px-2 py-1 text-[11px] whitespace-nowrap shadow-lg\"\n          style={{\n            left: x(at),\n            background: pal.tip,\n            border: `1px solid ${pal.tipBorder}`,\n            color: pal.text,\n          }}\n        >\n          <b className=\"tabular-nums\">{values[at]}</b>{\" \"}\n          <span style={{ color: pal.sub }}>\n            {unit} · {labelFor(at)}\n          </span>\n        </span>\n      )}\n    </span>\n  );\n}\n\nexport function SparklineTable({\n  theme = \"dark\",\n  title = \"Top products\",\n  subtitle = \"Last 30 days · sort by any column, hover a trend for daily units\",\n  rows = DEFAULT_ROWS,\n  endLabel = \"Nov 5\",\n  currency = \"$\",\n  className,\n  style,\n  ...props\n}: SparklineTableProps) {\n  const pal = PALETTES[theme];\n  const id = React.useId();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const compact = width > 0 && width < 640;\n  const [sort, setSort] = React.useState<{ key: SortKey; dir: 1 | -1 }>({\n    key: \"revenue\",\n    dir: -1,\n  });\n\n  // Change: last 7 days vs the 7 before.\n  const enriched = rows.map((r) => {\n    const units = r.series.reduce((s, v) => s + v, 0);\n    const recent = r.series.slice(-7).reduce((s, v) => s + v, 0);\n    const prior = r.series.slice(-14, -7).reduce((s, v) => s + v, 0);\n    return {\n      ...r,\n      units,\n      revenue: units * r.price,\n      change: prior ? (recent - prior) / prior : 0,\n    };\n  });\n  const totalRevenue = enriched.reduce((s, r) => s + r.revenue, 0);\n  const sorted = [...enriched].sort((a, b) => {\n    const va = a[sort.key];\n    const vb = b[sort.key];\n    return (\n      (typeof va === \"string\"\n        ? va.localeCompare(String(vb))\n        : (va as number) - (vb as number)) * sort.dir\n    );\n  });\n  const money = (v: number) =>\n    `${currency}${v >= 1e6 ? `${(v / 1e6).toFixed(2)}M` : v >= 10000 ? `${(v / 1000).toFixed(1)}K` : v.toLocaleString(\"en-US\")}`;\n  const end = (() => {\n    const [m, d] = endLabel.split(\" \");\n    return { m: MONTHS.indexOf(m), d: Number(d) };\n  })();\n  const labelFor = (n: number) => (i: number) => {\n    if (end.m < 0 || !end.d) return `day ${i + 1}`;\n    const date = new Date(Date.UTC(2025, end.m, end.d - (n - 1 - i)));\n    return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`;\n  };\n\n  const header = (\n    key: SortKey,\n    label: string,\n    align: \"left\" | \"right\" = \"right\",\n  ) => {\n    const activeSort = sort.key === key;\n    return (\n      <th\n        scope=\"col\"\n        aria-sort={\n          activeSort ? (sort.dir === 1 ? \"ascending\" : \"descending\") : \"none\"\n        }\n        className={cn(\n          \"px-3 py-2.5 font-medium\",\n          align === \"right\" ? \"text-right\" : \"text-left\",\n        )}\n      >\n        <button\n          type=\"button\"\n          onClick={() =>\n            setSort((s) =>\n              s.key === key\n                ? { key, dir: s.dir === 1 ? -1 : 1 }\n                : { key, dir: key === \"name\" ? 1 : -1 },\n            )\n          }\n          className={cn(\n            \"inline-flex cursor-pointer items-center gap-1 text-[11px] tracking-[0.04em] uppercase\",\n            align === \"right\" && \"flex-row-reverse\",\n          )}\n          style={{ color: activeSort ? pal.text : pal.faint }}\n        >\n          {label}\n          <svg width=\"8\" height=\"10\" viewBox=\"0 0 8 10\" aria-hidden=\"true\">\n            <path\n              d=\"M4 1L7 4H1z\"\n              fill=\"currentColor\"\n              opacity={activeSort && sort.dir === 1 ? 1 : 0.3}\n            />\n            <path\n              d=\"M4 9L1 6h6z\"\n              fill=\"currentColor\"\n              opacity={activeSort && sort.dir === -1 ? 1 : 0.3}\n            />\n          </svg>\n        </button>\n      </th>\n    );\n  };\n\n  return (\n    <div\n      ref={boxRef}\n      className={cn(\"w-full overflow-hidden rounded-[20px]\", className)}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-3 px-5 pt-5 pb-4 sm:px-6\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        <div className=\"text-right\">\n          <p className=\"text-[20px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\">\n            {money(totalRevenue)}\n          </p>\n          <p className=\"mt-0.5 text-[11.5px]\" style={{ color: pal.sub }}>\n            revenue, {rows.length} products\n          </p>\n        </div>\n      </div>\n      <div className=\"overflow-x-auto\">\n        <table\n          className=\"w-full border-collapse text-[13px]\"\n          style={{ minWidth: compact ? 0 : 640 }}\n        >\n          <thead>\n            <tr\n              className=\"border-y\"\n              style={{ borderColor: pal.border, background: pal.head }}\n            >\n              {header(\"name\", \"Product\", \"left\")}\n              {!compact && header(\"price\", \"Price\")}\n              {!compact && header(\"units\", \"Units\")}\n              {header(\"revenue\", \"Revenue\")}\n              <th\n                scope=\"col\"\n                className=\"px-3 py-2.5 text-left text-[11px] font-medium tracking-[0.04em] uppercase\"\n                style={{ color: pal.faint }}\n              >\n                30-day trend\n              </th>\n              {header(\"change\", \"7d\")}\n            </tr>\n          </thead>\n          <tbody>\n            {sorted.map((r, i) => {\n              const up = r.change >= 0;\n              const color = up ? pal.up : pal.down;\n              return (\n                <tr\n                  key={r.name}\n                  className=\"border-b transition-colors last:border-b-0\"\n                  style={{ borderColor: pal.border }}\n                  onMouseEnter={(e) =>\n                    (e.currentTarget.style.background = pal.hover)\n                  }\n                  onMouseLeave={(e) => (e.currentTarget.style.background = \"\")}\n                >\n                  <td className=\"px-3 py-2.5 pl-5 sm:pl-6\">\n                    <span className=\"flex items-center gap-2.5\">\n                      <span\n                        className=\"w-4 text-right text-[11px] tabular-nums\"\n                        style={{ color: pal.faint }}\n                      >\n                        {i + 1}\n                      </span>\n                      <span className=\"min-w-0\">\n                        <span className=\"block truncate font-medium\">\n                          {r.name}\n                        </span>\n                        {r.category && (\n                          <span\n                            className=\"block truncate text-[11.5px]\"\n                            style={{ color: pal.sub }}\n                          >\n                            {r.category}\n                          </span>\n                        )}\n                      </span>\n                    </span>\n                  </td>\n                  {!compact && (\n                    <td\n                      className=\"px-3 py-2.5 text-right tabular-nums\"\n                      style={{ color: pal.sub }}\n                    >\n                      {money(r.price)}\n                    </td>\n                  )}\n                  {!compact && (\n                    <td className=\"px-3 py-2.5 text-right tabular-nums\">\n                      {r.units.toLocaleString(\"en-US\")}\n                    </td>\n                  )}\n                  <td className=\"px-3 py-2.5 text-right\">\n                    <span className=\"block font-semibold tabular-nums\">\n                      {money(r.revenue)}\n                    </span>\n                    <span\n                      className=\"mt-1 ml-auto block h-1 w-20 overflow-hidden rounded-full\"\n                      style={{ background: pal.track }}\n                      title={`${((r.revenue / totalRevenue) * 100).toFixed(1)}% of revenue`}\n                    >\n                      <span\n                        className=\"block h-full rounded-full\"\n                        style={{\n                          width: `${(r.revenue / Math.max(...enriched.map((x) => x.revenue))) * 100}%`,\n                          background: pal.bar,\n                        }}\n                      />\n                    </span>\n                  </td>\n                  <td className=\"px-3 py-2.5\">\n                    <Sparkline\n                      values={r.series}\n                      color={color}\n                      w={compact ? 72 : 124}\n                      h={30}\n                      gradId={`${id}-g${i}`}\n                      labelFor={labelFor(r.series.length)}\n                      pal={pal}\n                      unit=\"units\"\n                    />\n                  </td>\n                  <td className=\"px-3 py-2.5 pr-5 text-right sm:pr-6\">\n                    <span\n                      className=\"inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-[11.5px] font-semibold tabular-nums\"\n                      style={{ color, background: `${color}1f` }}\n                    >\n                      {up ? \"▲\" : \"▼\"} {Math.abs(r.change * 100).toFixed(1)}%\n                    </span>\n                  </td>\n                </tr>\n              );\n            })}\n          </tbody>\n        </table>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}