{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "model-usage",
  "type": "registry:block",
  "title": "Model usage",
  "description": "An AI gateway dashboard: requests, tokens and spend, tokens by model over time, latency, a written summary, and a model table that focuses the chart.",
  "categories": [
    "blocks"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/model-usage.tsx",
      "type": "registry:component",
      "target": "components/overtrue/model-usage.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconCalendarStats, IconSparkles } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { NumberTicker } from \"./number-ticker\";\nimport { Sparkline } from \"./sparkline\";\nimport { DeltaBadge } from \"./delta-badge\";\nimport {\n  StackedAreaChart,\n  type StackedAreaAnnotation,\n} from \"./stacked-area-chart\";\nimport { LatencyHistogram } from \"./latency-histogram\";\nimport { InsightCard, type InsightSource } from \"./insight-card\";\n\nexport interface ModelUsageModel {\n  /** Field name for this model in each `usage` row. */\n  id: string;\n  label: string;\n  /** Provider or deployment, shown under the name. */\n  provider?: string;\n  color?: string;\n  requests: number;\n  inputTokens: number;\n  outputTokens: number;\n  /** Spend for the period, in currency units. */\n  cost: number;\n  /** 95th percentile latency in milliseconds. */\n  p95: number;\n  /** Failed requests as a fraction, e.g. 0.004 for 0.4%. */\n  errorRate: number;\n}\n\nexport interface ModelUsageMetric {\n  id: string;\n  label: string;\n  value: number;\n  format?: \"number\" | \"compact\" | \"currency\" | \"milliseconds\";\n  /** Fractional change against the previous period. */\n  change?: number;\n  /** Lower is better, e.g. spend or latency. */\n  invert?: boolean;\n  history?: number[];\n  hint?: string;\n}\n\nexport interface ModelUsageData {\n  title: string;\n  period: string;\n  currency?: string;\n  /** Headline figures; the first is lit as the hero. */\n  metrics: ModelUsageMetric[];\n  /** One row per day: an `date` ISO string plus a token count per model id. */\n  usage: Record<string, unknown>[];\n  models: ModelUsageModel[];\n  /** Markers on the usage chart, such as a routing change. */\n  annotations?: StackedAreaAnnotation[];\n  latency: {\n    /** Gateway request latencies in milliseconds. */\n    values: number[];\n    compare?: number[];\n    threshold?: number;\n  };\n  /** A written summary with optional `{{metric:…}}` and `{{cite:n}}` tokens. */\n  summary?: { text: string; sources?: InsightSource[] };\n}\n\nexport interface ModelUsageProps\n  extends Omit<React.ComponentProps<\"section\">, \"title\"> {\n  data: ModelUsageData;\n  actions?: React.ReactNode;\n  locale?: string;\n  /** Regenerate the summary with your own model. */\n  onRegenerateSummary?: () => void;\n  /** Show the summary as it streams in. */\n  summaryStreaming?: boolean;\n}\n\n/** An AI gateway dashboard: requests, tokens and spend by model, latency, and a written summary. */\nexport function ModelUsage({\n  data,\n  actions,\n  locale = \"en-US\",\n  onRegenerateSummary,\n  summaryStreaming = false,\n  className,\n  ...props\n}: ModelUsageProps) {\n  const currency = data.currency ?? \"USD\";\n  const [focused, setFocused] = React.useState<string | null>(null);\n  const formats = React.useMemo(\n    () => ({\n      compact: new Intl.NumberFormat(locale, {\n        notation: \"compact\",\n        maximumFractionDigits: 1,\n      }),\n      number: new Intl.NumberFormat(locale),\n      money: new Intl.NumberFormat(locale, {\n        style: \"currency\",\n        currency,\n        maximumFractionDigits: 0,\n      }),\n      percent: new Intl.NumberFormat(locale, {\n        style: \"percent\",\n        maximumFractionDigits: 2,\n      }),\n      day: new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\" }),\n    }),\n    [currency, locale],\n  );\n  const models = React.useMemo(\n    () => [...data.models].sort((a, b) => b.cost - a.cost),\n    [data.models],\n  );\n  const series = data.models.map((model) => ({\n    key: model.id,\n    label: model.label,\n    color: model.color,\n  }));\n  const hidden = focused\n    ? data.models.filter((model) => model.id !== focused).map((model) => model.id)\n    : [];\n  const maxCost = Math.max(...models.map((model) => model.cost), 1);\n  const totalCost = models.reduce((sum, model) => sum + model.cost, 0);\n\n  return (\n    <section\n      data-slot=\"model-usage\"\n      aria-label={`${data.title}, ${data.period}`}\n      className={cn(\n        \"@container/usage flex min-w-0 flex-col gap-3 text-foreground sm:gap-4\",\n        className,\n      )}\n      {...props}\n    >\n      <header\n        data-slot=\"model-usage-header\"\n        className=\"flex flex-wrap items-end justify-between gap-3\"\n      >\n        <div className=\"min-w-0\">\n          <h2 className=\"truncate text-base font-semibold tracking-tight\">\n            {data.title}\n          </h2>\n          <p className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n            <IconCalendarStats aria-hidden=\"true\" className=\"size-3.5\" />\n            {data.period}\n          </p>\n        </div>\n        {actions && (\n          <div className=\"flex flex-wrap items-center gap-2\">{actions}</div>\n        )}\n      </header>\n\n      <div className=\"grid gap-3 sm:gap-4\">\n        <dl\n          data-slot=\"model-usage-metrics\"\n          className=\"grid grid-cols-1 gap-px overflow-hidden rounded-2xl border border-border/70 bg-border/70 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] @md/usage:grid-cols-2 @4xl/usage:grid-cols-4 dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\"\n        >\n          {data.metrics.map((metric, index) => (\n            <UsageMetric\n              key={metric.id}\n              metric={metric}\n              hero={index === 0}\n              locale={locale}\n              currency={currency}\n            />\n          ))}\n        </dl>\n\n        <StackedAreaChart\n          title=\"Tokens by model\"\n          description={\n            focused\n              ? `Showing ${data.models.find((model) => model.id === focused)?.label} only. Select it again in the table to show every model.`\n              : \"Input and output tokens per day, stacked by model\"\n          }\n          data={data.usage}\n          index=\"date\"\n          series={series}\n          hiddenSeries={hidden}\n          onHiddenSeriesChange={(next) => {\n            const visible = data.models.filter((model) => !next.includes(model.id));\n            setFocused(visible.length === 1 ? visible[0].id : null);\n          }}\n          annotations={data.annotations}\n          height={300}\n          valueFormatter={(value) => formats.compact.format(value)}\n          xFormatter={(value) =>\n            formats.day.format(value instanceof Date ? value : new Date(String(value)))\n          }\n        />\n\n        <div className=\"grid gap-3 sm:gap-4 @4xl/usage:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)]\">\n          {data.summary && (\n            <InsightCard\n              title=\"Usage summary\"\n              source={data.period}\n              icon={<IconSparkles aria-hidden=\"true\" className=\"size-4\" />}\n              text={data.summary.text}\n              sources={data.summary.sources}\n              status={summaryStreaming ? \"streaming\" : \"done\"}\n              onRegenerate={onRegenerateSummary}\n            />\n          )}\n          <LatencyHistogram\n            title=\"Gateway latency\"\n            description=\"Every request in the period, against the previous one\"\n            values={data.latency.values}\n            compare={data.latency.compare}\n            compareLabel=\"Previous\"\n            seriesLabel=\"This period\"\n            threshold={data.latency.threshold}\n            thresholdLabel=\"SLO\"\n          />\n        </div>\n\n        <div\n          data-slot=\"model-usage-table\"\n          className=\"overflow-hidden rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\"\n        >\n          <div className=\"flex flex-wrap items-baseline justify-between gap-2 px-5 pt-5 pb-3\">\n            <div>\n              <h3 className=\"text-sm font-semibold tracking-tight\">Models</h3>\n              <p className=\"text-[13px] leading-5 text-muted-foreground\">\n                Select a model to show it alone on the chart.\n              </p>\n            </div>\n            <p className=\"text-xs text-muted-foreground tabular-nums\">\n              {formats.money.format(totalCost)} across {models.length} models\n            </p>\n          </div>\n          <div className=\"overflow-x-auto\">\n            <table className=\"w-full min-w-[640px] border-collapse text-sm\">\n              <thead>\n                <tr className=\"border-y border-border/60 text-left text-xs text-muted-foreground\">\n                  <th scope=\"col\" className=\"w-[24%] px-5 py-2 font-medium\">Model</th>\n                  <th scope=\"col\" className=\"px-3 py-2 text-right font-medium\">Requests</th>\n                  <th scope=\"col\" className=\"w-[22%] px-3 py-2 font-medium\">Tokens in · out</th>\n                  <th scope=\"col\" className=\"w-[28%] px-3 py-2 font-medium\">Spend</th>\n                  <th scope=\"col\" className=\"px-3 py-2 text-right font-medium\">p95</th>\n                  <th scope=\"col\" className=\"px-5 py-2 text-right font-medium\">Errors</th>\n                </tr>\n              </thead>\n              <tbody>\n                {models.map((model) => {\n                  const index = data.models.indexOf(model);\n                  const color = model.color ?? `var(--color-chart-${(index % 5) + 1})`;\n                  const tokens = model.inputTokens + model.outputTokens;\n                  const active = focused === model.id;\n                  const dimmed = focused !== null && !active;\n                  return (\n                    <tr\n                      key={model.id}\n                      data-slot=\"model-usage-row\"\n                      data-active={active || undefined}\n                      className={cn(\n                        \"border-b border-border/50 transition-opacity duration-150 last:border-b-0\",\n                        dimmed && \"opacity-45\",\n                        active && \"bg-primary/[0.04]\",\n                      )}\n                    >\n                      <th scope=\"row\" className=\"px-5 py-2.5 text-left font-normal\">\n                        <button\n                          type=\"button\"\n                          aria-pressed={active}\n                          onClick={() => setFocused(active ? null : model.id)}\n                          className=\"group flex items-center gap-2.5 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n                        >\n                          <span\n                            aria-hidden=\"true\"\n                            className=\"size-2.5 shrink-0 rounded-[3px] shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_16%,transparent)]\"\n                            style={{ background: color, color }}\n                          />\n                          <span className=\"min-w-0\">\n                            <span className=\"block truncate font-medium group-hover:underline group-hover:underline-offset-4\">\n                              {model.label}\n                            </span>\n                            {model.provider && (\n                              <span className=\"block truncate font-mono text-[11px] text-muted-foreground\">\n                                {model.provider}\n                              </span>\n                            )}\n                          </span>\n                        </button>\n                      </th>\n                      <td className=\"px-3 py-2.5 text-right tabular-nums\">\n                        {formats.compact.format(model.requests)}\n                      </td>\n                      <td className=\"px-3 py-2.5\">\n                        <div className=\"flex items-center gap-2.5\">\n                          <span className=\"w-12 shrink-0 tabular-nums\">\n                            {formats.compact.format(tokens)}\n                          </span>\n                          <span\n                            className=\"flex h-1.5 min-w-16 flex-1 overflow-hidden rounded-full bg-muted\"\n                            role=\"img\"\n                            aria-label={`${formats.compact.format(model.inputTokens)} input, ${formats.compact.format(model.outputTokens)} output`}\n                          >\n                            <span\n                              className=\"h-full\"\n                              style={{\n                                width: `${(model.inputTokens / Math.max(tokens, 1)) * 100}%`,\n                                background: color,\n                              }}\n                            />\n                            <span\n                              className=\"h-full opacity-45\"\n                              style={{ flex: 1, background: color }}\n                            />\n                          </span>\n                        </div>\n                      </td>\n                      <td className=\"px-3 py-2.5\">\n                        <div className=\"flex items-center gap-2.5\">\n                          <span className=\"w-16 shrink-0 tabular-nums\">\n                            {formats.money.format(model.cost)}\n                          </span>\n                          <span className=\"h-1.5 min-w-20 flex-1 overflow-hidden rounded-full bg-muted\">\n                            <span\n                              className=\"block h-full rounded-full\"\n                              style={{\n                                width: `${(model.cost / maxCost) * 100}%`,\n                                background: `linear-gradient(90deg, color-mix(in oklab, ${color} 70%, transparent), ${color})`,\n                              }}\n                            />\n                          </span>\n                          <span className=\"w-12 shrink-0 text-right text-xs text-muted-foreground tabular-nums\">\n                            {formats.percent.format(model.cost / Math.max(totalCost, 1))}\n                          </span>\n                        </div>\n                      </td>\n                      <td className=\"px-3 py-2.5 text-right tabular-nums\">\n                        {formats.number.format(Math.round(model.p95))}\n                        <span className=\"ml-0.5 text-xs text-muted-foreground\">ms</span>\n                      </td>\n                      <td className=\"px-5 py-2.5 text-right tabular-nums\">\n                        <span\n                          className={cn(\n                            \"inline-flex items-center gap-1.5\",\n                            model.errorRate >= 0.01\n                              ? \"text-rose-600 dark:text-rose-400\"\n                              : model.errorRate >= 0.005\n                                ? \"text-amber-700 dark:text-amber-300\"\n                                : \"text-muted-foreground\",\n                          )}\n                        >\n                          {model.errorRate >= 0.005 && (\n                            <span aria-hidden=\"true\" className=\"size-1.5 rounded-full bg-current\" />\n                          )}\n                          {formats.percent.format(model.errorRate)}\n                        </span>\n                      </td>\n                    </tr>\n                  );\n                })}\n              </tbody>\n            </table>\n          </div>\n        </div>\n      </div>\n    </section>\n  );\n}\n\nfunction UsageMetric({\n  metric,\n  hero,\n  locale,\n  currency,\n}: {\n  metric: ModelUsageMetric;\n  hero: boolean;\n  locale: string;\n  currency: string;\n}) {\n  const format = metric.format ?? \"number\";\n  return (\n    <div\n      data-slot=\"model-usage-metric\"\n      data-hero={hero || undefined}\n      className={cn(\n        \"relative flex min-w-0 flex-col gap-3 bg-card p-5\",\n        hero &&\n          \"bg-[radial-gradient(120%_90%_at_0%_0%,color-mix(in_oklab,var(--color-primary)_10%,transparent),transparent_60%)] bg-card\",\n      )}\n    >\n      <div className=\"flex items-center justify-between gap-2\">\n        <dt className=\"truncate text-xs text-muted-foreground\">{metric.label}</dt>\n        {metric.change !== undefined && (\n          <DeltaBadge delta={metric.change} invert={metric.invert} variant=\"soft\" />\n        )}\n      </div>\n      <dd className=\"flex min-w-0 flex-col gap-1\">\n        <NumberTicker\n          value={metric.value}\n          locale={locale}\n          currency={currency}\n          format={format === \"currency\" ? \"currency\" : format === \"compact\" ? \"compact\" : \"number\"}\n          formatOptions={\n            format === \"currency\"\n              ? { style: \"currency\", currency, maximumFractionDigits: 0 }\n              : format === \"compact\"\n                ? { notation: \"compact\", maximumFractionDigits: 1 }\n                : undefined\n          }\n          suffix={\n            format === \"milliseconds\" ? (\n              <span className=\"ml-0.5 text-base font-medium tracking-normal text-muted-foreground\">\n                ms\n              </span>\n            ) : undefined\n          }\n          className={cn(\n            \"font-semibold tracking-[-0.035em] tabular-nums\",\n            hero ? \"text-3xl\" : \"text-2xl\",\n          )}\n        />\n        {metric.hint && (\n          <span className=\"text-xs text-muted-foreground\">{metric.hint}</span>\n        )}\n      </dd>\n      {metric.history && metric.history.length > 1 && (\n        <Sparkline\n          data={metric.history}\n          label={`${metric.label}, recent trend`}\n          className={cn(\n            \"h-10\",\n            metric.change === undefined\n              ? \"text-muted-foreground\"\n              : (metric.change >= 0) !== Boolean(metric.invert)\n                ? \"text-primary\"\n                : \"text-rose-500 dark:text-rose-400\",\n          )}\n          filled\n          endpoint\n        />\n      )}\n    </div>\n  );\n}\n\n/* Sample data --------------------------------------------------------------- */\n\nfunction random(seed: number) {\n  return () => {\n    seed |= 0;\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction logNormal(count: number, median: number, spread: number, seed: number) {\n  const next = random(seed);\n  return Array.from({ length: count }, () => {\n    const u = Math.max(next(), 1e-9);\n    const v = next();\n    const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);\n    return Math.round(median * Math.exp(spread * z));\n  });\n}\n\nconst sampleModels = [\n  // id, label, provider, base daily tokens, $ per million tokens, output share, tokens per request, p95, error rate\n  [\"large\", \"Atlas Large\", \"atlas/large-2026-08\", 26_000_000, 15, 0.32, 3100, 2840, 0.0062],\n  [\"medium\", \"Atlas Medium\", \"atlas/medium-2026-06\", 42_000_000, 3, 0.28, 1900, 1320, 0.0031],\n  [\"small\", \"Atlas Small\", \"atlas/small-2026-09\", 31_000_000, 0.6, 0.24, 1100, 610, 0.0018],\n  [\"embed\", \"Embed v3\", \"atlas/embed-v3\", 54_000_000, 0.1, 0, 420, 140, 0.0004],\n  [\"rerank\", \"Rerank v2\", \"atlas/rerank-v2\", 13_000_000, 1, 0, 680, 210, 0.0011],\n] as const;\n\nfunction buildSampleUsage(): ModelUsageData {\n  const next = random(42);\n  const days = 30;\n  const routedOn = 17; // Summaries move from Large to Small on this day.\n  const usage: Record<string, unknown>[] = [];\n  const totals: Record<string, number> = {};\n  for (let day = 0; day < days; day++) {\n    const date = new Date(Date.UTC(2026, 8, 13 + day));\n    const weekday = date.getUTCDay();\n    const weekend = weekday === 0 || weekday === 6 ? 0.58 : 1;\n    const growth = 1 + day * 0.012;\n    const row: Record<string, unknown> = { date: date.toISOString().slice(0, 10) };\n    for (const [id, , , base] of sampleModels) {\n      let value = base * weekend * growth * (0.9 + next() * 0.2);\n      if (id === \"large\" && day >= routedOn) value *= 0.46;\n      if (id === \"small\" && day >= routedOn) value *= 1.55;\n      row[id] = Math.round(value);\n      totals[id] = (totals[id] ?? 0) + Math.round(value);\n    }\n    usage.push(row);\n  }\n  const models: ModelUsageModel[] = sampleModels.map(\n    ([id, label, provider, , price, outputShare, perRequest, p95, errorRate]) => {\n      const tokens = totals[id];\n      return {\n        id,\n        label,\n        provider,\n        requests: Math.round(tokens / perRequest),\n        inputTokens: Math.round(tokens * (1 - outputShare)),\n        outputTokens: Math.round(tokens * outputShare),\n        cost: Math.round((tokens / 1_000_000) * price),\n        p95,\n        errorRate,\n      };\n    },\n  );\n  const sum = (pick: (model: ModelUsageModel) => number) =>\n    models.reduce((total, model) => total + pick(model), 0);\n  const dailyTotals = usage.map((row) =>\n    sampleModels.reduce((total, [id]) => total + Number(row[id]), 0),\n  );\n  const weekly = (values: number[]) =>\n    Array.from({ length: Math.ceil(values.length / 3) }, (_, index) =>\n      values.slice(index * 3, index * 3 + 3).reduce((a, b) => a + b, 0),\n    );\n  const dailyCost = usage.map((row) =>\n    sampleModels.reduce(\n      (total, [id, , , , price]) => total + (Number(row[id]) / 1_000_000) * price,\n      0,\n    ),\n  );\n  const latency = [\n    ...logNormal(2600, 420, 0.7, 7),\n    ...logNormal(600, 1900, 0.35, 9),\n  ];\n  return {\n    title: \"AI gateway\",\n    period: \"Sep 13 – Oct 12, 2026\",\n    currency: \"USD\",\n    metrics: [\n      {\n        id: \"requests\",\n        label: \"Requests\",\n        value: sum((model) => model.requests),\n        format: \"compact\",\n        change: 0.214,\n        hint: \"Across five models\",\n        history: weekly(dailyTotals.map((tokens) => tokens / 1500)),\n      },\n      {\n        id: \"tokens\",\n        label: \"Tokens\",\n        value: sum((model) => model.inputTokens + model.outputTokens),\n        format: \"compact\",\n        change: 0.187,\n        hint: \"Input and output\",\n        history: weekly(dailyTotals),\n      },\n      {\n        id: \"spend\",\n        label: \"Spend\",\n        value: sum((model) => model.cost),\n        format: \"currency\",\n        change: -0.082,\n        invert: true,\n        hint: \"After routing summaries to Atlas Small\",\n        history: weekly(dailyCost),\n      },\n      {\n        id: \"p95\",\n        label: \"p95 latency\",\n        value: 1640,\n        format: \"milliseconds\",\n        change: -0.126,\n        invert: true,\n        hint: \"Gateway, end to end\",\n        history: [2010, 1980, 1940, 1890, 1860, 1720, 1690, 1660, 1650, 1640],\n      },\n    ],\n    usage,\n    models,\n    annotations: [\n      { x: usage[routedOn].date as string, label: \"Summaries routed to Atlas Small\" },\n    ],\n    latency: {\n      values: latency,\n      compare: [...logNormal(2600, 470, 0.72, 11), ...logNormal(700, 2300, 0.35, 13)],\n      threshold: 2500,\n    },\n    summary: {\n      text: \"Spend fell {{metric:Spend|-8.2%|positive}} while requests grew {{metric:Requests|+21.4%|neutral}}, because summaries moved from Atlas Large to Atlas Small on Sep 30 {{cite:1}}. Atlas Small now handles a third of all generation traffic at {{metric:p95|610 ms|positive}} {{cite:2}}. Atlas Large still has the highest error rate, mostly timeouts on long contexts {{cite:3}}; capping its context at 64K tokens would remove most of them.\",\n      sources: [\n        { id: \"1\", label: \"Routing rule summaries-v4\" },\n        { id: \"2\", label: \"Gateway latency\" },\n        { id: \"3\", label: \"Error log, Atlas Large\" },\n      ],\n    },\n  };\n}\n\n/** Fictional AI gateway usage for Acme Studio, for demos and tests. */\nexport const sampleModelUsage: ModelUsageData = buildSampleUsage();\n"
    },
    {
      "path": "src/registry/overtrue/number-ticker.tsx",
      "type": "registry:component",
      "target": "components/overtrue/number-ticker.tsx",
      "content": "\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type NumberTickerFormat = \"number\" | \"currency\" | \"percent\" | \"compact\";\n\nexport interface NumberTickerProps extends Omit<\n  ComponentProps<\"span\">,\n  \"children\" | \"prefix\"\n> {\n  value: number;\n  /** Preset Intl options. Percent expects a fraction: 0.124 renders 12.4%. */\n  format?: NumberTickerFormat;\n  /** Merged over the preset, e.g. `{ maximumFractionDigits: 0 }`. */\n  formatOptions?: Intl.NumberFormatOptions;\n  locale?: string;\n  /** ISO 4217 code used by the currency preset. */\n  currency?: string;\n  prefix?: ReactNode;\n  suffix?: ReactNode;\n  /** Roll duration in milliseconds. */\n  duration?: number;\n  /** Tint the number briefly: emerald when it rises, red when it falls. */\n  highlightChanges?: boolean;\n  /** Roll up from zero on first mount instead of rendering the value directly. */\n  animateOnMount?: boolean;\n}\n\n// Each column is a wheel of five 0–9 runs. It rests in the middle run, so two\n// rapid changes in either direction can always roll forward or backward.\nconst CELLS = 50;\nconst REST = 20;\nconst STAGGER = 32;\nconst MAX_STAGGER = 224;\nconst SLIDE_EASE = \"cubic-bezier(0.2, 1, 0.32, 1)\";\n// Overshoot scales with distance, so longer rolls get a gentler curve: every\n// wheel settles past its digit by about a tenth of a cell, whatever it travelled.\nconst SETTLE = [1.534, 1.368, 1.3, 1.262, 1.236, 1.217, 1.203, 1.191, 1.181];\nconst rollEase = (cells: number) =>\n  `cubic-bezier(0.2, ${SETTLE[Math.min(Math.max(Math.abs(cells), 1), 9) - 1]}, 0.32, 1)`;\nconst SIZE_EASE = \"cubic-bezier(0.32, 0.72, 0, 1)\";\nconst REDUCED_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeReducedMotion(callback: () => void) {\n  const query = window.matchMedia(REDUCED_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReducedMotion,\n    () => window.matchMedia(REDUCED_QUERY).matches,\n    () => false,\n  );\n}\n\nconst presets: Record<\n  NumberTickerFormat,\n  (currency: string) => Intl.NumberFormatOptions\n> = {\n  number: () => ({}),\n  currency: (currency) => ({ style: \"currency\", currency }),\n  percent: () => ({\n    style: \"percent\",\n    minimumFractionDigits: 1,\n    maximumFractionDigits: 1,\n  }),\n  compact: () => ({ notation: \"compact\", maximumSignificantDigits: 3 }),\n};\n\ninterface TickerFormatter {\n  format: Intl.NumberFormat;\n  /** The locale's digit glyphs, so Arabic-Indic or Devanagari numerals roll too. */\n  glyphs: string[];\n  /** One padded cell per wheel position, created once and shared by every column. */\n  cells: ReactNode[];\n}\n\nconst formatterCache = new Map<string, TickerFormatter>();\n\nfunction resolveOptions(\n  format: NumberTickerFormat,\n  currency: string,\n  overrides: Intl.NumberFormatOptions | undefined,\n): Intl.NumberFormatOptions {\n  const options = { ...presets[format](currency), ...overrides };\n  // Keep a preset's fixed precision from conflicting with a partial override.\n  const { minimumFractionDigits: min, maximumFractionDigits: max } = options;\n  if (min !== undefined && max !== undefined && min > max) {\n    if (overrides?.maximumFractionDigits !== undefined)\n      options.minimumFractionDigits = max;\n    else options.maximumFractionDigits = min;\n  }\n  return options;\n}\n\nfunction getFormatter(\n  locale: string,\n  options: Intl.NumberFormatOptions,\n): TickerFormatter {\n  const key = `${locale}|${JSON.stringify(options)}`;\n  let entry = formatterCache.get(key);\n  if (!entry) {\n    let format: Intl.NumberFormat;\n    try {\n      format = new Intl.NumberFormat(locale, options);\n    } catch {\n      format = new Intl.NumberFormat(\"en-US\");\n    }\n    const digits = new Intl.NumberFormat(format.resolvedOptions().locale, {\n      useGrouping: false,\n      numberingSystem: format.resolvedOptions().numberingSystem,\n    } as Intl.NumberFormatOptions);\n    const glyphs = Array.from({ length: 10 }, (_, digit) =>\n      digits.format(digit),\n    );\n    const cells = Array.from({ length: CELLS }, (_, cell) => (\n      <span key={cell} className=\"block py-(--ticker-gap)\">\n        {glyphs[cell % 10]}\n      </span>\n    ));\n    entry = { format, glyphs, cells };\n    formatterCache.set(key, entry);\n  }\n  return entry;\n}\n\ntype Slot =\n  | { key: string; kind: \"digit\"; digit: number; order: number }\n  | { key: string; kind: \"char\"; char: string };\n\ntype Item = Slot & { phase: \"idle\" | \"enter\" | \"exit\" };\n\n/**\n * Split a formatted number into keyed slots. Integer digits are keyed by place\n * value and fraction digits by position, so the ones column stays the ones\n * column when 999 becomes 1,000 and only the new leading columns enter.\n */\nfunction toSlots(value: number, formatter: TickerFormatter) {\n  if (!Number.isFinite(value)) {\n    return {\n      text: \"—\",\n      slots: [{ key: \"missing\", kind: \"char\", char: \"—\" }] as Slot[],\n    };\n  }\n  const parts = formatter.format.formatToParts(value);\n  const isDigit = (char: string) => formatter.glyphs.includes(char);\n  let integerDigits = 0;\n  for (const part of parts)\n    if (part.type === \"integer\")\n      for (const char of part.value) if (isDigit(char)) integerDigits++;\n\n  const slots: Slot[] = [];\n  const seen = new Map<string, number>();\n  let integerIndex = 0;\n  let fractionIndex = 0;\n  const pushChar = (type: string, char: string) => {\n    const count = seen.get(type) ?? 0;\n    seen.set(type, count + 1);\n    slots.push({ key: `${type}${count}:${char}`, kind: \"char\", char });\n  };\n  for (const part of parts) {\n    if (part.type === \"integer\" || part.type === \"fraction\") {\n      for (const char of part.value) {\n        const digit = formatter.glyphs.indexOf(char);\n        if (digit < 0) pushChar(part.type, char);\n        else if (part.type === \"integer\")\n          slots.push({\n            key: `i${integerDigits - 1 - integerIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n        else\n          slots.push({\n            key: `f${fractionIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n      }\n    } else if (part.type === \"group\") {\n      slots.push({\n        key: `g${integerDigits - integerIndex}:${part.value}`,\n        kind: \"char\",\n        char: part.value,\n      });\n    } else {\n      pushChar(part.type, part.value);\n    }\n  }\n  // Stagger from the rightmost digit outward, like a carry moving left.\n  let order = 0;\n  for (let i = slots.length - 1; i >= 0; i--) {\n    const slot = slots[i];\n    if (slot.kind === \"digit\") slots[i] = { ...slot, order: order++ };\n  }\n  return { text: parts.map((part) => part.value).join(\"\"), slots };\n}\n\n/** Keep removed slots in place for one transition so they can collapse out. */\nfunction mergeSlots(previous: Item[], next: Slot[], animate: boolean): Item[] {\n  const previousKeys = new Set(previous.map((item) => item.key));\n  const live: Item[] = next.map((slot) => ({\n    ...slot,\n    phase: animate && !previousKeys.has(slot.key) ? \"enter\" : \"idle\",\n  }));\n  if (!animate) return live;\n  const nextKeys = new Set(next.map((slot) => slot.key));\n  const leadingExits = new Map<string, Item[]>();\n  let pending: Item[] = [];\n  for (const item of previous) {\n    if (nextKeys.has(item.key)) {\n      if (pending.length) leadingExits.set(item.key, pending);\n      pending = [];\n    } else if (item.phase !== \"exit\") {\n      pending.push({ ...item, phase: \"exit\" });\n    }\n  }\n  const merged: Item[] = [];\n  for (const item of live) {\n    const exits = leadingExits.get(item.key);\n    if (exits) merged.push(...exits);\n    merged.push(item);\n  }\n  return merged.concat(pending);\n}\n\nfunction zeroed(slots: Slot[]): Slot[] {\n  return slots.map((slot) =>\n    slot.kind === \"digit\" ? { ...slot, digit: 0 } : slot,\n  );\n}\n\ninterface TickerState {\n  signature: string;\n  value: number;\n  items: Item[];\n  direction: number;\n  flash: \"up\" | \"down\" | null;\n  version: number;\n}\n\n/** An odometer-style number: each digit rolls on its own wheel when `value` changes. */\nexport function NumberTicker({\n  value,\n  format = \"number\",\n  formatOptions,\n  locale = \"en-US\",\n  currency = \"USD\",\n  prefix,\n  suffix,\n  duration = 800,\n  highlightChanges = false,\n  animateOnMount = false,\n  className,\n  ...props\n}: NumberTickerProps) {\n  const reduced = usePrefersReducedMotion();\n  const optionsKey = JSON.stringify(formatOptions ?? null);\n  const formatter = useMemo(\n    () => getFormatter(locale, resolveOptions(format, currency, formatOptions)),\n    // formatOptions is compared by content so inline objects stay cheap.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [locale, format, currency, optionsKey],\n  );\n  const { text, slots } = useMemo(\n    () => toSlots(value, formatter),\n    [value, formatter],\n  );\n\n  const [armed, setArmed] = useState(!animateOnMount);\n  const shown = armed ? slots : zeroed(slots);\n  const signature = (armed ? \"\" : \"0|\") + shown.map(slotKey).join(\"|\");\n  const shownValue = armed ? value : 0;\n\n  const [state, setState] = useState<TickerState>(() => ({\n    signature,\n    value: shownValue,\n    items: shown.map((slot) => ({ ...slot, phase: \"idle\" })),\n    direction: 0,\n    flash: null,\n    version: 0,\n  }));\n  if (state.signature !== signature) {\n    const direction = Math.sign(shownValue - state.value);\n    // The first roll up from zero is an entrance, not a change worth tinting.\n    const entrance = state.signature.startsWith(\"0|\");\n    setState({\n      signature,\n      value: shownValue,\n      items: mergeSlots(state.items, shown, !reduced),\n      direction,\n      flash:\n        highlightChanges && !entrance && direction !== 0\n          ? direction > 0\n            ? \"up\"\n            : \"down\"\n          : null,\n      version: state.version + 1,\n    });\n  }\n\n  // Roll up from zero after the first paint (or settle at once without motion).\n  useLayoutEffect(() => {\n    if (armed) return;\n    if (reduced) {\n      setArmed(true);\n      return;\n    }\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setArmed(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [armed, reduced]);\n\n  // Drop collapsed slots and fade the tint once the roll has settled.\n  const { version } = state;\n  const hasExits = state.items.some((item) => item.phase === \"exit\");\n  useEffect(() => {\n    if (!hasExits) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version\n            ? {\n                ...current,\n                items: current.items.filter((item) => item.phase !== \"exit\"),\n              }\n            : current,\n        ),\n      duration + MAX_STAGGER,\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, hasExits, duration]);\n  const flashing = state.flash !== null;\n  useEffect(() => {\n    if (!flashing) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version ? { ...current, flash: null } : current,\n        ),\n      Math.max(360, duration * 0.75),\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, flashing, duration]);\n\n  const animate = !reduced;\n  return (\n    <span\n      data-slot=\"number-ticker\"\n      data-direction={\n        state.direction > 0 ? \"up\" : state.direction < 0 ? \"down\" : undefined\n      }\n      className={cn(\"inline-block whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      {prefix}\n      <span className=\"sr-only\">{text}</span>\n      {/* Digits always run left to right, even inside right-to-left text. */}\n      <span\n        aria-hidden=\"true\"\n        dir=\"ltr\"\n        data-slot=\"number-ticker-value\"\n        className={cn(\n          \"transition-colors motion-reduce:transition-none\",\n          state.flash === \"up\" && \"text-emerald-700 dark:text-emerald-400\",\n          state.flash === \"down\" && \"text-red-600 dark:text-red-400\",\n        )}\n        style={{ transitionDuration: state.flash ? \"140ms\" : \"900ms\" }}\n      >\n        {state.items.map((item) => (\n          <TickerSlot\n            key={item.key}\n            item={item}\n            direction={state.direction}\n            formatter={formatter}\n            duration={duration}\n            animate={animate}\n          />\n        ))}\n      </span>\n      {suffix}\n    </span>\n  );\n}\n\nfunction slotKey(slot: Slot) {\n  return slot.kind === \"digit\" ? `${slot.key}=${slot.digit}` : slot.key;\n}\n\nfunction TickerSlot({\n  item,\n  direction,\n  formatter,\n  duration,\n  animate,\n}: {\n  item: Item;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  animate: boolean;\n}) {\n  // New slots mount collapsed, then open on the next frame so the change transitions.\n  const [open, setOpen] = useState(item.phase !== \"enter\" || !animate);\n  useEffect(() => {\n    if (open) return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setOpen(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [open]);\n\n  const collapsed = !open || item.phase === \"exit\";\n  const travel = direction < 0 ? -1 : 1;\n  const offset = item.phase === \"exit\" ? -travel : travel;\n  const delay =\n    item.kind === \"digit\" ? Math.min(item.order * STAGGER, MAX_STAGGER) : 0;\n  const style: CSSProperties = {\n    gridTemplateColumns: collapsed ? \"0fr\" : \"1fr\",\n    opacity: collapsed ? 0 : 1,\n    transform: collapsed ? `translateY(${offset * 0.42}em)` : undefined,\n    transition: animate\n      ? `grid-template-columns ${duration * 0.7}ms ${SIZE_EASE}, opacity ${duration * 0.5}ms ease, transform ${duration}ms ${SLIDE_EASE}`\n      : \"none\",\n  };\n  return (\n    <span className=\"inline-grid\" style={style} data-phase={item.phase}>\n      <span className=\"min-w-0 [clip-path:inset(-50%_0)]\">\n        {item.kind === \"digit\" ? (\n          <DigitWheel\n            digit={item.digit}\n            direction={direction}\n            formatter={formatter}\n            duration={duration}\n            delay={delay}\n            animate={animate}\n          />\n        ) : (\n          <span className=\"whitespace-pre\">{item.char}</span>\n        )}\n      </span>\n    </span>\n  );\n}\n\nfunction DigitWheel({\n  digit,\n  direction,\n  formatter,\n  duration,\n  delay,\n  animate,\n}: {\n  digit: number;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  delay: number;\n  animate: boolean;\n}) {\n  const [wheel, setWheel] = useState({\n    digit,\n    cell: REST + digit,\n    travel: 0,\n    rolling: false,\n  });\n  if (wheel.digit !== digit) {\n    // Roll forward when the value rises and backward when it falls, wrapping\n    // through 9 → 0 the way a mechanical counter carries.\n    const forward = (digit - wheel.digit + 10) % 10;\n    const backward = (wheel.digit - digit + 10) % 10;\n    const step =\n      direction > 0\n        ? forward\n        : direction < 0\n          ? -backward\n          : forward <= backward\n            ? forward\n            : -backward;\n    let cell = wheel.cell + step;\n    if (cell < 0 || cell >= CELLS) cell = REST + digit;\n    setWheel(\n      animate\n        ? { digit, cell, travel: cell - wheel.cell, rolling: true }\n        : { digit, cell: REST + digit, travel: 0, rolling: false },\n    );\n  }\n\n  // Once settled, jump back to the matching cell in the middle run (same glyph).\n  useEffect(() => {\n    if (!wheel.rolling) return;\n    const timer = window.setTimeout(\n      () =>\n        setWheel((current) => ({\n          digit: current.digit,\n          cell: REST + current.digit,\n          travel: 0,\n          rolling: false,\n        })),\n      duration + delay + 40,\n    );\n    return () => window.clearTimeout(timer);\n  }, [wheel, duration, delay]);\n\n  // Cells carry --ticker-gap of padding above and below, and the clipping window\n  // reaches that far past the line box. At rest only padding shows in the\n  // overhang; while rolling, neighbors fade through it like a real wheel.\n  return (\n    <span className=\"relative inline-block [--ticker-gap:0.2em]\">\n      <span className=\"invisible\">{formatter.glyphs[digit]}</span>\n      <span className=\"absolute inset-x-0 -inset-y-(--ticker-gap) overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,#000_var(--ticker-gap),#000_calc(100%_-_var(--ticker-gap)),transparent)]\">\n        <span\n          className=\"absolute inset-x-0 top-0 flex flex-col text-center\"\n          style={{\n            transform: `translateY(${(-wheel.cell * 100) / CELLS}%)`,\n            transition: wheel.rolling\n              ? `transform ${duration}ms ${rollEase(wheel.travel)} ${delay}ms`\n              : \"none\",\n            willChange: wheel.rolling ? \"transform\" : undefined,\n          }}\n        >\n          {formatter.cells}\n        </span>\n      </span>\n    </span>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/sparkline.tsx",
      "type": "registry:component",
      "target": "components/overtrue/sparkline.tsx",
      "content": "\"use client\";\nimport { useId, type CSSProperties } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SparklineProps {\n  data: number[];\n  label: string;\n  className?: string;\n  filled?: boolean;\n  /** Mark the most recent value. */\n  endpoint?: boolean;\n  /** Any CSS color. Defaults to the current text color, which is primary. */\n  color?: string;\n  /** Draw the line in and raise the area when the sparkline mounts. Skipped under reduced motion. */\n  animate?: boolean;\n}\n\nconst WIDTH = 240;\nconst HEIGHT = 48;\nconst PAD_X = 3;\nconst PAD_Y = 5;\nconst EASE = \"ease-[cubic-bezier(0.22,1,0.36,1)]\";\n\n/** Monotone cubic path: smooth, but never overshoots the data. */\nfunction monotonePath(points: [number, number][]) {\n  const n = points.length;\n  if (n < 2) return \"\";\n  const dx: number[] = [];\n  const slope: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    dx.push(points[i + 1][0] - points[i][0]);\n    slope.push((points[i + 1][1] - points[i][1]) / dx[i]);\n  }\n  const tangent = [slope[0]];\n  for (let i = 1; i < n - 1; i++) {\n    tangent.push(\n      slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2,\n    );\n  }\n  tangent.push(slope[n - 2]);\n  for (let i = 0; i < n - 1; i++) {\n    if (slope[i] === 0) {\n      tangent[i] = tangent[i + 1] = 0;\n      continue;\n    }\n    const a = tangent[i] / slope[i];\n    const b = tangent[i + 1] / slope[i];\n    const h = a * a + b * b;\n    if (h > 9) {\n      const t = 3 / Math.sqrt(h);\n      tangent[i] = t * a * slope[i];\n      tangent[i + 1] = t * b * slope[i];\n    }\n  }\n  const r = (value: number) => Math.round(value * 100) / 100;\n  let d = `M${r(points[0][0])},${r(points[0][1])}`;\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] / 3;\n    d += `C${r(x0 + h)},${r(y0 + tangent[i] * h)} ${r(x1 - h)},${r(y1 - tangent[i + 1] * h)} ${r(x1)},${r(y1)}`;\n  }\n  return d;\n}\n\n/** A compact overview. Use a full chart when individual values need inspection. */\nexport function Sparkline({\n  data,\n  label,\n  className,\n  filled = true,\n  endpoint = true,\n  color,\n  animate = true,\n}: SparklineProps) {\n  const gradient = `sparkline-${useId().replace(/:/g, \"\")}`;\n  const values = data.filter(Number.isFinite);\n  let low = Infinity,\n    high = -Infinity;\n  for (const value of values) {\n    low = Math.min(low, value);\n    high = Math.max(high, value);\n  }\n  const points = values.map((value, i): [number, number] => [\n    values.length > 1\n      ? PAD_X + (i / (values.length - 1)) * (WIDTH - PAD_X * 2)\n      : WIDTH / 2,\n    high === low\n      ? HEIGHT / 2\n      : HEIGHT - PAD_Y - ((value - low) / (high - low)) * (HEIGHT - PAD_Y * 2),\n  ]);\n  const line = monotonePath(points);\n  const last = points[points.length - 1];\n  const lastValue = values[values.length - 1];\n  const motion = animate ? \"motion-reduce:transition-none\" : \"transition-none\";\n  return (\n    <div\n      data-slot=\"sparkline\"\n      role=\"img\"\n      aria-label={`${label}: ${values.length ? values.join(\", \") : \"No data\"}`}\n      className={cn(\"relative h-12 w-full text-primary\", className)}\n      style={color ? { color } : undefined}\n    >\n      {values.length > 1 && filled && (\n        <svg\n          viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n          preserveAspectRatio=\"none\"\n          aria-hidden=\"true\"\n          data-slot=\"sparkline-area\"\n          className={cn(\n            \"absolute inset-0 size-full origin-bottom overflow-visible transition-[opacity,scale] delay-75 duration-700\",\n            EASE,\n            animate && \"starting:scale-y-0 starting:opacity-0\",\n            motion,\n          )}\n        >\n          <defs>\n            <linearGradient id={gradient} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n              <stop offset=\"0%\" stopColor=\"currentColor\" stopOpacity=\"0.28\" />\n              <stop offset=\"100%\" stopColor=\"currentColor\" stopOpacity=\"0\" />\n            </linearGradient>\n          </defs>\n          <path\n            d={`${line}L${last[0]},${HEIGHT}L${points[0][0]},${HEIGHT}Z`}\n            fill={`url(#${gradient})`}\n            className={cn(\"transition-[d] duration-500\", EASE, motion)}\n          />\n        </svg>\n      )}\n      <svg\n        viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n        preserveAspectRatio=\"none\"\n        aria-hidden=\"true\"\n        data-slot=\"sparkline-line\"\n        className={cn(\n          // The line wipes in from the left; the inset leaves room for its glow.\n          \"absolute inset-0 size-full overflow-visible [clip-path:inset(-60%_-8%_-60%_-8%)] transition-[clip-path] duration-700\",\n          EASE,\n          animate &&\n            values.length > 1 &&\n            \"starting:[clip-path:inset(-60%_100%_-60%_-8%)]\",\n          motion,\n        )}\n      >\n        {values.length > 1 ? (\n          <path\n            d={line}\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinejoin=\"round\"\n            strokeLinecap=\"round\"\n            vectorEffect=\"non-scaling-stroke\"\n            className={cn(\n              \"transition-[d] duration-500 dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,currentColor_50%,transparent))]\",\n              EASE,\n              motion,\n            )}\n          />\n        ) : values.length === 0 ? (\n          <path\n            d={`M${PAD_X} ${HEIGHT / 2}H${WIDTH - PAD_X}`}\n            stroke=\"currentColor\"\n            strokeDasharray=\"2 5\"\n            strokeLinecap=\"round\"\n            opacity=\"0.3\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        ) : null}\n      </svg>\n      {/* Drawn in HTML so the marker stays round when the line stretches. */}\n      {endpoint && last && (\n        <span\n          aria-hidden=\"true\"\n          data-slot=\"sparkline-endpoint\"\n          className={cn(\n            // Moves with the line, and on mount appears once the line has drawn in.\n            \"absolute -translate-x-1/2 -translate-y-1/2 [transition:left_500ms_cubic-bezier(0.22,1,0.36,1),top_500ms_cubic-bezier(0.22,1,0.36,1),opacity_300ms_ease-out_550ms,scale_500ms_cubic-bezier(0.22,1,0.36,1)_550ms]\",\n            animate && \"starting:scale-0 starting:opacity-0\",\n            motion,\n          )}\n          style={\n            {\n              left: `${(last[0] / WIDTH) * 100}%`,\n              top: `${(last[1] / HEIGHT) * 100}%`,\n            } as CSSProperties\n          }\n        >\n          {/* Pulses once whenever the latest value changes. */}\n          <span\n            key={lastValue}\n            className={cn(\n              \"absolute inset-0 scale-[3.2] rounded-full bg-current opacity-0 transition-[opacity,scale] duration-1000 ease-out starting:scale-100 starting:opacity-40 motion-reduce:hidden\",\n              !animate && \"hidden\",\n            )}\n          />\n          <span className=\"relative block size-2 rounded-full border-[1.5px] border-card bg-current shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_18%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_24%,transparent),0_0_12px_1px_color-mix(in_oklab,currentColor_70%,transparent)]\" />\n        </span>\n      )}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/delta-badge.tsx",
      "type": "registry:component",
      "target": "components/overtrue/delta-badge.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\nimport * as React from \"react\";\nimport {\n  IconArrowDownRight as ArrowDownRight,\n  IconArrowUpRight as ArrowUpRight,\n  IconMinus as Minus,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { formatDelta } from \"./metric-format\";\n\nexport type DeltaDirection = \"up\" | \"down\" | \"flat\";\n\nexport function getDeltaDirection(delta: number | undefined): DeltaDirection {\n  if (delta === undefined || delta === 0 || !Number.isFinite(delta))\n    return \"flat\";\n  return delta > 0 ? \"up\" : \"down\";\n}\n\nconst directionIcon: Record<DeltaDirection, React.ElementType> = {\n  up: ArrowUpRight,\n  down: ArrowDownRight,\n  flat: Minus,\n};\n\ntype Tone = \"positive\" | \"negative\" | \"neutral\";\n\nconst toneText: Record<Tone, string> = {\n  positive: \"text-emerald-700 dark:text-emerald-400\",\n  negative: \"text-rose-700 dark:text-rose-400\",\n  neutral: \"text-muted-foreground\",\n};\n\nconst toneSoft: Record<Tone, string> = {\n  positive: \"bg-emerald-500/10 dark:bg-emerald-400/10\",\n  negative: \"bg-rose-500/10 dark:bg-rose-400/10\",\n  neutral: \"bg-muted dark:bg-muted/70\",\n};\n\nconst toneOutline: Record<Tone, string> = {\n  positive:\n    \"bg-emerald-500/[0.06] ring-emerald-600/20 dark:bg-emerald-400/[0.07] dark:ring-emerald-400/25\",\n  negative:\n    \"bg-rose-500/[0.06] ring-rose-600/20 dark:bg-rose-400/[0.07] dark:ring-rose-400/25\",\n  neutral: \"bg-muted/40 ring-border\",\n};\n\nexport interface DeltaBadgeProps extends React.ComponentProps<\"span\"> {\n  /** Fractional change, e.g. 0.124 for +12.4%. */\n  delta: number;\n  /** Treat a decrease as good and an increase as bad (churn, latency, errors). */\n  invert?: boolean;\n  variant?: \"outline\" | \"soft\" | \"text\";\n  showIcon?: boolean;\n}\n\n/** A change chip: the arrow shows direction, the color shows whether it helps. */\nfunction DeltaBadge({\n  delta,\n  invert = false,\n  variant = \"outline\",\n  showIcon = true,\n  className,\n  children,\n  ...props\n}: DeltaBadgeProps) {\n  const direction = getDeltaDirection(delta);\n  const positive =\n    direction === \"flat\" ? null : (direction === \"up\") !== invert;\n  const tone: Tone =\n    positive === true\n      ? \"positive\"\n      : positive === false\n        ? \"negative\"\n        : \"neutral\";\n  const Icon = directionIcon[direction];\n  const pill = variant !== \"text\";\n\n  return (\n    <span\n      data-slot=\"delta-badge\"\n      data-direction={direction}\n      data-positive={positive}\n      data-variant={variant}\n      className={cn(\n        \"inline-flex shrink-0 items-center gap-0.5 text-xs leading-none font-medium tracking-[-0.01em] whitespace-nowrap tabular-nums\",\n        pill && \"h-5 rounded-full\",\n        pill && (showIcon ? \"pr-1.5 pl-1\" : \"px-1.5\"),\n        variant === \"outline\" && [\"ring-1 ring-inset\", toneOutline[tone]],\n        variant === \"soft\" && toneSoft[tone],\n        toneText[tone],\n        className,\n      )}\n      {...props}\n    >\n      {showIcon ? (\n        <Icon\n          data-slot=\"delta-badge-icon\"\n          className=\"size-3 shrink-0\"\n          stroke={2.5}\n          aria-hidden=\"true\"\n        />\n      ) : null}\n      {children ?? formatDelta(delta)}\n    </span>\n  );\n}\n\nexport { DeltaBadge };\n"
    },
    {
      "path": "src/registry/overtrue/metric-format.tsx",
      "type": "registry:component",
      "target": "components/overtrue/metric-format.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\nexport type NumberFormat = \"number\" | \"compact\" | \"currency\" | \"percent\";\n\nexport interface FormatNumberOptions {\n  format?: NumberFormat;\n  /** ISO 4217 code, used when format is \"currency\". Defaults to USD. */\n  currency?: string;\n  locale?: string;\n  maximumFractionDigits?: number;\n  /** Abbreviate large values, e.g. \"$158K\" instead of \"$158,143\". */\n  compact?: boolean;\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getFormatter(locale: string, options: Intl.NumberFormatOptions) {\n  const key = locale + JSON.stringify(options);\n  let formatter = formatterCache.get(key);\n  if (!formatter) {\n    formatter = new Intl.NumberFormat(locale, options);\n    formatterCache.set(key, formatter);\n  }\n  return formatter;\n}\n\n/**\n * Format a metric value for display.\n *\n * formatNumber(1234567)                          -> \"1,234,567\"\n * formatNumber(1234567, { format: \"compact\" })   -> \"1.2M\"\n * formatNumber(48.2, { format: \"currency\" })     -> \"$48.20\"\n * formatNumber(158143, { format: \"currency\", compact: true }) -> \"$158K\"\n * formatNumber(0.124, { format: \"percent\" })     -> \"12.4%\"\n */\nexport function formatNumber(\n  value: number,\n  {\n    format = \"number\",\n    currency = \"USD\",\n    locale = \"en-US\",\n    maximumFractionDigits,\n    compact = false,\n  }: FormatNumberOptions = {},\n): string {\n  if (!Number.isFinite(value)) return \"—\";\n\n  // Compact values keep three significant digits: $158K, $1.23M, 41.2K.\n  const compactOptions: Intl.NumberFormatOptions = compact\n    ? maximumFractionDigits === undefined\n      ? { notation: \"compact\", maximumSignificantDigits: 3 }\n      : { notation: \"compact\", maximumFractionDigits }\n    : {};\n  switch (format) {\n    case \"compact\":\n      return getFormatter(locale, {\n        notation: \"compact\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value);\n    case \"currency\":\n      return getFormatter(locale, {\n        style: \"currency\",\n        currency,\n        maximumFractionDigits: maximumFractionDigits ?? 2,\n        ...compactOptions,\n      }).format(value);\n    case \"percent\":\n      return getFormatter(locale, {\n        style: \"percent\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value);\n    default:\n      return getFormatter(locale, {\n        maximumFractionDigits: maximumFractionDigits ?? 0,\n        ...compactOptions,\n      }).format(value);\n  }\n}\n\n/**\n * Format a fractional change as a signed percentage.\n *\n * formatDelta(0.124)  -> \"+12.4%\"\n * formatDelta(-0.03)  -> \"-3.0%\"\n * formatDelta(0)      -> \"0.0%\"\n */\nexport function formatDelta(delta: number, locale = \"en-US\"): string {\n  if (!Number.isFinite(delta)) return \"—\";\n  return getFormatter(locale, {\n    style: \"percent\",\n    signDisplay: \"exceptZero\",\n    maximumFractionDigits: 1,\n    minimumFractionDigits: 1,\n  }).format(delta);\n}\n\n/**\n * Fractional change between two values. Returns 0 when there is no baseline.\n */\nexport function computeDelta(current: number, previous: number): number {\n  if (!previous) return 0;\n  return (current - previous) / Math.abs(previous);\n}\n"
    },
    {
      "path": "src/registry/overtrue/stacked-area-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/stacked-area-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\n/** How the series combine: stacked, normalised to 100%, centered as a streamgraph, or overlapping. */\nexport type StackedAreaStack = \"normal\" | \"expand\" | \"stream\" | \"none\";\nexport type StackedAreaCurve = \"monotone\" | \"linear\" | \"step\";\n/** An x value as it appears in the data: a number, an ISO date string, a Date, or a category label. */\nexport type StackedAreaXValue = string | number | Date;\n\nexport interface StackedAreaSeries {\n  /** Field in each row that holds this series' value. */\n  key: string;\n  /** Name in the legend and tooltip. Defaults to `key`. */\n  label?: string;\n  /** Any CSS color. Defaults to the chart palette, cycling with softer tints past five. */\n  color?: string;\n}\n\nexport interface StackedAreaReferenceLine {\n  /** Value on the y axis. Drawn in normal and overlapping modes, where the axis is in value units. */\n  y: number;\n  label?: string;\n  color?: string;\n}\n\nexport interface StackedAreaAnnotation {\n  /** Where the marker sits, in the same form as the index values. */\n  x: StackedAreaXValue;\n  label: string;\n  color?: string;\n}\n\n/** One series at one point, as listed in the tooltip. */\nexport interface StackedAreaItem {\n  key: string;\n  label: string;\n  color: string;\n  value: number;\n  /** Share of the visible total at this point (or over the range, in a summary), 0–1. */\n  share: number;\n}\n\n/** The point under the crosshair, passed to `renderTooltip` and `onHover`. */\nexport interface StackedAreaPoint {\n  /** Position in the sorted data. */\n  index: number;\n  /** A Date on time axes, otherwise the number or label from the data. */\n  x: StackedAreaXValue;\n  /** The x value formatted for the tooltip. */\n  label: string;\n  /** The original row. */\n  row: Record<string, unknown>;\n  /** Sum of the visible series. */\n  total: number;\n  /** Visible series, top of the stack first. */\n  items: StackedAreaItem[];\n  /** Annotations that fall on this point. */\n  annotations: StackedAreaAnnotation[];\n}\n\n/** Totals across the whole range, passed to a `header` function. */\nexport interface StackedAreaSummary {\n  /** Sum of every visible series over every point. */\n  total: number;\n  /** Visible total at the first and the last point. */\n  first: number;\n  last: number;\n  /** Every series with its total over the range and its share of `total`, in legend order. */\n  series: (StackedAreaItem & { hidden: boolean })[];\n  /** Number of points. */\n  count: number;\n  /** The chart's value formatter. */\n  format: (value: number) => string;\n}\n\nexport type StackedAreaXFormatter = (\n  value: StackedAreaXValue,\n  context: \"axis\" | \"tooltip\",\n) => string;\n\nexport interface StackedAreaChartProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Rows, one per x value. Missing or negative values count as zero. */\n  data: Record<string, unknown>[];\n  /** Field holding the x value: numbers, ISO date strings, Dates, or category labels. */\n  index: string;\n  /** Series to stack, bottom first. */\n  series: StackedAreaSeries[];\n  stack?: StackedAreaStack;\n  curve?: StackedAreaCurve;\n  /** Plot height in pixels. Defaults to 280. */\n  height?: number;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Content under the title, such as a headline total. A function receives the totals for the visible series. */\n  header?: React.ReactNode | ((summary: StackedAreaSummary) => React.ReactNode);\n  /** Formats values in the tooltip, legend, and summary. Defaults to compact numbers from 10,000. */\n  valueFormatter?: (value: number) => string;\n  /** Formats y axis ticks. Defaults to compact numbers such as 2.4M, or percentages when expanded. */\n  axisFormatter?: (value: number) => string;\n  /** Formats x values on the axis and in the tooltip. Dates default to Intl formats matched to the spacing. */\n  xFormatter?: StackedAreaXFormatter;\n  /** Short name of the y axis, shown above it. */\n  yLabel?: string;\n  referenceLines?: StackedAreaReferenceLine[];\n  /** Thin vertical markers with a label, for events such as a deploy. */\n  annotations?: StackedAreaAnnotation[];\n  /** Keys of hidden series. Pass with `onHiddenSeriesChange` to control the legend. */\n  hiddenSeries?: string[];\n  defaultHiddenSeries?: string[];\n  onHiddenSeriesChange?: (hidden: string[]) => void;\n  /** Show the interactive legend. Defaults to true. */\n  showLegend?: boolean;\n  legendPosition?: \"top\" | \"bottom\";\n  /** Replaces the tooltip content. */\n  renderTooltip?: (point: StackedAreaPoint) => React.ReactNode;\n  /** Called when the crosshair moves to a point, and with null when it leaves. */\n  onHover?: (point: StackedAreaPoint | null) => void;\n  /** Tween between states when series toggle, the stack mode changes, or data updates. Defaults to true. */\n  animate?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst DAY = 86_400_000;\nconst tidy = (value: number) => +value.toPrecision(12);\nconst lowerK = (text: string) => text.replace(/K$/, \"k\");\nconst compactAxis = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst compactValue = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumSignificantDigits: 3,\n});\nconst grouped = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 2 });\n\nfunction defaultValueFormatter(value: number) {\n  if (!Number.isFinite(value)) return \"—\";\n  return Math.abs(value) >= 10_000\n    ? lowerK(compactValue.format(value))\n    : grouped.format(value);\n}\n\nfunction defaultAxisFormatter(value: number) {\n  return value === 0 ? \"0\" : lowerK(compactAxis.format(value));\n}\n\nfunction percentAxis(value: number) {\n  return `${tidy(value * 100)}%`;\n}\n\nfunction formatShare(share: number, digits = 1) {\n  const pct = share * 100;\n  if (!Number.isFinite(pct) || pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  return `${pct.toFixed(digits)}%`;\n}\n\n// \"Atlas Large hidden\" reads better than a pressed state for screen readers.\nconst sentence = (parts: string[]) => parts.filter(Boolean).join(\" \");\n\n/* ------------------------------------------------------------------------ */\n/* X values                                                                  */\n/* ------------------------------------------------------------------------ */\n\ntype XKind = \"time\" | \"number\" | \"category\";\n\nconst DATE_ONLY = /^(\\d{4})-(\\d{2})(?:-(\\d{2}))?$/;\nconst DATE_TIME =\n  /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Date-only strings are local calendar days, so \"2026-10-03\" never renders as Oct 2. */\nfunction toTime(raw: unknown): number | null {\n  if (raw instanceof Date) {\n    const t = raw.getTime();\n    return Number.isNaN(t) ? null : t;\n  }\n  if (typeof raw !== \"string\") return null;\n  const day = DATE_ONLY.exec(raw);\n  if (day) return new Date(+day[1], +day[2] - 1, day[3] ? +day[3] : 1).getTime();\n  if (DATE_TIME.test(raw)) {\n    const t = Date.parse(raw.replace(\" \", \"T\"));\n    return Number.isNaN(t) ? null : t;\n  }\n  return null;\n}\n\nfunction xKindOf(values: unknown[]): XKind {\n  if (!values.length) return \"category\";\n  if (values.every((v) => typeof v === \"number\" && Number.isFinite(v)))\n    return \"number\";\n  if (values.every((v) => toTime(v) !== null)) return \"time\";\n  return \"category\";\n}\n\nfunction makeDateFormatter(step: number, spansYears: boolean) {\n  const f = (options: Intl.DateTimeFormatOptions) =>\n    new Intl.DateTimeFormat(\"en-US\", options);\n  if (step < DAY) {\n    const time = f({ hour: \"2-digit\", minute: \"2-digit\", hourCycle: \"h23\" });\n    const day = f({ month: \"short\", day: \"numeric\" });\n    const tip = f({\n      weekday: \"short\",\n      month: \"short\",\n      day: \"numeric\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n      hourCycle: \"h23\",\n    });\n    // Midnight ticks name the day, so a multi-day axis stays readable.\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      c === \"tooltip\"\n        ? tip.format(d)\n        : d.getHours() === 0 && d.getMinutes() === 0\n          ? day.format(d)\n          : time.format(d);\n  }\n  if (step < 28 * DAY) {\n    const axis = f({ month: \"short\", day: \"numeric\" });\n    const tip = f({\n      weekday: \"short\",\n      month: \"short\",\n      day: \"numeric\",\n      ...(spansYears ? { year: \"numeric\" } : {}),\n    });\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      (c === \"axis\" ? axis : tip).format(d);\n  }\n  if (step < 360 * DAY) {\n    const axis = f(\n      spansYears ? { month: \"short\", year: \"2-digit\" } : { month: \"short\" },\n    );\n    const tip = f({ month: \"long\", year: \"numeric\" });\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      (c === \"axis\" ? axis : tip).format(d);\n  }\n  const year = f({ year: \"numeric\" });\n  return (d: Date) => year.format(d);\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Model {\n  kind: XKind;\n  rows: Record<string, unknown>[];\n  /** Numeric x positions: epoch ms, numbers, or the row index for categories. */\n  xs: number[];\n  /** Parsed x values: Dates on time axes. */\n  xValues: StackedAreaXValue[];\n  /** Identity of each point, used to match points across updates. */\n  keys: string[];\n  /** Clean values per series and point. */\n  values: number[][];\n  /** Typical spacing between points, in x units. */\n  step: number;\n}\n\nfunction buildModel(\n  data: Record<string, unknown>[],\n  index: string,\n  keys: string[],\n): Model {\n  const kind = xKindOf(data.map((row) => row?.[index]));\n  const items = data.map((row, i) => {\n    const raw = row?.[index];\n    if (kind === \"number\") return { row, x: raw as number, value: raw as number };\n    if (kind === \"time\") {\n      const t = toTime(raw)!;\n      return { row, x: t, value: new Date(t) as StackedAreaXValue };\n    }\n    return { row, x: i, value: String(raw ?? \"\") as StackedAreaXValue };\n  });\n  if (kind !== \"category\") items.sort((a, b) => a.x - b.x);\n  const xs = items.map((item) => item.x);\n  const diffs: number[] = [];\n  for (let i = 1; i < xs.length; i++)\n    if (xs[i] > xs[i - 1]) diffs.push(xs[i] - xs[i - 1]);\n  diffs.sort((a, b) => a - b);\n  return {\n    kind,\n    rows: items.map((item) => item.row ?? {}),\n    xs,\n    xValues: items.map((item) => item.value),\n    keys:\n      kind === \"category\" ? items.map((_, i) => String(i)) : xs.map(String),\n    values: keys.map((key) =>\n      items.map((item) => {\n        const v = Number(item.row?.[key]);\n        return Number.isFinite(v) && v > 0 ? v : 0;\n      }),\n    ),\n    step: diffs.length ? diffs[diffs.length >> 1] : 1,\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Scales                                                                    */\n/* ------------------------------------------------------------------------ */\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Ticks from zero: three to `most` intervals of 1, 2, 2.5 or 5 × 10ⁿ, with the least wasted headroom. */\nfunction niceScale(max: number, most: number) {\n  if (!(max > 0)) return { hi: 1, ticks: [0, 0.5, 1] };\n  const target = max * 1.02;\n  const exponent = Math.floor(Math.log10(target));\n  let best: { step: number; count: number; score: number } | null = null;\n  for (let e = exponent - 2; e <= exponent + 1; e++)\n    for (const m of [1, 2, 2.5, 5]) {\n      const step = m * 10 ** e;\n      const count = Math.ceil(target / step - 1e-9);\n      if (count < 3 || count > most) continue;\n      const hi = count * step;\n      const score =\n        (hi - target) / hi + Math.abs(count - 4) * 0.04 + (m === 2.5 ? 0.04 : 0);\n      if (!best || score < best.score) best = { step, count, score };\n    }\n  const step = best?.step ?? niceStep(target / 4);\n  const count = best?.count ?? Math.max(1, Math.ceil(target / step - 1e-9));\n  return {\n    hi: tidy(count * step),\n    ticks: Array.from({ length: count + 1 }, (_, i) => tidy(i * step)),\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Frames: the stacked geometry in data units, tweened between states        */\n/* ------------------------------------------------------------------------ */\n\ninterface Frame {\n  keys: string[];\n  xs: number[];\n  series: string[];\n  /** Lower and upper edge per series and point, in y units. */\n  y0: number[][];\n  y1: number[][];\n  /** 1 when a series is shown, 0 when hidden; fractional mid-tween. */\n  weight: number[];\n  x0: number;\n  x1: number;\n  lo: number;\n  hi: number;\n}\n\nfunction stackFrame(\n  model: Model,\n  seriesKeys: string[],\n  visible: boolean[],\n  stack: StackedAreaStack,\n  lo: number,\n  hi: number,\n): Frame {\n  const n = model.xs.length;\n  const y0 = seriesKeys.map(() => new Array<number>(n).fill(0));\n  const y1 = seriesKeys.map(() => new Array<number>(n).fill(0));\n  for (let j = 0; j < n; j++) {\n    let total = 0;\n    for (let s = 0; s < seriesKeys.length; s++)\n      if (visible[s]) total += model.values[s][j];\n    if (stack === \"none\") {\n      for (let s = 0; s < seriesKeys.length; s++)\n        y1[s][j] = visible[s] ? model.values[s][j] : 0;\n      continue;\n    }\n    const scale = stack === \"expand\" ? (total > 0 ? 1 / total : 0) : 1;\n    let running = stack === \"stream\" ? -total / 2 : 0;\n    for (let s = 0; s < seriesKeys.length; s++) {\n      y0[s][j] = running;\n      running += visible[s] ? model.values[s][j] * scale : 0;\n      y1[s][j] = running;\n    }\n  }\n  const first = model.xs[0] ?? 0;\n  const last = model.xs[n - 1] ?? 1;\n  const pad = n > 1 ? 0 : model.step / 2 || 0.5;\n  return {\n    keys: model.keys,\n    xs: model.xs,\n    series: seriesKeys,\n    y0,\n    y1,\n    weight: visible.map((v) => (v ? 1 : 0)),\n    x0: first - pad,\n    x1: last + pad,\n    lo,\n    hi,\n  };\n}\n\nfunction framesEqual(a: Frame, b: Frame) {\n  if (a === b) return true;\n  const same = (p: number, q: number) => Math.abs(p - q) < 1e-9;\n  if (\n    a.keys.length !== b.keys.length ||\n    a.series.length !== b.series.length ||\n    !same(a.x0, b.x0) ||\n    !same(a.x1, b.x1) ||\n    !same(a.lo, b.lo) ||\n    !same(a.hi, b.hi)\n  )\n    return false;\n  for (let i = 0; i < a.keys.length; i++)\n    if (a.keys[i] !== b.keys[i] || !same(a.xs[i], b.xs[i])) return false;\n  for (let s = 0; s < a.series.length; s++) {\n    if (a.series[s] !== b.series[s] || a.weight[s] !== b.weight[s]) return false;\n    for (let i = 0; i < a.keys.length; i++)\n      if (!same(a.y0[s][i], b.y0[s][i]) || !same(a.y1[s][i], b.y1[s][i]))\n        return false;\n  }\n  return true;\n}\n\n/**\n * Interpolates two frames. Points are matched by identity, so a sliding window keeps\n * every shared point still and glides the x domain instead of morphing the shape.\n */\nfunction lerpFrame(a: Frame, b: Frame, t: number): Frame {\n  const mix = (p: number, q: number) => p + (q - p) * t;\n  const seriesIndex = new Map(a.series.map((key, i) => [key, i]));\n  let keys = b.keys;\n  let xs: number[];\n  let fromIndex: number[];\n  let toIndex: number[];\n  if (\n    a.keys.length === b.keys.length &&\n    a.keys.every((key, i) => key === b.keys[i])\n  ) {\n    xs = b.xs.map((x, i) => mix(a.xs[i], x));\n    fromIndex = toIndex = b.keys.map((_, i) => i);\n  } else {\n    const inA = new Map(a.keys.map((key, i) => [key, i]));\n    const inB = new Map(b.keys.map((key, i) => [key, i]));\n    const xOf = (key: string) =>\n      inB.has(key) ? b.xs[inB.get(key)!] : a.xs[inA.get(key)!];\n    keys = [...new Set([...a.keys, ...b.keys])].sort((p, q) => xOf(p) - xOf(q));\n    xs = keys.map(xOf);\n    fromIndex = keys.map((key) => inA.get(key) ?? -1);\n    toIndex = keys.map((key) => inB.get(key) ?? -1);\n  }\n  const y0: number[][] = [];\n  const y1: number[][] = [];\n  const weight: number[] = [];\n  b.series.forEach((key, s) => {\n    const sa = seriesIndex.get(key) ?? -1;\n    const lower: number[] = [];\n    const upper: number[] = [];\n    keys.forEach((_, j) => {\n      const ia = fromIndex[j];\n      const ib = toIndex[j];\n      const to0 = ib >= 0 ? b.y0[s][ib] : null;\n      const to1 = ib >= 0 ? b.y1[s][ib] : null;\n      // A new series grows from its own base; a leaving point holds still.\n      const from0 = sa >= 0 && ia >= 0 ? a.y0[sa][ia] : (to0 ?? 0);\n      const from1 = sa >= 0 && ia >= 0 ? a.y1[sa][ia] : (to0 ?? 0);\n      lower.push(mix(from0, to0 ?? from0));\n      upper.push(mix(from1, to1 ?? from1));\n    });\n    y0.push(lower);\n    y1.push(upper);\n    weight.push(mix(sa >= 0 ? a.weight[sa] : 0, b.weight[s]));\n  });\n  return {\n    keys,\n    xs,\n    series: b.series,\n    y0,\n    y1,\n    weight,\n    x0: mix(a.x0, b.x0),\n    x1: mix(a.x1, b.x1),\n    lo: mix(a.lo, b.lo),\n    hi: mix(a.hi, b.hi),\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Curves                                                                    */\n/* ------------------------------------------------------------------------ */\n\nconst r2 = (value: number) => Math.round(value * 100) / 100;\n\n/** Steffen's monotone tangents: no overshoot between points, so stacked edges never cross. */\nfunction monotoneTangents(xs: number[], ys: number[]) {\n  const n = xs.length;\n  const m = new Array<number>(n).fill(0);\n  if (n < 2) return m;\n  const h: number[] = [];\n  const d: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    h.push(xs[i + 1] - xs[i]);\n    d.push(h[i] ? (ys[i + 1] - ys[i]) / h[i] : 0);\n  }\n  if (n === 2) {\n    m[0] = m[1] = d[0];\n    return m;\n  }\n  for (let i = 1; i < n - 1; i++) {\n    const s0 = d[i - 1];\n    const s1 = d[i];\n    if (s0 * s1 <= 0) continue;\n    const p = (s0 * h[i] + s1 * h[i - 1]) / (h[i - 1] + h[i] || 1);\n    m[i] =\n      Math.sign(s0) *\n      Math.min(2 * Math.abs(s0), 2 * Math.abs(s1), Math.abs(p));\n  }\n  // One-sided ends keep the tangent within the first and last secant.\n  m[0] = (3 * d[0] - m[1]) / 2;\n  m[n - 1] = (3 * d[n - 2] - m[n - 2]) / 2;\n  return m;\n}\n\n/** Path commands from the first point to the last (or back), without the opening move. */\nfunction edge(\n  xs: number[],\n  ys: number[],\n  curve: StackedAreaCurve,\n  reverse: boolean,\n) {\n  const n = xs.length;\n  if (n < 2) return \"\";\n  let out = \"\";\n  if (curve === \"linear\") {\n    if (reverse)\n      for (let i = n - 2; i >= 0; i--) out += `L${r2(xs[i])} ${r2(ys[i])}`;\n    else for (let i = 1; i < n; i++) out += `L${r2(xs[i])} ${r2(ys[i])}`;\n    return out;\n  }\n  if (curve === \"step\") {\n    if (reverse)\n      for (let i = n - 2; i >= 0; i--) {\n        const mid = (xs[i] + xs[i + 1]) / 2;\n        out += `H${r2(mid)}V${r2(ys[i])}H${r2(xs[i])}`;\n      }\n    else\n      for (let i = 0; i < n - 1; i++) {\n        const mid = (xs[i] + xs[i + 1]) / 2;\n        out += `H${r2(mid)}V${r2(ys[i + 1])}H${r2(xs[i + 1])}`;\n      }\n    return out;\n  }\n  const m = monotoneTangents(xs, ys);\n  const segment = (i: number) => {\n    const h = (xs[i + 1] - xs[i]) / 3;\n    return [\n      xs[i] + h,\n      ys[i] + m[i] * h,\n      xs[i + 1] - h,\n      ys[i + 1] - m[i + 1] * h,\n    ];\n  };\n  if (reverse)\n    for (let i = n - 2; i >= 0; i--) {\n      const [c1x, c1y, c2x, c2y] = segment(i);\n      out += `C${r2(c2x)} ${r2(c2y)} ${r2(c1x)} ${r2(c1y)} ${r2(xs[i])} ${r2(ys[i])}`;\n    }\n  else\n    for (let i = 0; i < n - 1; i++) {\n      const [c1x, c1y, c2x, c2y] = segment(i);\n      out += `C${r2(c1x)} ${r2(c1y)} ${r2(c2x)} ${r2(c2y)} ${r2(xs[i + 1])} ${r2(ys[i + 1])}`;\n    }\n  return out;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst easeOut = (t: number) => 1 - (1 - t) ** 3;\nconst easeInOut = (t: number) =>\n  t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;\n\n/** Default palette: the five chart colors, then softer tints of the same five. */\nfunction paletteColor(i: number) {\n  const base = `var(--color-chart-${(i % 5) + 1})`;\n  const round = Math.floor(i / 5);\n  return round === 0\n    ? base\n    : `color-mix(in oklab, ${base} ${Math.max(40, 100 - round * 28)}%, var(--color-card))`;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_10%,transparent)]\";\nconst gridColor = \"color-mix(in oklab, var(--color-foreground) 7%, transparent)\";\nconst baseColor = \"color-mix(in oklab, var(--color-foreground) 14%, transparent)\";\n\n/* ------------------------------------------------------------------------ */\n/* StackedAreaChart                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A composition over time: stacked, normalised, streamgraph, or overlapping areas with\n * an interactive legend, a snapping crosshair, annotations, and tweened re-stacking.\n */\nexport function StackedAreaChart({\n  data,\n  index,\n  series,\n  stack = \"normal\",\n  curve = \"monotone\",\n  height = 280,\n  title,\n  description,\n  actions,\n  header,\n  valueFormatter = defaultValueFormatter,\n  axisFormatter,\n  xFormatter,\n  yLabel,\n  referenceLines,\n  annotations,\n  hiddenSeries,\n  defaultHiddenSeries = [],\n  onHiddenSeriesChange,\n  showLegend = true,\n  legendPosition = \"bottom\",\n  renderTooltip,\n  onHover,\n  animate = true,\n  className,\n  ...props\n}: StackedAreaChartProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const reduced = useReducedMotion();\n  const motion = animate && !reduced;\n\n  const [hidden, setHidden] = useControllable(\n    hiddenSeries,\n    defaultHiddenSeries,\n    onHiddenSeriesChange,\n  );\n  const hiddenSet = React.useMemo(() => new Set(hidden), [hidden]);\n\n  // Geometry depends only on series keys, so inline series arrays never restart a tween.\n  const seriesSignature = series.map((s) => s.key).join(\"\\u0000\");\n  const seriesKeys = React.useMemo(\n    () => (seriesSignature ? seriesSignature.split(\"\\u0000\") : []),\n    [seriesSignature],\n  );\n  const meta = series.map((s, i) => ({\n    key: s.key,\n    label: s.label ?? s.key,\n    color: s.color ?? paletteColor(i),\n  }));\n\n  const model = React.useMemo(\n    () => buildModel(data, index, seriesKeys),\n    [data, index, seriesKeys],\n  );\n  const n = model.xs.length;\n  const visible = seriesKeys.map((key) => !hiddenSet.has(key));\n  const visibleSignature = visible.map(Number).join(\"\");\n  const anyVisible = visible.some(Boolean);\n\n  /* ------------------------------------------------------------- format */\n\n  const formatX = React.useMemo(() => {\n    if (xFormatter) return xFormatter;\n    if (model.kind === \"time\") {\n      const first = model.xs[0] ?? 0;\n      const last = model.xs[n - 1] ?? 0;\n      const date = makeDateFormatter(\n        model.step,\n        new Date(first).getFullYear() !== new Date(last).getFullYear(),\n      );\n      return (value: StackedAreaXValue, context: \"axis\" | \"tooltip\") =>\n        date(value instanceof Date ? value : new Date(value), context);\n    }\n    if (model.kind === \"number\")\n      return (value: StackedAreaXValue) =>\n        typeof value === \"number\" ? grouped.format(value) : String(value);\n    return (value: StackedAreaXValue) => String(value);\n  }, [xFormatter, model, n]);\n\n  const formatTick = React.useMemo(\n    () =>\n      axisFormatter ?? (stack === \"expand\" ? percentAxis : defaultAxisFormatter),\n    [axisFormatter, stack],\n  );\n\n  /* -------------------------------------------------------------- scale */\n\n  const refs = React.useMemo(\n    () =>\n      (referenceLines ?? []).filter(\n        (line) => Number.isFinite(line.y) && (stack === \"normal\" || stack === \"none\"),\n      ),\n    [referenceLines, stack],\n  );\n\n  const scale = React.useMemo(() => {\n    const vis = visibleSignature.split(\"\").map((v) => v === \"1\");\n    let peak = 0;\n    for (let j = 0; j < n; j++) {\n      let total = 0;\n      for (let s = 0; s < seriesKeys.length; s++) {\n        if (!vis[s]) continue;\n        const v = model.values[s][j];\n        if (stack === \"none\") peak = Math.max(peak, v);\n        else total += v;\n      }\n      peak = Math.max(peak, total);\n    }\n    if (stack === \"expand\")\n      return { lo: 0, hi: 1, ticks: [0, 0.25, 0.5, 0.75, 1], peak };\n    if (stack === \"stream\") {\n      const half = (peak || 1) / 2;\n      return { lo: -half * 1.06, hi: half * 1.06, ticks: [0], peak };\n    }\n    for (const line of refs) peak = Math.max(peak, line.y);\n    const nice = niceScale(peak, height < 200 ? 4 : 5);\n    return { lo: 0, hi: nice.hi, ticks: nice.ticks, peak };\n  }, [model, n, seriesKeys, visibleSignature, stack, refs, height]);\n\n  const target = React.useMemo(\n    () =>\n      stackFrame(\n        model,\n        seriesKeys,\n        visibleSignature.split(\"\").map((v) => v === \"1\"),\n        stack,\n        scale.lo,\n        scale.hi,\n      ),\n    [model, seriesKeys, visibleSignature, stack, scale],\n  );\n\n  /* ------------------------------------------------------------- motion */\n\n  const [tween, setTween] = React.useState<Frame | null>(null);\n  const shownRef = React.useRef<Frame>(target);\n  const modelRef = React.useRef(model);\n  React.useLayoutEffect(() => {\n    const from = shownRef.current;\n    const dataChanged = modelRef.current !== model;\n    modelRef.current = model;\n    if (from === target) return;\n    if (!motion || framesEqual(from, target)) {\n      shownRef.current = target;\n      setTween(null);\n      return;\n    }\n    // Data updates glide a little longer than toggles, which should feel immediate.\n    const duration = dataChanged ? 460 : 320;\n    const ease = dataChanged ? easeInOut : easeOut;\n    const start = performance.now();\n    setTween(from);\n    let frame = requestAnimationFrame(function step(now) {\n      const t = Math.min(1, (now - start) / duration);\n      if (t >= 1) {\n        shownRef.current = target;\n        setTween(null);\n        return;\n      }\n      const next = lerpFrame(from, target, ease(t));\n      shownRef.current = next;\n      setTween(next);\n      frame = requestAnimationFrame(step);\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [target, model, motion]);\n  const shown = tween ?? target;\n\n  /* ------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(Math.round(el.clientWidth));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 640;\n  const H = Math.max(96, height);\n\n  // Annotation labels stack into lanes above the plot only when they would collide.\n  const marks = React.useMemo(() => {\n    if (!annotations?.length || !n) return [];\n    const lanes: number[] = [];\n    const span = target.x1 - target.x0 || 1;\n    return annotations\n      .map((note) => {\n        let x: number | null = null;\n        if (model.kind === \"time\") x = toTime(note.x);\n        else if (model.kind === \"number\")\n          x = typeof note.x === \"number\" ? note.x : Number(note.x);\n        else {\n          const i = model.xValues.findIndex((v) => v === String(note.x));\n          x = i >= 0 ? i : null;\n        }\n        if (x == null || !Number.isFinite(x)) return null;\n        // The nearest point, so the tooltip can repeat the note.\n        let nearest = 0;\n        for (let i = 1; i < n; i++)\n          if (Math.abs(model.xs[i] - x) < Math.abs(model.xs[nearest] - x))\n            nearest = i;\n        return { note, x, nearest, fraction: (x - target.x0) / span };\n      })\n      .filter((m): m is NonNullable<typeof m> => m !== null)\n      .filter((m) => m.fraction >= -0.001 && m.fraction <= 1.001)\n      .sort((a, b) => a.x - b.x)\n      .map((m) => {\n        const w = Math.min(W, m.note.label.length * 6.3 + 24);\n        const px = m.fraction * W;\n        const flip = px + w > W && px - w >= 0;\n        const left = flip ? px - w : Math.max(0, Math.min(px, W - w));\n        let lane = lanes.findIndex((right) => right + 6 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...m, w, left, lane, flip };\n      });\n  }, [annotations, n, model, target.x0, target.x1, W]);\n  const laneCount = marks.length\n    ? Math.max(...marks.map((m) => m.lane)) + 1\n    : 0;\n  const padTop = 8 + laneCount * 26;\n  const padBottom = 1;\n  const plotH = H - padTop - padBottom;\n\n  const X = (x: number) => ((x - shown.x0) / (shown.x1 - shown.x0 || 1)) * W;\n  const entranceBase =\n    padTop + ((scale.hi - (stack === \"stream\" ? 0 : scale.lo)) / (scale.hi - scale.lo || 1)) * plotH;\n  const Y = (y: number) =>\n    padTop + ((shown.hi - y) / (shown.hi - shown.lo || 1)) * plotH;\n\n  const geometry = React.useMemo(() => {\n    const px = shown.xs.map(\n      (x) => ((x - shown.x0) / (shown.x1 - shown.x0 || 1)) * W,\n    );\n    const py = (y: number) =>\n      padTop + ((shown.hi - y) / (shown.hi - shown.lo || 1)) * plotH;\n    return shown.series.map((key, s) => {\n      const top = shown.y1[s].map(py);\n      const bottom = shown.y0[s].map(py);\n      let thickness = 0;\n      for (let j = 0; j < top.length; j++)\n        thickness = Math.max(thickness, bottom[j] - top[j]);\n      if (!px.length) return { key, area: \"\", line: \"\", base: \"\", thickness };\n      const single = px.length === 1;\n      const xs = single ? [px[0] - W / 2, px[0] + W / 2] : px;\n      const t = single ? [top[0], top[0]] : top;\n      const b = single ? [bottom[0], bottom[0]] : bottom;\n      const head = `M${r2(xs[0])} ${r2(t[0])}${edge(xs, t, curve, false)}`;\n      return {\n        key,\n        line: head,\n        base: `M${r2(xs[0])} ${r2(b[0])}${edge(xs, b, curve, false)}`,\n        area: `${head}L${r2(xs[xs.length - 1])} ${r2(b[b.length - 1])}${edge(xs, b, curve, true)}Z`,\n        thickness,\n      };\n    });\n  }, [shown, W, padTop, plotH, curve]);\n\n  /* -------------------------------------------------------------- ticks */\n\n  const yTicks = scale.ticks;\n  const yTickLabels = stack === \"stream\" ? [] : yTicks.map(formatTick);\n\n  const xTicks = React.useMemo(() => {\n    if (!n) return [] as { x: number; label: string }[];\n    const labelWidth = 64;\n    const room = Math.max(2, Math.floor(W / labelWidth));\n    if (model.kind === \"number\") {\n      const lo = model.xs[0];\n      const hi = model.xs[n - 1];\n      if (hi <= lo) return [{ x: lo, label: formatX(lo, \"axis\") }];\n      const step = niceStep((hi - lo) / Math.max(1, room - 1));\n      const ticks: { x: number; label: string }[] = [];\n      for (\n        let v = Math.ceil(lo / step - 1e-9) * step;\n        v <= hi + step * 1e-6;\n        v += step\n      )\n        ticks.push({ x: tidy(v), label: formatX(tidy(v), \"axis\") });\n      return ticks;\n    }\n    // Every k-th point. Sub-day axes land on round hours; others count back from the\n    // latest point so the newest value is always labelled.\n    const subDay = model.kind === \"time\" && model.step < DAY;\n    const steps = subDay\n      ? [1, 2, 3, 4, 6, 8, 12, 24, 48, 72, 168]\n      : model.kind === \"time\" && model.step >= 28 * DAY\n        ? [1, 2, 3, 6, 12, 24, 60]\n        : [1, 2, 3, 4, 5, 7, 10, 14, 15, 20, 28, 30, 50, 60, 100];\n    const k =\n      steps.find((step) => Math.floor((n - 1) / step) + 1 <= room) ??\n      Math.ceil(n / room);\n    let phase = (n - 1) % k;\n    if (subDay) {\n      const span = k * model.step;\n      for (let o = 0; o < Math.min(k, n); o++) {\n        const d = new Date(model.xs[o]);\n        const sinceMidnight =\n          model.xs[o] - new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();\n        if (Math.round(sinceMidnight) % Math.round(span) === 0) {\n          phase = o;\n          break;\n        }\n      }\n    }\n    const ticks: { x: number; label: string }[] = [];\n    for (let i = phase; i < n; i += k)\n      ticks.push({ x: model.xs[i], label: formatX(model.xValues[i], \"axis\") });\n    return ticks;\n  }, [n, model, W, formatX]);\n\n  /* ---------------------------------------------------------- summaries */\n\n  const summary = React.useMemo<StackedAreaSummary>(() => {\n    const totals = seriesKeys.map((_, s) =>\n      model.values[s].reduce((sum, v) => sum + v, 0),\n    );\n    const vis = visibleSignature.split(\"\").map((v) => v === \"1\");\n    const total = totals.reduce((sum, v, s) => sum + (vis[s] ? v : 0), 0);\n    const at = (j: number) =>\n      j < 0\n        ? 0\n        : seriesKeys.reduce(\n            (sum, _, s) => sum + (vis[s] ? model.values[s][j] : 0),\n            0,\n          );\n    return {\n      total,\n      first: n ? at(0) : 0,\n      last: n ? at(n - 1) : 0,\n      count: n,\n      format: valueFormatter,\n      series: seriesKeys.map((key, s) => ({\n        key,\n        label: series[s]?.label ?? key,\n        color: series[s]?.color ?? paletteColor(s),\n        value: totals[s],\n        share: vis[s] && total > 0 ? totals[s] / total : 0,\n        hidden: !vis[s],\n      })),\n    };\n  }, [model, n, seriesKeys, visibleSignature, valueFormatter, series]);\n\n  const pointAt = React.useCallback(\n    (j: number): StackedAreaPoint => {\n      const items: StackedAreaItem[] = [];\n      let total = 0;\n      for (let s = 0; s < seriesKeys.length; s++)\n        if (visible[s]) total += model.values[s][j];\n      for (let s = seriesKeys.length - 1; s >= 0; s--) {\n        if (!visible[s]) continue;\n        const value = model.values[s][j];\n        items.push({\n          key: seriesKeys[s],\n          label: series[s]?.label ?? seriesKeys[s],\n          color: series[s]?.color ?? paletteColor(s),\n          value,\n          share: total > 0 ? value / total : 0,\n        });\n      }\n      return {\n        index: j,\n        x: model.xValues[j],\n        label: formatX(model.xValues[j], \"tooltip\"),\n        row: model.rows[j],\n        total,\n        items,\n        annotations: marks.filter((m) => m.nearest === j).map((m) => m.note),\n      };\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [model, seriesKeys, visibleSignature, series, formatX, marks],\n  );\n\n  /* -------------------------------------------------------- interaction */\n\n  const [active, setActive] = React.useState<number | null>(null);\n  const [pointerBand, setPointerBand] = React.useState<string | null>(null);\n  const [hovered, setHighlight] = React.useState<string | null>(null);\n  // A series hidden while hovered no longer dims the rest.\n  const highlight = hovered != null && !hiddenSet.has(hovered) ? hovered : null;\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const activeIndex = active != null && active < n ? active : null;\n  const activePoint = React.useMemo(\n    () => (activeIndex == null || !anyVisible ? null : pointAt(activeIndex)),\n    [activeIndex, anyVisible, pointAt],\n  );\n\n  const onHoverRef = React.useRef(onHover);\n  React.useEffect(() => {\n    onHoverRef.current = onHover;\n  });\n  React.useEffect(() => {\n    onHoverRef.current?.(activePoint);\n  }, [activePoint]);\n\n  const nearestIndex = (px: number) => {\n    if (!n) return null;\n    const x = target.x0 + (px / W) * (target.x1 - target.x0);\n    let lo = 0;\n    let hi = n - 1;\n    while (lo < hi) {\n      const mid = (lo + hi) >> 1;\n      if (model.xs[mid] < x) lo = mid + 1;\n      else hi = mid;\n    }\n    if (lo > 0 && Math.abs(model.xs[lo - 1] - x) <= Math.abs(model.xs[lo] - x))\n      lo -= 1;\n    return lo;\n  };\n\n  const handlePointer = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!n || !anyVisible) return;\n    const rect = event.currentTarget.getBoundingClientRect();\n    const px = event.clientX - rect.left;\n    const py = event.clientY - rect.top;\n    const j = nearestIndex(Math.min(W, Math.max(0, px)));\n    setActive(j);\n    if (j == null) return;\n    // Which band sits under the pointer, so its tooltip row can stand out.\n    let band: string | null = null;\n    for (let s = seriesKeys.length - 1; s >= 0; s--) {\n      if (!visible[s]) continue;\n      const top = Y(target.y1[s][j]);\n      const bottom = Y(target.y0[s][j]);\n      if (py >= Math.min(top, bottom) - 2 && py <= Math.max(top, bottom) + 2) {\n        band = seriesKeys[s];\n        break;\n      }\n    }\n    setPointerBand(band);\n  };\n\n  const describe = (point: StackedAreaPoint) =>\n    `${point.label}: total ${valueFormatter(point.total)}. ${point.items\n      .map(\n        (item) =>\n          `${item.label} ${valueFormatter(item.value)}, ${formatShare(item.share)}`,\n      )\n      .join(\"; \")}.${point.annotations.length ? ` ${point.annotations.map((a) => a.label).join(\". \")}.` : \"\"}`;\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!n || !anyVisible) return;\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\")\n      next = activeIndex == null ? 0 : Math.min(n - 1, activeIndex + 1);\n    else if (event.key === \"ArrowLeft\")\n      next = activeIndex == null ? n - 1 : Math.max(0, activeIndex - 1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = n - 1;\n    else if (event.key === \"Escape\" && activeIndex != null) {\n      event.preventDefault();\n      setActive(null);\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    setPointerBand(null);\n    setActive(next);\n    setAnnouncement(describe(pointAt(next)));\n  };\n\n  const toggle = (key: string, solo: boolean) => {\n    const label = series.find((s) => s.key === key)?.label ?? key;\n    if (solo) {\n      const only =\n        seriesKeys.filter((k) => !hiddenSet.has(k)).length === 1 &&\n        !hiddenSet.has(key);\n      setHidden(only ? [] : seriesKeys.filter((k) => k !== key));\n      setAnnouncement(only ? \"Showing all series.\" : `Showing only ${label}.`);\n      return;\n    }\n    const isHidden = hiddenSet.has(key);\n    setHidden(\n      isHidden ? hidden.filter((k) => k !== key) : [...hidden, key],\n    );\n    setAnnouncement(sentence([label, isHidden ? \"shown.\" : \"hidden.\"]));\n  };\n\n  /* -------------------------------------------------------------- render */\n\n  const headerContent =\n    typeof header === \"function\" ? header(summary) : header;\n  const hasHeader =\n    title != null || description != null || actions != null || headerContent != null;\n\n  const activeX = activeIndex != null ? X(model.xs[activeIndex]) : 0;\n  const activeKeyIndex =\n    activeIndex != null\n      ? shown.keys.indexOf(model.keys[activeIndex])\n      : -1;\n\n  // Keep the tooltip inside the plot, beside the crosshair on the roomier side.\n  const tooltipRef = React.useRef<HTMLDivElement>(null);\n  const [tooltipWidth, setTooltipWidth] = React.useState(200);\n  React.useLayoutEffect(() => {\n    const el = tooltipRef.current;\n    if (el && el.offsetWidth && el.offsetWidth !== tooltipWidth)\n      setTooltipWidth(el.offsetWidth);\n  });\n  const tooltipLeft =\n    activeX + 14 + tooltipWidth <= W || activeX < W / 2\n      ? Math.min(activeX + 14, Math.max(0, W - tooltipWidth))\n      : Math.max(0, activeX - 14 - tooltipWidth);\n\n  const glide = motion\n    ? \"transition-transform duration-150 ease-out\"\n    : \"\";\n\n  const summaryText = (() => {\n    if (!n) return \"No data.\";\n    const parts = summary.series\n      .filter((s) => !s.hidden)\n      .map((s) => `${s.label} ${formatShare(s.share, 0)}`)\n      .join(\", \");\n    const range =\n      n > 1\n        ? `from ${formatX(model.xValues[0], \"tooltip\")} to ${formatX(model.xValues[n - 1], \"tooltip\")}`\n        : formatX(model.xValues[0], \"tooltip\");\n    return `${stack === \"expand\" ? \"Share\" : \"Stacked values\"} of ${summary.series.filter((s) => !s.hidden).length} series ${range}. Total ${valueFormatter(summary.total)}: ${parts}.`;\n  })();\n\n  const legend = showLegend && seriesKeys.length > 0 && (\n    <div\n      role=\"group\"\n      aria-label=\"Series\"\n      data-slot=\"stacked-area-legend\"\n      className={cn(\n        \"flex flex-wrap items-center gap-x-0.5 gap-y-0.5 px-3\",\n        legendPosition === \"bottom\" ? \"mt-3 border-t py-2\" : \"mt-3\",\n      )}\n    >\n      {meta.map((s, i) => {\n        const isHidden = hiddenSet.has(s.key);\n        const share = summary.series[i]?.share ?? 0;\n        return (\n          <button\n            key={s.key}\n            type=\"button\"\n            data-slot=\"stacked-area-legend-item\"\n            data-key={s.key}\n            data-hidden={isHidden || undefined}\n            aria-pressed={!isHidden}\n            title=\"Click to toggle. Alt-click to show only this series.\"\n            onClick={(event) => toggle(s.key, event.altKey)}\n            onKeyDown={(event) => {\n              if (event.key === \"Enter\" && event.altKey) {\n                event.preventDefault();\n                toggle(s.key, true);\n              }\n            }}\n            onPointerEnter={() => !isHidden && setHighlight(s.key)}\n            onPointerLeave={() => setHighlight(null)}\n            onFocus={() => !isHidden && setHighlight(s.key)}\n            onBlur={() => setHighlight(null)}\n            className={cn(\n              \"group/legend inline-flex h-7 max-w-full items-center gap-2 rounded-md px-2 text-xs transition-colors hover:bg-muted/70 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <span\n              aria-hidden=\"true\"\n              className=\"size-2.5 shrink-0 rounded-[3px] transition-[background,box-shadow] duration-200 motion-reduce:transition-none\"\n              style={\n                isHidden\n                  ? {\n                      boxShadow: `inset 0 0 0 1.25px color-mix(in oklab, ${s.color} 55%, transparent)`,\n                    }\n                  : {\n                      background: `linear-gradient(to bottom, color-mix(in oklab, ${s.color} 55%, transparent), color-mix(in oklab, ${s.color} 16%, transparent))`,\n                      boxShadow: `inset 0 1.5px 0 ${s.color}`,\n                    }\n              }\n            />\n            <span\n              className={cn(\n                \"truncate font-medium transition-colors motion-reduce:transition-none\",\n                isHidden ? \"text-muted-foreground/70\" : \"text-foreground\",\n              )}\n            >\n              {s.label}\n            </span>\n            {!isHidden && (\n              <span className=\"text-muted-foreground tabular-nums\">\n                {formatShare(share, 0)}\n              </span>\n            )}\n          </button>\n        );\n      })}\n      {legendPosition === \"bottom\" && seriesKeys.length > 1 && (\n        <span className=\"ml-auto hidden pr-2 text-[11px] text-muted-foreground @3xl/stacked-area:inline\">\n          Alt-click to show one\n        </span>\n      )}\n    </div>\n  );\n\n  const crosshairDots =\n    activeIndex != null && activeKeyIndex >= 0\n      ? shown.series\n          .map((key, s) => {\n            if (!visible[s] || shown.weight[s] < 0.5) return null;\n            return {\n              key,\n              color: meta[s]?.color ?? paletteColor(s),\n              y: Y(shown.y1[s][activeKeyIndex]),\n            };\n          })\n          .filter((d): d is NonNullable<typeof d> => d !== null)\n      : [];\n\n  const lowestVisible = visible.indexOf(true);\n  // Larger overlapping areas sit behind smaller ones; stacked bands draw top first.\n  const drawOrder = React.useMemo(() => {\n    const order = seriesKeys.map((_, s) => s);\n    if (stack === \"none\")\n      return order.sort(\n        (a, b) =>\n          Math.max(0, ...model.values[b]) - Math.max(0, ...model.values[a]),\n      );\n    return order.reverse();\n  }, [seriesKeys, stack, model]);\n\n  return (\n    <div\n      data-slot=\"stacked-area-chart\"\n      data-stack={stack}\n      data-curve={curve}\n      data-highlight={highlight ?? undefined}\n      className={cn(\n        \"@container/stacked-area flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground\",\n        \"shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        \"[--sac-fill-bottom:0] [--sac-fill-top:0.32] dark:[--sac-fill-top:0.36] data-[stack=stream]:[--sac-fill-bottom:0.1]\",\n        !(showLegend && legendPosition === \"bottom\") && \"pb-5\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex flex-col gap-4 px-5 pt-5\">\n          {(title != null || description != null || actions != null) && (\n            <div className=\"flex flex-wrap items-start gap-x-4 gap-y-3\">\n              <div className=\"min-w-[min(100%,8rem)] flex-1 space-y-1\">\n                {title != null && (\n                  <h3 className=\"truncate text-sm leading-5 font-semibold tracking-tight\">\n                    {title}\n                  </h3>\n                )}\n                {description != null && (\n                  <p\n                    id={`${id}-description`}\n                    className=\"text-[13px] leading-5 text-muted-foreground\"\n                  >\n                    {description}\n                  </p>\n                )}\n              </div>\n              {actions != null && (\n                <div className=\"flex shrink-0 flex-wrap items-center gap-2\">{actions}</div>\n              )}\n            </div>\n          )}\n          {headerContent != null && (\n            <div data-slot=\"stacked-area-header\">{headerContent}</div>\n          )}\n        </div>\n      )}\n\n      {legendPosition === \"top\" && legend}\n\n      <div className={cn(\"px-5\", hasHeader || legendPosition === \"top\" ? \"mt-4\" : \"mt-5\")}>\n        {yLabel && stack !== \"stream\" && (\n          <p\n            aria-hidden=\"true\"\n            className=\"mb-1 text-[11px] leading-4 text-muted-foreground\"\n          >\n            {yLabel}\n          </p>\n        )}\n        <div className=\"flex\">\n          {/* Value axis: an invisible copy of the labels sizes the gutter, so nothing is measured. */}\n          {stack !== \"stream\" && (\n            <div\n              aria-hidden=\"true\"\n              className=\"relative shrink-0 pr-2 text-[11px] leading-none text-muted-foreground tabular-nums\"\n              style={{ height: H }}\n            >\n              <div className=\"invisible h-0 overflow-hidden\">\n                {yTickLabels.map((label, i) => (\n                  <div key={i}>{label}</div>\n                ))}\n              </div>\n              {yTicks.map((tick, i) => (\n                <span\n                  key={`${tick}-${i}`}\n                  className={cn(\"absolute right-2 top-0 whitespace-nowrap\", glide)}\n                  style={{ transform: `translateY(calc(${r2(Y(tick))}px - 50%))` }}\n                >\n                  {yTickLabels[i]}\n                </span>\n              ))}\n            </div>\n          )}\n\n          <div className=\"min-w-0 flex-1\">\n            <div\n              ref={plotRef}\n              role=\"group\"\n              aria-roledescription=\"stacked area chart\"\n              aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the left and right arrow keys to read each point.`}\n              aria-describedby={description != null ? `${id}-description` : undefined}\n              tabIndex={n && anyVisible ? 0 : -1}\n              data-slot=\"stacked-area-plot\"\n              onPointerMove={handlePointer}\n              onPointerDown={handlePointer}\n              onPointerLeave={() => {\n                setActive(null);\n                setPointerBand(null);\n              }}\n              onKeyDown={onKeyDown}\n              onBlur={() => setActive(null)}\n              className={cn(\n                \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n                \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n              )}\n              style={{ height: H }}\n            >\n              {/* Gridlines */}\n              <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\">\n                {yTicks.map((tick, i) => (\n                  <span\n                    key={`${tick}-${i}`}\n                    className={cn(\"absolute inset-x-0 top-0 h-px\", glide)}\n                    style={{\n                      transform: `translateY(${r2(Y(tick))}px)`,\n                      background:\n                        stack !== \"stream\" && tick === scale.lo ? baseColor : gridColor,\n                    }}\n                  />\n                ))}\n              </div>\n\n              <svg\n                aria-hidden=\"true\"\n                width=\"100%\"\n                height={H}\n                viewBox={`0 0 ${W} ${H}`}\n                preserveAspectRatio=\"none\"\n                className=\"absolute inset-0 overflow-visible\"\n              >\n                <defs>\n                  <clipPath id={`${id}-clip`}>\n                    <rect x={0} y={-6} width={W} height={H + 12} />\n                  </clipPath>\n                  {meta.map((s, i) => (\n                    <linearGradient\n                      key={s.key}\n                      id={`${id}-fill-${i}`}\n                      x1=\"0\"\n                      y1=\"0\"\n                      x2=\"0\"\n                      y2=\"1\"\n                    >\n                      <stop\n                        offset=\"0\"\n                        style={{ stopColor: s.color, stopOpacity: \"var(--sac-fill-top)\" }}\n                      />\n                      <stop\n                        offset=\"1\"\n                        style={{ stopColor: s.color, stopOpacity: \"var(--sac-fill-bottom)\" }}\n                      />\n                    </linearGradient>\n                  ))}\n                </defs>\n                <g clipPath={`url(#${id}-clip)`}>\n                  {drawOrder.map((s) => {\n                    const g = geometry[s];\n                    const m = meta[s];\n                    if (!g || !m) return null;\n                    const weight = shown.weight[s] ?? 0;\n                    const isHidden = !visible[s];\n                    const drawn = weight >= 0.002 || g.thickness >= 0.05;\n                    const dim = highlight != null && highlight !== m.key;\n                    const alpha = Math.min(1, weight * 1.5);\n                    // Bands rise from the baseline and lines draw in, bottom series first.\n                    const delay = `${s * 40}ms`;\n                    return (\n                      <g\n                        key={m.key}\n                        data-slot=\"stacked-area-series\"\n                        data-key={m.key}\n                        data-hidden={isHidden || undefined}\n                        className={cn(\n                          animate &&\n                            \"motion-safe:animate-[stacked-area-rise_760ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                        )}\n                        style={{ animationDelay: delay, transformOrigin: `0px ${r2(entranceBase)}px` }}\n                      >\n                        {drawn && (\n                          <g\n                            className=\"transition-opacity duration-150 motion-reduce:transition-none\"\n                            style={{ opacity: dim ? 0.24 : 1 }}\n                          >\n                            <path\n                              d={g.area}\n                              fill={`url(#${id}-fill-${s})`}\n                              fillOpacity={(stack === \"none\" ? 0.8 : 1) * alpha}\n                            />\n                            {stack === \"stream\" && s === lowestVisible && (\n                              <path\n                                d={g.base}\n                                fill=\"none\"\n                                stroke={m.color}\n                                strokeWidth={2}\n                                strokeLinejoin=\"round\"\n                                strokeLinecap=\"round\"\n                                strokeOpacity={alpha}\n                                pathLength={1}\n                                strokeDasharray=\"1 1\"\n                                className={cn(\n                                  \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,var(--sac-line)_50%,transparent))]\",\n                                  animate &&\n                                    \"motion-safe:animate-[stacked-area-draw_820ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                                )}\n                                style={\n                                  {\n                                    \"--sac-line\": m.color,\n                                    animationDelay: delay,\n                                  } as React.CSSProperties\n                                }\n                              />\n                            )}\n                            <path\n                              d={g.line}\n                              fill=\"none\"\n                              stroke={m.color}\n                              strokeWidth={2}\n                              strokeLinejoin=\"round\"\n                              strokeLinecap=\"round\"\n                              strokeOpacity={alpha}\n                              pathLength={1}\n                              strokeDasharray=\"1 1\"\n                              className={cn(\n                                \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,var(--sac-line)_50%,transparent))]\",\n                                animate &&\n                                  \"motion-safe:animate-[stacked-area-draw_820ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                              )}\n                              style={\n                                {\n                                  \"--sac-line\": m.color,\n                                  animationDelay: delay,\n                                } as React.CSSProperties\n                              }\n                            />\n                          </g>\n                        )}\n                      </g>\n                    );\n                  })}\n                </g>\n              </svg>\n\n              {/* Reference lines */}\n              {refs.map((line, i) => {\n                const color = line.color ?? \"var(--color-muted-foreground)\";\n                return (\n                  <div\n                    key={i}\n                    aria-hidden=\"true\"\n                    data-slot=\"stacked-area-reference\"\n                    className={cn(\"pointer-events-none absolute inset-x-0 top-0\", glide)}\n                    style={{ transform: `translateY(${r2(Y(line.y))}px)` }}\n                  >\n                    <div\n                      className=\"border-t border-dashed\"\n                      style={{ borderColor: `color-mix(in oklab, ${color} 70%, transparent)` }}\n                    />\n                    {line.label && (\n                      <span\n                        className=\"absolute right-0 bottom-1 rounded-sm bg-card/85 px-1 text-[10.5px] leading-4 font-medium whitespace-nowrap tabular-nums\"\n                        style={{ color }}\n                      >\n                        {line.label}\n                      </span>\n                    )}\n                  </div>\n                );\n              })}\n\n              {/* Annotations */}\n              {marks.map((m, i) => {\n                const color = m.note.color ?? \"var(--color-foreground)\";\n                const x = X(m.x);\n                const top = 4 + m.lane * 26;\n                return (\n                  <div\n                    key={i}\n                    aria-hidden=\"true\"\n                    data-slot=\"stacked-area-annotation\"\n                    data-active={m.nearest === activeIndex || undefined}\n                    className=\"pointer-events-none absolute inset-0\"\n                  >\n                    <span\n                      className=\"absolute bottom-0 w-0 border-l border-dashed\"\n                      style={{\n                        left: r2(x),\n                        top: top + 20,\n                        borderColor: `color-mix(in oklab, ${color} 38%, transparent)`,\n                      }}\n                    />\n                    <span\n                      className=\"absolute h-[7px] w-px\"\n                      style={{ left: r2(x), top: top + 14, background: `color-mix(in oklab, ${color} 38%, transparent)` }}\n                    />\n                    <span\n                      className=\"absolute flex h-5 max-w-full items-center gap-1.5 rounded-md border bg-card px-1.5 text-[11px] leading-none font-medium whitespace-nowrap text-foreground shadow-xs\"\n                      style={{\n                        top,\n                        left: r2(m.left + (x - m.fraction * W)),\n                        width: m.w,\n                      }}\n                    >\n                      <span\n                        className=\"size-1.5 shrink-0 rounded-full\"\n                        style={{ background: color }}\n                      />\n                      <span className=\"truncate\">{m.note.label}</span>\n                    </span>\n                  </div>\n                );\n              })}\n\n              {/* Crosshair */}\n              {activePoint && (\n                <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\">\n                  <div\n                    className={cn(\"absolute top-0 left-0 h-full w-px\", glide)}\n                    style={{ transform: `translateX(${r2(activeX)}px)` }}\n                  >\n                    <div\n                      className=\"absolute inset-x-0 bottom-0 bg-foreground/25\"\n                      style={{ top: padTop - 4 }}\n                    />\n                  </div>\n                  {crosshairDots.map((dot) => (\n                    <span\n                      key={dot.key}\n                      className={cn(\n                        \"absolute top-0 left-0 -mt-1 -ml-1 size-2 rounded-full\",\n                        glide,\n                      )}\n                      style={{\n                        background: dot.color,\n                        boxShadow: `0 0 0 1.5px var(--color-card), 0 0 0 5px color-mix(in oklab, ${dot.color} 18%, transparent)`,\n                        transform: `translate(${r2(activeX)}px, ${r2(dot.y)}px)`,\n                      }}\n                    />\n                  ))}\n                </div>\n              )}\n\n              {/* Tooltip */}\n              {activePoint && (\n                <div\n                  ref={tooltipRef}\n                  data-slot=\"stacked-area-tooltip\"\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"pointer-events-none absolute top-0 left-0 z-10 min-w-48 rounded-xl border border-border/70 bg-popover/90 px-3 py-2.5 text-xs text-popover-foreground shadow-xl backdrop-blur-md\",\n                    glide,\n                  )}\n                  style={{\n                    transform: `translate(${r2(tooltipLeft)}px, ${padTop}px)`,\n                  }}\n                >\n                  {renderTooltip ? (\n                    renderTooltip(activePoint)\n                  ) : (\n                    <DefaultTooltip\n                      point={activePoint}\n                      format={valueFormatter}\n                      emphasis={pointerBand}\n                    />\n                  )}\n                </div>\n              )}\n\n              {!n && (\n                <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                  No data to show.\n                </p>\n              )}\n              {n > 0 && !anyVisible && (\n                <div className=\"absolute inset-0 flex flex-col items-center justify-center gap-2 text-xs text-muted-foreground\">\n                  <p>Every series is hidden.</p>\n                  <button\n                    type=\"button\"\n                    onClick={() => setHidden([])}\n                    className={cn(\n                      \"h-7 rounded-md border bg-card px-2.5 font-medium text-foreground shadow-xs hover:bg-muted\",\n                      focusRing,\n                    )}\n                  >\n                    Show all\n                  </button>\n                </div>\n              )}\n            </div>\n\n            {/* Time axis */}\n            <div\n              aria-hidden=\"true\"\n              className=\"relative mt-2 h-4 text-[11px] leading-4 text-muted-foreground tabular-nums\"\n            >\n              {xTicks.map((tick, i) => {\n                const x = X(tick.x);\n                if (x < -1 || x > W + 1) return null;\n                const edgeClass =\n                  x < 28 ? \"\" : x > W - 28 ? \"-translate-x-full\" : \"-translate-x-1/2\";\n                return (\n                  <span\n                    key={`${tick.x}-${i}`}\n                    className={cn(\"absolute top-0 whitespace-nowrap\", edgeClass)}\n                    style={{ left: r2(x) }}\n                  >\n                    {tick.label}\n                  </span>\n                );\n              })}\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {legendPosition === \"bottom\" && legend}\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{index}</th>\n              {meta.map((s) => (\n                <th key={s.key} scope=\"col\">\n                  {s.label}\n                </th>\n              ))}\n              <th scope=\"col\">Total</th>\n            </tr>\n          </thead>\n          <tbody>\n            {model.rows.map((_, j) => (\n              <tr key={model.keys[j]}>\n                <th scope=\"row\">{formatX(model.xValues[j], \"tooltip\")}</th>\n                {meta.map((s, si) => (\n                  <td key={s.key}>{valueFormatter(model.values[si][j])}</td>\n                ))}\n                <td>\n                  {valueFormatter(\n                    model.values.reduce((sum, values) => sum + values[j], 0),\n                  )}\n                </td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </p>\n\n      <style href=\"overtrue-stacked-area-chart\" precedence=\"default\">\n        {`@keyframes stacked-area-rise{from{transform:scaleY(0)}to{transform:scaleY(1)}}@keyframes stacked-area-draw{from{stroke-dashoffset:1}to{stroke-dashoffset:0}}`}\n      </style>\n    </div>\n  );\n}\n\nfunction DefaultTooltip({\n  point,\n  format,\n  emphasis,\n}: {\n  point: StackedAreaPoint;\n  format: (value: number) => string;\n  emphasis: string | null;\n}) {\n  return (\n    <div className=\"grid grid-cols-[auto_minmax(0,1fr)_auto_auto] items-center gap-x-2 gap-y-1\">\n      <p className=\"col-span-4 mb-1 font-medium text-foreground\">{point.label}</p>\n      {point.items.map((item) => (\n        <React.Fragment key={item.key}>\n          <span\n            aria-hidden=\"true\"\n            className=\"h-2.5 w-[3px] rounded-full\"\n            style={{ background: item.color }}\n          />\n          <span\n            className={cn(\n              \"truncate\",\n              emphasis === item.key ? \"font-medium text-foreground\" : \"text-muted-foreground\",\n            )}\n          >\n            {item.label}\n          </span>\n          <span\n            className={cn(\n              \"pl-3 text-right tabular-nums\",\n              emphasis === item.key ? \"font-semibold\" : \"font-medium\",\n            )}\n          >\n            {format(item.value)}\n          </span>\n          <span className=\"w-11 text-right text-[11px] text-muted-foreground tabular-nums\">\n            {formatShare(item.share)}\n          </span>\n        </React.Fragment>\n      ))}\n      <span className=\"col-span-4 my-0.5 h-px bg-border\" />\n      <span />\n      <span className=\"text-muted-foreground\">Total</span>\n      <span className=\"pl-3 text-right font-semibold tabular-nums\">\n        {format(point.total)}\n      </span>\n      <span />\n      {point.annotations.map((note, i) => (\n        <p\n          key={i}\n          className=\"col-span-4 mt-1 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground\"\n        >\n          <span\n            aria-hidden=\"true\"\n            className=\"size-1.5 shrink-0 rounded-full\"\n            style={{ background: note.color ?? \"var(--color-foreground)\" }}\n          />\n          {note.label}\n        </p>\n      ))}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/latency-histogram.tsx",
      "type": "registry:component",
      "target": "components/overtrue/latency-histogram.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconX as X } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LatencyScale = \"linear\" | \"log\";\n\nexport type LatencyRange = [min: number, max: number];\n\nexport interface LatencyBucket {\n  /** Inclusive lower edge. */\n  start: number;\n  /** Exclusive upper edge. */\n  end: number;\n  count: number;\n}\n\n/** One bar as drawn, passed to `renderTooltip`. */\nexport interface LatencyHistogramBucket extends LatencyBucket {\n  index: number;\n  /** Share of all requests in this bucket, 0–1. */\n  share: number;\n  /** Share of requests at or below this bucket's upper edge, 0–1. */\n  cumulative: number;\n  /** Raw comparison count in the same range, when `compare` is set. */\n  compare?: number;\n  /** Comparison share of its own total, 0–1. */\n  compareShare?: number;\n  /** The catch-all bar for values past the linear domain. */\n  overflow: boolean;\n  /** Whether the bucket lies past `threshold`. */\n  overThreshold: boolean;\n}\n\nexport interface LatencyHistogramColors {\n  bar: string;\n  compare: string;\n  threshold: string;\n  marker: string;\n  selection: string;\n}\n\nexport interface LatencyHistogramProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Raw samples. Bucketed for you, with exact percentiles. */\n  values?: number[];\n  /** Pre-bucketed counts, used when `values` is not given. Percentiles are interpolated. */\n  buckets?: LatencyBucket[];\n  /** A comparison distribution, e.g. yesterday. Scaled to the main total so shapes compare. */\n  compare?: number[] | LatencyBucket[];\n  /** Name of the comparison in the legend and tooltip. */\n  compareLabel?: string;\n  /** Name of the main series in the legend. */\n  seriesLabel?: string;\n  /** Draw the comparison as a stepped line or as outlined bars. */\n  compareStyle?: \"step\" | \"outline\";\n  /** Percentiles to mark, as numbers such as 50 or 99.9. */\n  percentiles?: number[];\n  /** Latency objective. The slow tail past it is shaded and measured. */\n  threshold?: number;\n  thresholdLabel?: string;\n  /** X scale. Pass with `onScaleChange` to control the built-in toggle. */\n  scale?: LatencyScale;\n  defaultScale?: LatencyScale;\n  onScaleChange?: (scale: LatencyScale) => void;\n  /** Show the linear/log toggle. Defaults to true. */\n  showScaleToggle?: boolean;\n  /** Brushed range. Pass `null` for none; leave undefined to let the component manage it. */\n  range?: LatencyRange | null;\n  defaultRange?: LatencyRange | null;\n  onRangeChange?: (range: LatencyRange | null) => void;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the scale toggle. */\n  actions?: React.ReactNode;\n  /** Unit of the values. Defaults to \"ms\"; ms readouts switch to seconds from 1,000. */\n  unit?: string;\n  /** Formats latencies in readouts, markers, and ticks. */\n  valueFormatter?: (value: number) => string;\n  /** Target number of bars. Defaults to 40. */\n  bucketCount?: number;\n  /** Fix the latency domain. Linear charts otherwise end near p99.5 and gather the rest in an overflow bar. */\n  domain?: LatencyRange;\n  /** Plot height in pixels. Defaults to a third of the plot width, between 140 and 220. */\n  height?: number;\n  /** Override any series color with a CSS color. */\n  colors?: Partial<LatencyHistogramColors>;\n  /** Replaces the hover tooltip content. */\n  renderTooltip?: (bucket: LatencyHistogramBucket) => React.ReactNode;\n  /** Show the percentile summary above the plot. Defaults to true. */\n  showSummary?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst tidy = (value: number) => +value.toPrecision(12);\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst whole = new Intl.NumberFormat(\"en-US\");\n\nfunction makeFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  const join = (text: string, u: string) =>\n    u ? `${text}${tight ? \"\" : \" \"}${u}` : text;\n  return (value: number) => {\n    if (!Number.isFinite(value)) return \"—\";\n    const a = Math.abs(value);\n    if (unit === \"ms\" && a >= 1000)\n      return `${tidy(+(value / 1000).toFixed(a >= 10_000 ? 1 : 2))}s`;\n    const digits = a >= 100 || a === 0 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : 3;\n    return join(String(tidy(+value.toFixed(digits))), unit);\n  };\n}\n\nfunction makeTickFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  return (value: number) => {\n    if (value === 0) return \"0\";\n    if (unit === \"ms\" && Math.abs(value) >= 1000)\n      return `${tidy(value / 1000)}s`;\n    return `${tidy(value)}${tight ? \"\" : \" \"}${unit}`;\n  };\n}\n\nfunction percentLabel(share: number) {\n  const pct = share * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct > 99.9 && pct < 100) return \">99.9%\";\n  return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`;\n}\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Round down or up to the nearest 1, 2, or 5 times a power of ten. */\nfunction nice125(value: number, up: boolean) {\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const r = value / magnitude;\n  const steps = [1, 2, 5, 10];\n  if (up) return (steps.find((s) => s >= r - 1e-9) ?? 10) * magnitude;\n  return ([...steps].reverse().find((s) => s <= r + 1e-9) ?? 1) * magnitude;\n}\n\nfunction lowerBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] < value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\nfunction upperBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] <= value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Bar extends LatencyBucket {\n  overflow: boolean;\n  /** Left and right edges as 0–1 positions. */\n  x0: number;\n  x1: number;\n}\n\ninterface Distribution {\n  sorted: Float64Array | null;\n  buckets: LatencyBucket[] | null;\n  total: number;\n  min: number;\n  max: number;\n  mean: number;\n}\n\nfunction distributionOf(\n  values?: number[],\n  buckets?: LatencyBucket[],\n): Distribution {\n  if (values) {\n    const clean = values.filter((value) => Number.isFinite(value));\n    const sorted = Float64Array.from(clean).sort();\n    let sum = 0;\n    for (const value of sorted) sum += value;\n    return {\n      sorted,\n      buckets: null,\n      total: sorted.length,\n      min: sorted.length ? sorted[0] : 0,\n      max: sorted.length ? sorted[sorted.length - 1] : 0,\n      mean: sorted.length ? sum / sorted.length : 0,\n    };\n  }\n  const list = (buckets ?? [])\n    .filter(\n      (b) =>\n        Number.isFinite(b.start) && Number.isFinite(b.end) && b.end > b.start,\n    )\n    .sort((a, b) => a.start - b.start);\n  let total = 0;\n  let sum = 0;\n  for (const b of list) {\n    total += Math.max(0, b.count);\n    sum += (Math.max(0, b.count) * (b.start + b.end)) / 2;\n  }\n  return {\n    sorted: null,\n    buckets: list,\n    total,\n    min: list.length ? list[0].start : 0,\n    max: list.length ? list[list.length - 1].end : 0,\n    mean: total ? sum / total : 0,\n  };\n}\n\n/** Nearest-rank percentile from samples; interpolated inside buckets otherwise. */\nfunction quantile(d: Distribution, p: number) {\n  if (!d.total) return 0;\n  if (d.sorted)\n    return d.sorted[\n      Math.min(d.total - 1, Math.max(0, Math.ceil(p * d.total) - 1))\n    ];\n  const target = p * d.total;\n  let cumulative = 0;\n  for (const b of d.buckets!) {\n    if (cumulative + b.count >= target && b.count > 0)\n      return b.start + ((target - cumulative) / b.count) * (b.end - b.start);\n    cumulative += b.count;\n  }\n  return d.max;\n}\n\n/** Requests with a value in [a, b]. Partial buckets count in proportion. */\nfunction countBetween(d: Distribution, a: number, b: number) {\n  if (d.sorted) return upperBound(d.sorted, b) - lowerBound(d.sorted, a);\n  let count = 0;\n  for (const bucket of d.buckets!) {\n    const overlap = Math.min(b, bucket.end) - Math.max(a, bucket.start);\n    if (overlap > 0)\n      count += (bucket.count * overlap) / (bucket.end - bucket.start);\n  }\n  return count;\n}\n\nfunction countAbove(d: Distribution, value: number) {\n  if (d.sorted) return d.total - upperBound(d.sorted, value);\n  return countBetween(d, value, Infinity);\n}\n\ninterface Layout {\n  bars: Bar[];\n  lo: number;\n  hi: number;\n  /** Largest value covered, including the overflow bar. */\n  top: number;\n  pos: (value: number) => number;\n  inv: (x: number) => number;\n}\n\nfunction layoutOf(\n  d: Distribution,\n  scale: LatencyScale,\n  bucketCount: number,\n  reach: number,\n  domain?: LatencyRange,\n): Layout {\n  const count = Math.max(4, Math.round(bucketCount));\n  // Pre-bucketed data keeps its own edges.\n  if (d.buckets) {\n    const list = d.buckets;\n    const first = list[0]?.start ?? 0;\n    const last = list[list.length - 1]?.end ?? 1;\n    if (scale === \"log\") {\n      const positive =\n        list.find((b) => b.start > 0)?.start ?? list[0]?.end ?? 1;\n      const lo = first > 0 ? first : positive / 2;\n      const span = Math.log(last / lo) || 1;\n      const pos = (v: number) =>\n        Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n      const inv = (x: number) => lo * Math.exp(x * span);\n      return {\n        bars: list.map((b) => ({\n          ...b,\n          overflow: false,\n          x0: pos(b.start),\n          x1: pos(b.end),\n        })),\n        lo,\n        hi: last,\n        top: last,\n        pos,\n        inv,\n      };\n    }\n    const span = last - first || 1;\n    const pos = (v: number) => Math.min(1, Math.max(0, (v - first) / span));\n    const inv = (x: number) => first + x * span;\n    return {\n      bars: list.map((b) => ({\n        ...b,\n        overflow: false,\n        x0: pos(b.start),\n        x1: pos(b.end),\n      })),\n      lo: first,\n      hi: last,\n      top: last,\n      pos,\n      inv,\n    };\n  }\n\n  const sorted = d.sorted!;\n  if (scale === \"log\") {\n    const positive = sorted[lowerBound(sorted, Number.MIN_VALUE)] ?? 1;\n    const lo =\n      domain?.[0] && domain[0] > 0\n        ? domain[0]\n        : nice125(Math.max(positive, 1e-9), false);\n    const hi = Math.max(\n      domain?.[1] ?? nice125(Math.max(d.max, lo * 10), true),\n      lo * 1.0001,\n    );\n    const span = Math.log(hi / lo);\n    const step = span / count;\n    const bars: Bar[] = Array.from({ length: count }, (_, i) => ({\n      start: lo * Math.exp(i * step),\n      end: lo * Math.exp((i + 1) * step),\n      count: 0,\n      overflow: false,\n      x0: i / count,\n      x1: (i + 1) / count,\n    }));\n    for (const v of sorted) {\n      const i = v <= lo ? 0 : Math.floor(Math.log(v / lo) / step);\n      bars[Math.min(count - 1, Math.max(0, i))].count += 1;\n    }\n    const pos = (v: number) =>\n      Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n    return { bars, lo, hi, top: hi, pos, inv: (x) => lo * Math.exp(x * span) };\n  }\n\n  const lo = domain?.[0] ?? (d.min >= 0 ? 0 : -niceStep(-d.min));\n  const wanted = domain?.[1] ?? Math.max(reach, lo + 1e-9);\n  const step = niceStep((wanted - lo) / count);\n  const n = Math.max(1, Math.ceil((wanted - lo) / step - 1e-9));\n  const hi = lo + n * step;\n  const overflowCount = d.total - upperBound(sorted, hi);\n  const units = overflowCount > 0 ? n + 1.7 : n;\n  const bars: Bar[] = Array.from({ length: n }, (_, i) => ({\n    start: tidy(lo + i * step),\n    end: tidy(lo + (i + 1) * step),\n    count: 0,\n    overflow: false,\n    x0: i / units,\n    x1: (i + 1) / units,\n  }));\n  for (\n    let k = lowerBound(sorted, lo), end = upperBound(sorted, hi);\n    k < end;\n    k++\n  )\n    bars[Math.min(n - 1, Math.floor((sorted[k] - lo) / step))].count += 1;\n  // Values below a fixed domain fold into the first bar.\n  bars[0].count += lowerBound(sorted, lo);\n  const top = Math.max(hi, d.max);\n  if (overflowCount > 0)\n    bars.push({\n      start: hi,\n      end: top,\n      count: overflowCount,\n      overflow: true,\n      x0: (n + 0.7) / units,\n      x1: 1,\n    });\n  const mainEnd = n / units;\n  const overflowStart = (n + 0.7) / units;\n  const pos = (v: number) => {\n    if (v <= hi) return Math.max(0, ((v - lo) / (hi - lo)) * mainEnd);\n    if (overflowCount <= 0 || top <= hi) return mainEnd;\n    return Math.min(\n      1,\n      overflowStart + ((v - hi) / (top - hi)) * (1 - overflowStart),\n    );\n  };\n  const inv = (x: number) => {\n    if (x <= mainEnd) return lo + (x / mainEnd) * (hi - lo);\n    if (x < overflowStart || overflowCount <= 0) return hi;\n    return hi + ((x - overflowStart) / (1 - overflowStart)) * (top - hi);\n  };\n  return { bars, lo, hi, top, pos, inv };\n}\n\n/** Bin a comparison into the main bars' edges. */\nfunction binCompare(compare: number[] | LatencyBucket[], bars: Bar[]) {\n  const counts = new Array<number>(bars.length).fill(0);\n  if (!bars.length) return { counts, total: 0 };\n  const find = (v: number) => {\n    let lo = 0;\n    let hi = bars.length - 1;\n    while (lo < hi) {\n      const mid = (lo + hi + 1) >> 1;\n      if (bars[mid].start <= v) lo = mid;\n      else hi = mid - 1;\n    }\n    return lo;\n  };\n  let total = 0;\n  for (const item of compare as (number | LatencyBucket)[]) {\n    if (typeof item === \"number\") {\n      if (!Number.isFinite(item)) continue;\n      counts[find(item)] += 1;\n      total += 1;\n    } else if (Number.isFinite(item.count)) {\n      counts[find((item.start + item.end) / 2)] += item.count;\n      total += item.count;\n    }\n  }\n  return { counts, total };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\nconst percentileName = (p: number) => `p${tidy(p)}`;\n\n/* ------------------------------------------------------------------------ */\n/* LatencyHistogram                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A latency distribution: bucketed requests with percentile markers, an SLO tail,\n * an optional comparison, and brushing to measure any range.\n */\nexport function LatencyHistogram({\n  values,\n  buckets,\n  compare,\n  compareLabel = \"Previous\",\n  seriesLabel = \"Current\",\n  compareStyle = \"step\",\n  percentiles = [50, 90, 95, 99],\n  threshold,\n  thresholdLabel = \"SLO\",\n  scale: scaleProp,\n  defaultScale = \"linear\",\n  onScaleChange,\n  showScaleToggle = true,\n  range: rangeProp,\n  defaultRange = null,\n  onRangeChange,\n  title,\n  description,\n  actions,\n  unit = \"ms\",\n  valueFormatter,\n  bucketCount = 40,\n  domain,\n  height,\n  colors: colorsProp,\n  renderTooltip,\n  showSummary = true,\n  className,\n  ...props\n}: LatencyHistogramProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const format = React.useMemo(\n    () => valueFormatter ?? makeFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const formatTick = React.useMemo(\n    () => valueFormatter ?? makeTickFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const colors: LatencyHistogramColors = {\n    bar: \"var(--color-chart-1)\",\n    compare: \"var(--color-muted-foreground)\",\n    threshold: \"var(--color-destructive)\",\n    marker: \"var(--color-foreground)\",\n    selection: \"var(--color-primary)\",\n    ...colorsProp,\n  };\n  const [scale, setScale] = useControllable(\n    scaleProp,\n    defaultScale,\n    onScaleChange,\n  );\n  const [range, setRange] = useControllable<LatencyRange | null>(\n    rangeProp,\n    defaultRange,\n    onRangeChange,\n  );\n  const hasThreshold = threshold != null && Number.isFinite(threshold);\n\n  const dist = React.useMemo(\n    () => distributionOf(values, buckets),\n    [values, buckets],\n  );\n  const sortedPercentiles = React.useMemo(\n    () =>\n      [...new Set(percentiles.filter((p) => p > 0 && p < 100))].sort(\n        (a, b) => a - b,\n      ),\n    [percentiles],\n  );\n  const empty = dist.total === 0;\n  const marks = React.useMemo(\n    () =>\n      dist.total === 0\n        ? []\n        : sortedPercentiles.map((p) => ({ p, value: quantile(dist, p / 100) })),\n    [dist, sortedPercentiles],\n  );\n\n  // Linear charts end just past the slow tail (and the SLO); the rest lands in an overflow bar.\n  const reach = Math.max(\n    quantile(dist, 0.995),\n    (marks[marks.length - 1]?.value ?? 0) * 1.04,\n    hasThreshold ? threshold! * 1.12 : 0,\n  );\n  const layout = React.useMemo(\n    () => layoutOf(dist, scale, bucketCount, reach, domain),\n    [dist, scale, bucketCount, reach, domain],\n  );\n  const { bars, pos, inv } = layout;\n\n  const comparison = React.useMemo(() => {\n    if (!compare?.length) return null;\n    const { counts, total } = binCompare(compare, bars);\n    const percentilesOf = (() => {\n      if (typeof compare[0] === \"number\") {\n        const d = distributionOf(compare as number[]);\n        return sortedPercentiles.map((p) => quantile(d, p / 100));\n      }\n      const d = distributionOf(undefined, compare as LatencyBucket[]);\n      return sortedPercentiles.map((p) => quantile(d, p / 100));\n    })();\n    const factor = total ? dist.total / total : 0;\n    return {\n      counts,\n      total,\n      scaled: counts.map((c) => c * factor),\n      percentiles: percentilesOf,\n    };\n  }, [compare, bars, dist.total, sortedPercentiles]);\n\n  const maxCount = Math.max(\n    1,\n    ...bars.map((b) => b.count),\n    ...(comparison?.scaled ?? [0]),\n  );\n  // The tallest bar fills the plot; gridlines sit at round counts below it.\n  const yMax = maxCount * 1.06;\n  const yStep = niceStep(maxCount / 3.2);\n  const yTicks = Array.from(\n    { length: Math.floor(yMax / yStep + 1e-9) + 1 },\n    (_, i) => tidy(i * yStep),\n  );\n\n  const over = hasThreshold ? countAbove(dist, threshold!) : 0;\n  const overShare = dist.total ? over / dist.total : 0;\n  const thresholdX = hasThreshold ? pos(threshold!) : 1;\n\n  const cumulative = React.useMemo(() => {\n    let running = 0;\n    return bars.map((b) => (running += b.count) / (dist.total || 1));\n  }, [bars, dist.total]);\n\n  const bucketAt = (index: number): LatencyHistogramBucket => {\n    const b = bars[index];\n    return {\n      index,\n      start: b.start,\n      end: b.end,\n      count: b.count,\n      share: dist.total ? b.count / dist.total : 0,\n      cumulative: cumulative[index] ?? 0,\n      compare: comparison ? comparison.counts[index] : undefined,\n      compareShare: comparison?.total\n        ? comparison.counts[index] / comparison.total\n        : undefined,\n      overflow: b.overflow,\n      overThreshold: hasThreshold && b.start >= threshold!,\n    };\n  };\n\n  /* -------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(el.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 560;\n\n  // Percentile chips stack into lanes only when they would collide.\n  // With the summary on show, crowded chips drop their values, which the summary repeats.\n  const chips = React.useMemo(() => {\n    const place = (withValue: boolean) => {\n      const lanes: number[] = [];\n      return marks.map((mark) => {\n        const text = withValue\n          ? `${percentileName(mark.p)} ${format(mark.value)}`\n          : percentileName(mark.p);\n        const w = text.length * 6.1 + 14;\n        const x = pos(mark.value) * W;\n        const left = Math.min(Math.max(0, x - w / 2), Math.max(0, W - w));\n        let lane = lanes.findIndex((right) => right + 4 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...mark, x, left, lane, w, withValue };\n      });\n    };\n    const full = place(true);\n    if (!showSummary || full.every((chip) => chip.lane === 0)) return full;\n    return place(false);\n  }, [marks, pos, W, format, showSummary]);\n  const laneCount = Math.max(1, ...chips.map((chip) => chip.lane + 1));\n  const chipTop = laneCount * 20 + 6;\n  // Without a fixed height the plot follows the card width, shorter on narrow cards.\n  const H = Math.max(\n    80,\n    height ?? Math.round(Math.min(220, Math.max(140, W * 0.34))),\n  );\n  const barsHeight = H - chipTop;\n\n  const xTicks = React.useMemo(() => {\n    const ticks: number[] = [];\n    if (empty) return ticks;\n    if (scale === \"log\" || dist.buckets) {\n      if (scale === \"log\") {\n        const lo = layout.lo;\n        const hi = layout.hi;\n        const candidates: number[] = [];\n        for (\n          let e = Math.floor(Math.log10(lo));\n          e <= Math.ceil(Math.log10(hi));\n          e++\n        )\n          for (const m of [1, 2, 5]) {\n            const v = tidy(m * 10 ** e);\n            if (v >= lo * 0.999 && v <= hi * 1.001) candidates.push(v);\n          }\n        // Thin out 2s and then 5s until labels have room.\n        for (const keep of [[1, 2, 5], [1, 5], [1]]) {\n          const list = candidates.filter((v) =>\n            keep.includes(\n              Math.round(v / 10 ** Math.floor(Math.log10(v) + 1e-9)),\n            ),\n          );\n          let ok = true;\n          for (let i = 1; i < list.length; i++)\n            if ((pos(list[i]) - pos(list[i - 1])) * W < 44) ok = false;\n          if (ok || keep.length === 1) return list;\n        }\n      }\n    }\n    const lo = layout.lo;\n    const hi = layout.hi;\n    const step = niceStep((hi - lo) / Math.max(2, Math.floor(W / 76)));\n    for (\n      let v = Math.ceil(lo / step - 1e-9) * step;\n      v <= hi + step * 1e-6;\n      v += step\n    )\n      ticks.push(tidy(v));\n    return ticks;\n  }, [scale, dist.buckets, layout, pos, W, empty]);\n\n  /* ----------------------------------------------------------- animation */\n\n  // Bars grow in on mount and whenever the bucket layout changes; data updates tween.\n  // Keyed on scale and bar count only, so live data with a drifting tail tweens instead of regrowing.\n  const structure = `${scale}:${bars.length}`;\n  const [grown, setGrown] = React.useState<string | null>(null);\n  const [intro, setIntro] = React.useState(true);\n  React.useEffect(() => {\n    if (reduced) {\n      setGrown(structure);\n      setIntro(false);\n      return;\n    }\n    setIntro(true);\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => setGrown(structure));\n    });\n    const timer = window.setTimeout(\n      () => setIntro(false),\n      900 + bars.length * 9,\n    );\n    return () => {\n      cancelAnimationFrame(frame);\n      window.clearTimeout(timer);\n    };\n  }, [structure, reduced, bars.length]);\n  const isGrown = grown === structure;\n\n  /* --------------------------------------------------------- interaction */\n\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [brush, setBrush] = React.useState<LatencyRange | null>(null);\n  const drag = React.useRef<{\n    x: number;\n    value: number;\n    moved: boolean;\n  } | null>(null);\n  const anchor = React.useRef<number | null>(null);\n\n  const xToFraction = (clientX: number) => {\n    const rect = plotRef.current!.getBoundingClientRect();\n    return Math.min(1, Math.max(0, (clientX - rect.left) / (rect.width || 1)));\n  };\n  const barAt = (x: number) => {\n    for (let i = 0; i < bars.length; i++)\n      if (x >= bars[i].x0 && x <= bars[i].x1) return i;\n    // In a gap: the nearest bar.\n    let best = -1;\n    let distance = Infinity;\n    bars.forEach((b, i) => {\n      const dd = Math.min(Math.abs(x - b.x0), Math.abs(x - b.x1));\n      if (dd < distance) {\n        distance = dd;\n        best = i;\n      }\n    });\n    return best < 0 ? null : best;\n  };\n\n  const clampRange = (a: number, b: number): LatencyRange => [\n    Math.min(a, b),\n    Math.max(a, b),\n  ];\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || !bars.length) return;\n    const x = xToFraction(event.clientX);\n    drag.current = { x: event.clientX, value: inv(x), moved: false };\n    event.currentTarget.setPointerCapture(event.pointerId);\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const x = xToFraction(event.clientX);\n    const d = drag.current;\n    if (d) {\n      if (!d.moved && Math.abs(event.clientX - d.x) > 3) d.moved = true;\n      if (d.moved) {\n        setBrush(clampRange(d.value, inv(x)));\n        setHover(null);\n        return;\n      }\n    }\n    setHover(barAt(x));\n  };\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    drag.current = null;\n    if (!d) return;\n    if (d.moved) {\n      const next = clampRange(d.value, inv(xToFraction(event.clientX)));\n      setBrush(null);\n      setRange(next[1] - next[0] > 0 ? next : null);\n    } else if (range) setRange(null);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const current = active ?? -1;\n    const step = (delta: number) =>\n      Math.min(\n        bars.length - 1,\n        Math.max(\n          0,\n          current < 0 ? (delta > 0 ? 0 : bars.length - 1) : current + delta,\n        ),\n      );\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\") next = step(1);\n    else if (event.key === \"ArrowLeft\") next = step(-1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = bars.length - 1;\n    else if (event.key === \"Enter\" && current >= 0) {\n      setRange([bars[current].start, bars[current].end]);\n      event.preventDefault();\n      return;\n    } else if (event.key === \"Escape\") {\n      if (range) setRange(null);\n      else setActive(null);\n      anchor.current = null;\n      event.preventDefault();\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    if (event.shiftKey) {\n      if (anchor.current == null) anchor.current = current < 0 ? next : current;\n      const a = Math.min(anchor.current, next);\n      const b = Math.max(anchor.current, next);\n      setRange([bars[a].start, bars[b].end]);\n    } else anchor.current = null;\n    setActive(next);\n  };\n\n  const shownRange = brush ?? range;\n  const rangeCount = shownRange\n    ? countBetween(dist, shownRange[0], shownRange[1])\n    : 0;\n  const rangeShare = dist.total ? rangeCount / dist.total : 0;\n  const focusIndex = hover ?? active;\n  const focusBucket =\n    focusIndex != null && bars[focusIndex] ? bucketAt(focusIndex) : null;\n\n  /* -------------------------------------------------------------- render */\n\n  const describeBucket = (b: LatencyHistogramBucket) =>\n    `${b.overflow ? `${format(b.start)} and above` : `${format(b.start)} to ${format(b.end)}`}: ${whole.format(Math.round(b.count))} requests, ${percentLabel(b.share)}`;\n  const summaryText = [\n    `${whole.format(Math.round(dist.total))} requests.`,\n    marks\n      .map((mark) => `${percentileName(mark.p)} ${format(mark.value)}`)\n      .join(\", \") + \".\",\n    hasThreshold\n      ? `${percentLabel(overShare)} over the ${thresholdLabel} of ${format(threshold!)}.`\n      : \"\",\n  ]\n    .filter(Boolean)\n    .join(\" \");\n  const hasHeader =\n    title != null || description != null || actions != null || showScaleToggle;\n  const transition = intro\n    ? \"transform 760ms cubic-bezier(.16,1,.3,1)\"\n    : \"transform 520ms cubic-bezier(.16,1,.3,1)\";\n  const barFill = (color: string) =>\n    `color-mix(in oklab, ${color} 72%, var(--color-card))`;\n\n  // The comparison as one stepped path across the bars.\n  const comparePath = React.useMemo(() => {\n    if (!comparison || compareStyle !== \"step\") return null;\n    let path = \"\";\n    let previousEnd = -1;\n    bars.forEach((b, i) => {\n      const y = 100 - (comparison.scaled[i] / yMax) * 100;\n      const x0 = b.x0 * 1000;\n      const x1 = b.x1 * 1000;\n      if (Math.abs(x0 - previousEnd) > 0.5)\n        path += `${path ? \"V100\" : \"\"}M${x0.toFixed(2)} 100`;\n      path += `V${y.toFixed(2)}H${x1.toFixed(2)}`;\n      previousEnd = x1;\n    });\n    return path + \"V100\";\n  }, [comparison, compareStyle, bars, yMax]);\n\n  return (\n    <div\n      data-slot=\"latency-histogram\"\n      data-scale={scale}\n      data-brushing={brush ? true : undefined}\n      className={cn(\n        \"@container/histogram flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5\">\n          <div className=\"min-w-0 flex-1 space-y-1\">\n            {title != null && (\n              <h3 className=\"truncate text-sm leading-6 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            )}\n            {description != null && (\n              <p\n                id={`${id}-description`}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </p>\n            )}\n          </div>\n          <div className=\"flex shrink-0 items-center gap-2\">\n            {actions}\n            {showScaleToggle && (\n              <div\n                role=\"group\"\n                aria-label=\"X axis scale\"\n                data-slot=\"histogram-scale-toggle\"\n                className=\"inline-flex h-7 items-center rounded-md border bg-muted/40 p-0.5\"\n              >\n                {([\"linear\", \"log\"] as const).map((option) => (\n                  <button\n                    key={option}\n                    type=\"button\"\n                    aria-pressed={scale === option}\n                    onClick={() => setScale(option)}\n                    className={cn(\n                      \"h-full rounded-[5px] px-2 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs motion-reduce:transition-none\",\n                      focusRing,\n                    )}\n                  >\n                    {option === \"linear\" ? \"Linear\" : \"Log\"}\n                  </button>\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        // Narrow cards trade the stat grid for one line, so the distribution stays in view.\n        <dl\n          data-slot=\"histogram-summary-compact\"\n          className={cn(\n            \"mx-4 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs @md/histogram:hidden\",\n            hasHeader ? \"mt-1.5\" : \"mt-4\",\n          )}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div key={mark.p} className=\"flex items-baseline gap-1\">\n                <dt className=\"font-mono text-[11px] text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"font-semibold tabular-nums\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"font-mono text-[10px] tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"}\n                    {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"flex items-baseline gap-1\">\n              <dd\n                className={cn(\n                  \"font-semibold tabular-nums\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dt className=\"text-[11px] text-muted-foreground\">\n                over {thresholdLabel}\n              </dt>\n            </div>\n          )}\n        </dl>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        <dl\n          data-slot=\"histogram-summary\"\n          className={cn(\n            \"mx-4 hidden overflow-hidden rounded-lg bg-muted/50 @md/histogram:grid dark:bg-muted/30\",\n            hasHeader ? \"mt-3\" : \"mt-4\",\n          )}\n          style={{\n            gridTemplateColumns: `repeat(${marks.length + (hasThreshold ? 1 : 0)}, minmax(0, 1fr))`,\n          }}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div\n                key={mark.p}\n                className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\"\n              >\n                <dt className=\"font-mono text-[11px] leading-4 text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"truncate font-mono text-[11px] leading-4 whitespace-nowrap tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                    title={`${compareLabel}: ${format(previous!)}`}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"} {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\">\n              <dt className=\"truncate text-[11px] leading-4 text-muted-foreground\">\n                Over {thresholdLabel}\n              </dt>\n              <dd\n                className={cn(\n                  \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dd className=\"truncate font-mono text-[11px] leading-4 text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(over))}\n                <span className=\"hidden @sm/histogram:inline\">\n                  {\" \"}\n                  of {compact.format(dist.total).replace(\"K\", \"k\")}\n                </span>\n              </dd>\n            </div>\n          )}\n        </dl>\n      )}\n\n      <div className=\"mt-3 flex px-4 @md/histogram:mt-4\">\n        <div className=\"min-w-0 flex-1\">\n          <div\n            ref={plotRef}\n            data-slot=\"histogram-plot\"\n            role=\"group\"\n            aria-roledescription=\"histogram\"\n            aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the arrow keys to read buckets, Shift to select a range.`}\n            aria-describedby={\n              description != null ? `${id}-description` : undefined\n            }\n            tabIndex={0}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={() => {\n              drag.current = null;\n              setBrush(null);\n            }}\n            onPointerLeave={() => {\n              if (!drag.current) setHover(null);\n            }}\n            onKeyDown={onKeyDown}\n            onBlur={() => setActive(null)}\n            className={cn(\n              \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n              \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n            )}\n            style={{ height: H }}\n          >\n            {empty && (\n              <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                No requests to show.\n              </p>\n            )}\n\n            {/* Value grid */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {yTicks.map((tick) => (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute inset-x-0 h-px\",\n                    tick === 0 ? \"bg-border\" : \"bg-border/55\",\n                  )}\n                  style={{ bottom: `${(tick / yMax) * 100}%` }}\n                />\n              ))}\n            </div>\n\n            {/* SLO tail */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold-region\"\n                className=\"pointer-events-none absolute inset-y-0 right-0\"\n                style={{\n                  left: `${thresholdX * 100}%`,\n                  background: `linear-gradient(to bottom, color-mix(in oklab, ${colors.threshold} 9%, transparent), color-mix(in oklab, ${colors.threshold} 3%, transparent)), repeating-linear-gradient(-45deg, color-mix(in oklab, ${colors.threshold} 9%, transparent) 0 1px, transparent 1px 6px)`,\n                }}\n              />\n            )}\n\n            {/* Bars */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {comparison &&\n                compareStyle === \"outline\" &&\n                bars.map((b, i) => (\n                  <span\n                    key={`c-${structure}-${i}`}\n                    className=\"absolute bottom-0 origin-bottom rounded-t-[2px] border border-b-0 border-dashed\"\n                    style={{\n                      left: `calc(${b.x0 * 100}% + 1px)`,\n                      width: `calc(${(b.x1 - b.x0) * 100}% - 2px)`,\n                      height: `${(comparison.scaled[i] / yMax) * 100}%`,\n                      borderColor: `color-mix(in oklab, ${colors.compare} 70%, transparent)`,\n                      transform: `scaleY(${isGrown ? 1 : 0})`,\n                      transition: reduced ? undefined : transition,\n                    }}\n                  />\n                ))}\n              {bars.map((b, i) => {\n                const h = b.count / yMax;\n                const inRange = shownRange\n                  ? b.end > shownRange[0] && b.start < shownRange[1]\n                  : true;\n                const dim =\n                  (focusIndex != null && focusIndex !== i) || !inRange;\n                const split =\n                  hasThreshold && b.start < threshold! && b.end > threshold!;\n                const hot = hasThreshold && b.start >= threshold!;\n                const color = hot ? colors.threshold : colors.bar;\n                const cut = split\n                  ? ((thresholdX - b.x0) / (b.x1 - b.x0)) * 100\n                  : 0;\n                const fill = split\n                  ? `linear-gradient(to right, ${barFill(colors.bar)} ${cut}%, ${barFill(colors.threshold)} ${cut}%)`\n                  : barFill(color);\n                const cap = split\n                  ? `linear-gradient(to right, ${colors.bar} ${cut}%, ${colors.threshold} ${cut}%)`\n                  : color;\n                return (\n                  <span\n                    key={`${structure}-${i}`}\n                    data-slot=\"histogram-bar\"\n                    data-index={i}\n                    data-over={hot || undefined}\n                    data-overflow={b.overflow || undefined}\n                    className={cn(\n                      \"absolute inset-y-0 transition-opacity duration-200 motion-reduce:transition-none\",\n                      dim &&\n                        (shownRange && !inRange ? \"opacity-30\" : \"opacity-55\"),\n                    )}\n                    style={{\n                      left: `${b.x0 * 100}%`,\n                      width: `${(b.x1 - b.x0) * 100}%`,\n                    }}\n                  >\n                    <span\n                      className=\"absolute inset-x-px bottom-0 h-full origin-bottom @lg/histogram:inset-x-[1.5px]\"\n                      style={{\n                        transform: `scaleY(${isGrown ? h : 0})`,\n                        transition: reduced ? undefined : transition,\n                        transitionDelay:\n                          intro && !reduced ? `${i * 9}ms` : undefined,\n                      }}\n                    >\n                      <span\n                        className={cn(\n                          \"absolute inset-0 rounded-t-[2px]\",\n                          b.overflow &&\n                            \"[mask-image:repeating-linear-gradient(-45deg,#000_0_3px,rgb(0_0_0/0.55)_3px_5px)]\",\n                        )}\n                        style={{ background: fill }}\n                      />\n                    </span>\n                    {/* The cap is drawn unscaled so it stays a crisp line at any height. */}\n                    {b.count > 0 && (\n                      <span\n                        className=\"absolute inset-x-px h-[1.5px] rounded-full @lg/histogram:inset-x-[1.5px]\"\n                        style={{\n                          bottom: `calc(${(isGrown ? h : 0) * 100}% - 1px)`,\n                          background: cap,\n                          transition: reduced\n                            ? undefined\n                            : intro\n                              ? \"bottom 760ms cubic-bezier(.16,1,.3,1)\"\n                              : \"bottom 520ms cubic-bezier(.16,1,.3,1)\",\n                          transitionDelay:\n                            intro && !reduced ? `${i * 9}ms` : undefined,\n                        }}\n                      />\n                    )}\n                  </span>\n                );\n              })}\n              {comparePath && (\n                <svg\n                  data-slot=\"histogram-compare\"\n                  className=\"absolute inset-0 size-full origin-bottom overflow-visible\"\n                  viewBox=\"0 0 1000 100\"\n                  preserveAspectRatio=\"none\"\n                  style={{\n                    transform: `scaleY(${isGrown ? 1 : 0})`,\n                    transition: reduced ? undefined : transition,\n                  }}\n                >\n                  <path\n                    d={comparePath}\n                    fill=\"none\"\n                    stroke={colors.compare}\n                    strokeWidth={1.5}\n                    strokeDasharray=\"4 3\"\n                    strokeLinejoin=\"round\"\n                    vectorEffect=\"non-scaling-stroke\"\n                    opacity={0.85}\n                  />\n                </svg>\n              )}\n            </div>\n\n            {/* Selection */}\n            {shownRange && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-selection\"\n                className=\"pointer-events-none absolute inset-y-0\"\n                style={{\n                  left: `${pos(shownRange[0]) * 100}%`,\n                  width: `${Math.max(0, pos(shownRange[1]) - pos(shownRange[0])) * 100}%`,\n                  background: `color-mix(in oklab, ${colors.selection} 9%, transparent)`,\n                  boxShadow: `inset 1.5px 0 0 ${colors.selection}, inset -1.5px 0 0 ${colors.selection}`,\n                }}\n              >\n                <span\n                  className=\"absolute top-1/2 -left-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n                <span\n                  className=\"absolute top-1/2 -right-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n              </div>\n            )}\n\n            {/* Threshold line */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold\"\n                className=\"pointer-events-none absolute bottom-0\"\n                style={{ left: `${thresholdX * 100}%`, top: chipTop - 2 }}\n              >\n                <span\n                  className=\"absolute inset-y-0 w-0 border-l-[1.5px] border-dashed\"\n                  style={{ borderColor: colors.threshold }}\n                />\n                <span\n                  className=\"absolute top-1 left-1 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 font-medium whitespace-nowrap\"\n                  style={{ color: colors.threshold }}\n                >\n                  {thresholdLabel} {format(threshold!)}\n                </span>\n              </div>\n            )}\n\n            {/* Percentile markers */}\n            {chips.map((chip) => {\n              const hot = hasThreshold && chip.value > threshold!;\n              const color = hot ? colors.threshold : colors.marker;\n              return (\n                <div\n                  key={chip.p}\n                  data-slot=\"histogram-marker\"\n                  data-percentile={chip.p}\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none\"\n                >\n                  <span\n                    className=\"absolute bottom-0 w-0 border-l border-dashed opacity-55\"\n                    style={{\n                      left: chip.x,\n                      top: chip.lane * 20 + 18,\n                      borderColor: color,\n                    }}\n                  />\n                  <span\n                    className={cn(\n                      \"absolute flex h-[18px] items-center gap-1 rounded-[5px] border bg-card px-1.5 font-mono text-[10px] leading-none whitespace-nowrap shadow-xs tabular-nums\",\n                      intro &&\n                        !reduced &&\n                        \"motion-safe:animate-[histogram-rise_.5s_.35s_cubic-bezier(.16,1,.3,1)_both]\",\n                    )}\n                    style={{\n                      left: chip.left,\n                      top: chip.lane * 20,\n                      borderColor: `color-mix(in oklab, ${color} 28%, var(--color-border))`,\n                    }}\n                  >\n                    <span className=\"text-muted-foreground\">\n                      {percentileName(chip.p)}\n                    </span>\n                    {chip.withValue && (\n                      <span className=\"font-semibold\" style={{ color }}>\n                        {format(chip.value)}\n                      </span>\n                    )}\n                  </span>\n                </div>\n              );\n            })}\n\n            {/* Tooltip */}\n            {focusBucket && !brush && (\n              <div\n                data-slot=\"histogram-tooltip\"\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-popover px-2.5 py-2 text-xs text-popover-foreground shadow-md\"\n                style={{\n                  top: chipTop + 4,\n                  // Sit beside the bar, on the side with more room, so it never hides it.\n                  ...(bars[focusBucket.index].x0 + bars[focusBucket.index].x1 <\n                  1\n                    ? { left: bars[focusBucket.index].x1 * W + 8 }\n                    : { right: W - bars[focusBucket.index].x0 * W + 8 }),\n                }}\n              >\n                {renderTooltip ? (\n                  renderTooltip(focusBucket)\n                ) : (\n                  <>\n                    <p className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n                      {focusBucket.overflow\n                        ? `≥ ${format(focusBucket.start)}`\n                        : `${format(focusBucket.start)} – ${format(focusBucket.end)}`}\n                    </p>\n                    <p className=\"mt-0.5 flex items-baseline gap-1.5\">\n                      <span className=\"text-sm font-semibold tabular-nums\">\n                        {whole.format(Math.round(focusBucket.count))}\n                      </span>\n                      <span className=\"text-muted-foreground tabular-nums\">\n                        {percentLabel(focusBucket.share)}\n                      </span>\n                    </p>\n                    <p className=\"mt-1 text-[11px] text-muted-foreground tabular-nums\">\n                      {percentLabel(focusBucket.cumulative)} at or faster\n                    </p>\n                    {focusBucket.compare != null && comparison && (\n                      <p className=\"mt-1.5 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground tabular-nums\">\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"w-3 border-t-[1.5px] border-dashed\"\n                          style={{ borderColor: colors.compare }}\n                        />\n                        {compareLabel}\n                        <span className=\"ml-auto font-medium text-foreground\">\n                          {whole.format(Math.round(focusBucket.compare))}\n                        </span>\n                        <span>\n                          {percentLabel(focusBucket.compareShare ?? 0)}\n                        </span>\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n            )}\n          </div>\n\n          {/* Latency axis */}\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 font-mono text-[10px] leading-4 text-muted-foreground tabular-nums\"\n          >\n            {xTicks.map((tick, i) => {\n              const x = pos(tick);\n              if (x > layout.pos(layout.hi) + 1e-6) return null;\n              return (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute whitespace-nowrap\",\n                    i === 0 && x < 0.02\n                      ? \"\"\n                      : x > 0.97\n                        ? \"-translate-x-full\"\n                        : \"-translate-x-1/2\",\n                  )}\n                  style={{ left: `${x * 100}%` }}\n                >\n                  {formatTick(tick)}\n                </span>\n              );\n            })}\n            {bars[bars.length - 1]?.overflow && (\n              <span\n                className=\"absolute -translate-x-1/2 whitespace-nowrap\"\n                style={{\n                  left: `${((bars[bars.length - 1].x0 + 1) / 2) * 100}%`,\n                }}\n              >\n                +\n              </span>\n            )}\n          </div>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative ml-2 w-8 shrink-0\"\n          style={{ height: H }}\n        >\n          {yTicks.map((tick) => (\n            <span\n              key={tick}\n              className=\"absolute right-0 translate-y-1/2 font-mono text-[10px] leading-none text-muted-foreground tabular-nums\"\n              style={{ bottom: `${(tick / yMax) * (barsHeight / H) * 100}%` }}\n            >\n              {tick === 0 ? \"0\" : compact.format(tick).replace(\"K\", \"k\")}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      <div\n        data-slot=\"histogram-footer\"\n        className=\"mt-3 flex min-h-11 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t px-4 py-2\"\n      >\n        <div\n          data-slot=\"histogram-status\"\n          className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs\"\n        >\n          {shownRange ? (\n            <>\n              <span\n                className=\"rounded-[4px] px-1.5 py-px font-mono text-[11px] tabular-nums\"\n                style={{\n                  background: `color-mix(in oklab, ${colors.selection} 10%, transparent)`,\n                  color: colors.selection,\n                }}\n              >\n                {format(shownRange[0])} – {format(shownRange[1])}\n              </span>\n              <span className=\"font-semibold tabular-nums\">\n                {percentLabel(rangeShare)}\n              </span>\n              <span className=\"text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(rangeCount))} of{\" \"}\n                {whole.format(Math.round(dist.total))} requests\n              </span>\n              {!brush && (\n                <button\n                  type=\"button\"\n                  onClick={() => setRange(null)}\n                  className={cn(\n                    \"inline-flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\",\n                    focusRing,\n                  )}\n                >\n                  <X className=\"size-3.5\" aria-hidden=\"true\" />\n                  <span className=\"sr-only\">Clear selection</span>\n                </button>\n              )}\n            </>\n          ) : (\n            <span className=\"text-muted-foreground tabular-nums\">\n              <span className=\"font-medium text-foreground\">\n                {whole.format(Math.round(dist.total))}\n              </span>{\" \"}\n              requests\n              <span aria-hidden=\"true\"> · </span>mean{\" \"}\n              <span className=\"font-medium text-foreground\">\n                {format(dist.mean)}\n              </span>\n              <span className=\"hidden @md/histogram:inline\">\n                <span aria-hidden=\"true\"> · </span>max{\" \"}\n                <span className=\"font-medium text-foreground\">\n                  {format(dist.max)}\n                </span>\n              </span>\n              <span className=\"hidden @lg/histogram:inline\">\n                {\" \"}\n                · drag to measure a range\n              </span>\n            </span>\n          )}\n        </div>\n        {comparison && (\n          <div\n            data-slot=\"histogram-legend\"\n            className=\"flex items-center gap-3 text-[11px] text-muted-foreground\"\n          >\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 rounded-[2px]\"\n                style={{\n                  background: barFill(colors.bar),\n                  boxShadow: `inset 0 1.5px 0 ${colors.bar}`,\n                }}\n              />\n              {seriesLabel}\n            </span>\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"w-3.5 border-t-[1.5px] border-dashed\"\n                style={{ borderColor: colors.compare }}\n              />\n              {compareLabel}\n            </span>\n          </div>\n        )}\n      </div>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Latency</th>\n              <th scope=\"col\">Requests</th>\n              {comparison && <th scope=\"col\">{compareLabel}</th>}\n            </tr>\n          </thead>\n          <tbody>\n            {bars.map((b, i) =>\n              b.count > 0 || comparison?.counts[i] ? (\n                <tr key={i}>\n                  <th scope=\"row\">\n                    {b.overflow\n                      ? `${format(b.start)} and above`\n                      : `${format(b.start)} to ${format(b.end)}`}\n                  </th>\n                  <td>{whole.format(Math.round(b.count))}</td>\n                  {comparison && (\n                    <td>{whole.format(Math.round(comparison.counts[i]))}</td>\n                  )}\n                </tr>\n              ) : null,\n            )}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {active != null && bars[active]\n          ? describeBucket(bucketAt(active))\n          : range\n            ? `Selected ${format(range[0])} to ${format(range[1])}: ${percentLabel(dist.total ? countBetween(dist, range[0], range[1]) / dist.total : 0)} of requests.`\n            : \"\"}\n      </p>\n\n      <style href=\"overtrue-latency-histogram\" precedence=\"default\">\n        {`@keyframes histogram-rise{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}\n      </style>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/insight-card.tsx",
      "type": "registry:component",
      "target": "components/overtrue/insight-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertTriangle as AlertTriangle,\n  IconArrowDownRight as ArrowDownRight,\n  IconArrowUpRight as ArrowUpRight,\n  IconCheck as Check,\n  IconCopy as Copy,\n  IconFileAnalytics as FileAnalytics,\n  IconPlayerStopFilled as Stop,\n  IconRefresh as Refresh,\n  IconThumbDown as ThumbDown,\n  IconThumbDownFilled as ThumbDownFilled,\n  IconThumbUp as ThumbUp,\n  IconThumbUpFilled as ThumbUpFilled,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type InsightStatus =\n  \"idle\" | \"thinking\" | \"streaming\" | \"done\" | \"error\";\nexport type InsightTone = \"positive\" | \"negative\" | \"neutral\";\nexport type InsightFeedback = \"up\" | \"down\" | null;\n\n/**\n * An inline token parsed from `{{kind:arg|arg|arg}}`.\n * Built in: `{{metric:Label|+12.8%}}`, `{{metric:Churn|-0.4 pts|positive}}`, `{{cite:1}}`.\n */\nexport interface InsightToken {\n  /** The word before the colon, e.g. \"metric\" or \"cite\". */\n  kind: string;\n  /** First argument: the metric label or the source number / id. */\n  label: string;\n  /** Second argument: the metric value. */\n  value?: string;\n  /** Third argument when it is positive, negative or neutral; otherwise inferred from the value's sign. */\n  tone: InsightTone;\n  /** Which way the value moved, from its sign: drives the arrow, while tone drives the color. */\n  direction: \"up\" | \"down\" | \"flat\";\n  /** Every argument after the colon, trimmed. */\n  args: string[];\n  /** The original markup. */\n  raw: string;\n}\n\nexport type InsightSegment = string | InsightToken;\n\nexport interface InsightSource {\n  id: string;\n  label: string;\n  href?: string;\n}\n\nexport interface InsightCardLabels {\n  thinking: string;\n  streaming: string;\n  idle: string;\n  generate: string;\n  regenerate: string;\n  stop: string;\n  copy: string;\n  copied: string;\n  helpful: string;\n  notHelpful: string;\n  sources: string;\n  feedback: string;\n  error: string;\n  retry: string;\n}\n\nexport interface InsightCardColors {\n  /** Caret, summary icon and the optional moving border. */\n  accent?: string;\n  /** Enables the working border and glow with this second color. */\n  glow?: string;\n  positive?: string;\n  negative?: string;\n}\n\nexport interface InsightCardProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"onCopy\"\n> {\n  title?: React.ReactNode;\n  /** Model, dataset or time range, shown at the top right. */\n  source?: React.ReactNode;\n  /** Replaces the summary icon. */\n  icon?: React.ReactNode;\n  /** The insight, with optional `{{kind:arg|arg}}` tokens. Append to it while streaming. */\n  text?: string;\n  /** Shorthand for `status=\"streaming\"` while you append to `text`. */\n  streaming?: boolean;\n  /** Defaults to streaming, done or idle from `streaming`, `text` and `stream`. */\n  status?: InsightStatus;\n  /** Consumed internally; drives thinking, streaming, done and error. Pass a new iterable to regenerate. */\n  stream?: AsyncIterable<string>;\n  /** Message for the error state. */\n  error?: React.ReactNode;\n  sources?: InsightSource[];\n  /** Shows Regenerate, and Try again in the error state. */\n  onRegenerate?: () => void;\n  /** Shows Stop while thinking or streaming. */\n  onStop?: () => void;\n  /** Called with the plain text. Without it, Copy writes to the clipboard. */\n  onCopy?: (text: string) => void;\n  feedback?: InsightFeedback;\n  defaultFeedback?: InsightFeedback;\n  onFeedback?: (feedback: InsightFeedback) => void;\n  /** Render a token yourself. Return `undefined` to keep the built-in rendering. */\n  renderToken?: (\n    token: InsightToken,\n    index: number,\n  ) => React.ReactNode | undefined;\n  /** Replace the token parser. */\n  parse?: (text: string) => InsightSegment[];\n  /** Characters per second for revealing new text. 0 shows it immediately. */\n  speed?: number;\n  /** Called once streamed text has fully revealed. */\n  onStreamEnd?: () => void;\n  /** Extra buttons after Copy. */\n  actions?: React.ReactNode;\n  colors?: InsightCardColors;\n  labels?: Partial<InsightCardLabels>;\n}\n\nconst LABELS: InsightCardLabels = {\n  thinking: \"Thinking…\",\n  streaming: \"Writing…\",\n  idle: \"No insight yet.\",\n  generate: \"Generate\",\n  regenerate: \"Regenerate\",\n  stop: \"Stop\",\n  copy: \"Copy\",\n  copied: \"Copied\",\n  helpful: \"Helpful\",\n  notHelpful: \"Not helpful\",\n  sources: \"Sources\",\n  feedback: \"Feedback\",\n  error: \"Couldn’t generate this insight.\",\n  retry: \"Try again\",\n};\n\nconst TOKEN = /\\{\\{\\s*([A-Za-z][\\w-]*)\\s*:([^{}]*?)\\}\\}/g;\nconst TONES = new Set<string>([\"positive\", \"negative\", \"neutral\"]);\n\nfunction direction(value: string | undefined): InsightToken[\"direction\"] {\n  const sign = value?.trim()[0];\n  if (sign === \"+\" || sign === \"↑\") return \"up\";\n  if (sign === \"-\" || sign === \"−\" || sign === \"↓\") return \"down\";\n  return \"flat\";\n}\n\n/** Split text into strings and tokens. A token cut off at the end is dropped while it streams in. */\nexport function parseInsight(text: string): InsightSegment[] {\n  const segments: InsightSegment[] = [];\n  let from = 0;\n  for (const match of text.matchAll(TOKEN)) {\n    if (match.index > from) segments.push(text.slice(from, match.index));\n    const args = match[2].split(\"|\").map((arg) => arg.trim());\n    const [label = \"\", value, third] = args;\n    const moved = direction(value);\n    segments.push({\n      kind: match[1].toLowerCase(),\n      label,\n      value,\n      direction: moved,\n      tone:\n        third && TONES.has(third)\n          ? (third as InsightTone)\n          : moved === \"up\"\n            ? \"positive\"\n            : moved === \"down\"\n              ? \"negative\"\n              : \"neutral\",\n      args,\n      raw: match[0],\n    });\n    from = match.index + match[0].length;\n  }\n  let rest = text.slice(from);\n  const open = rest.lastIndexOf(\"{{\");\n  if (open !== -1 && !rest.includes(\"}}\", open)) rest = rest.slice(0, open);\n  if (rest) segments.push(rest);\n  return segments;\n}\n\n/** Plain text for copying and screen readers: metrics read \"Revenue +12.8%\", citations \"[1]\". */\nexport function insightToPlainText(\n  text: string,\n  parse: (text: string) => InsightSegment[] = parseInsight,\n) {\n  return parse(text)\n    .map((segment) =>\n      typeof segment === \"string\"\n        ? segment\n        : segment.kind === \"cite\"\n          ? `[${segment.label}]`\n          : [segment.label, segment.value].filter(Boolean).join(\" \"),\n    )\n    .join(\"\")\n    .trim();\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(REDUCED);\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\n// One reader per iterable, so StrictMode's double effects and remounts share progress.\ninterface StreamSession {\n  text: string;\n  status: \"thinking\" | \"streaming\" | \"done\" | \"error\";\n  error?: unknown;\n  listeners: Set<() => void>;\n  stop: () => void;\n}\nconst sessions = new WeakMap<AsyncIterable<string>, StreamSession>();\n\nfunction openSession(stream: AsyncIterable<string>) {\n  const existing = sessions.get(stream);\n  if (existing) return existing;\n  const iterator = stream[Symbol.asyncIterator]();\n  let stopped = false;\n  const session: StreamSession = {\n    text: \"\",\n    status: \"thinking\",\n    listeners: new Set(),\n    stop: () => {\n      if (stopped) return;\n      stopped = true;\n      if (session.status === \"thinking\" || session.status === \"streaming\")\n        session.status = \"done\";\n      void iterator.return?.();\n    },\n  };\n  const emit = () => session.listeners.forEach((listener) => listener());\n  sessions.set(stream, session);\n  void (async () => {\n    try {\n      while (!stopped) {\n        const result = await iterator.next();\n        if (stopped) return;\n        if (result.done) break;\n        session.text += String(result.value ?? \"\");\n        session.status = \"streaming\";\n        emit();\n      }\n      if (!stopped) {\n        session.status = \"done\";\n        emit();\n      }\n    } catch (error) {\n      if (stopped) return;\n      session.status = \"error\";\n      session.error = error;\n      emit();\n    }\n  })();\n  return session;\n}\n\nfunction useStreamSession(stream: AsyncIterable<string> | undefined) {\n  const [, rerender] = React.useReducer((count: number) => count + 1, 0);\n  React.useEffect(() => {\n    if (!stream) return;\n    const session = openSession(stream);\n    session.listeners.add(rerender);\n    rerender();\n    return () => {\n      session.listeners.delete(rerender);\n      // Stop reading only if nothing resubscribed (StrictMode remounts immediately).\n      window.setTimeout(() => {\n        if (!session.listeners.size) session.stop();\n      }, 0);\n    };\n  }, [stream]);\n  return stream ? (sessions.get(stream) ?? null) : null;\n}\n\n/** Move a reveal position past a whole token so chips appear complete. */\nfunction snap(text: string, position: number) {\n  const open = text.lastIndexOf(\"{{\", position - 1);\n  if (open === -1) return position;\n  const close = text.indexOf(\"}}\", open);\n  if (close === -1) return open;\n  return close + 2 > position ? close + 2 : position;\n}\n\nfunction useReveal(text: string, animate: boolean, speed: number) {\n  const [shown, setShown] = React.useState(() => (animate ? 0 : text.length));\n  const shownRef = React.useRef(shown);\n  const previous = React.useRef(text);\n\n  useIsoLayoutEffect(() => {\n    const set = (value: number) => {\n      shownRef.current = value;\n      setShown(value);\n    };\n    let start = shownRef.current;\n    // Replaced rather than appended: start over.\n    if (!text.startsWith(previous.current.slice(0, start))) start = 0;\n    previous.current = text;\n    if (!animate || !(speed > 0) || !Number.isFinite(speed))\n      start = text.length;\n    start = Math.min(start, text.length);\n    set(start);\n    if (start >= text.length) return;\n\n    let frame = 0;\n    let last = performance.now();\n    let carry = start;\n    const tick = (now: number) => {\n      const dt = Math.min(now - last, 100);\n      last = now;\n      // Catch up when the source runs ahead, so the reveal never lags by more than ~2s.\n      const backlog = text.length - carry;\n      carry = Math.min(\n        text.length,\n        carry + (speed * Math.max(1, backlog / (speed * 2)) * dt) / 1000,\n      );\n      const next = snap(text, Math.floor(carry));\n      if (next > shownRef.current) set(next);\n      // Wait for the rest of a half-received token before going on.\n      if (next < Math.floor(carry)) return;\n      if (next < text.length) frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [text, animate, speed]);\n\n  return Math.min(shown, text.length);\n}\n\nconst toneClass: Record<InsightTone, string> = {\n  positive:\n    \"border-(--insight-positive)/25 bg-(--insight-positive)/8 [--chip:var(--insight-positive)]\",\n  negative:\n    \"border-(--insight-negative)/25 bg-(--insight-negative)/8 [--chip:var(--insight-negative)]\",\n  neutral: \"border-border bg-muted/60 [--chip:var(--color-muted-foreground)]\",\n};\n\nfunction MetricChip({ token }: { token: InsightToken }) {\n  const Arrow =\n    token.direction === \"up\"\n      ? ArrowUpRight\n      : token.direction === \"down\"\n        ? ArrowDownRight\n        : null;\n  return (\n    <span\n      data-slot=\"insight-token\"\n      data-kind=\"metric\"\n      data-tone={token.tone}\n      className={cn(\n        \"mx-px inline-flex translate-y-[-1px] items-center gap-1 rounded-md border px-1.5 align-middle text-[12.5px] leading-5 whitespace-nowrap\",\n        \"transition-[opacity,scale] duration-300 ease-out starting:scale-90 starting:opacity-0 motion-reduce:transition-none\",\n        toneClass[token.tone],\n      )}\n    >\n      {token.label && (\n        <span className=\"font-medium text-foreground\">{token.label}</span>\n      )}\n      {token.value && (\n        <span className=\"inline-flex items-center gap-0.5 font-mono text-[12px] font-medium text-[color-mix(in_oklab,var(--chip)_82%,var(--color-foreground))] tabular-nums\">\n          {Arrow && (\n            <Arrow className=\"size-3\" aria-hidden=\"true\" stroke={2.25} />\n          )}\n          {token.value}\n        </span>\n      )}\n    </span>\n  );\n}\n\nconst styles = `@property --insight-angle{syntax:\"<angle>\";inherits:false;initial-value:0deg}@keyframes insight-spin{to{--insight-angle:360deg}}@keyframes insight-shimmer{from{background-position:100% 0}to{background-position:-100% 0}}@keyframes insight-caret{0%,50%{opacity:1}50.01%,100%{opacity:0}}`;\n\nconst ring =\n  \"conic-gradient(from var(--insight-angle), transparent 0%, var(--insight-accent) 12%, var(--insight-glow) 22%, transparent 34%, transparent 50%, var(--insight-glow) 62%, var(--insight-accent) 72%, transparent 84%)\";\n\nconst ringMask: React.CSSProperties = {\n  padding: 1,\n  WebkitMask:\n    \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\",\n  WebkitMaskComposite: \"xor\",\n  mask: \"linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0)\",\n};\n\n/**\n * An AI summary for dashboards: streams text with a caret, turns `{{metric:…}}` markup\n * into delta chips, cites numbered sources, and offers regenerate, copy and feedback.\n */\nexport function InsightCard({\n  title = \"Insight\",\n  source,\n  icon,\n  text = \"\",\n  streaming,\n  status: statusProp,\n  stream,\n  error,\n  sources,\n  onRegenerate,\n  onStop,\n  onCopy,\n  feedback: feedbackProp,\n  defaultFeedback = null,\n  onFeedback,\n  renderToken,\n  parse = parseInsight,\n  speed = 90,\n  onStreamEnd,\n  actions,\n  colors,\n  labels: labelsProp,\n  className,\n  style,\n  ...props\n}: InsightCardProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const reduced = useReducedMotion();\n  const session = useStreamSession(stream);\n\n  const fullText = stream ? (session?.text ?? \"\") : text;\n  const sourceStatus: InsightStatus = stream\n    ? (statusProp ?? session?.status ?? \"thinking\")\n    : (statusProp ?? (streaming ? \"streaming\" : text ? \"done\" : \"idle\"));\n  const active = sourceStatus === \"thinking\" || sourceStatus === \"streaming\";\n\n  const [feedbackState, setFeedbackState] =\n    React.useState<InsightFeedback>(defaultFeedback);\n  const feedback = feedbackProp !== undefined ? feedbackProp : feedbackState;\n\n  // \"Live\" spans one generation: from thinking/streaming until the reveal catches up.\n  const [live, setLive] = React.useState(active);\n  if (active && !live) {\n    setLive(true);\n    // Feedback belongs to the previous answer.\n    setFeedbackState(null);\n  }\n\n  // Hold the reveal while thinking, so text supplied early still streams in afterwards.\n  const revealText = sourceStatus === \"thinking\" ? \"\" : fullText;\n  const shown = useReveal(revealText, live && !reduced, speed);\n  const revealing = shown < revealText.length;\n  const status: InsightStatus =\n    sourceStatus === \"error\"\n      ? \"error\"\n      : sourceStatus === \"thinking\"\n        ? \"thinking\"\n        : sourceStatus === \"streaming\" || (live && revealing)\n          ? \"streaming\"\n          : fullText\n            ? \"done\"\n            : \"idle\";\n\n  const onStreamEndRef = React.useRef(onStreamEnd);\n  onStreamEndRef.current = onStreamEnd;\n  React.useEffect(() => {\n    if (live && !active && !revealing) {\n      setLive(false);\n      if (sourceStatus === \"done\") onStreamEndRef.current?.();\n    }\n  }, [live, active, revealing, sourceStatus]);\n\n  const setFeedback = (value: InsightFeedback) => {\n    const next = value === feedback ? null : value;\n    if (feedbackProp === undefined) setFeedbackState(next);\n    onFeedback?.(next);\n  };\n\n  const [copied, setCopied] = React.useState(false);\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(false), 1600);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n\n  const [hoveredSource, setHoveredSource] = React.useState<string | null>(null);\n\n  const plain = React.useMemo(\n    () => insightToPlainText(fullText, parse),\n    [fullText, parse],\n  );\n  const visible =\n    shown >= fullText.length ? fullText : fullText.slice(0, shown);\n  const segments = React.useMemo(() => parse(visible), [parse, visible]);\n\n  const copy = async () => {\n    if (onCopy) onCopy(plain);\n    else {\n      try {\n        await navigator.clipboard?.writeText(plain);\n      } catch {\n        return;\n      }\n    }\n    setCopied(true);\n  };\n\n  const findSource = (ref: string) => {\n    if (!sources) return undefined;\n    const index = /^\\d+$/.test(ref)\n      ? Number(ref) - 1\n      : sources.findIndex((item) => item.id === ref);\n    return index >= 0 && index < sources.length\n      ? { source: sources[index], number: index + 1 }\n      : undefined;\n  };\n\n  const renderSegment = (\n    segment: InsightSegment,\n    index: number,\n  ): React.ReactNode => {\n    if (typeof segment === \"string\") return segment;\n    const custom = renderToken?.(segment, index);\n    if (custom !== undefined) return custom;\n    if (segment.kind === \"metric\") return <MetricChip token={segment} />;\n    if (segment.kind === \"cite\") {\n      const found = findSource(segment.label);\n      const number = found?.number ?? segment.label;\n      const chip = cn(\n        \"mx-px inline-flex h-4 min-w-4 -translate-y-px items-center justify-center rounded-[4px] bg-muted px-1 align-middle font-mono text-[10px] leading-none font-medium text-muted-foreground transition-colors\",\n        \"transition-[opacity,background-color,color] duration-300 starting:opacity-0 motion-reduce:transition-none\",\n      );\n      const highlight = {\n        onPointerEnter: () => found && setHoveredSource(found.source.id),\n        onPointerLeave: () => setHoveredSource(null),\n        onFocus: () => found && setHoveredSource(found.source.id),\n        onBlur: () => setHoveredSource(null),\n      };\n      return found?.source.href ? (\n        <a\n          data-slot=\"insight-token\"\n          data-kind=\"cite\"\n          href={found.source.href}\n          target=\"_blank\"\n          rel=\"noreferrer\"\n          aria-label={`${labels.sources} ${number}: ${found.source.label}`}\n          className={cn(\n            chip,\n            \"hover:bg-(--insight-accent)/12 hover:text-(--insight-accent)\",\n            focusRing,\n          )}\n          {...highlight}\n        >\n          {number}\n        </a>\n      ) : (\n        <span\n          data-slot=\"insight-token\"\n          data-kind=\"cite\"\n          title={found?.source.label}\n          className={cn(\n            chip,\n            found &&\n              \"cursor-default hover:bg-(--insight-accent)/12 hover:text-(--insight-accent)\",\n          )}\n          {...highlight}\n        >\n          {number}\n        </span>\n      );\n    }\n    return (\n      <span\n        data-slot=\"insight-token\"\n        data-kind={segment.kind}\n        className=\"font-medium\"\n      >\n        {segment.label}\n      </span>\n    );\n  };\n\n  // Paragraphs on blank lines, line breaks on single newlines. A paragraph made only\n  // of tokens becomes a row of highlights.\n  const paragraphs: { nodes: React.ReactNode[]; prose: boolean }[] = [\n    { nodes: [], prose: false },\n  ];\n  let attachedCitation = -1;\n  segments.forEach((segment, index) => {\n    if (index === attachedCitation) return;\n    if (typeof segment !== \"string\") {\n      paragraphs[paragraphs.length - 1].nodes.push(\n        <React.Fragment key={index}>\n          {renderSegment(segment, index)}\n        </React.Fragment>,\n      );\n      return;\n    }\n    // Keep a citation with its last word, including in narrow previews.\n    const next = segments[index + 1];\n    const lastWord =\n      typeof next === \"object\" && next.kind === \"cite\" && !/[\\r\\n]$/.test(segment)\n        ? segment.match(/(\\S+[^\\S\\r\\n]*)$/)\n        : null;\n    const content = lastWord ? segment.slice(0, lastWord.index) : segment;\n    content.split(/\\n{2,}/).forEach((chunk, part) => {\n      if (part > 0) paragraphs.push({ nodes: [], prose: false });\n      chunk.split(\"\\n\").forEach((line, row) => {\n        const target = paragraphs[paragraphs.length - 1];\n        if (row > 0)\n          target.nodes.push(<br key={`${index}-${part}-${row}-br`} />);\n        if (line.trim()) target.prose = true;\n        if (line)\n          target.nodes.push(\n            <React.Fragment key={`${index}-${part}-${row}`}>\n              {line}\n            </React.Fragment>,\n          );\n      });\n    });\n    if (lastWord) {\n      const target = paragraphs[paragraphs.length - 1];\n      target.prose = true;\n      target.nodes.push(\n        <span key={`${index}-citation`} className=\"inline-block max-w-full\">\n          {lastWord[0]}\n          {renderSegment(next, index + 1)}\n        </span>,\n      );\n      attachedCitation = index + 1;\n    }\n  });\n\n  const busy = status === \"thinking\" || status === \"streaming\";\n  const colorVars = colors\n    ? ({\n        ...(colors.accent && { \"--insight-accent\": colors.accent }),\n        ...(colors.glow && { \"--insight-glow\": colors.glow }),\n        ...(colors.positive && { \"--insight-positive\": colors.positive }),\n        ...(colors.negative && { \"--insight-negative\": colors.negative }),\n      } as React.CSSProperties)\n    : undefined;\n\n  const button = cn(\n    \"inline-flex h-7 items-center justify-center gap-1.5 rounded-md text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\",\n    focusRing,\n  );\n\n  return (\n    <div\n      data-slot=\"insight-card\"\n      data-status={status}\n      aria-busy={busy || undefined}\n      className={cn(\n        \"@container/insight relative isolate flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        \"[--insight-accent:var(--color-primary)] [--insight-glow:var(--color-chart-4)] [--insight-negative:var(--color-destructive)] [--insight-positive:var(--color-emerald-600)] dark:[--insight-positive:var(--color-emerald-400)]\",\n        className,\n      )}\n      style={{ ...colorVars, ...style }}\n      {...props}\n    >\n      <style href=\"overtrue-insight-card\" precedence=\"default\">\n        {styles}\n      </style>\n\n      {colors?.glow && (\n        <>\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"insight-glow\"\n            className={cn(\n              \"pointer-events-none absolute -inset-px -z-10 rounded-[inherit] blur-md transition-opacity duration-700 motion-safe:animate-[insight-spin_3.2s_linear_infinite] motion-reduce:transition-none\",\n              busy ? \"opacity-35 dark:opacity-45\" : \"opacity-0\",\n            )}\n            style={{ background: ring }}\n          />\n          <span\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-0 -z-5 rounded-[inherit] bg-card\"\n          />\n          <span\n            aria-hidden=\"true\"\n            className={cn(\n              \"pointer-events-none absolute -inset-px rounded-[inherit] transition-opacity duration-700 motion-safe:animate-[insight-spin_3.2s_linear_infinite] motion-reduce:transition-none\",\n              busy ? \"opacity-100\" : \"opacity-0\",\n            )}\n            style={{ ...ringMask, background: ring }}\n          />\n        </>\n      )}\n\n      <div className=\"relative flex flex-wrap items-center gap-x-3 gap-y-2 px-4 pt-3.5 @sm/insight:px-5 @sm/insight:pt-4\">\n        <div className=\"flex min-w-0 flex-1 basis-full items-center gap-2.5 @lg/insight:basis-44\">\n          <span\n            aria-hidden=\"true\"\n            className=\"flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-(--insight-accent)\"\n          >\n            {icon ?? (\n              <FileAnalytics className=\"size-4\" stroke={1.75} />\n            )}\n          </span>\n          <div className=\"flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n            <div className=\"text-sm leading-5 font-semibold tracking-tight [overflow-wrap:anywhere]\">\n              {title}\n            </div>\n            {busy && (\n              <div\n                data-slot=\"insight-progress\"\n                className=\"hidden shrink-0 bg-linear-to-r from-muted-foreground @xs/insight:block via-foreground to-muted-foreground bg-size-[200%_100%] bg-clip-text text-xs text-transparent motion-safe:animate-[insight-shimmer_1.8s_linear_infinite] motion-reduce:text-muted-foreground\"\n              >\n                {status === \"thinking\" ? labels.thinking : labels.streaming}\n              </div>\n            )}\n          </div>\n        </div>\n        {source && (\n          <div\n            data-slot=\"insight-source-label\"\n            className=\"flex min-w-0 items-center gap-1.5 pl-9.5 text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere] @lg/insight:pl-0\"\n          >\n            {source}\n          </div>\n        )}\n      </div>\n\n      <div className=\"relative px-4 pt-3 pb-4 @sm/insight:px-5\">\n        {status === \"thinking\" ? (\n          <div\n            data-slot=\"insight-skeleton\"\n            className=\"space-y-2.5 py-1\"\n            aria-hidden=\"true\"\n          >\n            {[92, 100, 78, 56].map((width, index) => (\n              <div\n                key={index}\n                className=\"h-2.5 rounded-full bg-linear-to-r from-muted via-foreground/[0.07] to-muted bg-size-[200%_100%] motion-safe:animate-[insight-shimmer_1.6s_linear_infinite] dark:via-foreground/[0.1]\"\n                style={{\n                  width: `${width}%`,\n                  animationDelay: `${index * 120}ms`,\n                }}\n              />\n            ))}\n          </div>\n        ) : status === \"error\" ? (\n          <div\n            data-slot=\"insight-error\"\n            role=\"alert\"\n            className=\"flex items-start gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.06] p-3\"\n          >\n            <AlertTriangle\n              className=\"mt-0.5 size-4 shrink-0 text-destructive\"\n              aria-hidden=\"true\"\n            />\n            <div className=\"min-w-0 flex-1\">\n              <div className=\"text-sm font-medium\">{labels.error}</div>\n              {error && (\n                <div className=\"mt-0.5 text-xs leading-5 text-muted-foreground\">\n                  {error}\n                </div>\n              )}\n              {onRegenerate && (\n                <button\n                  type=\"button\"\n                  onClick={onRegenerate}\n                  className={cn(\n                    \"mt-2 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none\",\n                    focusRing,\n                  )}\n                >\n                  <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n                  {labels.retry}\n                </button>\n              )}\n            </div>\n          </div>\n        ) : status === \"idle\" ? (\n          <div className=\"flex items-center justify-between gap-3 rounded-lg border border-dashed px-3 py-2.5\">\n            <span className=\"text-sm text-muted-foreground\">{labels.idle}</span>\n            {onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={onRegenerate}\n                className={cn(\n                  \"inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 motion-reduce:transition-none\",\n                  focusRing,\n                )}\n              >\n                <FileAnalytics className=\"size-3.5\" aria-hidden=\"true\" />\n                {labels.generate}\n              </button>\n            )}\n          </div>\n        ) : (\n          <div\n            data-slot=\"insight-body\"\n            className=\"space-y-3 text-sm leading-6 text-pretty text-foreground/90\"\n          >\n            {paragraphs.map((paragraph, index) => {\n              const caret = status === \"streaming\" &&\n                index === paragraphs.length - 1 && (\n                  <span\n                    aria-hidden=\"true\"\n                    data-slot=\"insight-caret\"\n                    className=\"ml-0.5 inline-block h-[1.05em] w-[2px] translate-y-[0.18em] rounded-full bg-(--insight-accent) motion-safe:animate-[insight-caret_1s_linear_infinite]\"\n                  />\n                );\n              return paragraph.prose || paragraph.nodes.length === 0 ? (\n                <p key={index} className=\"break-words\">\n                  {paragraph.nodes}\n                  {caret}\n                </p>\n              ) : (\n                <div\n                  key={index}\n                  data-slot=\"insight-highlights\"\n                  className=\"flex flex-wrap items-center gap-1.5 [&_[data-slot=insight-token]]:mx-0\"\n                >\n                  {paragraph.nodes}\n                  {caret}\n                </div>\n              );\n            })}\n          </div>\n        )}\n\n        {status === \"done\" && sources && sources.length > 0 && (\n          <div\n            data-slot=\"insight-sources\"\n            className=\"mt-3.5 flex flex-wrap items-center gap-1.5 transition-[opacity,translate] duration-500 ease-out starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\"\n          >\n            <span className=\"mr-0.5 text-xs text-muted-foreground\">\n              {labels.sources}\n            </span>\n            {sources.map((item, index) => {\n              const content = (\n                <>\n                  <span className=\"flex h-4 min-w-4 items-center justify-center rounded-[4px] bg-muted px-1 font-mono text-[10px] leading-none font-medium text-muted-foreground\">\n                    {index + 1}\n                  </span>\n                  <span className=\"min-w-0 truncate\">{item.label}</span>\n                  {item.href && (\n                    <ArrowUpRight\n                      className=\"size-3 shrink-0 text-muted-foreground\"\n                      aria-hidden=\"true\"\n                    />\n                  )}\n                </>\n              );\n              const chip = cn(\n                \"inline-flex h-6 max-w-full min-w-0 items-center gap-1.5 rounded-md border bg-card pr-2 pl-1 text-xs transition-colors motion-reduce:transition-none\",\n                hoveredSource === item.id &&\n                  \"border-(--insight-accent)/40 bg-(--insight-accent)/[0.06]\",\n              );\n              return item.href ? (\n                <a\n                  key={item.id}\n                  data-slot=\"insight-source\"\n                  data-active={hoveredSource === item.id || undefined}\n                  href={item.href}\n                  target=\"_blank\"\n                  rel=\"noreferrer\"\n                  className={cn(chip, \"hover:bg-muted\", focusRing)}\n                >\n                  {content}\n                </a>\n              ) : (\n                <span\n                  key={item.id}\n                  data-slot=\"insight-source\"\n                  data-active={hoveredSource === item.id || undefined}\n                  className={chip}\n                >\n                  {content}\n                </span>\n              );\n            })}\n          </div>\n        )}\n      </div>\n\n      {status !== \"idle\" && status !== \"error\" && (\n        <div\n          data-slot=\"insight-actions\"\n          className=\"relative mt-auto flex items-center gap-1 border-t px-2 py-1.5 @sm/insight:px-3\"\n        >\n          {busy && onStop ? (\n            <button\n              type=\"button\"\n              onClick={onStop}\n              className={cn(button, \"px-2\")}\n            >\n              <Stop className=\"size-3\" aria-hidden=\"true\" />\n              {labels.stop}\n            </button>\n          ) : (\n            onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={onRegenerate}\n                disabled={busy}\n                aria-label={labels.regenerate}\n                title={labels.regenerate}\n                className={cn(button, \"px-2\")}\n              >\n                <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n                <span className=\"hidden @xs/insight:inline\">\n                  {labels.regenerate}\n                </span>\n              </button>\n            )\n          )}\n          <button\n            type=\"button\"\n            onClick={copy}\n            disabled={busy || !plain}\n            aria-label={copied ? labels.copied : labels.copy}\n            title={labels.copy}\n            className={cn(button, \"px-2\")}\n          >\n            {copied ? (\n              <Check\n                className=\"size-3.5 text-(--insight-positive)\"\n                aria-hidden=\"true\"\n              />\n            ) : (\n              <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n            )}\n            <span className=\"hidden @xs/insight:inline\">\n              {copied ? labels.copied : labels.copy}\n            </span>\n          </button>\n          {actions}\n          <div\n            className=\"ml-auto flex items-center gap-0.5\"\n            role=\"group\"\n            aria-label={labels.feedback}\n          >\n            <button\n              type=\"button\"\n              aria-pressed={feedback === \"up\"}\n              aria-label={labels.helpful}\n              title={labels.helpful}\n              disabled={busy || status !== \"done\"}\n              onClick={() => setFeedback(\"up\")}\n              className={cn(\n                button,\n                \"size-7\",\n                feedback === \"up\" &&\n                  \"text-(--insight-accent) hover:text-(--insight-accent)\",\n              )}\n            >\n              {feedback === \"up\" ? (\n                <ThumbUpFilled className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <ThumbUp className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n            </button>\n            <button\n              type=\"button\"\n              aria-pressed={feedback === \"down\"}\n              aria-label={labels.notHelpful}\n              title={labels.notHelpful}\n              disabled={busy || status !== \"done\"}\n              onClick={() => setFeedback(\"down\")}\n              className={cn(\n                button,\n                \"size-7\",\n                feedback === \"down\" && \"text-foreground\",\n              )}\n            >\n              {feedback === \"down\" ? (\n                <ThumbDownFilled className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <ThumbDown className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n            </button>\n          </div>\n        </div>\n      )}\n\n      {/* Announce once: the finished text, not every token. */}\n      <div className=\"sr-only\" aria-live=\"polite\" aria-atomic=\"true\">\n        {status === \"done\"\n          ? plain\n          : status === \"thinking\"\n            ? labels.thinking\n            : \"\"}\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/blocks/model-usage. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
