# Add the "Fireflies Banner" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/fireflies-banner) to this Pantheon Content Publisher (P1) Next.js project. Evening-event banner with a dusk sky, tree line and blinking fireflies, plus event details and a call to action.

## 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/fireflies-banner-block.tsx`, `components/puck/fireflies-banner.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 { firefliesBannerBlock } from "./components/puck/fireflies-banner-block";`
4. Register it under `components` as `FirefliesBannerBlock: firefliesBannerBlock`.
5. Add `"FirefliesBannerBlock"` 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/fireflies-banner-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { FirefliesCanvas } from "./fireflies-banner.client";

/**
 * Fireflies Banner — an evening-event banner (parks after dark, night hikes, outdoor concerts):
 * a dusk sky and tree line with softly blinking, drifting fireflies (vgpu / WebGPU), plus event
 * details and a call to action. Content is server-rendered; non-WebGPU browsers get a CSS dusk
 * gradient and SVG tree line. Needs `pnpm add vgpu` and fireflies-banner.client.tsx.
 * Register: `FirefliesBannerBlock: firefliesBannerBlock` in puck.config.tsx.
 */

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

type Detail = { label: string; value: string };

export type FirefliesBannerProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  details: Detail[];
  primaryLabel: string;
  primaryHref: string;
  secondaryLabel: string;
  secondaryHref: string;
  skyColor: string;
  horizonColor: string;
  glowColor: string;
  treeColor: string;
  fireflies: "0.6" | "1" | "1.4";
  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 colorHelp = "A hex color such as #fcd34d.";

// A fixed, hand-tuned conifer silhouette for the no-WebGPU fallback (viewBox 1200 × 170).
const TREES = (() => {
  const peaks = [
    [0, 92], [38, 40], [70, 104], [104, 22], [140, 100], [172, 56], [206, 108], [244, 12], [282, 98], [318, 48],
    [352, 104], [392, 28], [428, 100], [462, 62], [498, 108], [536, 18], [574, 96], [608, 52], [646, 104], [684, 30],
    [722, 100], [756, 64], [792, 108], [830, 14], [868, 98], [904, 44], [940, 104], [978, 26], [1014, 100], [1050, 58],
    [1088, 108], [1124, 20], [1162, 96], [1200, 50],
  ];
  return `M0 170 ${peaks.map(([x, y]) => `L${x} ${y}`).join(" ")} L1200 170 Z`;
})();

export const firefliesBannerBlock: ComponentConfig<FirefliesBannerProps> = {
  label: "Fireflies Banner",
  fields: {
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the heading, like the series name. Leave blank to hide it." } },
    heading: { type: "textarea", label: "Heading" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H1 (page title)", value: "h1" },
        { label: "H2", value: "h2" },
        { label: "H3", value: "h3" },
        { label: "H4", value: "h4" },
      ],
      metadata: { help: "Use H1 when this banner is the top of the page. The look doesn't change." },
    },
    body: { type: "textarea", label: "Body" },
    details: {
      type: "array",
      label: "Event details",
      min: 0,
      max: 5,
      getItemSummary: (item) => item.label || "Detail",
      defaultItemProps: { label: "When", value: "Friday, 8 pm" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        value: { type: "text", label: "Value" },
      },
      metadata: { help: "Short facts shown in a panel: date, time, place, cost." },
    },
    primaryLabel: { type: "text", label: "Primary button text", metadata: { help: "Leave blank to hide it." } },
    primaryHref: { type: "text", label: "Primary button link" },
    secondaryLabel: { type: "text", label: "Secondary link text", metadata: { help: "Leave blank to hide it." } },
    secondaryHref: { type: "text", label: "Secondary link" },
    skyColor: { type: "text", label: "Sky color", metadata: { help: `${colorHelp} The top of the sky, behind the text. Keep it dark: the text is white.` } },
    horizonColor: { type: "text", label: "Horizon color", metadata: { help: `${colorHelp} The last light low in the sky.` } },
    glowColor: { type: "text", label: "Firefly color", metadata: { help: colorHelp } },
    treeColor: { type: "text", label: "Tree line color", metadata: { help: `${colorHelp} Keep it near black.` } },
    fireflies: {
      type: "radio",
      label: "Fireflies",
      options: [
        { label: "A few", value: "0.6" },
        { label: "Plenty", value: "1" },
        { label: "A swarm", value: "1.4" },
      ],
    },
    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: "Parks After Dark · Summer Series",
    heading: "Firefly walks at Cherokee Hollow",
    headingLevel: "h2",
    body: "Join a naturalist on the lower meadow trail as the synchronous fireflies light up. Lights stay off, voices stay low, and red-filter flashlights are provided at the trailhead.",
    details: [
      { label: "Dates", value: "Fridays, June 6 – July 11" },
      { label: "Time", value: "8:45 – 10:15 pm" },
      { label: "Meet at", value: "Meadow Trailhead, Lot C" },
      { label: "Cost", value: "Free · registration required" },
    ],
    primaryLabel: "Reserve a spot",
    primaryHref: "/events/firefly-walks",
    secondaryLabel: "What to bring",
    secondaryHref: "/events/firefly-walks#prepare",
    skyColor: "#12122f",
    horizonColor: "#5b4373",
    glowColor: "#fde68a",
    treeColor: "#080a14",
    fireflies: "1",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, details, primaryLabel, primaryHref, secondaryLabel, secondaryHref, skyColor, horizonColor, glowColor, treeColor, fireflies, speed }) => {
    const H = headingLevel || "h2";
    const skyTop = hex(skyColor, "#12122f");
    const horizon = hex(horizonColor, "#5b4373");
    const glow = hex(glowColor, "#fde68a");
    const trees = hex(treeColor, "#080a14");
    const rows = (details ?? []).filter((d) => d?.label || d?.value);

    return (
      <section className="relative isolate overflow-hidden" style={{ backgroundColor: skyTop, backgroundImage: `linear-gradient(to bottom, ${skyTop} 15%, ${horizon})` }}>
        <svg aria-hidden="true" viewBox="0 0 1200 170" preserveAspectRatio="xMidYMax slice" className="absolute inset-x-0 bottom-0 h-40 w-full" fill={trees}>
          <path d={TREES} />
        </svg>
        <FirefliesCanvas colors={{ skyTop, horizon, glow, trees }} density={Number(fireflies) || 1} speed={Number(speed) || 1} />

        <div className="relative mx-auto grid max-w-7xl grid-cols-1 gap-10 px-4 pt-16 pb-52 sm:px-6 sm:pt-20 lg:grid-cols-[minmax(0,7fr)_minmax(0,5fr)] lg:items-start lg:gap-16 lg:px-8 lg:pt-24 lg:pb-56">
          <div className="max-w-2xl">
            {eyebrow ? <p className="text-sm font-semibold tracking-widest text-white/85 uppercase">{eyebrow}</p> : null}
            {heading ? <H className="mt-4 text-4xl font-semibold tracking-tight text-balance text-white sm:text-5xl lg:text-6xl">{heading}</H> : null}
            {body ? <p className="mt-6 text-lg leading-8 text-pretty text-white/85">{body}</p> : null}
            {primaryLabel || secondaryLabel ? (
              <div className="mt-10 flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-6">
                {primaryLabel ? (
                  <a
                    href={primaryHref || "#"}
                    className="inline-flex min-h-11 items-center justify-center rounded-lg bg-white px-5 py-3 text-base font-semibold text-neutral-950 shadow-sm transition hover:bg-white/90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
                  >
                    {primaryLabel}
                  </a>
                ) : null}
                {secondaryLabel ? (
                  <a
                    href={secondaryHref || "#"}
                    className="group inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg px-1 text-base font-semibold text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
                  >
                    {secondaryLabel}
                    <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 transition group-hover:translate-x-0.5">
                      <path fillRule="evenodd" d="M3 10a.75.75 0 0 1 .75-.75h10.64l-3.22-3.22a.75.75 0 1 1 1.06-1.06l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06l3.22-3.22H3.75A.75.75 0 0 1 3 10Z" clipRule="evenodd" />
                    </svg>
                  </a>
                ) : null}
              </div>
            ) : null}
          </div>

          {rows.length ? (
            <dl className="grid grid-cols-1 gap-x-6 gap-y-5 rounded-2xl bg-neutral-950/45 p-6 ring-1 ring-white/15 backdrop-blur-sm ring-inset sm:grid-cols-2 sm:p-8 lg:mt-2 lg:grid-cols-1">
              {rows.map((d, i) => (
                <div key={i} className="border-l-2 border-white/25 pl-4">
                  {d.label ? <dt className="text-sm font-medium text-white/75">{d.label}</dt> : null}
                  {d.value ? <dd className="mt-1 text-base font-semibold text-white">{d.value}</dd> : null}
                </div>
              ))}
            </dl>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/fireflies-banner.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 Fireflies Banner: a dusk sky over a two-layer tree line, with fireflies that drift
 * and blink in slow, uneven pulses (vgpu / WebGPU). Decorative only; event details are
 * server-rendered and the CSS dusk gradient and tree line underneath are the fallback.
 */

const FIREFLIES_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  density: f32,
  css: vec2f,
  skyTop: vec3f,
  horizon: vec3f,
  glow: vec3f,
  trees: 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);
}

fn noise(x: f32) -> f32 {
  let i = floor(x);
  let f = fract(x);
  return mix(hash(vec2f(i, 3.7)), hash(vec2f(i + 1.0, 3.7)), f * f * (3.0 - 2.0 * f));
}

// Coverage (0..1) of a ragged conifer line at (x, height above the bottom edge), in CSS px.
fn treeLine(x: f32, y: f32, width: f32, tall: f32, seed: f32) -> f32 {
  // Low understory: rolling, rounded scrub between the trunks.
  let scrub = tall * (0.16 + 0.1 * noise(x / (width * 0.9) + seed) + 0.06 * noise(x / (width * 0.3) + seed * 2.0));
  var m = smoothstep(scrub + 0.8, scrub - 0.8, y);
  let c = floor(x / width);
  for (var k = -2; k <= 2; k++) {
    let id = c + f32(k);
    let r = hash2(vec2f(id, seed));
    let cx = (id + 0.5 + 0.5 * (r.x - 0.5)) * width;
    let th = tall * (0.5 + 0.5 * r.y);
    let f = y / th;
    if (f >= 1.0) { continue; }
    // Tiered branches: each tier flares out, then tucks in under the next.
    let tier = fract(f * (4.0 + 2.0 * r.x) + r.y);
    let hw = width * (0.32 + 0.14 * r.x) * (1.0 - f) * (0.72 + 0.38 * (1.0 - tier));
    let trunk = width * 0.035;
    let edge = max(hw, trunk * step(f, 0.2)) - abs(x - cx);
    m = max(m, smoothstep(-0.8, 0.8, edge));
  }
  return m;
}

// One firefly per cell; returns its glow at q (CSS px).
fn fireflies(q: vec2f, cellPx: f32, t: f32, prob: f32, size: f32, seed: f32) -> f32 {
  let p = q / cellPx;
  let g = floor(p);
  var light = 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 * 1.37 + seed) > prob) { continue; }
      let k = hash2(id + seed + 9.1);
      let drift = vec2f(
        sin(t * (0.18 + 0.2 * k.x) + h.x * 6.2832) + 0.4 * sin(t * 0.53 + h.y * 9.0),
        cos(t * (0.14 + 0.18 * k.y) + h.y * 6.2832),
      );
      let pos = (id + 0.5 + 0.38 * drift) * cellPx;
      let d = length(q - pos);
      // Mostly dark, then a soft pulse: the uneven rhythm reads as fireflies, not stars.
      let ph = fract(t * (0.12 + 0.16 * k.x) + h.x);
      let blink = 0.12 + 0.88 * smoothstep(0.0, 0.08, ph) * smoothstep(0.55, 0.18, ph);
      let r = size * (0.75 + 0.5 * k.y);
      let core = exp(-d * d / (r * r)) * 1.6;
      let halo = exp(-d * d / (r * r * 34.0)) * 0.55;
      light += (core + halo) * blink;
    }
  }
  return light;
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let q = uv * params.css;
  let fromBottom = params.css.y - q.y;

  // Dusk: deep at the top, warming toward the horizon behind the trees.
  let skyMix = smoothstep(0.0, 1.0, uv.y);
  var col = mix(params.skyTop, params.horizon, skyMix * skyMix);
  let star = step(0.9965, hash(floor(q / 2.0))) * smoothstep(0.55, 0.0, uv.y) * (0.5 + 0.5 * sin(t * 0.7 + hash(floor(q / 2.0) + 4.0) * 30.0));
  col += vec3f(0.85, 0.88, 1.0) * star * 0.45;

  // Far fireflies sit behind the trees.
  let rise = smoothstep(params.css.y * 0.12, params.css.y * 0.6, q.y);
  let far = fireflies(q, 58.0, t, params.density * 0.6, 1.6, 3.0) * rise * 0.6;
  col += params.glow * far;

  let backMask = treeLine(q.x + 31.0, fromBottom, 34.0, 124.0, 1.7);
  col = mix(col, mix(params.trees, params.horizon, 0.3), backMask);

  let frontMask = treeLine(q.x, fromBottom, 52.0, 168.0, 8.3);
  col = mix(col, params.trees, frontMask);

  // Near fireflies drift in front of everything, a few low over the trees.
  let rise2 = smoothstep(params.css.y * 0.25, params.css.y * 0.75, q.y);
  let near = fireflies(q + vec2f(17.0, 0.0), 96.0, t * 0.9, params.density * 0.75, 3.2, 11.0) * rise2;
  col += params.glow * near;

  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 = { skyTop: string; horizon: string; glow: string; trees: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type FirefliesCanvasProps = { colors: Colors; density: number; speed: number };

export function FirefliesCanvas({ colors, density, speed }: FirefliesCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, density, speed });
  live.current = { colors, density, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (c: Colors, d: number) => ({
    density: d,
    skyTop: hexToVec3(c.skyTop, [0.07, 0.07, 0.2]),
    horizon: hexToVec3(c.horizon, [0.36, 0.26, 0.45]),
    glow: hexToVec3(c.glow, [1, 0.85, 0.4]),
    trees: hexToVec3(c.trees, [0.03, 0.04, 0.08]),
  });

  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] });
        // The scene is laid out in CSS pixels so trees and fireflies keep their size at any width.
        const sized = () => ({ css: [canvas.clientWidth || target.size[0], canvas.clientHeight || target.size[1]] });
        const fx = effect(gpu, FIREFLIES_WGSL, {
          label: "fireflies-banner",
          set: { params: { time: 5, ...sized(), ...uniforms(live.current.colors, live.current.density) } },
        });
        fxRef.current = fx;
        const time = clock(gpu);

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

        let onScreen = false;
        const sync = () => (onScreen && !document.hidden ? start() : still ? undefined : stop());
        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;
      redrawRef.current = null;
      gpu?.dispose();
    };
  }, []);

  // Live-update colors and density from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: uniforms(colors, density) });
    redrawRef.current?.();
  }, [colors.skyTop, colors.horizon, colors.glow, colors.trees, density]); // 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"}`}
    />
  );
}
```
