# Add the "Stacked Area Chart" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/stacked-area-chart) to this Pantheon Content Publisher (P1) Next.js project. Two to four series stacked over time, with a legend of each series' latest value and the running total.

## Steps

1. Create `components/puck/stacked-area-chart-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 { stackedAreaChartBlock } from "./components/puck/stacked-area-chart-block";`
3. Register it under `components` as `StackedAreaChartBlock: stackedAreaChartBlock`.
4. Add `"StackedAreaChartBlock"` 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/stacked-area-chart-block.tsx`

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

/**
 * Stacked Area Chart — two to four series stacked over shared x labels, so the outline is the
 * total and each band is one part of it. The legend shows each series' latest value and the
 * total. Every value is a text field, bindable to a P1 data source. Place inside a Dashboard Grid.
 * Register: `StackedAreaChartBlock: stackedAreaChartBlock` in puck.config.tsx.
 */

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

type Series = { name: string; values: string };

export type StackedAreaChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  xLabels: string;
  series: Series[];
  yPrefix: string;
  ySuffix: 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;
}

/** A comma-separated string (or a bound array) → trimmed parts. */
function splitList(raw: unknown): string[] {
  if (Array.isArray(raw)) return raw.map((v) => String(v ?? "").trim());
  if (raw == null || String(raw).trim() === "") return [];
  return String(raw)
    .split(",")
    .map((v) => v.trim());
}

/** Round, human-friendly axis ticks (1, 2, 2.5, 5 × 10ⁿ) covering lo..hi. */
function niceTicks(lo: number, hi: number, count = 4): number[] {
  if (lo === hi) {
    if (lo === 0) hi = 1;
    else if (lo > 0) lo = 0;
    else hi = 0;
  }
  const rough = (hi - lo) / count;
  const pow = Math.pow(10, Math.floor(Math.log10(rough)));
  const f = rough / pow;
  const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * pow;
  const start = Math.floor(lo / step) * step;
  const end = Math.ceil(hi / step) * step;
  const ticks: number[] = [];
  for (let v = start; v <= end + step / 2 && ticks.length < 12; v += step) ticks.push(Number(v.toPrecision(12)));
  return ticks;
}

const compact = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 });
const full = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });

function format(n: number | null, prefix = "", suffix = "", short = false) {
  if (n === null) return "—";
  const unit = suffix && /^[a-z]/i.test(suffix) ? ` ${suffix}` : suffix;
  return `${n < 0 ? "−" : ""}${prefix}${(short ? compact : full).format(Math.abs(n))}${unit}`;
}

// Darkest band sits on the baseline, so the eye reads the biggest, steadiest series first.
const STYLES = [
  { fill: "fill-indigo-600", key: "bg-indigo-600" },
  { fill: "fill-indigo-400", key: "bg-indigo-400" },
  { fill: "fill-indigo-200", key: "bg-indigo-200" },
  { fill: "fill-neutral-400", key: "bg-neutral-400" },
] as const;

const CHART_HEIGHT = "h-44 @md:h-56";

export const stackedAreaChartBlock: ComponentConfig<StackedAreaChartProps> = {
  label: "Stacked Area Chart",
  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. Monthly, Oct 2025–Sep 2026. Leave blank to hide." } },
    xLabels: {
      type: "text",
      label: "X-axis labels",
      metadata: { help: "Comma-separated, oldest first, e.g. Jan, Feb, Mar. Or bind them, e.g. {{ meals.months }}." },
    },
    series: {
      type: "array",
      label: "Series (bottom to top)",
      min: 1,
      max: 4,
      getItemSummary: (item) => item?.name || "Series",
      defaultItemProps: { name: "New series", values: "" },
      arrayFields: {
        name: { type: "text", label: "Name" },
        values: {
          type: "text",
          label: "Values",
          metadata: { help: "Comma-separated, one per x label, e.g. 12, 18, 9. Blanks and negatives count as zero in the stack." },
        },
      },
    },
    yPrefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    ySuffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. % or meals. Leave blank for none." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Meals distributed by program",
    headingLevel: "h3",
    subtitle: "Monthly, Oct 2025–Sep 2026",
    xLabels: "Oct, Nov, Dec, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep",
    series: [
      { name: "Pantry pickups", values: "21400, 23900, 27800, 24100, 22600, 23300, 22900, 23700, 25200, 26800, 27400, 25900" },
      { name: "Mobile market", values: "8200, 8600, 9400, 7100, 6900, 8300, 9600, 11200, 12900, 13800, 13100, 11700" },
      { name: "Home delivery", values: "3100, 3300, 3900, 4200, 4300, 4400, 4500, 4700, 4800, 5000, 5100, 5300" },
    ],
    yPrefix: "",
    ySuffix: "",
    footnote: "Sample data · Source: pantry distribution logs",
  },
  render: ({ title, headingLevel, subtitle, xLabels, series, yPrefix, ySuffix, footnote }) => {
    const H = headingLevel || "h3";
    const labels = splitList(xLabels);
    const rows = (Array.isArray(series) ? series : []).slice(0, 4).map((s, i) => ({
      id: `s${i}`,
      name: s?.name?.trim() || `Series ${i + 1}`,
      values: splitList(s?.values).map((v) => toNumber(v)),
      style: STYLES[i],
    }));
    const n = Math.max(labels.length, ...rows.map((r) => r.values.length), 0);
    const hasData = n > 0 && rows.some((r) => r.values.some((v) => v !== null));

    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 (!hasData) {
      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">
              <path d="M3 3v18h18" strokeLinecap="round" />
              <path d="m6 16 4-4 3 2 6-6M6 19l4-3 3 1 6-4" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">The chart appears once values are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    // Running totals per x: cum[k][i] is the top edge of band k.
    const cum: number[][] = [];
    rows.forEach((r, k) => {
      cum[k] = Array.from({ length: n }, (_, i) => (k ? cum[k - 1][i] : 0) + Math.max(0, r.values[i] ?? 0));
    });
    const totals: (number | null)[] = Array.from({ length: n }, (_, i) =>
      rows.some((r) => (r.values[i] ?? null) !== null) ? cum[rows.length - 1][i] : null,
    );
    const known = totals.filter((v): v is number => v !== null);
    const ticks = niceTicks(0, Math.max(...known, 0), 4);
    const hi = ticks[ticks.length - 1] || 1;
    const y = (v: number) => 100 - (v / hi) * 100;
    // A single point is drawn as a flat band across the full width.
    const xs = n > 1 ? Array.from({ length: n }, (_, i) => (i / (n - 1)) * 100) : [0, 100];
    const at = (j: number) => (n > 1 ? j : 0);
    const axisSuffix = ySuffix && ySuffix.trim().length <= 1 ? ySuffix.trim() : "";

    const edge = (k: number) => xs.map((px, j) => [px, k < 0 ? 100 : y(cum[k][at(j)])] as const);
    const bands = rows.map((r, k) => {
      const top = edge(k);
      const bottom = edge(k - 1).reverse();
      const d = [...top, ...bottom].map(([px, py], j) => `${j ? "L" : "M"}${px.toFixed(2)} ${py.toFixed(2)}`).join(" ") + " Z";
      const line = top.map(([px, py], j) => `${j ? "L" : "M"}${px.toFixed(2)} ${py.toFixed(2)}`).join(" ");
      return { ...r, d, line };
    });

    let lastIndex = -1;
    for (let i = n - 1; i >= 0; i--) if (totals[i] !== null) { lastIndex = i; break; }
    const latestTotal = lastIndex >= 0 ? totals[lastIndex] : null;
    const latestLabel = lastIndex >= 0 ? labels[lastIndex] : "";

    const narrowStep = Math.max(1, Math.ceil(n / 4));
    const wideStep = Math.max(1, Math.ceil(n / 7));

    const summary = `${title ? `${title}. ` : ""}Stacked area chart, ${n} points from ${labels[0] || "the first point"} to ${
      labels[n - 1] || "the latest point"
    }. Latest${latestLabel ? ` (${latestLabel})` : ""}: ${rows
      .map((r) => `${r.name} ${format(lastIndex >= 0 ? (r.values[lastIndex] ?? null) : null, yPrefix, ySuffix)}`)
      .join(", ")}; total ${format(latestTotal, yPrefix, ySuffix)}. Total ranged from ${format(Math.min(...known), yPrefix, ySuffix)} to ${format(
      Math.max(...known),
      yPrefix,
      ySuffix,
    )}.`;

    return (
      <div className={card}>
        {header}

        <dl className="mt-4 grid grid-cols-1 gap-x-6 gap-y-3 @3xs:grid-cols-2 @lg:flex @lg:flex-wrap">
          <div className="min-w-0 @3xs:col-span-2 @lg:order-last @lg:col-span-1 @lg:border-l @lg:border-neutral-200 @lg:pl-6">
            <dt className="text-xs text-neutral-600">Total{latestLabel ? `, ${latestLabel}` : ""}</dt>
            <dd className="mt-1 text-2xl font-semibold tracking-tight text-neutral-950 tabular-nums">{format(latestTotal, yPrefix, ySuffix)}</dd>
          </div>
          {[...rows].reverse().map((r) => (
            <div key={r.id} className="min-w-0">
              <dt className="flex items-center gap-2 text-xs text-neutral-600">
                <span aria-hidden="true" className={`size-2.5 shrink-0 rounded-sm ${r.style.key}`} />
                <span className="truncate">{r.name}</span>
              </dt>
              <dd className="mt-1 text-lg font-semibold tracking-tight text-neutral-950 tabular-nums">
                {format(lastIndex >= 0 ? (r.values[lastIndex] ?? null) : null, yPrefix, ySuffix)}
              </dd>
            </div>
          ))}
        </dl>

        <div role="img" aria-label={summary} className="mt-6 flex gap-3">
          <div className={`relative shrink-0 ${CHART_HEIGHT}`}>
            {ticks.map((t) => (
              <span key={`w${t}`} className="invisible block h-0 overflow-hidden text-xs tabular-nums">
                {format(t, yPrefix, axisSuffix, true)}
              </span>
            ))}
            {ticks.map((t) => (
              <span key={t} className="absolute right-0 -translate-y-1/2 text-xs leading-none text-neutral-500 tabular-nums" style={{ top: `${y(t)}%` }}>
                {format(t, yPrefix, axisSuffix, true)}
              </span>
            ))}
          </div>

          <div className="relative min-w-0 flex-1">
            <div className={`relative ${CHART_HEIGHT}`}>
              <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" className="absolute inset-0 size-full overflow-visible">
                {bands.map((b) => (
                  <path key={b.id} d={b.d} className={b.style.fill} />
                ))}
                {bands.slice(0, -1).map((b) => (
                  <path key={`l${b.id}`} d={b.line} fill="none" className="stroke-white" strokeWidth="1.5" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
                ))}
                <path d={bands[bands.length - 1].line} fill="none" className="stroke-indigo-700" strokeWidth="1.5" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
                {ticks.map((t, i) => (
                  <line
                    key={t}
                    x1="0"
                    x2="100"
                    y1={y(t)}
                    y2={y(t)}
                    className={i === 0 ? "stroke-neutral-300" : "stroke-neutral-950/10"}
                    strokeWidth="1"
                    strokeDasharray={i === 0 ? undefined : "2 3"}
                    vectorEffect="non-scaling-stroke"
                  />
                ))}
                {lastIndex >= 0 && n > 1 ? (
                  <line x1={xs[lastIndex]} x2={xs[lastIndex]} y1="0" y2="100" className="stroke-neutral-950/20" strokeWidth="1" vectorEffect="non-scaling-stroke" />
                ) : null}
              </svg>
            </div>

            <div className="relative mt-2 h-4">
              {Array.from({ length: n }, (_, i) => {
                const fromEnd = n - 1 - i;
                const narrow = fromEnd % narrowStep === 0;
                const wide = fromEnd % wideStep === 0;
                if ((!narrow && !wide) || !labels[i]) return null;
                const visibility = narrow && wide ? "" : narrow ? "@md:hidden" : "hidden @md:block";
                const align = n > 1 && i === n - 1 ? "-translate-x-full" : n > 1 && i === 0 ? "" : "-translate-x-1/2";
                return (
                  <span
                    key={i}
                    className={`absolute top-0 text-xs leading-4 whitespace-nowrap text-neutral-500 ${align} ${visibility}`}
                    style={{ left: `${n > 1 ? xs[i] : 50}%` }}
                  >
                    {labels[i]}
                  </span>
                );
              })}
            </div>
          </div>
        </div>

        <details className="group mt-4">
          <summary className="inline-flex min-h-11 cursor-pointer list-none items-center gap-1.5 rounded-md text-sm font-medium text-indigo-700 hover:text-indigo-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 [&::-webkit-details-marker]:hidden">
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-4 transition-transform group-open:rotate-90 motion-reduce:transition-none">
              <path d="M6.22 4.22a.75.75 0 0 1 1.06 0l3.25 3.25a.75.75 0 0 1 0 1.06l-3.25 3.25a.75.75 0 0 1-1.06-1.06L8.94 8 6.22 5.28a.75.75 0 0 1 0-1.06Z" />
            </svg>
            View data table
          </summary>
          <div className="mt-2 relative overflow-x-auto rounded-lg ring-1 ring-neutral-950/5">
            <table className="w-full text-left text-sm">
              {title ? <caption className="sr-only">{title}</caption> : null}
              <thead className="bg-neutral-50 text-xs text-neutral-600">
                <tr>
                  <th scope="col" className="px-3 py-2 font-medium">
                    Period
                  </th>
                  {rows.map((r) => (
                    <th key={r.id} scope="col" className="px-3 py-2 text-right font-medium">
                      {r.name}
                    </th>
                  ))}
                  <th scope="col" className="px-3 py-2 text-right font-semibold text-neutral-900">
                    Total
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {Array.from({ length: n }, (_, i) => (
                  <tr key={i}>
                    <th scope="row" className="px-3 py-2 font-normal whitespace-nowrap text-neutral-700">
                      {labels[i] || `Point ${i + 1}`}
                    </th>
                    {rows.map((r) => (
                      <td key={r.id} className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">
                        {format(r.values[i] ?? null, yPrefix, ySuffix)}
                      </td>
                    ))}
                    <td className="px-3 py-2 text-right font-semibold whitespace-nowrap text-neutral-950 tabular-nums">{format(totals[i], yPrefix, ySuffix)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

        {foot}
      </div>
    );
  },
};
```
