# Add the "Period Comparison" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/period-comparison) to this Pantheon Content Publisher (P1) Next.js project. This period against the last, metric by metric, with absolute and percent change worked out for you.

## Steps

1. Create `components/puck/period-comparison-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 { periodComparisonBlock } from "./components/puck/period-comparison-block";`
3. Register it under `components` as `PeriodComparisonBlock: periodComparisonBlock`.
4. Add `"PeriodComparisonBlock"` 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/period-comparison-block.tsx`

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

/**
 * Period Comparison — this period against the last, metric by metric, with the absolute and
 * percent change worked out for you. Every value is a text field, so it can be bound to a P1
 * data source. A real table on wide screens; stacks on phones. Place inside a Dashboard Grid.
 * Register: `PeriodComparisonBlock: periodComparisonBlock` in puck.config.tsx.
 */
// spec: status-colors

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

export type PeriodComparisonProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  currentLabel: string;
  previousLabel: string;
  rows: {
    metric: string;
    current: string;
    previous: string;
    goodWhen: "up" | "down";
  }[];
  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;
}

const MINUS = "−";

/** Borrows the unit from how the value was written: "$84,250" → "$", "2.4 days" → " days". */
function units(raw: string) {
  const s = raw.trim();
  const prefix = (s.match(/^[^0-9.\-]*/)?.[0] ?? "").replace(/[+\s]+$/, "");
  const suffix = s.match(/[^0-9.,]*$/)?.[0] ?? "";
  const decimals = s.match(/\.(\d+)/)?.[1].length ?? 0;
  return { prefix, suffix, decimals: Math.min(decimals, 2) };
}

function compare(current: string, previous: string) {
  const cur = toNumber(current);
  const prev = toNumber(previous);
  if (cur === null || prev === null) return null;
  const diff = cur - prev;
  const { prefix, suffix, decimals } = units(current || previous);
  const isPercent = suffix.trim() === "%";
  const abs = Math.abs(diff).toLocaleString("en-US", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  const sign = diff > 0 ? "+" : diff < 0 ? MINUS : "";
  // A rate already in percent changes by percentage points, not percent.
  const absolute = `${sign}${prefix}${abs}${isPercent ? " pts" : suffix}`;
  const pct = prev === 0 ? null : (diff / Math.abs(prev)) * 100;
  const pctText = pct === null ? null : `${pct > 0 ? "+" : pct < 0 ? MINUS : ""}${Math.abs(pct).toFixed(1)}%`;
  return { diff, absolute, pctText };
}

const Arrow = ({ dir }: { dir: "up" | "down" | "flat" }) =>
  dir === "flat" ? (
    <svg aria-hidden="true" viewBox="0 0 12 12" fill="currentColor" className="size-3">
      <rect x="2" y="5.25" width="8" height="1.5" rx=".75" />
    </svg>
  ) : (
    <svg aria-hidden="true" viewBox="0 0 12 12" fill="currentColor" className={`size-3 ${dir === "down" ? "rotate-180" : ""}`}>
      <path d="M6 2.5 10 8H2l4-5.5Z" />
    </svg>
  );

export const periodComparisonBlock: ComponentConfig<PeriodComparisonProps> = {
  label: "Period Comparison",
  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", metadata: { help: "Leave blank to hide." } },
    currentLabel: { type: "text", label: "This period", metadata: { help: "Column heading, e.g. Sep 2026 or {{ report.period }}." } },
    previousLabel: { type: "text", label: "Comparison period", metadata: { help: "Column heading, e.g. Sep 2025." } },
    rows: {
      type: "array",
      label: "Metrics",
      min: 1,
      max: 12,
      getItemSummary: (item) => item?.metric || "Metric",
      defaultItemProps: { metric: "New metric", current: "", previous: "", goodWhen: "up" },
      arrayFields: {
        metric: { type: "text", label: "Metric" },
        current: {
          type: "text",
          label: "This period",
          metadata: { help: "Shown as written, e.g. $84,250, 41.2% or 2.4 days. Bind it: {{ report.donations }}." },
        },
        previous: { type: "text", label: "Comparison period", metadata: { help: "Same units as this period." } },
        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." },
        },
      },
    },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the numbers come from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "September, year over year",
    headingLevel: "h3",
    subtitle: "Giving and program results",
    currentLabel: "Sep 2026",
    previousLabel: "Sep 2025",
    rows: [
      { metric: "Online donations", current: "$84,250", previous: "$71,900", goodWhen: "up" },
      { metric: "New donors", current: "312", previous: "268", goodWhen: "up" },
      { metric: "Volunteer hours", current: "1,940", previous: "2,105", goodWhen: "up" },
      { metric: "Email open rate", current: "41.2%", previous: "38.5%", goodWhen: "up" },
      { metric: "Avg. days to answer a request", current: "2.4 days", previous: "3.1 days", goodWhen: "down" },
    ],
    footnote: "Sample data · Source: donation platform and volunteer log",
  },
  render: ({ title, headingLevel, subtitle, currentLabel, previousLabel, rows, footnote }) => {
    const H = headingLevel || "h3";
    const list = (rows ?? []).filter((r) => r?.metric);
    const cur = currentLabel || "This period";
    const prev = previousLabel || "Previous";

    return (
      <div className="@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">
        {title || subtitle ? (
          <div>
            {title ? <H className="text-base font-semibold text-neutral-950">{title}</H> : null}
            {subtitle ? <p className="mt-1 text-sm text-neutral-600">{subtitle}</p> : null}
          </div>
        ) : null}

        {list.length ? (
          <table className={`w-full text-left text-sm ${title || subtitle ? "mt-4" : ""}`}>
            <caption className="sr-only">
              {title ? `${title}: ` : ""}
              {cur} compared with {prev}
            </caption>
            <thead className="border-b border-neutral-200 text-xs font-medium text-neutral-500">
              <tr>
                <th scope="col" className="py-2 pr-3 font-medium">
                  Metric
                </th>
                <th scope="col" className="hidden py-2 pr-3 text-right font-medium @sm:table-cell">
                  {cur}
                </th>
                <th scope="col" className="hidden py-2 pr-3 text-right font-medium @sm:table-cell">
                  {prev}
                </th>
                <th scope="col" className="py-2 text-right font-medium">
                  Change
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100">
              {list.map((row, i) => {
                const c = compare(row.current ?? "", row.previous ?? "");
                const dir = !c || c.diff === 0 ? "flat" : c.diff > 0 ? "up" : "down";
                const good = !c || c.diff === 0 ? null : (c.diff > 0) === (row.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 shownCur = row.current?.trim() || "—";
                const shownPrev = row.previous?.trim() || "—";
                return (
                  <tr key={`${row.metric}-${i}`} className="align-top">
                    <th scope="row" className="py-3 pr-3 font-medium text-neutral-900">
                      <span className="block text-pretty">{row.metric}</span>
                      <span className="mt-1 block text-xs font-normal text-neutral-500 tabular-nums @sm:hidden">
                        <span className="font-medium text-neutral-900">{shownCur}</span>
                        <span className="sr-only"> in {cur}</span>
                        <span aria-hidden="true"> vs. </span>
                        <span className="sr-only">, compared with </span>
                        {shownPrev}
                        <span className="sr-only"> in {prev}</span>
                      </span>
                    </th>
                    <td className="hidden py-3 pr-3 text-right font-semibold whitespace-nowrap text-neutral-950 tabular-nums @sm:table-cell">{shownCur}</td>
                    <td className="hidden py-3 pr-3 text-right whitespace-nowrap text-neutral-600 tabular-nums @sm:table-cell">{shownPrev}</td>
                    <td className="py-3 text-right whitespace-nowrap">
                      {c ? (
                        <span className="inline-flex flex-col items-end gap-1">
                          <span className={`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-semibold tabular-nums ${tone}`}>
                            <Arrow dir={dir} />
                            <span className="sr-only">{dir === "flat" ? "No change" : dir === "up" ? "Up" : "Down"} </span>
                            {c.pctText ?? c.absolute}
                            {good !== null ? <span className="sr-only">{good ? " (better)" : " (worse)"}</span> : null}
                          </span>
                          {c.pctText && c.diff !== 0 ? <span className="text-xs text-neutral-500 tabular-nums">{c.absolute}</span> : null}
                        </span>
                      ) : (
                        <span className="text-neutral-400">
                          <span aria-hidden="true">—</span>
                          <span className="sr-only">Not available</span>
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        ) : (
          <p className="mt-4 text-sm text-neutral-500">No metrics to compare yet.</p>
        )}

        {footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null}
      </div>
    );
  },
};
```
