# Integrate `FlipCard` from Motion Garden

You are helping me add the **FlipCard** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** FlipCard
- **Category:** Micro-interactions
- **Summary:** A grid card that flips out of its cell — GSAP Flip carries it to viewport center while it rotates to reveal its back face, then returns on close.
- **Reference:** https://motion-garden.netlify.app/components/flip-card
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add gsap lucide-react clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme inline {
  --color-raised: var(--sg-raised);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-raised: #eceaef;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-raised: #191d21;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/flip-card/flip-card.tsx`

```tsx
"use client";

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import gsap from "gsap";
import { Flip } from "gsap/Flip";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

gsap.registerPlugin(Flip);

const FOCUSABLE_SELECTOR =
  'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

export interface FlipCardItem {
  id: string;
  front: ReactNode;
  back: ReactNode;
}

export interface FlipCardProps {
  items: FlipCardItem[];
  flipDuration?: number;
  perspective?: number;
  expandedWidth?: number;
  expandedHeight?: number;
  backdropBlur?: number;
  reducedMotion?: boolean;
  className?: string;
  cardClassName?: string;
}

export default function FlipCard({
  items,
  flipDuration = 0.5,
  perspective = 1200,
  expandedWidth = 400,
  expandedHeight = 480,
  backdropBlur = 2,
  reducedMotion = false,
  className,
  cardClassName,
}: FlipCardProps) {
  const cardRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const cardInnerRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const placeholderRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const tlRef = useRef<gsap.core.Timeline | null>(null);
  const portalRef = useRef<HTMLDivElement | null>(null);

  const [activeId, setActiveId] = useState<string | null>(null);
  const [isAnimating, setIsAnimating] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [osReduced, setOsReduced] = useState(false);

  const reduce = osReduced || reducedMotion;

  useEffect(() => {
    setMounted(true);
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    setOsReduced(query.matches);
    const onChange = (e: MediaQueryListEvent) => setOsReduced(e.matches);
    query.addEventListener("change", onChange);
    return () => query.removeEventListener("change", onChange);
  }, []);

  useEffect(() => {
    const el = document.createElement("div");
    el.setAttribute("data-flip-card-portal", "");
    document.body.appendChild(el);
    portalRef.current = el;
    return () => {
      tlRef.current?.kill();
      el.remove();
      portalRef.current = null;
    };
  }, []);

  const handleOpen = useCallback(
    (id: string) => {
      if (isAnimating || activeId) return;

      const card = cardRefs.current[id];
      const cardInner = cardInnerRefs.current[id];
      const portal = portalRef.current;
      if (!card || !cardInner || !portal) return;

      setIsAnimating(true);
      setActiveId(id);
      tlRef.current?.kill();

      const flipState = Flip.getState(card);
      portal.appendChild(card);

      const width = Math.min(expandedWidth, window.innerWidth - 32);
      const height = Math.min(expandedHeight, window.innerHeight - 64);
      gsap.set(card, {
        position: "fixed",
        top: window.innerHeight / 2 - height / 2,
        left: window.innerWidth / 2 - width / 2,
        right: "auto",
        bottom: "auto",
        xPercent: 0,
        yPercent: 0,
        width,
        height,
        zIndex: 60,
      });

      const frontFace = cardInner.querySelector(".front-face");
      const backFace = cardInner.querySelector<HTMLElement>(".back-face");

      const tl = gsap.timeline({
        onComplete: () => {
          setIsAnimating(false);
          const focusable =
            backFace?.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
          (focusable ?? card).focus();
        },
      });
      tlRef.current = tl;

      if (reduce) {
        tl.add(
          Flip.from(flipState, {
            duration: flipDuration * 0.6,
            ease: "power2.inOut",
            absolute: true,
          }),
        )
          .to(frontFace, { opacity: 0, duration: 0.2 }, 0.1)
          .set(frontFace, { visibility: "hidden" })
          .set(cardInner, { rotateY: 180 })
          .set(backFace, { visibility: "visible", opacity: 0 })
          .to(backFace, { opacity: 1, duration: 0.2 });
      } else {
        tl.add(
          Flip.from(flipState, {
            duration: flipDuration,
            ease: "power3.inOut",
            absolute: true,
          }),
        )
          .to(
            cardInner,
            { rotateY: 90, duration: flipDuration / 2, ease: "power2.in" },
            flipDuration * 0.4,
          )
          .set(frontFace, { visibility: "hidden" })
          .set(backFace, { visibility: "visible", opacity: 1 })
          .to(cardInner, {
            rotateY: 180,
            duration: flipDuration / 2,
            ease: "power2.out",
          });
      }
    },
    [activeId, isAnimating, expandedWidth, expandedHeight, flipDuration, reduce],
  );

  const handleClose = useCallback(() => {
    if (isAnimating || !activeId) return;

    const id = activeId;
    const card = cardRefs.current[id];
    const cardInner = cardInnerRefs.current[id];
    const placeholder = placeholderRefs.current[id];
    if (!card || !cardInner || !placeholder) return;

    setIsAnimating(true);
    setActiveId(null);
    tlRef.current?.kill();

    const returnState = Flip.getState(card);

    gsap.set(placeholder, { zIndex: 50 });
    placeholder.appendChild(card);
    gsap.set(card, {
      clearProps:
        "position,top,left,right,bottom,xPercent,yPercent,width,height,zIndex",
    });

    const frontFace = cardInner.querySelector(".front-face");
    const backFace = cardInner.querySelector(".back-face");

    const tl = gsap.timeline({
      onComplete: () => {
        setIsAnimating(false);
        gsap.set(placeholder, { clearProps: "zIndex" });
        card.focus();
      },
    });
    tlRef.current = tl;

    if (reduce) {
      tl.to(backFace, { opacity: 0, duration: 0.2 })
        .set(backFace, { visibility: "hidden" })
        .set(cardInner, { rotateY: 0 })
        .set(frontFace, { visibility: "visible", opacity: 0 })
        .to(frontFace, { opacity: 1, duration: 0.2 })
        .add(
          Flip.from(returnState, {
            duration: flipDuration * 0.6,
            ease: "power2.inOut",
            absolute: true,
          }),
          0,
        );
    } else {
      tl.to(cardInner, {
        rotateY: 90,
        duration: flipDuration / 2,
        ease: "power2.in",
      })
        .set(backFace, { visibility: "hidden" })
        .set(frontFace, { visibility: "visible", opacity: 1 })
        .to(cardInner, {
          rotateY: 0,
          duration: flipDuration / 2,
          ease: "power2.out",
        })
        .add(
          Flip.from(returnState, {
            duration: flipDuration,
            ease: "power3.inOut",
            absolute: true,
          }),
          flipDuration * 0.4,
        );
    }
  }, [activeId, isAnimating, flipDuration, reduce]);

  useEffect(() => {
    if (!activeId) return;

    document.body.classList.add("overflow-hidden");

    const onKey = (e: KeyboardEvent) => {
      if (e.key !== "Escape") return;
      const card = cardRefs.current[activeId];
      const dialogs = document.querySelectorAll(
        '[role="dialog"][aria-modal="true"]',
      );
      if (Array.from(dialogs).some((node) => node !== card)) return;
      e.preventDefault();
      handleClose();
    };

    const onClickOutside = (e: MouseEvent) => {
      const card = cardRefs.current[activeId];
      if (card && !card.contains(e.target as Node)) handleClose();
    };

    window.addEventListener("keydown", onKey);
    const timeoutId = setTimeout(() => {
      document.addEventListener("mousedown", onClickOutside);
    }, 100);

    return () => {
      document.body.classList.remove("overflow-hidden");
      window.removeEventListener("keydown", onKey);
      clearTimeout(timeoutId);
      document.removeEventListener("mousedown", onClickOutside);
    };
  }, [activeId, handleClose]);

  useEffect(() => {
    if (!activeId || isAnimating) return;
    const card = cardRefs.current[activeId];
    if (!card) return;

    const recenter = () => {
      const width = Math.min(expandedWidth, window.innerWidth - 32);
      const height = Math.min(expandedHeight, window.innerHeight - 64);
      gsap.set(card, {
        top: window.innerHeight / 2 - height / 2,
        left: window.innerWidth / 2 - width / 2,
        width,
        height,
      });
    };
    recenter();
    window.addEventListener("resize", recenter);
    return () => window.removeEventListener("resize", recenter);
  }, [activeId, isAnimating, expandedWidth, expandedHeight]);

  return (
    <>
      {mounted &&
        createPortal(
          <div
            aria-hidden
            onClick={handleClose}
            className={cn(
              "fixed inset-0 z-50 bg-white/40 transition-opacity duration-300 dark:bg-black/50",
              activeId
                ? "pointer-events-auto opacity-100"
                : "pointer-events-none opacity-0",
            )}
            style={{
              backdropFilter: activeId ? `blur(${backdropBlur}px)` : undefined,
            }}
          />,
          document.body,
        )}

      <div className={cn("grid grid-cols-3 gap-3", className)}>
        {items.map((item) => {
          const isActive = activeId === item.id;
          const isOtherActive = Boolean(activeId) && !isActive;
          return (
            <div
              key={item.id}
              ref={(el) => {
                placeholderRefs.current[item.id] = el;
              }}
              className="relative"
              style={{ aspectRatio: "1 / 1" }}
            >
              <div
                ref={(el) => {
                  cardRefs.current[item.id] = el;
                }}
                role={isActive ? "dialog" : "button"}
                aria-modal={isActive || undefined}
                aria-haspopup="dialog"
                tabIndex={isOtherActive ? -1 : 0}
                onClick={() => handleOpen(item.id)}
                onKeyDown={(e) => {
                  if (isActive) return;
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    handleOpen(item.id);
                  }
                }}
                className={cn(
                  "group absolute inset-0 cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-accent/60",
                  cardClassName,
                )}
                style={{
                  perspective: `${perspective}px`,
                  opacity: isOtherActive ? 0.3 : 1,
                  pointerEvents: isAnimating || isOtherActive ? "none" : "auto",
                  transition: "opacity 0.3s ease",
                }}
              >
                <div
                  ref={(el) => {
                    cardInnerRefs.current[item.id] = el;
                  }}
                  className="relative h-full w-full"
                  style={{ transformStyle: "preserve-3d" }}
                >
                  <div
                    className="front-face absolute inset-0 h-full w-full overflow-hidden"
                    style={{ backfaceVisibility: "hidden" } as CSSProperties}
                  >
                    <div className="h-full w-full transition-transform duration-500 ease-out group-hover:scale-[0.98]">
                      {item.front}
                    </div>
                  </div>

                  <div
                    className="back-face absolute inset-0 h-full w-full overflow-hidden"
                    style={
                      {
                        backfaceVisibility: "hidden",
                        transform: "rotateY(180deg)",
                        visibility: "hidden",
                      } as CSSProperties
                    }
                  >
                    {item.back}
                    {isActive && (
                      <button
                        type="button"
                        aria-label="Close"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleClose();
                        }}
                        className="absolute top-3 right-3 z-10 rounded-md p-1.5 text-ink-dim transition-colors hover:bg-raised hover:text-ink"
                      >
                        <X className="size-4" />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `flipDuration` | `number` | `0.5` | Duration of the Flip flight; rotation timing derives from it. Range 0.2–1.2 s. |
| `perspective` | `number` | `1200` | 3D perspective depth on each card. Range 400–2400 px. |
| `expandedWidth` | `number` | `400` | Expanded card width (clamped to the viewport). Range 280–640 px. |
| `expandedHeight` | `number` | `480` | Expanded card height (clamped to the viewport). Range 320–720 px. |
| `backdropBlur` | `number` | `2` | Backdrop scrim blur while a card is open. Range 0–16 px. |

## Usage

```tsx
import FlipCard from "@/components/registry/flip-card/flip-card";

<FlipCard
  flipDuration={0.5}
  perspective={1200}
  expandedWidth={400}
  expandedHeight={480}
  backdropBlur={2}
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
