# Add the "KPI Card" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/kpi-card) to this Pantheon Content Publisher (P1) Next.js project. One headline metric with change vs. a prior period and a sparkline. Every value binds to a P1 data source.

## Steps

1. Create `components/puck/kpi-card-block.tsx` with the exact file contents below. If `components/puck/` doesn't exist, find the folder where this project keeps its Puck components (look at the imports in `puck.config.tsx`) and put it there.
2. In `puck.config.tsx`, import it: `import { kpiCardBlock } from "./components/puck/kpi-card-block";`
3. Register it under `components` as `KpiCardBlock: kpiCardBlock`.
4. Add `"KpiCardBlock"` to the best-fitting entry in `categories` (this block's library category is "Dashboards"). Create a category only if none fits.
5. Dashboard widgets are designed to sit inside the Dashboard Grid block (https://p1-blocks.prolificdigital.io/r/dashboard-grid.md). If the project doesn't have it yet, offer to add it too.
6. Run the project's type check (usually `pnpm typecheck`) and resolve anything project-specific.
7. If `package.json` has a `sync:registry` script, tell the user it must run (or that CI will run it) before the new component appears in the P1 editor.

## Rules

- Do not add dependencies. The block is self-contained by design: one type-only import from `@puckeditor/core`, Tailwind v4 classes, no client JavaScript.
- Keep the files as-is unless the user asks for changes. The accent color is `indigo-*`; if the project has brand colors, offer to swap them with a find-and-replace on `indigo-`.
- Data values are text fields on purpose: P1 data-source tokens (`{{ source.field }}`) only bind in text fields. Don't convert them to number fields.
- Don't change prop names in `defaultProps`. Content editors' saved pages depend on them.

## File: `components/puck/kpi-card-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";

/**
 * KPI Card — one headline metric with its change versus a prior period and an optional
 * sparkline. Every value is a text field, so it can be bound to a P1 data source
 * ({{ source.field }}). Place inside a Dashboard Grid.
 * Register: `KpiCardBlock: kpiCardBlock` in puck.config.tsx.
 */
// spec: status-colors

type Heading = "h2" | "h3" | "h4" | "p";

export type KpiCardProps = {
  title: string;
  headingLevel: Heading;
  value: string;
  prefix: string;
  suffix: string;
  change: string;
  changeLabel: string;
  goodWhen: "up" | "down";
  trend: string;
  footnote: string;
};

/** "1,234.5", "$12k" or "-3.2%" → number; anything unparseable → null. */
function toNumber(raw: string | undefined): number | null {
  if (raw == null) return null;
  const cleaned = String(raw).replace(/[^0-9.\-]/g, "");
  if (cleaned === "" || cleaned === "-" || cleaned === ".") return null;
  const n = Number(cleaned);
  return Number.isFinite(n) ? n : null;
}

function sparkPath(values: number[], w: number, h: number) {
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = max - min || 1;
  const step = values.length > 1 ? w / (values.length - 1) : 0;
  const points = values.map((v, i) => [i * step, h - 2 - ((v - min) / span) * (h - 4)] as const);
  const line = points.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`).join(" ");
  return { line, area: `${line} L${w} ${h} L0 ${h} Z`, last: points[points.length - 1] };
}

export const kpiCardBlock: ComponentConfig<KpiCardProps> = {
  label: "KPI Card",
  fields: {
    title: { type: "text", label: "Metric name" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H2", value: "h2" },
        { label: "H3 (recommended inside a dashboard)", value: "h3" },
        { label: "H4", value: "h4" },
        { label: "Not a heading", value: "p" },
      ],
      metadata: { help: "Sets the page outline for screen readers and search. The look doesn't change." },
    },
    value: { type: "text", label: "Value", metadata: { help: "Type it or bind it, e.g. {{ metrics.meals_served }}. Shown as written." } },
    prefix: { type: "text", label: "Prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    suffix: { type: "text", label: "Suffix", metadata: { help: "e.g. % or hrs. Leave blank for none." } },
    change: { type: "text", label: "Change (%)", metadata: { help: "Percent change vs. the comparison period, e.g. 12.4 or -3. Leave blank to hide." } },
    changeLabel: { type: "text", label: "Compared with", metadata: { help: "e.g. vs. last quarter." } },
    goodWhen: {
      type: "radio",
      label: "An increase is",
      options: [
        { label: "Good", value: "up" },
        { label: "Bad", value: "down" },
      ],
      metadata: { help: "Colors the change green or red. Wait times and costs are usually better when they go down." },
    },
    trend: {
      type: "text",
      label: "Trend values",
      metadata: { help: "Comma-separated, oldest first, e.g. 12, 15, 14, 19. Draws the sparkline. Leave blank to hide." },
    },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the number comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Meals served",
    headingLevel: "h3",
    value: "48,210",
    prefix: "",
    suffix: "",
    change: "12.4",
    changeLabel: "vs. last quarter",
    goodWhen: "up",
    trend: "31, 34, 33, 38, 36, 41, 44, 43, 48",
    footnote: "Pantry check-ins, Jul–Sep 2026",
  },
  render: ({ title, headingLevel, value, prefix, suffix, change, changeLabel, goodWhen, trend, footnote }) => {
    const H = headingLevel || "h3";
    const delta = toNumber(change);
    const series = (trend ?? "")
      .split(",")
      .map((v) => toNumber(v))
      .filter((v): v is number => v !== null);
    const spark = series.length > 1 ? sparkPath(series, 120, 40) : null;
    const up = delta !== null && delta > 0;
    const flat = delta === 0;
    const good = flat ? null : up === (goodWhen !== "down");
    const tone = good === null ? "bg-neutral-100 text-neutral-700" : good ? "bg-emerald-50 text-emerald-800" : "bg-red-50 text-red-800";
    const shown = value?.trim() ? value : "—";

    return (
      <div className="flex h-full flex-col rounded-xl bg-white p-5 shadow-xs ring-1 ring-neutral-950/5 sm:p-6 not-in-data-[dashboard-grid]:mx-4 not-in-data-[dashboard-grid]:my-8 sm:not-in-data-[dashboard-grid]:mx-auto sm:not-in-data-[dashboard-grid]:max-w-2xl">
        {title ? <H className="text-sm font-medium text-neutral-600">{title}</H> : null}
        <div className="mt-2 flex items-end justify-between gap-4">
          <p className="text-3xl font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-4xl">
            {shown !== "—" && prefix ? <span className="mr-0.5 text-neutral-500">{prefix}</span> : null}
            {shown}
            {shown !== "—" && suffix ? <span className="ml-1 text-xl text-neutral-500 sm:text-2xl">{suffix}</span> : null}
          </p>
          {spark ? (
            <svg
              viewBox="0 0 120 40"
              preserveAspectRatio="none"
              role="img"
              aria-label={`Trend: ${series.join(", ")}`}
              className="h-10 w-24 shrink-0 overflow-visible text-indigo-600 sm:w-28"
            >
              <path d={spark.area} className="fill-indigo-600/10" />
              <path d={spark.line} fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
              <circle cx={spark.last[0]} cy={spark.last[1]} r="3" className="fill-white" stroke="currentColor" strokeWidth="2" vectorEffect="non-scaling-stroke" />
            </svg>
          ) : null}
        </div>
        {delta !== null ? (
          <p className="mt-3 flex flex-wrap items-center gap-2 text-sm text-neutral-600">
            <span className={`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 font-semibold tabular-nums ${tone}`}>
              <svg aria-hidden="true" viewBox="0 0 12 12" fill="currentColor" className={`size-3 ${flat ? "hidden" : up ? "" : "rotate-180"}`}>
                <path d="M6 2.5 10 8H2l4-5.5Z" />
              </svg>
              <span className="sr-only">{flat ? "No change" : up ? "Up" : "Down"}</span>
              {up ? "+" : ""}
              {delta}%
              {good !== null ? <span className="sr-only">{good ? " (better)" : " (worse)"}</span> : null}
            </span>
            {changeLabel ? <span>{changeLabel}</span> : null}
          </p>
        ) : null}
        {footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null}
      </div>
    );
  },
};
```
