# Add the "Metric Grid" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/metric-grid) to this Pantheon Content Publisher (P1) Next.js project. Up to nine small stats with changes in one dense card for an at-a-glance overview.

## Steps

1. Create `components/puck/metric-grid-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 { metricGridBlock } from "./components/puck/metric-grid-block";`
3. Register it under `components` as `MetricGridBlock: metricGridBlock`.
4. Add `"MetricGridBlock"` 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/metric-grid-block.tsx`

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

/**
 * Metric Grid — up to nine small stats in one card, divided by hairlines, for a dense
 * at-a-glance overview. Each cell has a label, value and optional change. Every value is a
 * text field, bindable to a P1 data source. Place inside a Dashboard Grid.
 * Register: `MetricGridBlock: metricGridBlock` in puck.config.tsx.
 */
// spec: status-colors

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

type Metric = { label: string; value: string; change: string; goodWhen: "up" | "down" };

export type MetricGridProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  metrics: Metric[];
  columns: "2" | "3";
  changeLabel: 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;
}

export const metricGridBlock: ComponentConfig<MetricGridProps> = {
  label: "Metric Grid",
  fields: {
    title: { type: "text", label: "Title" },
    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." },
    },
    subtitle: { type: "text", label: "Subtitle or period", metadata: { help: "e.g. September 2026. Leave blank to hide." } },
    metrics: {
      type: "array",
      label: "Metrics",
      min: 1,
      max: 9,
      getItemSummary: (item) => (item?.label ? `${item.label}${item.value ? ` · ${item.value}` : ""}` : "Metric"),
      defaultItemProps: { label: "New metric", value: "", change: "", goodWhen: "up" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        value: { type: "text", label: "Value", metadata: { help: "Shown as written, e.g. 48.2k or $1,120. Or bind it, e.g. {{ stats.visits }}." } },
        change: { type: "text", label: "Change (%)", metadata: { help: "e.g. 6.1 or -4. Leave blank to hide." } },
        goodWhen: {
          type: "radio",
          label: "An increase is",
          options: [
            { label: "Good", value: "up" },
            { label: "Bad", value: "down" },
          ],
        },
      },
    },
    columns: {
      type: "radio",
      label: "Columns (wide cards)",
      options: [
        { label: "2", value: "2" },
        { label: "3", value: "3" },
      ],
      metadata: { help: "Narrow cards always stack to fit. Pick 3 for six or nine metrics." },
    },
    changeLabel: { type: "text", label: "Changes compared with", metadata: { help: "e.g. vs. September 2025. Shown once, under the grid." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Library system at a glance",
    headingLevel: "h3",
    subtitle: "September 2026",
    metrics: [
      { label: "Branch visits", value: "48.2k", change: "6.1", goodWhen: "up" },
      { label: "New library cards", value: "1,284", change: "12.4", goodWhen: "up" },
      { label: "Program attendance", value: "9,630", change: "3.2", goodWhen: "up" },
      { label: "Wi-Fi sessions", value: "22.9k", change: "-4.0", goodWhen: "up" },
      { label: "Avg. hold wait", value: "9.4 days", change: "-11.3", goodWhen: "down" },
      { label: "Volunteer hours", value: "1,120", change: "0", goodWhen: "up" },
    ],
    columns: "3",
    changeLabel: "vs. September 2025",
    footnote: "Sample data · Source: ILS circulation and door-counter reports",
  },
  render: ({ title, headingLevel, subtitle, metrics, columns, changeLabel, footnote }) => {
    const H = headingLevel || "h3";
    const items = (Array.isArray(metrics) ? metrics : [])
      .slice(0, 9)
      .map((m, i) => ({
        key: `m${i}`,
        label: m?.label?.trim() || "",
        value: m?.value?.trim() || "",
        change: toNumber(m?.change),
        goodWhen: m?.goodWhen === "down" ? ("down" as const) : ("up" as const),
      }))
      .filter((m) => m.label || m.value);
    const three = columns !== "2";

    const header = (
      <div>
        {title ? <H className="text-sm font-semibold text-neutral-950">{title}</H> : null}
        {subtitle ? <p className="mt-0.5 text-sm text-neutral-500">{subtitle}</p> : null}
      </div>
    );
    const foot = footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null;
    const card =
      "@container 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";

    if (!items.length) {
      return (
        <div className={card}>
          {header}
          <div className="mt-4 flex flex-1 flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-neutral-200 px-4 py-10 text-center">
            <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="size-6 text-neutral-400">
              <rect x="3" y="3" width="7.5" height="7.5" rx="1" />
              <rect x="13.5" y="3" width="7.5" height="7.5" rx="1" />
              <rect x="3" y="13.5" width="7.5" height="7.5" rx="1" />
              <rect x="13.5" y="13.5" width="7.5" height="7.5" rx="1" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">Stats appear once metrics are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    // Blank cells pad the last row so the hairline grid never shows a grey gap.
    const n = items.length;
    const pad2 = (2 - (n % 2)) % 2;
    const pad3 = (3 - (n % 3)) % 3;
    const fillers = [0, 1].map((i) => {
      const at2 = i < pad2 ? "@2xs:block" : "";
      if (!three) return at2;
      return `${at2} ${i < pad3 ? "@lg:block" : "@lg:hidden"}`.trim();
    });

    return (
      <div className={card}>
        {header}
        <div
          className={`mt-4 grid grid-cols-1 gap-px overflow-hidden rounded-lg bg-neutral-200 ring-1 ring-neutral-200 @2xs:grid-cols-2 ${three ? "@lg:grid-cols-3" : ""}`}
        >
          {items.map((m) => {
            const up = m.change !== null && m.change > 0;
            const flat = m.change === 0;
            const good = m.change === null || flat ? null : up === (m.goodWhen !== "down");
            const tone = good === null ? "text-neutral-600" : good ? "text-emerald-700" : "text-red-700";
            return (
              <dl key={m.key} className="flex min-w-0 flex-col bg-white px-4 py-3.5">
                <dt className="truncate text-xs text-neutral-600">{m.label || "—"}</dt>
                <dd className="mt-1 flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
                  <span className="text-xl font-semibold tracking-tight text-neutral-950 tabular-nums @lg:text-2xl">{m.value || "—"}</span>
                  {m.change !== null ? (
                    <span className={`inline-flex items-center gap-0.5 text-xs font-semibold tabular-nums ${tone}`}>
                      <svg aria-hidden="true" viewBox="0 0 12 12" fill="currentColor" className={`size-2.5 ${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 ? "+" : flat ? "" : "−"}
                      {Math.abs(m.change)}%
                      <span className="sr-only">
                        {good === null ? "" : good ? ", better" : ", worse"}
                        {changeLabel ? ` ${changeLabel.trim()}` : ""}
                      </span>
                    </span>
                  ) : null}
                </dd>
              </dl>
            );
          })}
          {fillers.map((cls, i) => (cls ? <div key={`f${i}`} aria-hidden="true" className={`hidden bg-white ${cls}`} /> : null))}
        </div>
        {changeLabel && items.some((m) => m.change !== null) ? <p className="mt-3 text-xs text-neutral-500">Changes {changeLabel.trim()}</p> : null}
        {foot}
      </div>
    );
  },
};
```
