# Add the "Metaball Stats" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/metaball-stats) to this Pantheon Content Publisher (P1) Next.js project. Up to five impact figures as soft merging GPU blobs sized by value, mirrored as a semantic list.

## Steps

1. Install the dependency: `pnpm add vgpu` (use the project's package manager if it isn't pnpm).
2. Create these files with the exact contents below, in the same folder: `components/puck/metaball-stats-block.tsx`, `components/puck/metaball-stats.client.tsx`. If `components/puck/` doesn't exist, use the folder where this project keeps its Puck components (look at the imports in `puck.config.tsx`).
3. In `puck.config.tsx`, import it: `import { metaballStatsBlock } from "./components/puck/metaball-stats-block";`
4. Register it under `components` as `MetaballStatsBlock: metaballStatsBlock`.
5. Add `"MetaballStatsBlock"` to the best-fitting entry in `categories` (this block's library category is "GPU effects"). Create a category only if none fits.
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

- The block is two files: a server-safe Puck config and a `"use client"` island it imports by relative path. Keep both files in the same folder and keep the island's file name unchanged.
- WebGPU effects are progressive enhancement: content is server-rendered and a CSS fallback shows wherever WebGPU is unavailable. Don't move content into the client file.
- 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-`.
- Images are plain `imageUrl` + `imageAlt` text fields. If this project defines a P1 media-library field (search for `"p1-media"`), offer to switch to it.
- Don't change prop names in `defaultProps`. Content editors' saved pages depend on them.

## File: `components/puck/metaball-stats-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { MetaballCanvas } from "./metaball-stats.client";

/**
 * Metaball Stats — up to five impact figures drawn as soft, merging GPU blobs (vgpu / WebGPU)
 * whose size follows each value. Figures are text fields (bindable to P1 data sources) and are
 * always a server-rendered <dl>; CSS circles stand in without WebGPU.
 * Needs `pnpm add vgpu` and metaball-stats.client.tsx. Register: `MetaballStatsBlock: metaballStatsBlock`.
 */

type Heading = "h1" | "h2" | "h3" | "h4";
type Stat = { value: string; label: string };

export type MetaballStatsProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  stats: Stat[];
  footnote: string;
  blobColor: string;
  backgroundColor: string;
  speed: "0.5" | "1" | "1.6";
};

const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
const hex = (value: string | undefined, fallback: string) => (HEX.test((value ?? "").trim()) ? `#${value!.trim().replace(/^#/, "")}` : fallback);

const toNumber = (value: string | undefined) => {
  const cleaned = String(value ?? "").replace(/[^0-9.-]/g, "");
  if (!cleaned) return null;
  const n = Number.parseFloat(cleaned);
  return Number.isFinite(n) ? n : null;
};

/** Slot layout in canvas fractions: x of width, y and r of height. Radius is sqrt-scaled so area tracks value. */
const layout = (values: (number | null)[]) => {
  const n = values.length;
  const max = Math.max(0, ...values.map((v) => (v === null ? 0 : Math.abs(v))));
  return values.map((v, i) => ({
    x: n === 1 ? 0.5 : 0.08 + (0.84 * (i + 0.5)) / n,
    y: n === 1 ? 0.5 : i % 2 === 0 ? 0.36 : 0.64,
    r: 0.15 + 0.08 * (max > 0 && v !== null ? Math.sqrt(Math.abs(v) / max) : 0),
  }));
};

const colorHelp = "A hex color such as #3730a3.";

export const metaballStatsBlock: ComponentConfig<MetaballStatsProps> = {
  label: "Metaball Stats",
  fields: {
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the heading. Leave blank to hide it." } },
    heading: { type: "textarea", label: "Heading" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H1", value: "h1" },
        { label: "H2", value: "h2" },
        { label: "H3", value: "h3" },
        { label: "H4", value: "h4" },
      ],
      metadata: { help: "Sets the page outline for screen readers and search. The look doesn't change." },
    },
    body: { type: "textarea", label: "Body" },
    stats: {
      type: "array",
      label: "Stats",
      min: 1,
      max: 5,
      getItemSummary: (item) => [item?.value, item?.label].filter(Boolean).join(" ") || "Stat",
      defaultItemProps: { value: "1,000", label: "people reached" },
      arrayFields: {
        value: {
          type: "text",
          label: "Value",
          metadata: { help: "Shown exactly as typed, like 48,200 or 96%. The number inside sets the blob size. Bind a data source with {{ }}." },
        },
        label: { type: "text", label: "Label" },
      },
    },
    footnote: { type: "text", label: "Source note", metadata: { help: "Where the figures come from, like FY2025 annual report. Leave blank to hide it." } },
    blobColor: { type: "text", label: "Blob color", metadata: { help: `${colorHelp} Keep it dark: on large screens the figures sit on it in white.` } },
    backgroundColor: { type: "text", label: "Background color", metadata: { help: `${colorHelp} Keep it light.` } },
    speed: {
      type: "radio",
      label: "Motion",
      options: [
        { label: "Drifting", value: "0.5" },
        { label: "Gentle", value: "1" },
        { label: "Lively", value: "1.6" },
      ],
      metadata: { help: "Visitors who ask their device for reduced motion always see a still frame." },
    },
  },
  defaultProps: {
    eyebrow: "2025 Impact",
    heading: "One year of showing up for our neighbors",
    headingLevel: "h2",
    body: "Every number here is a person, a family or a partner who chose to work alongside us. The bigger the circle, the bigger the figure.",
    stats: [
      { value: "48,200", label: "meals served" },
      { value: "12,400", label: "volunteer hours" },
      { value: "1,840", label: "families housed" },
      { value: "312", label: "partner agencies" },
      { value: "96%", label: "still housed after a year" },
    ],
    footnote: "Sample figures. Source: FY2025 annual report.",
    blobColor: "#3730a3",
    backgroundColor: "#eef2ff",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, stats, footnote, blobColor, backgroundColor, speed }) => {
    const H = headingLevel || "h2";
    const blob = hex(blobColor, "#3730a3");
    const bg = hex(backgroundColor, "#eef2ff");
    const items = (stats ?? []).filter((s) => s?.value || s?.label).slice(0, 5);
    const slots = layout(items.map((s) => toNumber(s.value)));

    return (
      <section className="bg-white px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto max-w-7xl">
          {eyebrow || heading || body ? (
            <header className="max-w-2xl">
              {eyebrow ? <p className="text-sm font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
              {heading ? <H className="mt-4 text-3xl font-semibold tracking-tight text-balance text-neutral-900 sm:text-5xl">{heading}</H> : null}
              {body ? <p className="mt-5 text-lg leading-8 text-pretty text-neutral-600">{body}</p> : null}
            </header>
          ) : null}

          {items.length ? (
            <div className="relative mt-12">
              <div aria-hidden="true" className="relative isolate h-56 overflow-hidden rounded-3xl sm:h-72 lg:aspect-[2/1] lg:h-auto" style={{ backgroundColor: bg }}>
                {slots.map((s, i) => (
                  <span
                    key={i}
                    className="absolute aspect-square -translate-x-1/2 -translate-y-1/2 rounded-full"
                    style={{ left: `${s.x * 100}%`, top: `${s.y * 100}%`, height: `${s.r * 200}%`, backgroundColor: blob }}
                  />
                ))}
                <MetaballCanvas slots={slots} blob={blob} background={bg} speed={Number(speed) || 1} />
              </div>

              <dl className="mt-8 grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 lg:pointer-events-none lg:absolute lg:inset-0 lg:mt-0 lg:block">
                {items.map((s, i) => (
                  <div
                    key={i}
                    className="flex flex-col-reverse lg:absolute lg:w-36 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:items-center lg:text-center xl:w-44"
                    style={{ left: `${slots[i].x * 100}%`, top: `${slots[i].y * 100}%` }}
                  >
                    <dt className="mt-1 text-sm leading-5 text-neutral-600 lg:text-white/85">{s.label}</dt>
                    <dd className="text-3xl font-semibold tracking-tight text-neutral-900 tabular-nums lg:text-white xl:text-4xl">{s.value || "—"}</dd>
                  </div>
                ))}
              </dl>
            </div>
          ) : null}

          {footnote ? <p className="mt-6 text-sm text-neutral-500">{footnote}</p> : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/metaball-stats.client.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { clock, effect, frameLoop, init, surface } from "vgpu";
import type { FrameLoopHandle } from "vgpu";

/**
 * GPU half of Metaball Stats: one soft blob per stat, sized by its value, drifting around a
 * fixed slot and merging with its neighbours (smooth-min SDF), drawn with vgpu (WebGPU).
 * Decorative: the figures are a server-rendered <dl>, and CSS circles are the fallback.
 */

const METABALL_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  blob: vec3f,
  background: vec3f,
  b0: vec4f,
  b1: vec4f,
  b2: vec4f,
  b3: vec4f,
  b4: vec4f,
}
@group(0) @binding(0) var<uniform> params: Params;

fn smin(a: f32, b: f32, k: f32) -> f32 {
  let h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
  return mix(b, a, h) - k * h * (1.0 - h);
}

fn ball(p: vec2f, b: vec4f, i: f32) -> f32 {
  if (b.w <= 0.0) { return 10.0; }
  let t = params.time;
  // A slow orbit around the slot, small enough that the labels stay on their blob.
  let orbit = vec2f(sin(t * 0.31 + i * 1.7), cos(t * 0.27 + i * 2.3)) * 0.018;
  let c = vec2f(b.x * params.aspect, b.y) + orbit;
  let breathe = 1.0 + 0.025 * sin(t * 0.5 + i * 1.1);
  return length(p - c) - b.z * breathe;
}

fn field(p: vec2f) -> f32 {
  let k = 0.12;
  var d = ball(p, params.b0, 0.0);
  d = smin(d, ball(p, params.b1, 1.0), k);
  d = smin(d, ball(p, params.b2, 2.0), k);
  d = smin(d, ball(p, params.b3, 3.0), k);
  d = smin(d, ball(p, params.b4, 4.0), k);
  return d;
}

fn hash(p: vec2f) -> f32 {
  return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let p = vec2f(uv.x * params.aspect, uv.y);
  let d = field(p);
  let e = 0.002;
  let grad = vec2f(field(p + vec2f(e, 0.0)) - d, field(p + vec2f(0.0, e)) - d) / e;

  // Background, with a soft tinted halo and a contact shadow below each blob.
  var col = params.background;
  let shadow = field(p - vec2f(0.0, 0.025));
  col = mix(col, params.blob, exp(-max(d, 0.0) * 14.0) * 0.10);
  col = mix(col, params.background * 0.86, smoothstep(0.05, -0.02, shadow) * smoothstep(-0.03, 0.02, d) * 0.5);

  // Blob surface: a pillowy normal from the distance gradient, lit from the top left.
  let bulge = smoothstep(0.0, -0.11, d);
  let n = normalize(vec3f(grad * (1.0 - bulge), 0.55 + bulge));
  let light = normalize(vec3f(-0.45, -0.6, 0.75));
  let diffuse = dot(n, light);
  var body = params.blob * (0.86 + 0.2 * diffuse);
  let spec = pow(max(dot(reflect(-light, n), vec3f(0.0, 0.0, 1.0)), 0.0), 24.0);
  body = mix(body, vec3f(1.0), spec * 0.22 * (1.0 - bulge * 0.7));
  // Rim: a thin lighter edge so merged necks read as one liquid skin.
  body = mix(body, vec3f(1.0), smoothstep(-0.012, 0.0, d) * 0.12);

  let aa = 1.5 / 640.0;
  col = mix(col, body, smoothstep(aa, -aa, d));
  col += (hash(uv * vec2f(1931.0, 1093.0)) - 0.5) * 0.015;
  return vec4f(col, 1.0);
}
`;

type Vec3 = [number, number, number];

function hexToVec3(hex: string | undefined, fallback: Vec3): Vec3 {
  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((hex ?? "").trim());
  if (!m) return fallback;
  const h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1];
  return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255) as Vec3;
}

export type MetaballSlot = { x: number; y: number; r: number };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type MetaballCanvasProps = { slots: MetaballSlot[]; blob: string; background: string; speed: number };

const slotUniforms = (slots: MetaballSlot[]) =>
  Object.fromEntries(
    [0, 1, 2, 3, 4].map((i) => {
      const s = slots[i];
      return [`b${i}`, s ? [s.x, s.y, s.r, 1] : [0, 0, 0, 0]];
    }),
  );

export function MetaballCanvas({ slots, blob, background, speed }: MetaballCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const live = useRef({ slots, blob, background, speed });
  live.current = { slots, blob, background, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (v: typeof live.current) => ({
    blob: hexToVec3(v.blob, [0.22, 0.19, 0.64]),
    background: hexToVec3(v.background, [0.93, 0.95, 1]),
    ...slotUniforms(v.slots),
  });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !("gpu" in navigator)) return;
    let disposed = false;
    let loop: FrameLoopHandle | undefined;
    let gpu: Awaited<ReturnType<typeof init>> | undefined;
    let observer: IntersectionObserver | undefined;
    const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    void (async () => {
      try {
        gpu = await init();
        if (disposed) return gpu.dispose();
        const target = surface(gpu, canvas, { dpr: [1, 2] });
        const aspect = () => (target.size[1] ? target.size[0] / target.size[1] : 1);
        const fx = effect(gpu, METABALL_WGSL, {
          label: "metaball-stats",
          set: { params: { time: 0, aspect: aspect(), ...uniforms(live.current) } },
        });
        fxRef.current = fx;
        target.onResize(() => fx.set({ params: { aspect: aspect() } }));
        const time = clock(gpu);

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (frame) => {
              fx.set({ params: { time: time.time * live.current.speed } });
              frame.pass(target, fx);
              if (still) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        observer = new IntersectionObserver(([entry]) => (entry?.isIntersecting ? start() : still ? undefined : stop()));
        observer.observe(canvas);
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS circles are the look.
      }
    })();

    return () => {
      disposed = true;
      observer?.disconnect();
      loop?.stop();
      fxRef.current = null;
      gpu?.dispose();
    };
  }, []);

  const slotKey = slots.map((s) => `${s.x},${s.y},${s.r}`).join("|");
  useEffect(() => {
    fxRef.current?.set({ params: uniforms({ slots, blob, background, speed }) });
  }, [slotKey, blob, background]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      className={`absolute inset-0 size-full transition-opacity duration-1000 ${ready ? "opacity-100" : "opacity-0"}`}
    />
  );
}
```
