# Integrate `Holofoil` from Motion Garden

You are helping me add the **Holofoil** 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:** Holofoil
- **Category:** Micro-interactions
- **Summary:** Holographic trading-card foil over real content. The diffraction band travels against the tilt while the specular follows it, and the flake only lights where the rainbow currently falls, which is what stops the whole thing reading as one gradient sliding around.
- **Reference:** https://motion-garden.netlify.app/components/holofoil
- **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
# Holofoil needs no npm packages
```

## 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/holofoil/holofoil.tsx`

```tsx
"use client";

import { memo, useEffect, useRef, type ReactNode } from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type HolofoilPattern = "rainbow" | "reverse" | "cosmic" | "linear" | "none";
export type HolofoilBlend =
  | "color-dodge"
  | "screen"
  | "overlay"
  | "hard-light"
  | "plus-lighter";

export interface HolofoilProps {
  children?: ReactNode;
  maxTilt?: number;
  perspective?: number;
  foil?: HolofoilPattern;
  foilIntensity?: number;
  sparkle?: number;
  glare?: number;
  idleDrift?: number;
  settle?: number;
  blendMode?: HolofoilBlend;
  sheenColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const FOIL_LAYERS: Record<Exclude<HolofoilPattern, "none">, string> = {
  rainbow:
    "repeating-linear-gradient(115deg, #ff2f6a 0%, #ffdd55 8%, #4dff9b 16%, #35d7ff 24%, #9b6bff 32%, #ff2f6a 40%)",
  reverse:
    "repeating-linear-gradient(-115deg, #35d7ff 0%, #9b6bff 8%, #ff2f6a 16%, #ffdd55 24%, #4dff9b 32%, #35d7ff 40%)",
  cosmic:
    "conic-gradient(from 210deg, #ff2f6a, #ffdd55, #4dff9b, #35d7ff, #9b6bff, #ff2f6a)",
  linear:
    "linear-gradient(115deg, transparent 30%, #ffffff 48%, #cbd5ff 52%, transparent 70%)",
};

const Holofoil = memo(
  ({
    children,
    maxTilt = 14,
    perspective = 800,
    foil = "rainbow",
    foilIntensity = 0.75,
    sparkle = 0.5,
    glare = 0.45,
    idleDrift = 0.2,
    settle = 0.12,
    blendMode = "color-dodge",
    sheenColor = "#a855f7",
    paused = false,
    reducedMotion = false,
    className,
  }: HolofoilProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const cardRef = useRef<HTMLDivElement>(null);
    const foilRef = useRef<HTMLDivElement>(null);
    const sparkleRef = useRef<HTMLDivElement>(null);
    const glareRef = useRef<HTMLDivElement>(null);

    const live = useRef({
      maxTilt, perspective, foil, foilIntensity, sparkle, glare,
      idleDrift, settle, blendMode, sheenColor, reducedMotion,
    });
    live.current = {
      maxTilt, perspective, foil, foilIntensity, sparkle, glare,
      idleDrift, settle, blendMode, sheenColor, reducedMotion,
    };

    const state = useRef({ tx: 0, ty: 0, x: 0, y: 0, drift: 0, over: false });

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused,
      onFrame: ({ dt }) => {
        const l = live.current;
        const s = state.current;

        if (!s.over && !l.reducedMotion) {
          s.drift += dt * l.idleDrift;
          s.tx = Math.sin(s.drift * 1.7) * 0.55;
          s.ty = Math.cos(s.drift * 1.1) * 0.4;
        }

        const k = l.reducedMotion ? 1 : Math.min(1, dt / Math.max(l.settle, 0.02));
        s.x += (s.tx - s.x) * k;
        s.y += (s.ty - s.y) * k;

        const card = cardRef.current;
        if (card) {
          card.style.transform =
            `rotateY(${(s.x * l.maxTilt).toFixed(3)}deg) rotateX(${(-s.y * l.maxTilt).toFixed(3)}deg)`;
        }

        const foilEl = foilRef.current;
        if (foilEl) {
          const px = 50 - s.x * 60;
          const py = 50 - s.y * 60;
          foilEl.style.backgroundPosition = `${px.toFixed(2)}% ${py.toFixed(2)}%`;
          foilEl.style.opacity = String(
            l.foil === "none" ? 0 : Math.min(1, l.foilIntensity * (0.55 + 0.45 * Math.abs(s.x))),
          );
        }

        const sparkleEl = sparkleRef.current;
        if (sparkleEl) {
          sparkleEl.style.backgroundPosition = `${(50 - s.x * 90).toFixed(2)}% ${(50 - s.y * 90).toFixed(2)}%`;
          sparkleEl.style.maskPosition = `${(50 - s.x * 60).toFixed(2)}% ${(50 - s.y * 60).toFixed(2)}%`;
          sparkleEl.style.opacity = String(Math.min(1, l.sparkle * 0.8));
        }

        const glareEl = glareRef.current;
        if (glareEl) {
          glareEl.style.backgroundPosition = `${(50 + s.x * 55).toFixed(2)}% ${(50 + s.y * 55).toFixed(2)}%`;
          glareEl.style.opacity = String(Math.min(1, l.glare * (0.4 + 0.6 * Math.hypot(s.x, s.y))));
        }
      },
      deps: [],
    });

    useEffect(() => {
      const foilEl = foilRef.current;
      if (foilEl) {
        foilEl.style.backgroundImage =
          foil === "none" ? "none" : FOIL_LAYERS[foil];
        foilEl.style.backgroundSize = foil === "cosmic" ? "180% 180%" : "260% 260%";
        foilEl.style.mixBlendMode = blendMode;
      }
      const glareEl = glareRef.current;
      if (glareEl) {
        glareEl.style.backgroundImage = `radial-gradient(60% 55% at 50% 50%, ${sheenColor}cc 0%, #ffffff66 35%, transparent 72%)`;
      }
      loop.paint();
    }, [foil, blendMode, sheenColor, loop]);

    useEffect(() => {
      loop.paint();
    }, [maxTilt, perspective, foilIntensity, sparkle, glare, idleDrift, settle, loop]);

    const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
      if (e.pointerType === "touch" || live.current.reducedMotion) return;
      const r = e.currentTarget.getBoundingClientRect();
      if (r.width === 0 || r.height === 0) return;
      const s = state.current;
      s.over = true;
      s.tx = ((e.clientX - r.left) / r.width) * 2 - 1;
      s.ty = ((e.clientY - r.top) / r.height) * 2 - 1;
      loop.start();
    };

    const onPointerLeave = () => {
      state.current.over = false;
      loop.start();
    };

    return (
      <div
        ref={containerRef}
        className={className ?? "relative"}
        style={{ perspective: `${perspective}px` }}
        onPointerMove={onPointerMove}
        onPointerLeave={onPointerLeave}
      >
        <div
          ref={cardRef}
          className="relative isolate overflow-hidden rounded-2xl"
          style={{ transformStyle: "preserve-3d", willChange: "transform" }}
        >
          {children}

          <div
            ref={foilRef}
            aria-hidden
            className="pointer-events-none absolute inset-0"
            style={{ backgroundRepeat: "repeat" }}
          />

          <div
            ref={sparkleRef}
            aria-hidden
            className="pointer-events-none absolute inset-0"
            style={{
              mixBlendMode: "color-dodge",
              backgroundImage:
                "radial-gradient(#ffffff 0.7px, transparent 0.8px), radial-gradient(#ffffff 0.5px, transparent 0.6px)",
              backgroundSize: "37px 41px, 23px 29px",
              backgroundPosition: "50% 50%",
              maskImage:
                "repeating-linear-gradient(115deg, #000 0%, #fff 8%, #000 16%)",
              maskSize: "260% 260%",
            }}
          />

          <div
            ref={glareRef}
            aria-hidden
            className="pointer-events-none absolute inset-0"
            style={{ mixBlendMode: "plus-lighter", backgroundSize: "180% 180%" }}
          />
        </div>
      </div>
    );
  },
);

Holofoil.displayName = "Holofoil";

export default Holofoil;
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `maxTilt` | `number` | `14` | Maximum lean at the card's edge. The tilt is only the carrier here — set it to zero and the foil still moves, because the bands are driven by pointer position rather than by the rotation. Range 0–30 °. |
| `perspective` | `number` | `800` | Depth of the projection. Lower exaggerates the lean; the value that reads as expensive is nearly always further away than instinct suggests. Range 300–2400 px. |
| `foil` | `"rainbow" | "reverse" | "cosmic" | "linear" | "none"` | `"rainbow"` | Which diffraction pattern the laminate carries. Rainbow is the repeating twelve-stop spectrum a real holographic sheet produces — it repeats rather than running one rainbow across the card. Reverse runs it the other way so the band travels against the tilt, which is what most people actually recognise as foil. |
| `foilIntensity` | `number` | `0.75` | Strength of the diffraction band. Past about one it stops being laminate and starts being a sticker. Range 0–1.5. Ignored while `foil` is `none`. |
| `sparkle` | `number` | `0.5` | Density of the flake. It is masked by the diffraction band rather than laid over the card, and that coupling is the entire reason the specks read as suspended inside the laminate instead of as dust on your screen. Range 0–1.5. |
| `glare` | `number` | `0.45` | The broad specular band, kept separate from the foil on purpose. Foil is diffraction and moves against the tilt; glare is reflection and follows it. Running both, opposed, is what gives the surface a material. Range 0–1.2. |
| `idleDrift` | `number` | `0.2` | How much the foil keeps moving with no pointer on it, on two incommensurate rates so the idle never settles into an obvious period. A card in a case is never quite still, and a completely dead card in a grid reads as an image rather than an object. Range 0–1 ×. |
| `settle` | `number` | `0.12` | Seconds the card takes to catch up to the pointer. Near zero it is welded to the cursor and reads as a texture map; too high and it lags far enough that the foil stops feeling attached to your hand. Range 0.02–0.5. |
| `blendMode` | `"color-dodge" | "screen" | "overlay" | "hard-light" | "plus-lighter"` | `"color-dodge"` | How the foil composites onto whatever you wrapped. Colour-dodge behaves like real foil — it blows out where the card is already bright and does almost nothing in the shadows. Screen is the safe one on a light card. |
| `sheenColor` | `string (hex)` | `"#a855f7"` | The colour carried by the specular sheen. |

## Usage

```tsx
import Holofoil from "@/components/registry/holofoil/holofoil";

<Holofoil
  maxTilt={14}
  perspective={800}
  foil="rainbow"
  foilIntensity={0.75}
  sparkle={0.5}
  glare={0.45}
  idleDrift={0.2}
  settle={0.12}
  blendMode="color-dodge"
  sheenColor="#a855f7"
/>
```

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`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. 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.
