# Perk Picker

A "Level up! Pick one" screen: a few perk cards pop in, the player chooses one and confirms. Rarity colours the card edge, upgrades show "Lv 2 → 3" or "New", and the game can offer rerolls and a skip. Cards are a row on wide containers and a vertical list on narrow ones. Controlled or uncontrolled, with radiogroup keyboard support.

Docs: https://cozy-ui.solo.engineer/docs/components/perk-picker/

Install: `npx shadcn@latest add @cozy/perk-picker`

### Usage

```tsx
import { PerkPicker, type Perk } from "@/components/ui/perk-picker"

const perks: Perk[] = [
  { id: "paddy", name: "Wider paddy", icon: <PaddyIcon />, rarity: "common", level: 1, maxLevel: 5, description: "Every plot grows bigger." },
  { id: "net", name: "Lucky net", icon: "/icons/net.png", rarity: "rare", description: "Golden carp swim by." },
]

<PerkPicker
  title="Level up!"
  perks={perks}
  rerolls={2}
  onReroll={() => setPerks(drawPerks())}
  onSkip={() => addCoins(50)}
  skipLabel="Skip, +50 coins"
  onConfirm={(perk) => applyPerk(perk.id)}
/>
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| perks | `Perk<T>[]` | – | { id, name, label?, icon?, description?, rarity?, tags?, level?, maxLevel?, stats?, locked?, data? }. `icon` is a React node or an image URL. A new array with different ids replays the reveal. |
| value / defaultValue / onValueChange | `string \| null / (id, perk) => void` | `null` | The chosen perk id. Arrow keys, click and tap change it. |
| onConfirm / confirmLabel | `(perk) => void / ReactNode` | `"Take it"` | Setting onConfirm shows the confirm button. Double-click and Enter on a card confirm too. |
| title / subtitle | `ReactNode` | `"Pick a perk"` | Heading and the line under it. |
| rerolls / onReroll | `number / () => void` | – | Shows "Reroll (2)"; disabled at 0. The game decides the new perks and passes a new `perks` array. |
| onSkip / skipLabel | `() => void / ReactNode` | `"Skip"` | A secondary way out, e.g. "Skip, +50 coins". |
| variant | `"cards" \| "list"` | `auto` | Auto uses cards when the container is at least 560px wide and a list below that. |
| renderPerk | `(perk, { selected, locked, index }) => ReactNode` | – | Replace the inside of a card; frame, selection and keyboard stay. |
| rarities | `Record<string, { label, color }>` | `DEFAULT_RARITIES` | Your own rarity names and colours. |
| labels | `Partial<PerkPickerLabels>` | `English` | title, new, upgrade ("Lv {from} → {to}"), max, confirm, reroll, skip, chosen ("{name} chosen"), locked, empty. |

Keyboard: the cards are a radio group. Arrow keys, Home and End move and select, Space selects, Enter selects and confirms. The choice is announced through a polite live region.

The picker holds no rules. After a reroll or a confirm, pass a new `perks` array; an uncontrolled choice that is no longer offered is cleared.

Reduced motion removes the staggered pop-in.

### Example

```tsx
import * as React from "react";
import { toast } from "sonner";
import { PerkPicker } from "@/components/ui/perk-picker";
import { FIRST_THREE, draw } from "./perks-data";

export default function Demo() {
  const [perks, setPerks] = React.useState(FIRST_THREE);
  const [rerolls, setRerolls] = React.useState(2);
  return (
    <PerkPicker
      title="Level up!"
      subtitle="Pick one perk for your village."
      perks={perks}
      rerolls={rerolls}
      onReroll={() => { setRerolls((r) => r - 1); setPerks(draw(3, perks.map((p) => p.id))); }}
      onSkip={() => toast("Skipped, +50 coins")}
      skipLabel="Skip, +50 coins"
      onConfirm={(perk) => { toast.success(`Picked ${typeof perk.name === "string" ? perk.name : perk.id}`); setPerks(draw(3)); setRerolls(2); }}
    />
  );
}
```

### Source (components/ui/perk-picker.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "./button";
import { GameIcon, RarityBadge, rarityStyle, type ItemStat, type Rarity, type RarityConfig } from "./game-core";

/* "Level up! Pick one": a reveal of a few perk cards, one is chosen and
   confirmed. The game owns the offers and the rules; this only shows them. */

/** One perk offered to the player. */
export type Perk<T = unknown> = {
  /** Stable id. Used for `value` and returned in callbacks. */
  id: string;
  /** Display name. */
  name: React.ReactNode;
  /** Plain-text name for aria. Falls back to `name` when it is a string, else the id. */
  label?: string;
  /** A React node (SVG, sprite, <img>) or an image URL. */
  icon?: React.ReactNode;
  /** What the perk does. */
  description?: React.ReactNode;
  /** Colours the card edge and shows a badge. */
  rarity?: Rarity;
  /** Small chips, e.g. "Farming". */
  tags?: string[];
  /** Level the player has now. 0 or missing shows "New"; with `level` the card says "Lv 2 → 3". */
  level?: number;
  /** Highest level. A perk at its max shows "Max". Setting it (or `level`) turns the level line on. */
  maxLevel?: number;
  /** Stat lines, e.g. `{ label: "Yield", value: "+10%" }`. */
  stats?: ItemStat[];
  /** The perk cannot be picked. A string is shown as the reason. */
  locked?: boolean | string;
  /** Your own object; passed back in every callback. */
  data?: T;
};

/** What `renderPerk` is told about a card. */
export type PerkState = {
  /** This card is the chosen one. */
  selected: boolean;
  /** This card cannot be picked. */
  locked: boolean;
  /** Position in `perks`, from 0. */
  index: number;
};

/** Every built-in string. `{name}`, `{from}`, `{to}` and `{count}` are replaced. */
export type PerkPickerLabels = {
  /** Default "Pick a perk". */
  title: string;
  /** Level line of a perk the player does not have. Default "New". */
  new: string;
  /** Level line of an upgrade. Default "Lv {from} → {to}". */
  upgrade: string;
  /** Level line of a perk at max level. Default "Max". */
  max: string;
  /** Default "Take it". */
  confirm: string;
  /** Default "Reroll". The remaining count is added as "Reroll (2)". */
  reroll: string;
  /** Default "Skip". */
  skip: string;
  /** Spoken when a card is chosen. Default "{name} chosen". */
  chosen: string;
  /** Shown on a locked card without a reason. Default "Locked". */
  locked: string;
  /** Shown when `perks` is empty. Default "No perks to offer." */
  empty: string;
};

const DEFAULT_LABELS: PerkPickerLabels = {
  title: "Pick a perk", new: "New", upgrade: "Lv {from} → {to}", max: "Max", confirm: "Take it",
  reroll: "Reroll", skip: "Skip", chosen: "{name} chosen", locked: "Locked", empty: "No perks to offer.",
};

const fill = (text: string, vars: Record<string, string | number>) => text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
const plainName = (p: Perk<any>) => p.label ?? (typeof p.name === "string" ? p.name : p.id);
const isLocked = (p: Perk<any>) => !!p.locked;

type PerkPickerProps<T = unknown> = Omit<React.ComponentProps<"div">, "title" | "defaultValue" | "onChange"> & {
  /** The offers. A new array with different ids replays the reveal (use it after a reroll). */
  perks: Perk<T>[];
  /** Chosen perk id (controlled). */
  value?: string | null;
  /** Initially chosen perk id (uncontrolled). Default none. */
  defaultValue?: string | null;
  /** Called when the choice changes, with the id (null when it is cleared). */
  onValueChange?: (id: string | null, perk: Perk<T> | null) => void;
  /** Called to confirm the chosen perk: Confirm button, double-click, or Enter on a card. Setting it shows the Confirm button. */
  onConfirm?: (perk: Perk<T>) => void;
  /** Confirm button text. Default "Take it". */
  confirmLabel?: React.ReactNode;
  /** Heading. Default "Pick a perk". */
  title?: React.ReactNode;
  /** Line under the heading. */
  subtitle?: React.ReactNode;
  /** Rerolls left. Shows "Reroll (2)"; disabled at 0. Without it the button shows only when `onReroll` is set. */
  rerolls?: number;
  /** Called by the Reroll button. The game should pass a new `perks` array. Setting it shows the button. */
  onReroll?: () => void;
  /** Called by the Skip button (e.g. take coins instead). Setting it shows the button. */
  onSkip?: () => void;
  /** Skip button text, e.g. "Skip, +50 coins". Default "Skip". */
  skipLabel?: React.ReactNode;
  /** "cards" forces a row of tall cards, "list" forces a vertical list. Default: cards when the container is wide, list when narrow. */
  variant?: "cards" | "list";
  /** Your own rarity colours and names. Default DEFAULT_RARITIES. */
  rarities?: Record<string, RarityConfig>;
  /** Replaces the inside of a card (icon, name, text). The frame, selection and keyboard stay. */
  renderPerk?: (perk: Perk<T>, state: PerkState) => React.ReactNode;
  /** Override built-in text for translation. */
  labels?: Partial<PerkPickerLabels>;
};

function CheckMark() {
  return (
    <span className="cz-perks__check" aria-hidden>
      <svg viewBox="0 0 24 24"><path d="m5.5 12.8 4.2 4.2 8.8-9.4" fill="none" stroke="currentColor" strokeWidth="3.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
    </span>
  );
}

/** Choose one perk out of a few offers: reveal, select, optional reroll, skip and confirm. */
function PerkPicker<T = unknown>({
  perks, value, defaultValue = null, onValueChange, onConfirm, confirmLabel, title, subtitle, rerolls, onReroll, onSkip, skipLabel,
  variant, rarities, renderPerk, labels: labelsProp, className, ...props
}: PerkPickerProps<T>) {
  const L = { ...DEFAULT_LABELS, ...labelsProp };
  const uid = React.useId();
  const [inner, setInner] = React.useState<string | null>(defaultValue);
  const controlled = value !== undefined;
  const selectedId = controlled ? value : inner;
  const selected = perks.find((p) => p.id === selectedId) ?? null;
  const [announce, setAnnounce] = React.useState("");
  const cardRefs = React.useRef(new Map<string, HTMLElement>());
  const revealKey = perks.map((p) => p.id).join("\u0001");

  // A new offer set drops a choice that is no longer on the table.
  React.useEffect(() => {
    if (!controlled && inner != null && !perks.some((p) => p.id === inner)) setInner(null);
  }, [revealKey]); // eslint-disable-line react-hooks/exhaustive-deps

  const select = (perk: Perk<T>) => {
    if (isLocked(perk) || perk.id === selectedId) return;
    if (!controlled) setInner(perk.id);
    onValueChange?.(perk.id, perk);
    setAnnounce(fill(L.chosen, { name: plainName(perk) }));
  };
  const confirm = (perk: Perk<T> | null) => { if (perk && !isLocked(perk)) onConfirm?.(perk); };

  const enabled = perks.filter((p) => !isLocked(p));
  const tabStop = selected && !isLocked(selected) ? selected.id : enabled[0]?.id;

  const move = (from: Perk<T>, step: 1 | -1 | "first" | "last") => {
    if (!enabled.length) return;
    const at = enabled.findIndex((p) => p.id === from.id);
    const next = step === "first" ? enabled[0] : step === "last" ? enabled[enabled.length - 1] : enabled[(at + step + enabled.length) % enabled.length];
    select(next);
    cardRefs.current.get(next.id)?.focus();
  };

  const onKeyDown = (e: React.KeyboardEvent, perk: Perk<T>) => {
    if (e.target !== e.currentTarget) return;
    switch (e.key) {
      case "ArrowRight": case "ArrowDown": e.preventDefault(); move(perk, 1); break;
      case "ArrowLeft": case "ArrowUp": e.preventDefault(); move(perk, -1); break;
      case "Home": e.preventDefault(); move(perk, "first"); break;
      case "End": e.preventDefault(); move(perk, "last"); break;
      case " ": e.preventDefault(); select(perk); break;
      case "Enter": e.preventDefault(); if (!isLocked(perk)) { select(perk); confirm(perk); } break;
    }
  };

  const levelText = (p: Perk<T>) => {
    if (p.level == null && p.maxLevel == null) return null;
    const lv = p.level ?? 0;
    if (p.maxLevel != null && lv >= p.maxLevel) return L.max;
    return lv <= 0 ? L.new : fill(L.upgrade, { from: lv, to: lv + 1 });
  };

  const showReroll = onReroll != null || rerolls != null;
  const showFooter = showReroll || onSkip || onConfirm;
  const titleId = `${uid}-title`;

  return (
    <div
      data-slot="perk-picker"
      data-variant={variant}
      className={cn("cz-perks", className)}
      {...props}
    >
      <div className="cz-perks__head">
        <h3 className="cz-perks__title" id={titleId}>{title ?? L.title}</h3>
        {subtitle != null && <p className="cz-perks__subtitle">{subtitle}</p>}
      </div>

      {perks.length === 0 ? (
        <p className="cz-perks__empty">{L.empty}</p>
      ) : (
        <div key={revealKey} className="cz-perks__cards" role="radiogroup" aria-labelledby={titleId} data-count={perks.length} style={{ "--n": Math.min(perks.length, 4) } as React.CSSProperties}>
          {perks.map((perk, index) => {
            const locked = isLocked(perk);
            const isSel = perk.id === selectedId && !locked;
            const lvl = levelText(perk);
            const reason = typeof perk.locked === "string" ? perk.locked : L.locked;
            return (
              <div
                key={perk.id}
                ref={(el) => { if (el) cardRefs.current.set(perk.id, el); else cardRefs.current.delete(perk.id); }}
                role="radio"
                aria-checked={isSel}
                aria-disabled={locked || undefined}
                tabIndex={perk.id === tabStop ? 0 : -1}
                aria-label={`${plainName(perk)}${lvl ? `, ${lvl}` : ""}${locked ? `, ${reason}` : ""}`}
                data-slot="perk-card"
                data-perk={perk.id}
                data-selected={isSel || undefined}
                data-locked={locked || undefined}
                data-rarity={perk.rarity}
                className="cz-perks__card"
                style={{ "--i": index, ...rarityStyle(perk.rarity, rarities) } as React.CSSProperties}
                onClick={() => select(perk)}
                onDoubleClick={() => { if (!locked) { select(perk); confirm(perk); } }}
                onKeyDown={(e) => onKeyDown(e, perk)}
              >
                <CheckMark />
                {renderPerk ? renderPerk(perk, { selected: isSel, locked, index }) : (
                  <>
                    {perk.icon != null && <span className="cz-perks__icon"><GameIcon icon={perk.icon} alt="" /></span>}
                    <span className="cz-perks__body">
                      {(perk.rarity || lvl) && (
                        <span className="cz-perks__meta">
                          <RarityBadge rarity={perk.rarity} rarities={rarities} />
                          {lvl && <span className="cz-perks__level" data-new={lvl === L.new || undefined}>{lvl}</span>}
                        </span>
                      )}
                      <span className="cz-perks__name">{perk.name}</span>
                      {perk.description != null && <span className="cz-perks__desc">{perk.description}</span>}
                      {perk.stats && perk.stats.length > 0 && (
                        <span className="cz-perks__stats">
                          {perk.stats.map((s, i) => <span key={i} className="cz-perks__stat"><span>{s.label}</span><b>{s.value}</b></span>)}
                        </span>
                      )}
                      {perk.tags && perk.tags.length > 0 && (
                        <span className="cz-perks__tags">{perk.tags.map((t) => <span key={t} className="cz-perks__tag">{t}</span>)}</span>
                      )}
                      {locked && <span className="cz-perks__lock">{reason}</span>}
                    </span>
                  </>
                )}
              </div>
            );
          })}
        </div>
      )}

      {showFooter && (
        <div className="cz-perks__foot">
          {onSkip && <Button type="button" variant="outline" className="cz-perks__skip" onClick={onSkip}>{skipLabel ?? L.skip}</Button>}
          {showReroll && (
            <Button type="button" variant="secondary" className="cz-perks__reroll" disabled={rerolls != null && rerolls <= 0} onClick={onReroll}>
              {L.reroll}{rerolls != null ? ` (${rerolls})` : ""}
            </Button>
          )}
          {onConfirm && (
            <Button type="button" variant="reward" className="cz-perks__confirm" disabled={!selected || isLocked(selected)} onClick={() => confirm(selected)}>
              {confirmLabel ?? L.confirm}
            </Button>
          )}
        </div>
      )}
      <div className="cz-sr-only" aria-live="polite" role="status">{announce}</div>
    </div>
  );
}

export { PerkPicker };
export type { PerkPickerProps };
```

npm: `import { PerkPicker } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
