# Item Card

Ready-made collectible cards for games: an original frame with a rarity edge, an element tint, big art, abilities, flavour text and a set footer. Cards tilt toward the pointer with a foil shine, flip to a custom back, and scale every part from one width. CardHand fans them like a hand; CardGrid lays out a binder.

Docs: https://cozy-ui.solo.engineer/docs/components/item-card/

Install: `npx shadcn@latest add @cozy/item-card`

### Usage

```tsx
import { ItemCard, type CardData } from "@/components/ui/item-card"

const carp: CardData = {
  id: "carp", name: "River Carp", art: "/cards/carp.png", rarity: "rare", element: "water",
  stat: { label: "HP", value: 60 }, type: "Fish · River",
  abilities: [{ name: "Splash", cost: 1, value: 20, text: "Water two plots." }],
  footer: { number: "012/120", set: "Village Set" },
}

<ItemCard card={carp} size="md" onSelect={(c) => play(c)} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| card | `CardData<T>` | – | { id, name, label?, art?, rarity?, element?, stat?, type?, abilities?, flavor?, footer?, foil?, badge?, data? }. `art` is a React node or an image URL. |
| size | `"sm" \| "md" \| "lg" \| number` | `"md"` | 160, 240 or 320 px wide, or any width. Height follows the 5:7 card shape and everything inside scales with it. Never wider than its container. |
| onSelect / selected / disabled | `(card) => void / boolean` | – | With onSelect the card is a button (click, Enter, Space). |
| flipped / defaultFlipped / onFlippedChange / flipOnClick | `boolean / fn` | `false` | Show the back. flipOnClick turns the card on click instead of selecting it. |
| back | `ReactNode` | `pattern` | Your own card back (logo, set art). |
| tilt | `boolean` | `true` | 3D tilt and glare toward the pointer. Off under reduced motion. |
| owned | `boolean` | `true` | false shows a dark silhouette with ??? for cards not collected yet. |
| card.foil | `"holo" \| "shimmer" \| "none"` | `by rarity` | Holo for epic and legendary, shimmer for rare, none otherwise. |
| elements / rarities | `Record<string, { label, color, icon? }>` | `DEFAULT_ELEMENTS / DEFAULT_RARITIES` | Your own element and rarity sets; colours are any CSS colour. |
| renderArt / renderAbility / renderFooter | `fn` | – | Replace parts of the front, e.g. a 3D canvas or animated sprite as the art. |
| CardHand | `{ cards, size?, selectedId?, onSelect?, spread?, overlap?, disabledIds?, cardProps? }` | `spread 24, overlap 0.45` | A fanned hand. `spread` is the total angle in degrees, `overlap` the share each card hides of the previous one. |
| CardGrid | `{ cards, size?, selectedId?, onSelect?, ownedIds?, cardProps? }` | – | A responsive binder grid; cards not in ownedIds show as silhouettes. |

### Example

```tsx
import { toast } from "sonner";
import { ItemCard } from "@/components/ui/item-card";
import { CARDS } from "./game-data";

export default function ItemCardDemo() {
  return (
    <div className="flex w-full flex-wrap items-start justify-center gap-6">
      {[CARDS[0], CARDS[1], CARDS[3]].map((card) => (
        <ItemCard key={card.id} card={card} size="md" onSelect={(c) => toast(`Played ${c.name}`)} />
      ))}
    </div>
  );
}
```

### Source (components/ui/item-card.tsx)

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

/* Collectible cards for games: an original cozy frame with a rarity edge,
   an element tint, a big art window, abilities, flavour text and a footer.
   They tilt toward the pointer with a foil shine, flip to a custom back, and
   scale every part with their width (container units), so one prop sizes
   the whole card. Data in, events out. */

export type CardAbility = {
  name: React.ReactNode;
  /** Cost shown before the name: a number, text or small icons. */
  cost?: React.ReactNode;
  text?: React.ReactNode;
  /** Big number on the right, e.g. damage or yield. */
  value?: React.ReactNode;
};

export type CardData<T = unknown> = {
  id: string;
  name: React.ReactNode;
  /** Plain-text name for accessible labels (defaults to name if it is a string). */
  label?: string;
  /** A React node (SVG, sprite, canvas) or an image URL. */
  art?: React.ReactNode;
  rarity?: Rarity;
  /** Key into `elements` for the frame tint, e.g. "water". */
  element?: string;
  /** Top-right stat, e.g. { label: "HP", value: 120 }. */
  stat?: { label?: React.ReactNode; value: React.ReactNode };
  /** Type line under the art, e.g. "Tool · Spring". */
  type?: React.ReactNode;
  abilities?: CardAbility[];
  flavor?: React.ReactNode;
  /** Bottom line: card number, set name, artist. */
  footer?: { number?: React.ReactNode; set?: React.ReactNode; artist?: React.ReactNode };
  /** Foil finish. Default: "holo" for epic and legendary, "shimmer" for rare, none otherwise. */
  foil?: "holo" | "shimmer" | "none";
  /** Small corner badge, e.g. "×2" or "New". */
  badge?: React.ReactNode;
  data?: T;
};

export type ElementConfig = { label: string; /** Any CSS colour. */ color: string; icon?: React.ReactNode };

export const DEFAULT_ELEMENTS: Record<string, ElementConfig> = {
  sun: { label: "Sun", color: "#E9A23B" },
  water: { label: "Water", color: "#4F97C7" },
  leaf: { label: "Leaf", color: "#5E9E3E" },
  earth: { label: "Earth", color: "#A8714A" },
  spirit: { label: "Spirit", color: "#9A6BD6" },
  ember: { label: "Ember", color: "#D8573A" },
  moon: { label: "Moon", color: "#6F7FA8" },
};

const SIZES = { sm: 160, md: 240, lg: 320 } as const;

type ItemCardProps<T> = Omit<React.ComponentProps<"div">, "onSelect"> & {
  card: CardData<T>;
  /** "sm" 160px, "md" 240px (default), "lg" 320px, or a width in px. Height follows the 5:7 card shape. */
  size?: keyof typeof SIZES | number;
  /** Show the back. Controlled with onFlippedChange, or use defaultFlipped. */
  flipped?: boolean;
  defaultFlipped?: boolean;
  onFlippedChange?: (flipped: boolean) => void;
  /** Click (or Enter) flips the card instead of selecting it. */
  flipOnClick?: boolean;
  /** Custom back face. Default: a cozy pattern with the logo slot. */
  back?: React.ReactNode;
  /** Tilt toward the pointer with a foil shine. Off under reduced motion. Default true. */
  tilt?: boolean;
  /** false shows a silhouette with "???" (not collected yet). Default true. */
  owned?: boolean;
  selected?: boolean;
  disabled?: boolean;
  /** Click or Enter. When set, the card is a button. */
  onSelect?: (card: CardData<T>) => void;
  elements?: Record<string, ElementConfig>;
  rarities?: Record<string, RarityConfig>;
  /** Replace parts of the front. */
  renderArt?: (card: CardData<T>) => React.ReactNode;
  renderAbility?: (ability: CardAbility, index: number, card: CardData<T>) => React.ReactNode;
  renderFooter?: (card: CardData<T>) => React.ReactNode;
};

const plain = (c: CardData<unknown>) => c.label ?? (typeof c.name === "string" ? c.name : c.id);

function useReducedMotion() {
  const [reduced, setReduced] = React.useState(false);
  React.useEffect(() => {
    const m = window.matchMedia("(prefers-reduced-motion: reduce)");
    setReduced(m.matches);
    const on = () => setReduced(m.matches);
    m.addEventListener("change", on);
    return () => m.removeEventListener("change", on);
  }, []);
  return reduced;
}

/** One collectible card. */
function ItemCard<T = unknown>({
  card, size = "md", flipped: flippedProp, defaultFlipped = false, onFlippedChange, flipOnClick = false, back, tilt = true,
  owned = true, selected, disabled, onSelect, elements = DEFAULT_ELEMENTS, rarities, renderArt, renderAbility, renderFooter,
  className, style, ...props
}: ItemCardProps<T>) {
  const [flipInner, setFlipInner] = React.useState(defaultFlipped);
  const flipped = flippedProp ?? flipInner;
  const reduced = useReducedMotion();
  const ref = React.useRef<HTMLDivElement>(null);
  const width = typeof size === "number" ? size : SIZES[size];
  const el = card.element ? elements[card.element] : undefined;
  const foil = owned ? card.foil ?? (card.rarity === "epic" || card.rarity === "legendary" ? "holo" : card.rarity === "rare" ? "shimmer" : "none") : "none";
  const interactive = !!onSelect || flipOnClick;

  const setFlip = (v: boolean) => { if (flippedProp === undefined) setFlipInner(v); onFlippedChange?.(v); };
  const activate = () => {
    if (disabled) return;
    if (flipOnClick) setFlip(!flipped);
    else onSelect?.(card);
  };

  const onMove = (e: React.PointerEvent) => {
    if (!tilt || reduced || !ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width, y = (e.clientY - r.top) / r.height;
    ref.current.style.setProperty("--rx", `${(0.5 - y) * 14}deg`);
    ref.current.style.setProperty("--ry", `${(x - 0.5) * 18}deg`);
    ref.current.style.setProperty("--mx", `${x * 100}%`);
    ref.current.style.setProperty("--my", `${y * 100}%`);
    ref.current.dataset.active = "";
  };
  const onLeave = () => {
    const n = ref.current;
    if (!n) return;
    n.style.setProperty("--rx", "0deg"); n.style.setProperty("--ry", "0deg");
    delete n.dataset.active;
  };

  const name = owned ? card.name : "???";
  const a11y = owned ? `${plain(card)}${card.rarity ? `, ${rarityLabel(card.rarity, rarities)}` : ""}${flipped ? ", back" : ""}` : "Card not collected yet";

  return (
    <div
      ref={ref}
      data-slot="item-card"
      data-rarity={card.rarity}
      data-element={card.element}
      data-foil={foil !== "none" ? foil : undefined}
      data-flipped={flipped || undefined}
      data-unowned={!owned || undefined}
      data-selected={selected || undefined}
      data-disabled={disabled || undefined}
      className={cn("cz-tcard", className)}
      style={{ "--card-w": `${width}px`, ...(el ? { "--element": el.color } : null), ...rarityStyle(card.rarity, rarities), ...style } as React.CSSProperties}
      onPointerMove={onMove}
      onPointerLeave={onLeave}
      {...(interactive
        ? { role: "button", tabIndex: disabled ? -1 : 0, "aria-disabled": disabled || undefined, "aria-pressed": selected ?? undefined, "aria-label": a11y,
            onClick: activate, onKeyDown: (e: React.KeyboardEvent) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); activate(); } } }
        : { role: "img", "aria-label": a11y })}
      {...props}
    >
      <div className="cz-tcard__inner">
        <div className="cz-tcard__face cz-tcard__front" aria-hidden={flipped || undefined}>
          <div className="cz-tcard__head">
            <span className="cz-tcard__name">{name}</span>
            {owned && card.stat && (
              <span className="cz-tcard__stat">{card.stat.label != null && <small>{card.stat.label}</small>}{card.stat.value}</span>
            )}
          </div>
          <div className="cz-tcard__art">
            {renderArt ? renderArt(card) : <GameIcon icon={card.art} alt="" />}
            {owned && card.badge != null && <span className="cz-tcard__badge">{card.badge}</span>}
          </div>
          <div className="cz-tcard__type">
            <span>{owned ? card.type : "Not collected yet"}</span>
            {owned && el && <span className="cz-tcard__element">{el.icon}{el.label}</span>}
          </div>
          {owned && (card.abilities?.length || card.flavor != null) ? (
            <div className="cz-tcard__body">
              {card.abilities?.map((a, i) => renderAbility ? <React.Fragment key={i}>{renderAbility(a, i, card)}</React.Fragment> : (
                <div key={i} className="cz-tcard__ability">
                  <div className="cz-tcard__ability-head">
                    {a.cost != null && <span className="cz-tcard__cost">{a.cost}</span>}
                    <span className="cz-tcard__ability-name">{a.name}</span>
                    {a.value != null && <span className="cz-tcard__ability-value">{a.value}</span>}
                  </div>
                  {a.text != null && <div className="cz-tcard__ability-text">{a.text}</div>}
                </div>
              ))}
              {card.flavor != null && <div className="cz-tcard__flavor">{card.flavor}</div>}
            </div>
          ) : <div className="cz-tcard__body cz-tcard__body--empty" />}
          <div className="cz-tcard__foot">
            {renderFooter ? renderFooter(card) : (
              <>
                <span>{card.footer?.number}</span>
                {card.rarity && <span className="cz-tcard__gem" title={rarityLabel(card.rarity, rarities)} aria-hidden />}
                <span className="cz-tcard__set">{card.footer?.set}{card.footer?.artist != null && <> · {card.footer.artist}</>}</span>
              </>
            )}
          </div>
          {foil !== "none" && <span className="cz-tcard__foil" aria-hidden />}
          <span className="cz-tcard__glare" aria-hidden />
        </div>
        <div className="cz-tcard__face cz-tcard__back" aria-hidden={!flipped || undefined}>
          {back ?? <div className="cz-tcard__back-art"><span className="cz-tcard__back-mark" /></div>}
        </div>
      </div>
    </div>
  );
}

type CardHandProps<T> = Omit<React.ComponentProps<"div">, "onSelect"> & {
  cards: CardData<T>[];
  size?: keyof typeof SIZES | number;
  selectedId?: string | null;
  onSelect?: (card: CardData<T>, index: number) => void;
  /** Total fan angle in degrees. Default 24. */
  spread?: number;
  /** Share of a card hidden under the next one, 0–0.9. Default 0.45. */
  overlap?: number;
  disabledIds?: string[];
  /** Extra props for every card (elements, rarities, renderers…). */
  cardProps?: Partial<Omit<ItemCardProps<T>, "card" | "size" | "selected" | "onSelect">>;
  label?: string;
};

/** Cards held in a fan. Hover or focus raises a card; the selected one stays up. */
function CardHand<T = unknown>({ cards, size = "sm", selectedId, onSelect, spread = 24, overlap = 0.45, disabledIds, cardProps, label = "Hand", className, style, ...props }: CardHandProps<T>) {
  const width = typeof size === "number" ? size : SIZES[size];
  const n = cards.length;
  return (
    <div data-slot="card-hand" role="group" aria-label={label} className={cn("cz-hand", className)} style={{ "--card-w": `${width}px`, "--overlap": overlap, "--n": n, ...style } as React.CSSProperties} {...props}>
      {cards.map((c, i) => {
        const t = n > 1 ? i / (n - 1) - 0.5 : 0;
        return (
          <div key={c.id} className="cz-hand__slot" style={{ "--a": `${t * spread}deg`, "--lift": `${Math.abs(t) * Math.abs(t) * width * 0.35}px`, zIndex: i } as React.CSSProperties} data-selected={selectedId === c.id || undefined}>
            <ItemCard card={c} size={width} tilt={false} selected={selectedId === c.id} disabled={disabledIds?.includes(c.id)} onSelect={onSelect ? () => onSelect(c, i) : undefined} {...cardProps} style={{ "--card-w": "var(--hand-card)", ...cardProps?.style } as React.CSSProperties} />
          </div>
        );
      })}
    </div>
  );
}

type CardGridProps<T> = Omit<React.ComponentProps<"div">, "onSelect"> & {
  cards: CardData<T>[];
  size?: keyof typeof SIZES | number;
  selectedId?: string | null;
  onSelect?: (card: CardData<T>, index: number) => void;
  /** Ids you own; others show as silhouettes. Omit to show all as owned. */
  ownedIds?: string[];
  cardProps?: Partial<Omit<ItemCardProps<T>, "card" | "size" | "selected" | "onSelect" | "owned">>;
  label?: string;
};

/** A responsive grid of cards (a deck, a binder page, a shop shelf). */
function CardGrid<T = unknown>({ cards, size = "sm", selectedId, onSelect, ownedIds, cardProps, label = "Cards", className, style, ...props }: CardGridProps<T>) {
  const width = typeof size === "number" ? size : SIZES[size];
  return (
    <div data-slot="card-grid" role="list" aria-label={label} className={cn("cz-cardgrid", className)} style={{ "--card-w": `${width}px`, ...style } as React.CSSProperties} {...props}>
      {cards.map((c, i) => (
        <div key={c.id} role="listitem" className="cz-cardgrid__cell">
          <ItemCard card={c} size={width} owned={ownedIds ? ownedIds.includes(c.id) : true} selected={selectedId === c.id} onSelect={onSelect ? () => onSelect(c, i) : undefined} {...cardProps} />
        </div>
      ))}
    </div>
  );
}

export { ItemCard, CardHand, CardGrid };
export type { ItemCardProps, CardHandProps, CardGridProps };
```

npm: `import { ItemCard, CardHand, CardGrid, DEFAULT_ELEMENTS } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
