# AI insight card

> Self-explaining KPI card with annotated sparkline, Explain toggle, three ranked contribution bars and follow-up question chips.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-insight-card`
- File: `src/components/haze/blocks/ai-insight-card.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-insight-card

## Use when
- Explaining why a key business or product metric moved without opening a full BI dashboard
- Linking ranked contributing drivers directly to numbered points on a trend sparkline

## Avoid when
- Displaying a plain metric with no AI breakdown; use stat or sparkline

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-insight-card" | no | Unique prefix for panel and aria-controls IDs. |
| metric | `string` | "Net expansion MRR" | no | KPI label. |
| value | `string` | "$148.4k" | no | Headline metric value. |
| delta | `string` | "+18.4% vs last 30d" | no | Comparison badge text. |
| drivers | `{ id: number; label: string; share: number; delta: string }[]` | 3 ranked drivers | no | Ranked contributing factors with contribution bar widths. |
| followUps | `string[]` | 3 follow-up chips | no | Suggested drill-down questions. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The sparkline SVG carries role="img" and a descriptive aria-label summarizing the trend.
- The Explain button exposes aria-expanded and aria-controls for the collapsible explanation panel.
- Key Tab: Move between the Explain toggle and follow-up question buttons
- Key Enter / Space: Expand or collapse the explanation panel or trigger a follow-up query

## Agent prompts

### Install and use

Install the Haze UI block "AI insight card" with `npx shadcn@latest add @haze/ai-insight-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 AiInsightCard from "@/components/haze/blocks/ai-insight-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/blocks/ai-insight-card.md

### Customize with real content

Adapt the Haze ai-insight-card block for our product. Replace the demo values of these props with our real content: id, metric, value, delta, drivers, followUps, class. Keep the layout, the heading level rules and these accessibility details: The sparkline SVG carries role="img" and a descriptive aria-label summarizing the trend. The Explain button exposes aria-expanded and aria-controls for the collapsible explanation panel. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-insight-card, check it fits: use it when explaining why a key business or product metric moved without opening a full bi dashboard; linking ranked contributing drivers directly to numbered points on a trend sparkline. Avoid it when displaying a plain metric with no ai breakdown; use stat or sparkline. Alternatives: @haze/stat, @haze/sparkline.

## Example requests that should lead here
- Create an AI insight KPI card with sparkline markers, Explain toggle, ranked driver bars and follow-up chips

## Source

```astro
---
import { ArrowUpRight, Sparkles, TrendingUp } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Driver {
  id: number;
  label: string;
  share: number;
  delta: string;
}

interface Props {
  id?: string;
  metric?: string;
  value?: string;
  delta?: string;
  drivers?: Driver[];
  followUps?: string[];
  class?: string;
}

const {
  id = "haze-ai-insight-card",
  metric = "Net expansion MRR",
  value = "$148.4k",
  delta = "+18.4% vs last 30d",
  drivers = [
    { id: 1, label: "Annual Pro upgrades from team trials", share: 54, delta: "+$12.6k" },
    { id: 2, label: "Seat additions in EMEA accounts", share: 31, delta: "+$7.2k" },
    { id: 3, label: "Lower voluntary churn after v2.6", share: 15, delta: "+$3.4k" },
  ],
  followUps = ["Break down by plan tier", "Compare with Q3 cohort", "List top 5 accounts"],
  class: className,
} = Astro.props;
---

<section aria-labelledby={`${id}-title`} data-haze-ai-insight class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
  <div class="mx-auto max-w-xl rounded-2xl border border-border bg-card p-5 sm:p-6">
    <div class="flex flex-wrap items-start justify-between gap-3">
      <div>
        <h2 id={`${id}-title`} class="text-xs/5 font-medium text-muted-foreground">{metric}</h2>
        <p class="mt-1 flex items-baseline gap-2.5">
          <span class="text-3xl/9 font-semibold tracking-tight text-foreground tabular-nums">{value}</span>
          <span class="inline-flex items-center gap-1 rounded-full border border-frame-success bg-success/10 px-2 py-0.5 text-xs font-medium text-success">
            <TrendingUp class="size-3" aria-hidden="true" />
            {delta}
          </span>
        </p>
      </div>
      <button
        type="button"
        data-ins-toggle
        aria-expanded="true"
        aria-controls={`${id}-explain`}
        class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg border border-frame bg-muted px-3 text-xs font-medium text-foreground transition-colors duration-150 hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
      >
        <Sparkles class="size-3.5" aria-hidden="true" />
        Explain
      </button>
    </div>

    <div class="mt-4 rounded-xl border border-border bg-muted/40 p-3">
      <svg viewBox="0 0 360 84" class="h-20 w-full overflow-visible" role="img" aria-label="30-day trend sparkline showing upward inflection with three driver markers">
        <path
          d="M 8 68 C 46 66, 78 60, 114 54 C 152 48, 178 46, 214 34 C 254 20, 294 22, 352 10"
          fill="none"
          stroke="currentColor"
          stroke-width="2.25"
          class="text-foreground"
        />
        <circle data-ins-dot="1" cx="114" cy="54" r="5" class="fill-background stroke-foreground stroke-2 transition-transform duration-150 data-[lit=true]:fill-foreground" />
        <circle data-ins-dot="2" cx="214" cy="34" r="5" class="fill-background stroke-foreground stroke-2 transition-transform duration-150 data-[lit=true]:fill-foreground" />
        <circle data-ins-dot="3" cx="322" cy="15" r="5" class="fill-background stroke-foreground stroke-2 transition-transform duration-150 data-[lit=true]:fill-foreground" />
      </svg>
    </div>

    <div id={`${id}-explain`} data-ins-panel class="mt-4 space-y-4 border-t border-border pt-4">
      <p class="text-sm/6 text-pretty text-foreground">
        Expansion accelerated after week 2 when annual Pro upgrades converted at 2.1x the trailing baseline, led by mid-market teams adding seats.
      </p>

      <ol role="list" class="space-y-2.5">
        {
          drivers.map((d) => (
            <li data-ins-driver={String(d.id)} class="rounded-xl border border-border bg-muted/40 p-3 transition-colors duration-150 hover:border-foreground">
              <div class="flex items-center justify-between gap-2 text-xs/5">
                <span class="flex items-center gap-2 font-medium text-foreground">
                  <span class="inline-flex size-4 items-center justify-center rounded-sm bg-muted font-mono text-[0.625rem] font-semibold text-foreground">{d.id}</span>
                  {d.label}
                </span>
                <span class="font-mono font-medium text-success tabular-nums">{d.delta}</span>
              </div>
              <div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted">
                <div class="h-full rounded-full bg-primary" style={`width: ${d.share}%`}></div>
              </div>
            </li>
          ))
        }
      </ol>

      <div class="flex flex-wrap gap-1.5">
        {
          followUps.map((q) => (
            <button
              type="button"
              data-ins-q={q}
              class="inline-flex h-7 cursor-pointer items-center gap-1 rounded-full border border-frame bg-field px-2.5 text-xs text-muted-foreground hover:border-frame-strong hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75"
            >
              {q}
              <ArrowUpRight class="size-3" aria-hidden="true" />
            </button>
          ))
        }
      </div>
    </div>

    <p data-ins-status role="status" class="mt-3 min-h-4 text-xs/4 text-muted-foreground"></p>
  </div>
</section>

<script>
  function initInsightCards() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-insight]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");
      const toggle = root.querySelector<HTMLButtonElement>("[data-ins-toggle]");
      const panel = root.querySelector<HTMLElement>("[data-ins-panel]");
      const status = root.querySelector<HTMLElement>("[data-ins-status]");

      toggle?.addEventListener("click", () => {
        if (!panel) return;
        panel.hidden = !panel.hidden;
        toggle.setAttribute("aria-expanded", String(!panel.hidden));
      });

      root.querySelectorAll<HTMLElement>("[data-ins-driver]").forEach((row) => {
        const id = row.dataset.insDriver;
        const setLit = (on: boolean) => root.querySelector<SVGElement>(`[data-ins-dot="${id}"]`)?.setAttribute("data-lit", String(on));
        row.addEventListener("mouseenter", () => setLit(true));
        row.addEventListener("mouseleave", () => setLit(false));
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ins-q]").forEach((btn) => {
        btn.addEventListener("click", () => {
          if (status) status.textContent = `Running follow-up analysis: "${btn.dataset.insQ}".`;
        });
      });
    });
  }
  initInsightCards();
  document.addEventListener("astro:page-load", initInsightCards);
</script>
```
