# Add the "Leaderboard" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/leaderboard) to this Pantheon Content Publisher (P1) Next.js project. A ranked list sorted highest first, with proportional bars, top-three emphasis and an optional top-N limit.

## Steps

1. Create `components/puck/leaderboard-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 { leaderboardBlock } from "./components/puck/leaderboard-block";`
3. Register it under `components` as `LeaderboardBlock: leaderboardBlock`.
4. Add `"LeaderboardBlock"` 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/leaderboard-block.tsx`

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

/**
 * Leaderboard — a ranked list, sorted highest first, with a proportional bar under each row
 * and the top three gently emphasized. Values are text fields, so rows can be bound to a
 * P1 data source. Place inside a Dashboard Grid.
 * Register: `LeaderboardBlock: leaderboardBlock` in puck.config.tsx.
 */

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

export type LeaderboardProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  items: { label: string; value: string; sublabel: string }[];
  prefix: string;
  suffix: string;
  limit: 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;
}

const fmt = (n: number) => n.toLocaleString("en-US", { maximumFractionDigits: 1 });

export const leaderboardBlock: ComponentConfig<LeaderboardProps> = {
  label: "Leaderboard",
  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: "Period or subtitle", metadata: { help: "e.g. Jul–Sep 2026. Leave blank to hide." } },
    items: {
      type: "array",
      label: "Entries",
      min: 0,
      max: 50,
      getItemSummary: (item) => item?.label || "Entry",
      defaultItemProps: { label: "New entry", value: "0", sublabel: "" },
      arrayFields: {
        label: { type: "text", label: "Name" },
        value: { type: "text", label: "Value", metadata: { help: "A number, e.g. 1,284. Bind with {{ item.field }}. Sorted automatically, highest first." } },
        sublabel: { type: "text", label: "Detail", metadata: { help: "Optional second line, e.g. 42 volunteers." } },
      },
    },
    prefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    suffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. hrs or %. Leave blank for none." } },
    limit: { type: "text", label: "Show top", metadata: { help: "How many entries to show, e.g. 5. Leave blank to show all." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the numbers come from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Volunteer hours by team",
    headingLevel: "h3",
    subtitle: "Jul–Sep 2026",
    items: [
      { label: "Northside Youth Corps", value: "1,102", sublabel: "38 volunteers" },
      { label: "Riverside Tenants' Association", value: "1,284", sublabel: "51 volunteers" },
      { label: "St. Mark's Food Ministry", value: "968", sublabel: "29 volunteers" },
      { label: "Bellwood Garden Club", value: "731", sublabel: "22 volunteers" },
      { label: "Eastside Service Learning", value: "655", sublabel: "64 volunteers" },
      { label: "Westend Mutual Aid", value: "512", sublabel: "17 volunteers" },
      { label: "Friends of the Library", value: "430", sublabel: "14 volunteers" },
    ],
    prefix: "",
    suffix: "hrs",
    limit: "5",
    footnote: "Sample data · Source: Volunteer hours log, Sep 30, 2026",
  },
  render: ({ id, title, headingLevel, subtitle, items, prefix, suffix, limit, footnote }) => {
    const H = headingLevel || "h3";
    const titleId = `${id}-title`;
    const all = (items ?? [])
      .filter((it) => it?.label?.trim())
      .map((it, i) => ({ ...it, n: toNumber(it.value), i }))
      .sort((a, b) => (b.n ?? -Infinity) - (a.n ?? -Infinity) || a.i - b.i);
    const cap = toNumber(limit);
    const shown = cap !== null && cap >= 1 ? all.slice(0, Math.floor(cap)) : all;
    const max = Math.max(0, ...shown.map((it) => it.n ?? 0));
    // Competition ranking: ties share a rank (1, 2, 2, 4).
    const ranks = shown.map((it) => (it.n === null ? null : shown.findIndex((o) => o.n === it.n) + 1));
    const unit = (n: number | null) => {
      if (n === null) return "—";
      const sfx = suffix?.trim();
      return `${prefix ?? ""}${fmt(n)}${sfx ? (/^[%°]/.test(sfx) ? sfx : ` ${sfx}`) : ""}`;
    };

    return (
      <div className="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">
        {title || subtitle ? (
          <div>
            {title ? (
              <H id={titleId} className="text-sm font-semibold text-neutral-950">
                {title}
              </H>
            ) : null}
            {subtitle ? <p className="mt-1 text-sm text-neutral-500">{subtitle}</p> : null}
          </div>
        ) : null}

        {shown.length === 0 ? (
          <div className="mt-4 flex flex-1 flex-col items-center justify-center rounded-lg border border-dashed border-neutral-300 px-4 py-10 text-center">
            <p className="text-sm font-medium text-neutral-900">No entries yet</p>
            <p className="mt-1 text-sm text-neutral-500">Add entries with a name and value, or bind a data source.</p>
          </div>
        ) : (
          <ol role="list" aria-labelledby={title ? titleId : undefined} className="mt-5 space-y-4">
            {shown.map((it, i) => {
              const rank = ranks[i];
              const top = rank !== null && rank <= 3;
              const pct = it.n !== null && max > 0 ? Math.max(0, (it.n / max) * 100) : 0;
              return (
                <li key={`${it.label}-${it.i}`} className="flex gap-3">
                  <span
                    className={`mt-px flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-semibold tabular-nums ${
                      top ? "bg-indigo-50 text-indigo-700 ring-1 ring-indigo-600/20 ring-inset" : "text-neutral-500"
                    }`}
                  >
                    <span className="sr-only">Rank </span>
                    {rank ?? "–"}
                  </span>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-baseline justify-between gap-3">
                      <p className={`min-w-0 truncate text-sm ${top ? "font-semibold text-neutral-950" : "font-medium text-neutral-800"}`} title={it.label}>
                        {it.label}
                      </p>
                      <p className={`shrink-0 text-sm tabular-nums ${top ? "font-semibold text-neutral-950" : "text-neutral-700"}`}>{unit(it.n)}</p>
                    </div>
                    {it.sublabel ? <p className="truncate text-xs text-neutral-500">{it.sublabel}</p> : null}
                    <div aria-hidden="true" className="mt-2 h-1.5 overflow-hidden rounded-full bg-neutral-100">
                      <div className={`h-full rounded-full ${top ? "bg-indigo-600" : "bg-indigo-300"}`} style={{ width: `${pct}%` }} />
                    </div>
                  </div>
                </li>
              );
            })}
          </ol>
        )}

        {shown.length > 0 && shown.length < all.length ? (
          <p className="mt-4 text-xs text-neutral-500 tabular-nums">
            Showing top {shown.length} of {all.length}
          </p>
        ) : null}
        {footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null}
      </div>
    );
  },
};
```
