# Add the "Sunburst Celebration" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/sunburst-celebration) to this Pantheon Content Publisher (P1) Next.js project. Goal-reached section whose sunburst turns and confetti falls only once the raised amount meets the goal.

## 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/sunburst-celebration-block.tsx`, `components/puck/sunburst-celebration.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 { sunburstCelebrationBlock } from "./components/puck/sunburst-celebration-block";`
4. Register it under `components` as `SunburstCelebrationBlock: sunburstCelebrationBlock`.
5. Add `"SunburstCelebrationBlock"` 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/sunburst-celebration-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { SunburstCanvas } from "./sunburst-celebration.client";

/**
 * Sunburst Celebration — a "goal reached" moment for campaigns and challenges. Raised and goal are
 * text fields (bindable to P1 data sources); once raised meets the goal, sunburst rays turn and
 * confetti falls (vgpu / WebGPU). Before that, the rays rest and the copy switches to an
 * in-progress heading. Figures are always server-rendered text; non-WebGPU browsers get CSS rays.
 * Needs `pnpm add vgpu` and sunburst-celebration.client.tsx. Register: `SunburstCelebrationBlock: sunburstCelebrationBlock`.
 */

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

export type SunburstCelebrationProps = {
  reachedLabel: string;
  heading: string;
  progressLabel: string;
  progressHeading: string;
  headingLevel: Heading;
  body: string;
  raised: string;
  goal: string;
  currency: string;
  supporters: string;
  ctaLabel: string;
  ctaHref: string;
  backgroundColor: string;
  rayColor: string;
  confettiColor1: string;
  confettiColor2: string;
  rays: "10" | "14" | "20";
  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;
};

const colorHelp = "A hex color such as #e0e7ff.";
const dataHelp = "A number. Commas and symbols are ignored, so you can bind a data source with {{ }}.";

export const sunburstCelebrationBlock: ComponentConfig<SunburstCelebrationProps> = {
  label: "Sunburst Celebration",
  fields: {
    raised: { type: "text", label: "Amount raised", metadata: { help: `${dataHelp} The celebration starts when this meets the goal.` } },
    goal: { type: "text", label: "Goal", metadata: { help: dataHelp } },
    currency: { type: "text", label: "Currency symbol", metadata: { help: "Shown before each amount, like $ or €. Leave blank for counts." } },
    supporters: { type: "text", label: "Supporters", metadata: { help: "Free text, like 1,204 donors. Leave blank to hide it." } },
    reachedLabel: { type: "text", label: "Badge (goal met)", metadata: { help: "Small badge above the heading once the goal is met." } },
    heading: { type: "textarea", label: "Heading (goal met)" },
    progressLabel: { type: "text", label: "Badge (in progress)", metadata: { help: "Shown before the goal is met." } },
    progressHeading: { type: "textarea", label: "Heading (in progress)", metadata: { help: "Shown before the goal is met." } },
    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" },
    ctaLabel: { type: "text", label: "Button text", metadata: { help: "Leave blank to hide it." } },
    ctaHref: { type: "text", label: "Button link" },
    backgroundColor: { type: "text", label: "Background color", metadata: { help: `${colorHelp} Keep it light: the text is dark.` } },
    rayColor: { type: "text", label: "Ray color", metadata: { help: `${colorHelp} Keep it close to the background so the text stays easy to read.` } },
    confettiColor1: { type: "text", label: "Confetti color 1", metadata: { help: colorHelp } },
    confettiColor2: { type: "text", label: "Confetti color 2", metadata: { help: colorHelp } },
    rays: {
      type: "radio",
      label: "Rays",
      options: [
        { label: "Broad", value: "10" },
        { label: "Classic", value: "14" },
        { label: "Fine", value: "20" },
      ],
    },
    speed: {
      type: "radio",
      label: "Motion",
      options: [
        { label: "Slow", value: "0.5" },
        { label: "Gentle", value: "1" },
        { label: "Lively", value: "1.6" },
      ],
      metadata: { help: "Motion runs only once the goal is met. Visitors who ask for reduced motion always see a still frame." },
    },
  },
  defaultProps: {
    raised: "82410",
    goal: "75000",
    currency: "$",
    supporters: "1,204 neighbors gave",
    reachedLabel: "Goal reached",
    heading: "We filled the shelves for the whole school year",
    progressLabel: "Campaign in progress",
    progressHeading: "Help us fill the shelves for the school year",
    headingLevel: "h2",
    body: "Every dollar over the goal goes to the summer meal program, which feeds about 300 kids a week when school cafeterias close.",
    ctaLabel: "Keep the momentum going",
    ctaHref: "/donate",
    backgroundColor: "#eef2ff",
    rayColor: "#c7d2fe",
    confettiColor1: "#6366f1",
    confettiColor2: "#fbbf24",
    rays: "14",
    speed: "1",
  },
  render: ({ id, reachedLabel, heading, progressLabel, progressHeading, headingLevel, body, raised, goal, currency, supporters, ctaLabel, ctaHref, backgroundColor, rayColor, confettiColor1, confettiColor2, rays, speed }) => {
    const H = headingLevel || "h2";
    const base = hex(backgroundColor, "#eef2ff");
    const ray = hex(rayColor, "#c7d2fe");
    const confetti1 = hex(confettiColor1, "#6366f1");
    const confetti2 = hex(confettiColor2, "#fbbf24");
    const rayCount = Number(rays) || 14;
    const sym = (currency ?? "").trim();
    const raisedN = toNumber(raised);
    const goalN = toNumber(goal);
    const reached = raisedN !== null && goalN !== null && goalN > 0 && raisedN >= goalN;
    const pct = raisedN !== null && goalN !== null && goalN > 0 ? `${Math.round((Math.max(raisedN, 0) / goalN) * 100)}%` : "—";
    const money = (n: number | null) => (n === null ? "—" : `${sym}${Math.round(n).toLocaleString("en-US")}`);
    const badge = reached ? reachedLabel : progressLabel;
    const title = reached ? heading : progressHeading;
    const headingId = `${id}-sunburst-heading`;
    // CSS rays: the look wherever WebGPU isn't available.
    const wedge = 360 / rayCount / 2;
    const fallback = {
      backgroundColor: base,
      backgroundImage: `radial-gradient(circle at 50% 42%, #ffffffcc, transparent 35%), repeating-conic-gradient(from 0deg at 50% 42%, ${ray} 0deg ${wedge}deg, ${base} ${wedge}deg ${wedge * 2}deg)`,
    };

    return (
      <section aria-labelledby={title ? headingId : undefined} className="relative isolate overflow-hidden px-4 py-20 sm:px-6 sm:py-24 lg:px-8 lg:py-32" style={fallback}>
        <SunburstCanvas colors={{ base, ray, confetti1, confetti2 }} celebrate={reached} rays={rayCount} speed={Number(speed) || 1} />

        <div className="relative mx-auto max-w-3xl text-center">
          {badge ? (
            <p className="inline-flex items-center gap-2 rounded-full bg-white px-4 py-1.5 text-sm font-semibold text-indigo-800 shadow-sm ring-1 ring-indigo-900/10">
              {reached ? (
                <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4">
                  <path fillRule="evenodd" d="M16.7 5.3a1 1 0 0 1 0 1.4l-8 8a1 1 0 0 1-1.4 0l-4-4a1 1 0 1 1 1.4-1.4L8 12.58l7.3-7.3a1 1 0 0 1 1.4 0Z" clipRule="evenodd" />
                </svg>
              ) : (
                <span aria-hidden="true" className="size-1.5 rounded-full bg-indigo-600" />
              )}
              {badge}
            </p>
          ) : null}
          {title ? (
            <H id={headingId} className="mt-6 text-3xl font-semibold tracking-tight text-balance text-neutral-900 sm:text-5xl">
              {title}
            </H>
          ) : null}

          <p className="mt-10 tabular-nums">
            <span className="block text-6xl font-semibold tracking-tight text-indigo-950 sm:text-8xl">{money(raisedN)}</span>
            <span className="mt-3 block text-lg text-neutral-700">
              raised of <span className="font-semibold text-neutral-900">{money(goalN)}</span> goal · <span className="font-semibold text-neutral-900">{pct}</span>
              {supporters ? <span className="block sm:inline sm:before:mx-2 sm:before:content-['·']">{supporters}</span> : null}
            </span>
          </p>

          {body ? <p className="mx-auto mt-8 max-w-2xl text-lg leading-8 text-pretty text-neutral-700">{body}</p> : null}
          {ctaLabel ? (
            <a
              href={ctaHref || "#"}
              className="mt-10 inline-flex min-h-11 items-center justify-center rounded-lg bg-indigo-600 px-5 py-3 text-base font-semibold text-white shadow-sm transition hover:bg-indigo-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
            >
              {ctaLabel}
            </a>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/sunburst-celebration.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 Sunburst Celebration: tone-on-tone rays that slowly turn, with confetti specks
 * tumbling down, once a goal is met (vgpu / WebGPU). Before the goal the rays sit still and no
 * frame loop runs. Decorative only; the figures are server-rendered text and the CSS
 * conic-gradient rays underneath are the fallback.
 */

const SUNBURST_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  celebrate: f32,
  rays: f32,
  center: vec2f,
  base: vec3f,
  ray: vec3f,
  confetti1: vec3f,
  confetti2: vec3f,
}
@group(0) @binding(0) var<uniform> params: Params;

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

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

// One confetti speck per cell: a small rectangle that tumbles (its width flips) as it falls.
fn confetti(p0: vec2f, scale: f32, t: f32, seed: f32) -> vec4f {
  let p = p0 * scale;
  let g = floor(p);
  var out = vec4f(0.0);
  for (var j = -1; j <= 1; j++) {
    for (var i = -1; i <= 1; i++) {
      let id = g + vec2f(f32(i), f32(j));
      let h = hash2(id + seed);
      if (hash(id + seed * 3.1) > 0.42) { continue; }
      let pos = id + 0.5 + 0.3 * vec2f(sin(t * 0.9 + h.x * 6.2832), h.y - 0.5);
      let a = t * (1.2 + 2.0 * h.y) + h.x * 6.2832;
      let flip = abs(cos(t * (1.5 + 2.5 * h.x) + h.y * 9.0));
      let d = p - pos;
      let r = vec2f(cos(a) * d.x - sin(a) * d.y, sin(a) * d.x + cos(a) * d.y);
      let size = vec2f(0.09 * (0.35 + 0.65 * flip), 0.045);
      let box = max(abs(r.x) - size.x, abs(r.y) - size.y);
      let m = smoothstep(0.02, -0.01, box);
      if (m > out.a) {
        var c = params.confetti1;
        if (h.y > 0.5) { c = params.confetti2; }
        // Lighter as the speck turns edge-on, so it reads as tumbling paper.
        out = vec4f(mix(c, vec3f(1.0), (1.0 - flip) * 0.35), m);
      }
    }
  }
  return out;
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let p = vec2f(uv.x * params.aspect, uv.y);
  let c = vec2f(params.center.x * params.aspect, params.center.y);
  let d = p - c;
  let r = length(d);
  let ang = atan2(d.y, d.x);

  // Rays: soft-edged wedges that turn slowly while celebrating, still otherwise.
  let spin = t * 0.05 * params.celebrate;
  let s = sin((ang + spin) * params.rays);
  let wedge = smoothstep(-0.12, 0.12, s);
  let reach = smoothstep(0.02, 0.2, r) * (1.0 - 0.45 * smoothstep(0.3, 1.4, r));
  var col = mix(params.base, params.ray, wedge * reach * (0.85 + 0.15 * params.celebrate));

  // A warm bloom at the center, a touch brighter when the goal is met.
  let bloom = exp(-r * r * 5.0) * (0.35 + 0.25 * params.celebrate);
  col = mix(col, vec3f(1.0), bloom);

  if (params.celebrate > 0.0) {
    // Two depths of confetti, faded over the centered text column so the figures stay legible.
    let clear = max(smoothstep(0.32, 0.7, abs(d.x)), 0.3) * smoothstep(0.12, 0.4, r);
    let fall1 = vec2f(p.x + 0.04 * sin(t * 0.4), p.y - t * 0.05);
    let fall2 = vec2f(p.x + 0.07 * sin(t * 0.3 + 2.0), p.y - t * 0.085);
    let far = confetti(fall1, 9.0, t, 1.0);
    col = mix(col, mix(far.rgb, params.base, 0.45), far.a * 0.8 * clear * params.celebrate);
    let near = confetti(fall2, 5.5, t, 7.0);
    col = mix(col, near.rgb, near.a * clear * params.celebrate);
  }

  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;
}

type Colors = { base: string; ray: string; confetti1: string; confetti2: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type SunburstCanvasProps = { colors: Colors; celebrate: boolean; rays: number; speed: number };

export function SunburstCanvas({ colors, celebrate, rays, speed }: SunburstCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const syncRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, celebrate, rays, speed });
  live.current = { colors, celebrate, rays, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (v: typeof live.current) => ({
    celebrate: v.celebrate ? 1 : 0,
    rays: v.rays,
    base: hexToVec3(v.colors.base, [0.93, 0.95, 1]),
    ray: hexToVec3(v.colors.ray, [0.78, 0.82, 1]),
    confetti1: hexToVec3(v.colors.confetti1, [0.39, 0.4, 0.95]),
    confetti2: hexToVec3(v.colors.confetti2, [0.98, 0.75, 0.14]),
  });

  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;
    let removeVisibility: (() => void) | 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, SUNBURST_WGSL, {
          label: "sunburst-celebration",
          set: { params: { time: 2, aspect: aspect(), center: [0.5, 0.42], ...uniforms(live.current) } },
        });
        fxRef.current = fx;
        const time = clock(gpu);

        // Animate only while celebrating; otherwise (or with reduced motion) draw one still frame.
        const animate = () => live.current.celebrate && !still;
        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (frame) => {
              fx.set({ params: { time: 2 + time.time * live.current.speed } });
              frame.pass(target, fx);
              if (!animate()) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };
        target.onResize(() => {
          fx.set({ params: { aspect: aspect() } });
          if (!animate()) start();
        });

        let onScreen = false;
        const sync = () => {
          if (onScreen && !document.hidden) start();
          else if (animate()) stop();
        };
        syncRef.current = () => {
          stop();
          sync();
        };
        observer = new IntersectionObserver(([entry]) => {
          onScreen = Boolean(entry?.isIntersecting);
          sync();
        });
        observer.observe(canvas);
        document.addEventListener("visibilitychange", sync);
        removeVisibility = () => document.removeEventListener("visibilitychange", sync);
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fallback is the look.
      }
    })();

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

  // Live-update colors, ray count and the goal state from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: uniforms({ colors, celebrate, rays, speed }) });
    syncRef.current?.();
  }, [colors.base, colors.ray, colors.confetti1, colors.confetti2, celebrate, rays]); // 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"}`}
    />
  );
}
```
