# Add the "Testimonial Carousel" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/testimonial-carousel) to this Pantheon Content Publisher (P1) Next.js project. One large quote at a time, crossfading with a soft lift, picked from a row of avatar tabs. Rotation is optional.

## Steps

1. Install the dependency: `pnpm add gsap` (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/testimonial-carousel-block.tsx`, `components/puck/testimonial-carousel.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 { testimonialCarouselBlock } from "./components/puck/testimonial-carousel-block";`
4. Register it under `components` as `TestimonialCarouselBlock: testimonialCarouselBlock`.
5. Add `"TestimonialCarouselBlock"` to the best-fitting entry in `categories` (this block's library category is "Carousels"). 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/testimonial-carousel-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { TestimonialCarouselStage } from "./testimonial-carousel.client";

/**
 * Testimonial Carousel — one large quote at a time, crossfading with a soft lift (GSAP), picked
 * from a row of avatar tabs. Rotation is optional and off by default. Without JavaScript the
 * quotes are a swipeable scroll-snap row. Needs `pnpm add gsap` and the companion
 * testimonial-carousel.client.tsx file. Register: `TestimonialCarouselBlock: testimonialCarouselBlock` in puck.config.tsx.
 */

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

type Testimonial = { quote: string; name: string; role: string; avatarUrl: string; avatarAlt: string };

export type TestimonialCarouselProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  testimonials: Testimonial[];
  autoplay: "off" | "on";
  interval: "6" | "8" | "10";
};

export const testimonialCarouselBlock: ComponentConfig<TestimonialCarouselProps> = {
  label: "Testimonial Carousel",
  fields: {
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the heading. Leave blank to hide it." } },
    heading: { type: "text", label: "Heading", metadata: { help: "Leave blank to let the quotes stand alone." } },
    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." },
    },
    testimonials: {
      type: "array",
      label: "Testimonials",
      min: 1,
      max: 8,
      getItemSummary: (item) => item?.name?.slice(0, 48) || item?.quote?.slice(0, 48) || "Testimonial",
      defaultItemProps: {
        quote: "What changed for you, in your own words.",
        name: "Full name",
        role: "Program participant",
        avatarUrl: "",
        avatarAlt: "",
      },
      arrayFields: {
        quote: { type: "textarea", label: "Quote", metadata: { help: "Two to four sentences reads best at this size." } },
        name: { type: "text", label: "Name" },
        role: { type: "text", label: "Role or context", metadata: { help: "Such as \"Parent, Class of 2027\". Leave blank to hide it." } },
        avatarUrl: { type: "text", label: "Photo URL", metadata: { help: "A square headshot. Leave blank to show initials." } },
        avatarAlt: { type: "text", label: "Photo description", metadata: { help: "Usually blank: the name beside the photo already says who it is." } },
      },
    },
    autoplay: {
      type: "radio",
      label: "Rotate automatically",
      options: [
        { label: "Off", value: "off" },
        { label: "On", value: "on" },
      ],
      metadata: { help: "Adds a Pause button. Rotation stops on hover and focus, and never runs for visitors who ask for reduced motion." },
    },
    interval: {
      type: "select",
      label: "Time per quote",
      options: [
        { label: "6 seconds", value: "6" },
        { label: "8 seconds", value: "8" },
        { label: "10 seconds", value: "10" },
      ],
      metadata: { help: "Only used when rotation is on. Longer quotes need more time." },
    },
  },
  defaultProps: {
    eyebrow: "In their words",
    heading: "What families tell us",
    headingLevel: "h2",
    autoplay: "off",
    interval: "8",
    testimonials: [
      {
        quote: "Before the pantry opened on Saturdays, I had to choose between a shift and groceries. Now my kids and I come together, and they pick out the vegetables.",
        name: "Danielle Brooks",
        role: "Shopper since 2023",
        avatarUrl: "https://picsum.photos/seed/danielle/160/160",
        avatarAlt: "",
      },
      {
        quote: "I came to volunteer for one afternoon and stayed four years. You see the same faces every week, and you start to notice when someone needs more than food.",
        name: "Tomás Herrera",
        role: "Volunteer shift lead",
        avatarUrl: "https://picsum.photos/seed/tomas/160/160",
        avatarAlt: "",
      },
      {
        quote: "Their staff helped me sign up for SNAP in twenty minutes. I'd put it off for a year because the forms felt impossible.",
        name: "Grace Okafor",
        role: "Benefits clinic visitor",
        avatarUrl: "https://picsum.photos/seed/graceo/160/160",
        avatarAlt: "",
      },
      {
        quote: "As a grocer, our surplus used to end up in a dumpster. Now it's on a family's table by dinner, and our team asks to drive the pickup route.",
        name: "Martin Liu",
        role: "Store manager, Eastside Market",
        avatarUrl: "https://picsum.photos/seed/martinliu/160/160",
        avatarAlt: "",
      },
    ],
  },
  render: ({ id, eyebrow, heading, headingLevel, testimonials, autoplay, interval }) => {
    const H = headingLevel || "h2";
    const list = (testimonials ?? []).filter((t) => t?.quote);
    const headingId = `${id}-heading`;
    const hasHeader = Boolean(eyebrow || heading);

    const slides = list.map((t, i) => (
      <figure
        key={`${t.name}-${i}`}
        id={`${id}-slide-${i}`}
        data-slide=""
        role="group"
        aria-roledescription="slide"
        aria-label={`${i + 1} of ${list.length}`}
        className="w-full shrink-0 snap-center"
      >
        <blockquote data-anim="" className="font-serif text-2xl leading-snug tracking-tight text-pretty text-neutral-950 sm:text-3xl lg:text-4xl lg:leading-tight">
          <p>&ldquo;{t.quote}&rdquo;</p>
        </blockquote>
        {t.name || t.role ? (
          <figcaption data-anim="" className="mt-8 flex items-center gap-4">
            {t.avatarUrl ? <img data-avatar="" src={t.avatarUrl} alt={t.avatarAlt || ""} className="size-12 shrink-0 rounded-full object-cover" /> : null}
            <div>
              {t.name ? <p className="text-base font-semibold text-neutral-950">{t.name}</p> : null}
              {t.role ? <p className="text-sm text-neutral-600">{t.role}</p> : null}
            </div>
          </figcaption>
        ) : null}
      </figure>
    ));

    return (
      <section aria-labelledby={heading ? headingId : undefined} className="relative isolate overflow-hidden bg-neutral-50 px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto grid max-w-7xl grid-cols-1 gap-10 lg:grid-cols-12 lg:gap-16">
          <div className={hasHeader ? "lg:col-span-4" : "hidden lg:col-span-4 lg:block"}>
            <svg aria-hidden="true" viewBox="0 0 64 48" fill="currentColor" className="h-10 w-auto text-indigo-600 sm:h-14">
              <path d="M0 48V30C0 13 9 3 26 0l3 7c-9 3-14 9-14 18h12v23H0Zm35 0V30C35 13 44 3 61 0l3 7c-9 3-14 9-14 18h12v23H35Z" />
            </svg>
            {eyebrow ? <p className="mt-8 text-sm font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
            {heading ? (
              <H id={headingId} className="mt-3 text-3xl font-semibold tracking-tight text-balance text-neutral-950 sm:text-4xl">
                {heading}
              </H>
            ) : null}
          </div>
          <div className="min-w-0 lg:col-span-8">
            {slides.length > 0 ? (
              <TestimonialCarouselStage
                baseId={id}
                label={heading || "Testimonials"}
                people={list.map((t) => ({ name: t.name || "", avatarUrl: t.avatarUrl || "" }))}
                autoplay={autoplay === "on"}
                interval={Number(interval) || 8}
              >
                {slides}
              </TestimonialCarouselStage>
            ) : null}
          </div>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/testimonial-carousel.client.tsx`

```tsx
"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { KeyboardEvent, ReactNode } from "react";
import { gsap } from "gsap";

/**
 * Interactive half of the Testimonial Carousel. Quotes arrive server-rendered as children in a
 * scroll-snap row; once hydrated they stack in one grid cell and crossfade with a soft lift,
 * picked from a row of avatar tabs. Optional rotation draws a ring around the active avatar as
 * its timer, and pauses on hover, on focus, or with the Pause button.
 */

type Person = { name: string; avatarUrl: string };
type Api = { go: (to: number, announce?: boolean) => void };

export type TestimonialCarouselStageProps = {
  children: ReactNode;
  baseId: string;
  label: string;
  people: Person[];
  autoplay: boolean;
  interval: number;
};

const initials = (name: string) =>
  name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase())
    .join("");

export function TestimonialCarouselStage({ children, baseId, label, people, autoplay, interval }: TestimonialCarouselStageProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const stageRef = useRef<HTMLDivElement>(null);
  const tabsRef = useRef<HTMLDivElement>(null);
  const api = useRef<Api | null>(null);
  const userPausedRef = useRef(false);
  const resumeRef = useRef<(() => void) | null>(null);
  const [enhanced, setEnhanced] = useState(false);
  const [reduced, setReduced] = useState(false);
  const [active, setActive] = useState(0);
  const [userPaused, setUserPaused] = useState(false);
  const [status, setStatus] = useState("");
  const count = people.length;
  const interactive = enhanced && count > 1;
  const rotates = interactive && autoplay && !reduced;
  const rotating = rotates && !userPaused;

  useEffect(() => {
    setReduced(window.matchMedia("(prefers-reduced-motion: reduce)").matches);
    setEnhanced(true);
  }, []);

  useLayoutEffect(() => {
    const root = rootRef.current;
    const stage = stageRef.current;
    if (!interactive || !root || !stage) return;
    const slides = Array.from(stage.querySelectorAll<HTMLElement>(":scope > [data-slide]"));
    if (slides.length < 2) return;

    let current = 0;
    let hovered = false;
    let focused = false;
    let tl: gsap.core.Timeline | undefined;
    let timer: gsap.core.Tween | undefined;
    const rings = () => Array.from(root.querySelectorAll<SVGCircleElement>("[data-ring]"));

    const ctx = gsap.context(() => {
      stage.scrollLeft = 0;
      gsap.set(slides, { gridArea: "1 / 1" });
      gsap.set(slides.slice(1), { autoAlpha: 0 });
      gsap.set(stage.querySelectorAll("[data-avatar]"), { display: "none" });
      slides.forEach((s, i) => {
        s.setAttribute("role", "tabpanel");
        s.inert = i !== 0;
      });
    }, root);

    // The active ring doubles as the rotation timer; without rotation it's simply drawn.
    const arm = ctx.add("arm", () => {
      timer?.kill();
      const all = rings();
      gsap.set(all, { strokeDashoffset: 1 });
      const ring = all[current];
      if (!ring) return;
      if (!rotates || userPausedRef.current) {
        gsap.to(ring, { strokeDashoffset: 0, duration: reduced ? 0 : 0.6, ease: "power2.out" });
        return;
      }
      timer = gsap.fromTo(ring, { strokeDashoffset: 1 }, { strokeDashoffset: 0, duration: interval, ease: "none", onComplete: () => go(current + 1) });
      if (hovered || focused) timer.pause();
    }) as () => void;

    const go = ctx.add("go", (to: number, announce = false) => {
      const next = ((to % slides.length) + slides.length) % slides.length;
      if (next === current) return;
      const dir = to > current ? 1 : -1;
      const out = slides[current];
      const inn = slides[next];
      tl?.progress(1);
      out.inert = true;
      inn.inert = false;
      current = next;
      setActive(next);
      if (announce) setStatus(`Testimonial ${next + 1} of ${slides.length}${people[next]?.name ? `: ${people[next].name}` : ""}`);

      const parts = inn.querySelectorAll("[data-anim]");
      if (reduced) {
        tl = gsap.timeline().to(out, { autoAlpha: 0, duration: 0.25 }).to(inn, { autoAlpha: 1, duration: 0.3 }, "<0.1");
      } else {
        tl = gsap
          .timeline()
          .to(out, { autoAlpha: 0, y: -14 * dir, filter: "blur(4px)", duration: 0.45, ease: "power2.in" })
          .set(inn, { autoAlpha: 1, y: 0, filter: "none" }, "<0.3")
          .fromTo(
            parts,
            { autoAlpha: 0, y: 22 * dir, filter: "blur(6px)" },
            { autoAlpha: 1, y: 0, filter: "blur(0px)", duration: 1.1, stagger: 0.14, ease: "power3.out", clearProps: "filter" },
            "<",
          )
          .set(out, { y: 0, filter: "none" });
      }
      arm();
    }) as Api["go"];

    api.current = { go: (to, announce) => go(to, announce) };
    // Called by the Pause/Play button, after it flips userPausedRef.
    resumeRef.current = () => arm();
    arm();

    const sync = () => {
      if (!timer) return;
      if (hovered || focused) timer.pause();
      else timer.resume();
    };
    const onEnter = () => ((hovered = true), sync());
    const onLeave = () => ((hovered = false), sync());
    const onFocusIn = () => ((focused = true), sync());
    const onFocusOut = (e: FocusEvent) => {
      if (root.contains(e.relatedTarget as Node | null)) return;
      focused = false;
      sync();
    };
    root.addEventListener("pointerenter", onEnter);
    root.addEventListener("pointerleave", onLeave);
    root.addEventListener("focusin", onFocusIn);
    root.addEventListener("focusout", onFocusOut);
    const onVisibility = () => (document.hidden ? timer?.pause() : sync());
    document.addEventListener("visibilitychange", onVisibility);

    return () => {
      root.removeEventListener("pointerenter", onEnter);
      root.removeEventListener("pointerleave", onLeave);
      root.removeEventListener("focusin", onFocusIn);
      root.removeEventListener("focusout", onFocusOut);
      document.removeEventListener("visibilitychange", onVisibility);
      ctx.revert();
      slides.forEach((s) => {
        s.inert = false;
        s.setAttribute("role", "group");
      });
      api.current = null;
      resumeRef.current = null;
      setActive(0);
    };
  }, [interactive, rotates, interval, reduced, count]); // eslint-disable-line react-hooks/exhaustive-deps

  const step = (dir: 1 | -1, focusTab = false) => {
    const to = (active + dir + count) % count;
    // Pass the unwrapped index so the motion direction follows the arrow, even across the loop.
    api.current?.go(active + dir, true);
    if (focusTab) tabsRef.current?.querySelectorAll<HTMLButtonElement>("[role=tab]")[to]?.focus();
  };

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    if (!api.current || (e.key !== "ArrowRight" && e.key !== "ArrowLeft")) return;
    e.preventDefault();
    const onTab = (e.target as HTMLElement).getAttribute("role") === "tab";
    step(e.key === "ArrowRight" ? 1 : -1, onTab);
  };

  const togglePause = () => {
    userPausedRef.current = !userPausedRef.current;
    setUserPaused(userPausedRef.current);
    resumeRef.current?.();
  };

  const roundButton =
    "inline-flex size-11 items-center justify-center rounded-full text-neutral-900 ring-1 ring-neutral-300 transition-colors ring-inset hover:bg-neutral-950 hover:text-white hover:ring-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600";

  return (
    <div ref={rootRef} role="region" aria-roledescription="carousel" aria-label={label} onKeyDown={onKeyDown}>
      <div
        ref={stageRef}
        className={
          interactive
            ? "grid grid-cols-1"
            : "flex snap-x snap-mandatory gap-8 relative overflow-x-auto overscroll-x-contain pb-4"
        }
      >
        {children}
      </div>

      {interactive ? (
        <div className="mt-10 flex flex-wrap items-center gap-x-6 gap-y-5 border-t border-neutral-200 pt-8 sm:mt-14">
          {rotates ? (
            <button type="button" onClick={togglePause} className={roundButton} aria-label={userPaused ? "Start rotating testimonials" : "Pause rotating testimonials"}>
              {userPaused ? (
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-4">
                  <path d="M4.5 2.8v10.4a.6.6 0 0 0 .9.5l8.3-5.2a.6.6 0 0 0 0-1L5.4 2.3a.6.6 0 0 0-.9.5Z" />
                </svg>
              ) : (
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-4">
                  <rect x="3.5" y="2.5" width="3" height="11" rx="0.75" />
                  <rect x="9.5" y="2.5" width="3" height="11" rx="0.75" />
                </svg>
              )}
            </button>
          ) : null}

          <div ref={tabsRef} role="tablist" aria-label="Choose a testimonial" className="flex flex-1 flex-wrap items-center gap-2">
            {people.map((p, i) => {
              const selected = i === active;
              return (
                <button
                  key={`${p.name}-${i}`}
                  type="button"
                  role="tab"
                  id={`${baseId}-tab-${i}`}
                  aria-selected={selected}
                  aria-controls={`${baseId}-slide-${i}`}
                  aria-label={p.name || `Testimonial ${i + 1}`}
                  tabIndex={selected ? 0 : -1}
                  onClick={() => api.current?.go(i, true)}
                  className="group relative inline-flex size-12 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
                >
                  <span
                    className={`relative flex size-10 items-center justify-center overflow-hidden rounded-full bg-indigo-100 text-xs font-semibold text-indigo-900 transition duration-500 ${
                      selected ? "scale-100" : "scale-80 opacity-60 grayscale group-hover:scale-90 group-hover:opacity-100 group-hover:grayscale-0"
                    }`}
                  >
                    {p.avatarUrl ? <img src={p.avatarUrl} alt="" draggable={false} className="size-full object-cover" /> : initials(p.name) || i + 1}
                  </span>
                  <svg aria-hidden="true" viewBox="0 0 48 48" className="pointer-events-none absolute inset-0 size-full -rotate-90">
                    <circle data-ring="" cx="24" cy="24" r="22.5" fill="none" stroke="currentColor" strokeWidth="1.5" pathLength={1} strokeDasharray="1" strokeDashoffset="1" className="text-indigo-600" />
                  </svg>
                </button>
              );
            })}
          </div>

          <div className="flex items-center gap-4">
            <p aria-hidden="true" className="text-sm font-medium text-neutral-600 tabular-nums">
              {String(active + 1).padStart(2, "0")}
              <span className="mx-1.5 text-neutral-400">/</span>
              {String(count).padStart(2, "0")}
            </p>
            <div className="flex gap-2">
              <button type="button" aria-label="Previous testimonial" onClick={() => step(-1)} className={roundButton}>
                <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 rotate-180">
                  <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>
              </button>
              <button type="button" aria-label="Next testimonial" onClick={() => step(1)} className={roundButton}>
                <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-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>
              </button>
            </div>
          </div>
          <p aria-live={rotating ? "off" : "polite"} className="sr-only">
            {status}
          </p>
        </div>
      ) : null}
    </div>
  );
}
```
