# Metric card

> An executive KPI card with timeframe switching, a dual-series Bezier chart with hover readout, and a proportional breakdown.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/metric-card`
- File: `src/components/haze/ui/metric-card.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/metric-card

## Use when
- A dashboard tile presents a headline KPI alongside interactive timeframe switching (7D, 30D, 90D) and period-over-period comparison
- Users benefit from seeing both trajectory against the previous period and a compact revenue or usage mix breakdown in one card

## Avoid when
- You need a minimal figure without charts or timeframe switching. Use stat.
- You need full multi-axis charting with zoom and export controls. Use line-chart.

## Alternatives
- [stat](https://hazeui.com/ui/stat.md)
- [sparkline](https://hazeui.com/ui/sparkline.md)
- [line-chart](https://hazeui.com/ui/line-chart.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-metric-card" | no | Unique identifier used to scope the SVG area gradient. |
| label | `string` | "Revenue" | no | Metric title rendered in the card header. |
| timeframes | `MetricTimeframe[]` |  | no | Array of timeframe datasets (id, label, value, delta, series, previousSeries, breakdown) for the pill switcher. |
| defaultTimeframe | `string` | "30d" | no | Timeframe id selected on initial render. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level for the metric label. |
| class | `string` |  | no | Additional classes on the outer card element. |

## Accessibility
- Timeframe pills are native buttons with aria-pressed state and clear focus rings.
- The delta readout pairs a directional triangle with screen-reader phrasing ('Increased by' / 'Decreased by') so meaning never relies on color alone.
- The chart container is keyboard-focusable and supports Left/Right arrow inspection, announcing the hovered or focused data point in an aria-live readout.
- Key Tab / Enter or Space: Switch between 7D, 30D, and 90D timeframe pills.
- Key Left or Right Arrow: Step through individual data points when the trend chart is focused.
- Key Escape: Clear the active point readout and return to the latest endpoint.

## Agent prompts

### Install and use

Install the Haze UI component "Metric card" with `npx shadcn@latest add @haze/metric-card`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import MetricCard from "@/components/haze/ui/metric-card.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/metric-card.md

### Customize with real content

Adapt the Haze metric-card ui for our product. Replace the demo values of these props with our real content: id, label, timeframes, defaultTimeframe, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Timeframe pills are native buttons with aria-pressed state and clear focus rings. The delta readout pairs a directional triangle with screen-reader phrasing ('Increased by' / 'Decreased by') so meaning never relies on color alone. The chart container is keyboard-focusable and supports Left/Right arrow inspection, announcing the hovered or focused data point in an aria-live readout. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using metric-card, check it fits: use it when a dashboard tile presents a headline kpi alongside interactive timeframe switching (7d, 30d, 90d) and period-over-period comparison; users benefit from seeing both trajectory against the previous period and a compact revenue or usage mix breakdown in one card. Avoid it when you need a minimal figure without charts or timeframe switching. use stat.; you need full multi-axis charting with zoom and export controls. use line-chart.. Alternatives: @haze/stat, @haze/sparkline, @haze/line-chart.

## Example requests that should lead here
- Create an executive Revenue metric card with 7D/30D/90D switcher, dual-series comparison curve, and Plans/Usage/Services breakdown.
- Build an analytics KPI card showing period-over-period growth with interactive data point inspection.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

type Trend = "up" | "down" | "flat";
type Tone = "positive" | "negative" | "neutral";
type SegmentTone = "foreground" | "brand" | "muted" | "success" | "warning";

interface BreakdownItem {
  label: string;
  value: string;
  share: number;
  tone?: SegmentTone;
}

interface MetricTimeframe {
  id: string;
  label: string;
  value: string;
  delta: string;
  trend?: Trend;
  tone?: Tone;
  comparison: string;
  startDate: string;
  endDate: string;
  series: number[];
  previousSeries?: number[];
  pointLabels?: string[];
  unitPrefix?: string;
  breakdown?: BreakdownItem[];
}

interface Props {
  /** Optional unique id for SVG gradient scoping. */
  id?: string;
  label?: string;
  timeframes?: MetricTimeframe[];
  defaultTimeframe?: string;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}

const defaultTimeframes: MetricTimeframe[] = [
  {
    id: "7d",
    label: "7D",
    value: "$12,480",
    delta: "4.2%",
    trend: "up",
    comparison: "vs previous 7 days",
    startDate: "Oct 8",
    endDate: "Oct 14",
    unitPrefix: "$",
    pointLabels: ["Oct 8", "Oct 9", "Oct 10", "Oct 11", "Oct 12", "Oct 13", "Oct 14"],
    series: [1540, 1690, 1610, 1820, 1780, 1940, 2100],
    previousSeries: [1480, 1520, 1640, 1610, 1710, 1790, 1880],
    breakdown: [
      { label: "Plans", value: "$7,862", share: 63, tone: "foreground" },
      { label: "Usage", value: "$3,494", share: 28, tone: "brand" },
      { label: "Services", value: "$1,124", share: 9, tone: "muted" },
    ],
  },
  {
    id: "30d",
    label: "30D",
    value: "$51,612",
    delta: "6.8%",
    trend: "up",
    comparison: "vs previous 30 days",
    startDate: "Sep 15",
    endDate: "Oct 14",
    unitPrefix: "$",
    pointLabels: [
      "Sep 15", "Sep 18", "Sep 21", "Sep 24", "Sep 27", "Sep 30",
      "Oct 2", "Oct 5", "Oct 7", "Oct 10", "Oct 12", "Oct 14",
    ],
    series: [3420, 3780, 3610, 4050, 3920, 4280, 4190, 4560, 4490, 4820, 5040, 5452],
    previousSeries: [3290, 3410, 3580, 3520, 3740, 3810, 3960, 4040, 4180, 4260, 4390, 4510],
    breakdown: [
      { label: "Plans", value: "$32,060", share: 62, tone: "foreground" },
      { label: "Usage", value: "$15,002", share: 29, tone: "brand" },
      { label: "Services", value: "$4,550", share: 9, tone: "muted" },
    ],
  },
  {
    id: "90d",
    label: "90D",
    value: "$148,940",
    delta: "14.3%",
    trend: "up",
    comparison: "vs previous 90 days",
    startDate: "Jul 17",
    endDate: "Oct 14",
    unitPrefix: "$",
    pointLabels: [
      "Jul 17", "Jul 25", "Aug 2", "Aug 10", "Aug 18", "Aug 26",
      "Sep 3", "Sep 11", "Sep 19", "Sep 27", "Oct 5", "Oct 14",
    ],
    series: [9800, 10420, 10900, 10650, 11480, 12100, 11920, 12780, 13450, 14120, 15180, 16140],
    previousSeries: [9100, 9450, 9620, 9880, 10120, 10480, 10760, 11100, 11420, 11850, 12210, 12690],
    breakdown: [
      { label: "Plans", value: "$89,364", share: 60, tone: "foreground" },
      { label: "Usage", value: "$46,171", share: 31, tone: "brand" },
      { label: "Services", value: "$13,405", share: 9, tone: "muted" },
    ],
  },
];

const {
  id = "haze-metric-card",
  label = "Revenue",
  timeframes = defaultTimeframes,
  defaultTimeframe = "30d",
  headingLevel = 3,
  class: className,
} = Astro.props;

const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];
const defaultToneByTrend: Record<Trend, Tone> = { up: "positive", down: "negative", flat: "neutral" };
const defaultSegmentTones: SegmentTone[] = ["foreground", "brand", "muted"];

function toPoints(values: number[], minVal: number, maxVal: number) {
  const span = maxVal - minVal;
  return values.map((val, idx) => ({
    x: values.length <= 1 ? 180 : 10 + (idx * 340) / (values.length - 1),
    y: span === 0 ? 58 : 16 + 84 * ((maxVal - val) / span),
    val,
  }));
}

function buildSmoothPath(pts: { x: number; y: number }[]) {
  if (pts.length === 0) return "";
  if (pts.length === 1) return `M ${pts[0]!.x.toFixed(1)} ${pts[0]!.y.toFixed(1)}`;
  let d = `M ${pts[0]!.x.toFixed(1)} ${pts[0]!.y.toFixed(1)}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[Math.max(0, i - 1)]!;
    const p1 = pts[i]!;
    const p2 = pts[i + 1]!;
    const p3 = pts[Math.min(pts.length - 1, i + 2)]!;
    const cp1x = p1.x + (p2.x - p0.x) / 6;
    const cp1y = p1.y + (p2.y - p0.y) / 6;
    const cp2x = p2.x - (p3.x - p1.x) / 6;
    const cp2y = p2.y - (p3.y - p1.y) / 6;
    d += ` C ${cp1x.toFixed(1)} ${cp1y.toFixed(1)}, ${cp2x.toFixed(1)} ${cp2y.toFixed(1)}, ${p2.x.toFixed(1)} ${p2.y.toFixed(1)}`;
  }
  return d;
}

const prepared = timeframes.map((tf) => {
  const trend: Trend = tf.trend ?? "up";
  const tone: Tone = tf.tone ?? defaultToneByTrend[trend];
  const validCurrent = tf.series.filter((n) => Number.isFinite(n));
  const validPrev = (tf.previousSeries ?? []).filter((n) => Number.isFinite(n));
  const allValues = [...validCurrent, ...validPrev];
  const minVal = allValues.length ? Math.min(...allValues) : 0;
  const maxVal = allValues.length ? Math.max(...allValues) : 1;
  const currentPts = toPoints(validCurrent, minVal, maxVal);
  const prevPts = toPoints(validPrev, minVal, maxVal);
  const currentPath = buildSmoothPath(currentPts);
  const prevPath = buildSmoothPath(prevPts);
  const areaPath =
    currentPts.length > 1
      ? `${currentPath} L ${currentPts.at(-1)!.x.toFixed(1)} 114 L ${currentPts[0]!.x.toFixed(1)} 114 Z`
      : "";
  const breakdown = (tf.breakdown ?? []).map((item, idx) => ({
    label: item.label,
    value: item.value,
    share: Math.max(0, Math.min(100, item.share)),
    tone: item.tone ?? defaultSegmentTones[idx % defaultSegmentTones.length]!,
  }));
  return {
    id: tf.id,
    label: tf.label,
    value: tf.value,
    delta: tf.delta,
    trend,
    tone,
    comparison: tf.comparison,
    startDate: tf.startDate,
    endDate: tf.endDate,
    unitPrefix: tf.unitPrefix ?? "",
    pointLabels: tf.pointLabels ?? [],
    currentPts,
    prevPts,
    currentPath,
    prevPath,
    areaPath,
    breakdown,
  };
});

const activeIndex = Math.max(
  0,
  prepared.findIndex((tf) => tf.id === defaultTimeframe),
);
const initial = prepared[activeIndex] ?? prepared[0]!;
const endpoint = initial.currentPts.at(-1);

const arrowGlyph: Record<Trend, string> = { up: "▲", down: "▼", flat: "—" };
const spokenTrend: Record<Trend, string> = {
  up: "Increased by",
  down: "Decreased by",
  flat: "Unchanged at",
};

const segmentClasses: Record<SegmentTone, string> = {
  foreground: "bg-foreground",
  brand: "bg-brand",
  muted: "bg-muted-foreground/50",
  success: "bg-success",
  warning: "bg-warning",
};
---

<article
  id={id}
  data-haze-metric-card
  data-active-index={String(activeIndex)}
  data-timeframes={JSON.stringify(prepared)}
  class={cn(
    "w-full max-w-[420px] min-w-0 rounded-xl border border-border bg-card p-5 text-card-foreground",
    className,
  )}
>
  <div class="flex min-w-0 items-center justify-between gap-3">
    <Heading class="min-w-0 truncate text-sm/5 font-medium text-muted-foreground">
      {label}
    </Heading>

    {
      prepared.length > 1 && (
        <div role="group" aria-label={`${label} timeframe`} class="inline-flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-1">
          {prepared.map((tf, index) => (
            <button
              type="button"
              data-metric-range={String(index)}
              aria-pressed={index === activeIndex ? "true" : "false"}
              class="relative cursor-pointer rounded-md px-2 py-1 text-[0.6875rem]/4 font-medium text-muted-foreground transition-[background-color,color,box-shadow,scale] duration-150 ease-snappy hover:text-foreground active:scale-[0.97] active:duration-100 focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-key"
            >
              {tf.label}
            </button>
          ))}
        </div>
      )
    }
  </div>

  <div class="mt-2.5 grid min-w-0 gap-1">
    <p
      data-metric-value
      class="text-3xl/9 font-semibold tracking-tight text-foreground tabular-nums wrap-anywhere"
    >
      <span data-metric-value-spoken class="sr-only">{initial.value}</span><span data-metric-value-visual aria-hidden="true">{initial.value}</span>
    </p>
    <p class="flex min-w-0 flex-wrap items-center gap-1.5 text-xs/4">
      <span
        data-metric-delta-wrap
        data-tone={initial.tone}
        class="inline-flex items-center gap-1 font-medium tabular-nums data-[tone=negative]:text-destructive data-[tone=neutral]:text-muted-foreground data-[tone=positive]:text-success"
      >
        <span aria-hidden="true" data-metric-arrow class="text-[0.6875rem]/4">{arrowGlyph[initial.trend]}</span>
        <span class="sr-only" data-metric-spoken>{spokenTrend[initial.trend]}</span>
        <span data-metric-delta>{initial.delta}</span>
      </span>
      <span data-metric-comparison class="text-muted-foreground">{initial.comparison}</span>
    </p>
  </div>

  <div class="mt-4 grid min-w-0 gap-1.5">
    <div
      data-metric-chart-wrap
      tabindex="0"
      role="group"
      aria-label={`${label} trend chart. Hover or use left and right arrow keys to inspect individual data points.`}
      class="relative min-w-0 rounded-lg focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
    >
      <div
        data-metric-readout
        data-active="false"
        aria-live="polite"
        class="pointer-events-none absolute top-0 left-0 z-10 rounded-md border border-border bg-popover/95 px-2 py-0.5 font-mono text-[0.6875rem]/4 text-popover-foreground opacity-0 shadow-float tabular-nums transition-opacity duration-150 ease-snappy data-[active=true]:opacity-100"
      ></div>

      <svg
        aria-hidden="true"
        data-metric-svg
        viewBox="0 0 360 120"
        class="h-32 w-full overflow-visible"
      >
        <defs>
          <linearGradient id={`${id}-area`} x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stop-color="currentColor" stop-opacity="0.14"></stop>
            <stop offset="100%" stop-color="currentColor" stop-opacity="0"></stop>
          </linearGradient>
        </defs>

        <line x1="8" y1="28" x2="352" y2="28" class="stroke-border/60" stroke-width="1" vector-effect="non-scaling-stroke" />
        <line x1="8" y1="70" x2="352" y2="70" class="stroke-border/60" stroke-width="1" vector-effect="non-scaling-stroke" />
        <line x1="8" y1="112" x2="352" y2="112" class="stroke-border" stroke-width="1" vector-effect="non-scaling-stroke" />

        <path
          data-metric-area
          d={initial.areaPath}
          class="text-foreground"
          fill={`url(#${id}-area)`}
        />

        <path
          data-metric-prev
          d={initial.prevPath}
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-dasharray="3 3"
          stroke-linecap="round"
          class="text-muted-foreground/50"
          vector-effect="non-scaling-stroke"
        />

        <path
          data-metric-current
          d={initial.currentPath}
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          class="text-foreground"
          vector-effect="non-scaling-stroke"
        />

        <line
          data-metric-cursor
          x1="0"
          y1="10"
          x2="0"
          y2="112"
          stroke="currentColor"
          stroke-width="1"
          stroke-dasharray="2 2"
          class="text-muted-foreground/70 opacity-0 transition-opacity duration-150 ease-snappy data-[active=true]:opacity-100"
          vector-effect="non-scaling-stroke"
        />

        <circle
          data-metric-prev-dot
          cx={initial.prevPts.at(-1)?.x ?? 0}
          cy={initial.prevPts.at(-1)?.y ?? 0}
          r="3"
          stroke="currentColor"
          stroke-width="1.5"
          class="fill-card text-muted-foreground opacity-0 transition-opacity duration-150 ease-snappy data-[active=true]:opacity-100"
        />

        <circle
          data-metric-end-halo
          cx={endpoint?.x ?? 0}
          cy={endpoint?.y ?? 0}
          r="8"
          fill="currentColor"
          fill-opacity="0.18"
          class="text-foreground"
        />
        <circle
          data-metric-end-dot
          cx={endpoint?.x ?? 0}
          cy={endpoint?.y ?? 0}
          r="3.5"
          fill="currentColor"
          class="text-foreground"
        />
      </svg>
    </div>

    <div class="flex min-w-0 items-center justify-between gap-2 text-[0.6875rem]/4 text-muted-foreground tabular-nums">
      <span data-metric-start>{initial.startDate}</span>
      <span class="inline-flex items-center gap-1.5">
        <span aria-hidden="true" class="w-3.5 border-t border-dashed border-muted-foreground/60"></span>
        <span>Previous period</span>
      </span>
      <span data-metric-end>{initial.endDate}</span>
    </div>
  </div>

  {
    initial.breakdown.length > 0 && (
      <div data-metric-breakdown>
        <div
          aria-hidden="true"
          class="mt-4 flex h-1.5 w-full gap-0.5 overflow-hidden rounded-full bg-muted"
        >
          {initial.breakdown.map((item, idx) => (
            <span
              data-metric-bar={String(idx)}
              class={cn(
                "h-full transition-[width] duration-300 ease-snappy first:rounded-l-full last:rounded-r-full",
                segmentClasses[item.tone],
              )}
              style={`width: ${item.share}%`}
            />
          ))}
        </div>

        <ul role="list" class="mt-4 space-y-2 text-xs/5">
          {initial.breakdown.map((item, idx) => (
            <li data-metric-row={String(idx)} class="flex min-w-0 items-center justify-between gap-3">
              <span class="inline-flex min-w-0 items-center gap-2 text-muted-foreground">
                <span
                  aria-hidden="true"
                  class={cn("size-2 shrink-0 rounded-full", segmentClasses[item.tone])}
                />
                <span data-metric-row-label class="truncate text-card-foreground">{item.label}</span>
              </span>
              <span class="inline-flex shrink-0 items-baseline gap-2.5 tabular-nums">
                <span data-metric-row-value class="font-medium text-foreground">{item.value}</span>
                <span data-metric-row-share class="w-8 text-right text-muted-foreground">{item.share}%</span>
              </span>
            </li>
          ))}
        </ul>
      </div>
    )
  }
</article>

<script>
  const reduced = matchMedia("(prefers-reduced-motion: reduce)");
  // Digit roll (NumberFlow behaviour): only characters that changed move, up when the value rises, down when it falls.
  const roll = (el: HTMLElement, next: string, direction: number) => {
    const before = Array.from(el.dataset.rolled ?? el.textContent ?? "");
    el.dataset.rolled = next;
    el.replaceChildren();
    if (reduced.matches) { el.textContent = next; return; }
    const easing = getComputedStyle(el).getPropertyValue("--ease-snappy").trim() || "ease";
    const after = Array.from(next);
    after.forEach((character, index) => {
      const previous = before[before.length - after.length + index];
      const column = document.createElement("span");
      column.className = "relative inline-grid overflow-hidden align-bottom whitespace-pre";
      const digit = document.createElement("span");
      digit.textContent = character;
      column.append(digit);
      el.append(column);
      if (previous === character) return;
      const shift = /\p{Nd}/u.test(character) ? 100 : 30;
      digit.animate([{ opacity: 0, translate: `0 ${direction * shift}%` }, { opacity: 1, translate: "0 0" }], { duration: 250, easing });
      if (previous === undefined) return;
      const ghost = document.createElement("span");
      ghost.className = "absolute inset-0";
      ghost.textContent = previous;
      column.append(ghost);
      const out = ghost.animate([{ opacity: 1, translate: "0 0" }, { opacity: 0, translate: `0 ${-direction * shift}%` }], { duration: 250, easing });
      out.finished.then(() => ghost.remove(), () => ghost.remove());
    });
  };
  interface Point {
    x: number;
    y: number;
    val: number;
  }

  interface BreakdownPayload {
    label: string;
    value: string;
    share: number;
  }

  interface TimeframePayload {
    id: string;
    label: string;
    value: string;
    delta: string;
    trend: "up" | "down" | "flat";
    tone: "positive" | "negative" | "neutral";
    comparison: string;
    startDate: string;
    endDate: string;
    unitPrefix: string;
    pointLabels: string[];
    currentPts: Point[];
    prevPts: Point[];
    currentPath: string;
    prevPath: string;
    areaPath: string;
    breakdown: BreakdownPayload[];
  }

  const arrowMap = { up: "▲", down: "▼", flat: "—" } as const;
  const spokenMap = { up: "Increased by", down: "Decreased by", flat: "Unchanged at" } as const;
  const numFmt = new Intl.NumberFormat("en", { maximumFractionDigits: 0 });

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const raw = root.dataset.timeframes;
    if (!raw) return;

    let frames: TimeframePayload[];
    try {
      frames = JSON.parse(raw) as TimeframePayload[];
    } catch {
      return;
    }
    if (!frames.length) return;

    const rangeButtons = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-metric-range]"));
    const valueEl = root.querySelector<HTMLElement>("[data-metric-value]");
    const deltaWrap = root.querySelector<HTMLElement>("[data-metric-delta-wrap]");
    const arrowEl = root.querySelector<HTMLElement>("[data-metric-arrow]");
    const spokenEl = root.querySelector<HTMLElement>("[data-metric-spoken]");
    const deltaEl = root.querySelector<HTMLElement>("[data-metric-delta]");
    const compEl = root.querySelector<HTMLElement>("[data-metric-comparison]");
    const startEl = root.querySelector<HTMLElement>("[data-metric-start]");
    const endEl = root.querySelector<HTMLElement>("[data-metric-end]");
    const areaEl = root.querySelector<SVGPathElement>("[data-metric-area]");
    const prevEl = root.querySelector<SVGPathElement>("[data-metric-prev]");
    const currentEl = root.querySelector<SVGPathElement>("[data-metric-current]");
    const endHalo = root.querySelector<SVGCircleElement>("[data-metric-end-halo]");
    const endDot = root.querySelector<SVGCircleElement>("[data-metric-end-dot]");
    const prevDot = root.querySelector<SVGCircleElement>("[data-metric-prev-dot]");
    const cursorEl = root.querySelector<SVGLineElement>("[data-metric-cursor]");
    const chartWrap = root.querySelector<HTMLElement>("[data-metric-chart-wrap]");
    const svgEl = root.querySelector<SVGSVGElement>("[data-metric-svg]");
    const readoutEl = root.querySelector<HTMLElement>("[data-metric-readout]");

    let activeIdx = Number(root.dataset.activeIndex ?? 0) || 0;
    let inspectedIdx: number | null = null;

    const formatVal = (tf: TimeframePayload, n: number) => `${tf.unitPrefix}${numFmt.format(n)}`;

    const syncInspect = (pointIdx: number | null) => {
      const tf = frames[activeIdx]!;
      const pts = tf.currentPts;
      if (!pts.length) return;

      inspectedIdx = pointIdx;
      const targetIdx = pointIdx === null ? pts.length - 1 : Math.max(0, Math.min(pts.length - 1, pointIdx));
      const pt = pts[targetIdx]!;
      const prevPt = tf.prevPts[targetIdx];

      endHalo?.setAttribute("cx", String(pt.x));
      endHalo?.setAttribute("cy", String(pt.y));
      endDot?.setAttribute("cx", String(pt.x));
      endDot?.setAttribute("cy", String(pt.y));

      const isInspecting = pointIdx !== null;
      if (cursorEl) {
        cursorEl.setAttribute("x1", String(pt.x));
        cursorEl.setAttribute("x2", String(pt.x));
        cursorEl.setAttribute("data-active", String(isInspecting));
      }
      if (prevDot) {
        if (prevPt && isInspecting) {
          prevDot.setAttribute("cx", String(prevPt.x));
          prevDot.setAttribute("cy", String(prevPt.y));
          prevDot.setAttribute("data-active", "true");
        } else {
          prevDot.setAttribute("data-active", "false");
        }
      }
      if (readoutEl) {
        if (isInspecting) {
          const dayLabel = tf.pointLabels[targetIdx] ?? `Point ${targetIdx + 1}`;
          const prevText = prevPt ? ` · prev ${formatVal(tf, prevPt.val)}` : "";
          readoutEl.textContent = `${dayLabel}: ${formatVal(tf, pt.val)}${prevText}`;
          readoutEl.setAttribute("data-active", "true");
        } else {
          readoutEl.setAttribute("data-active", "false");
        }
      }
    };

    const renderFrame = (idx: number) => {
      activeIdx = Math.max(0, Math.min(frames.length - 1, idx));
      const tf = frames[activeIdx]!;

      rangeButtons.forEach((btn, i) => btn.setAttribute("aria-pressed", String(i === activeIdx)));
      if (valueEl) {
        const spoken = valueEl.querySelector<HTMLElement>("[data-metric-value-spoken]");
        const visual = valueEl.querySelector<HTMLElement>("[data-metric-value-visual]");
        const numeric = (text: string) => Number.parseFloat(text.replace(/[^0-9.-]/g, ""));
        if (spoken) spoken.textContent = tf.value;
        if (visual && (visual.dataset.rolled ?? visual.textContent) !== tf.value) {
          const direction = numeric(tf.value) >= numeric(visual.dataset.rolled ?? visual.textContent ?? "") ? 1 : -1;
          roll(visual, tf.value, direction);
        }
      }
      if (deltaWrap) deltaWrap.setAttribute("data-tone", tf.tone);
      if (arrowEl) arrowEl.textContent = arrowMap[tf.trend];
      if (spokenEl) spokenEl.textContent = spokenMap[tf.trend];
      if (deltaEl) deltaEl.textContent = tf.delta;
      if (compEl) compEl.textContent = tf.comparison;
      if (startEl) startEl.textContent = tf.startDate;
      if (endEl) endEl.textContent = tf.endDate;
      if (areaEl) areaEl.setAttribute("d", tf.areaPath);
      if (prevEl) prevEl.setAttribute("d", tf.prevPath);
      if (currentEl) currentEl.setAttribute("d", tf.currentPath);

      tf.breakdown.forEach((item, i) => {
        const bar = root.querySelector<HTMLElement>(`[data-metric-bar="${i}"]`);
        const row = root.querySelector<HTMLElement>(`[data-metric-row="${i}"]`);
        if (bar) bar.style.width = `${item.share}%`;
        if (row) {
          const rLabel = row.querySelector<HTMLElement>("[data-metric-row-label]");
          const rVal = row.querySelector<HTMLElement>("[data-metric-row-value]");
          const rShare = row.querySelector<HTMLElement>("[data-metric-row-share]");
          if (rLabel) rLabel.textContent = item.label;
          if (rVal) rVal.textContent = item.value;
          if (rShare) rShare.textContent = `${item.share}%`;
        }
      });

      syncInspect(null);
    };

    rangeButtons.forEach((btn, i) => {
      btn.addEventListener("click", () => renderFrame(i));
    });

    if (chartWrap && svgEl) {
      const indexFromClientX = (clientX: number) => {
        const tf = frames[activeIdx]!;
        const pts = tf.currentPts;
        if (pts.length <= 1) return 0;
        const rect = svgEl.getBoundingClientRect();
        if (rect.width <= 0) return pts.length - 1;
        const svgX = ((clientX - rect.left) / rect.width) * 360;
        let closest = 0;
        let bestDist = Infinity;
        for (let i = 0; i < pts.length; i++) {
          const dist = Math.abs(pts[i]!.x - svgX);
          if (dist < bestDist) {
            bestDist = dist;
            closest = i;
          }
        }
        return closest;
      };

      chartWrap.addEventListener("pointermove", (event) => {
        syncInspect(indexFromClientX(event.clientX));
      });
      chartWrap.addEventListener("pointerleave", () => syncInspect(null));
      chartWrap.addEventListener("blur", () => syncInspect(null));
      chartWrap.addEventListener("keydown", (event) => {
        const pts = frames[activeIdx]!.currentPts;
        if (!pts.length) return;
        if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
          event.preventDefault();
          const base = inspectedIdx === null ? pts.length - 1 : inspectedIdx;
          const step = event.key === "ArrowRight" ? 1 : -1;
          const next = Math.max(0, Math.min(pts.length - 1, base + step));
          syncInspect(next);
        } else if (event.key === "Escape") {
          syncInspect(null);
        }
      });
    }

    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-metric-card]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-metric-card-listener")) {
    document.documentElement.setAttribute("data-haze-metric-card-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
