# Integrate `HorizonAurora` from Motion Garden

You are helping me add the **HorizonAurora** 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:** HorizonAurora
- **Category:** Backgrounds
- **Summary:** Smoky first light rising off a curved horizon. A domain-warped fbm field is sheared along a slow lean, so the noise stretches into strands of smoke, and a thin bright rim pools right on the horizon line the way light gathers at the edge of a planet. Move the pointer over it and the plume leans toward it and climbs to meet it, then drifts home when you leave. The horizon lies along the bottom edge or the top, and sits wherever you put it: right on the edge as a footer or header glow, or moved in with dark ground behind it.
- **Reference:** https://motion-garden.netlify.app/components/horizon-aurora
- **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
# HorizonAurora 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/horizon-aurora/horizon-aurora.tsx`

```tsx
"use client";

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

export interface HorizonAuroraProps {
  position?: "bottom" | "top";
  horizon?: number;
  curvature?: number;
  reach?: number;
  speed?: number;
  intensity?: number;
  pull?: number;
  coreColor?: string;
  hazeColor?: string;
  skyColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const VERTEX = `
attribute vec2 position;
void main() { gl_Position = vec4(position, 0.0, 1.0); }
`;

const FRAGMENT = `
precision highp float;
uniform vec2 uRes;
uniform float uFlip;
uniform float uTime;
uniform vec3 uPointer; // x, y, pull (0 to 1)
uniform vec3 uCore;
uniform vec3 uHaze;
uniform float uHorizon;
uniform float uCurve;
uniform float uReach;
uniform float uIntensity;

// Sin-free hash: stays stable as the drift carries the noise coordinates far from the origin.
float hash(vec2 p) {
  vec3 p3 = fract(vec3(p.xyx) * 0.1031);
  p3 += dot(p3, p3.yzx + 33.33);
  return fract((p3.x + p3.y) * p3.z);
}
float noise(vec2 p) {
  vec2 i = floor(p), f = fract(p), u = f * f * (3.0 - 2.0 * f);
  return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
             mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}
float fbm(vec2 p) {
  float v = 0.0, a = 0.5;
  for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + vec2(17.3, 9.1); a *= 0.5; }
  return v;
}

void main() {
  vec2 frag = gl_FragCoord.xy;
  if (uFlip > 0.5) frag.y = uRes.y - frag.y;
  vec2 p = frag / uRes.y;
  float aspect = uRes.x / uRes.y;
  float cx = p.x - aspect * 0.5;
  float t = uTime;

  // The horizon arcs down at the edges, so the light tapers into the corners.
  float d = p.y - uHorizon + cx * cx * (uCurve / aspect);

  // Near the pointer the strands lean toward it and the light climbs to meet it.
  float dx = uPointer.x - p.x;
  float near = uPointer.z * exp(-dx * dx * 1.6) * exp(-max(uPointer.y - uHorizon - 0.3 * uReach, 0.0) * 1.5);
  float lean = 0.3 * sin(t * 0.07 + cx * 1.3) + clamp(dx, -0.7, 0.7) * near * 2.4;

  // Shear the field along the lean: noise stretched that way reads as strands of smoke.
  vec2 q = vec2(cx - d * lean, d / uReach);
  vec2 warp = vec2(fbm(q * vec2(1.4, 2.2) + vec2(t * 0.04, -t * 0.07)),
                   fbm(q * vec2(1.4, 2.2) + vec2(5.2, 1.3) - t * 0.05));
  float body = fbm(vec2(q.x * 1.6 + warp.x * 1.2 + t * 0.03, q.y * 1.4 + warp.y * 0.8 - t * 0.06));
  float strands = fbm(vec2(q.x * 7.0 + warp.x * 2.5, q.y * 1.1 - t * 0.09));

  float reach = (0.06 + 0.24 * body * body + near * 0.3) * uReach;
  float density = exp(-max(d, 0.0) / reach) * (0.35 + 1.3 * strands * body) * (1.0 + 0.9 * near);
  // A bright rim right on the horizon, the way light pools at the edge of a planet.
  density += exp(-max(d, 0.0) / 0.025) * 0.45;
  density *= smoothstep(-0.03, 0.0, d);
  // Gone before the top edge, wherever the horizon sits and whatever the pointer pulls up.
  density *= 1.0 - smoothstep(0.45 * uReach, 0.95 * uReach, d);
  density *= 1.0 - smoothstep(0.82, 1.0, p.y);
  density *= uIntensity;

  // Thin smoke falls off fast, and it blends mostly as light:
  // alpha below coverage, so the sky behind stays lit.
  float a = pow(clamp(density, 0.0, 1.0), 1.5);
  vec3 col = mix(uHaze, uCore, smoothstep(0.35, 0.95, density));
  gl_FragColor = vec4(col * a, a * 0.7);
}
`;

function hexToRgb01(hex: string): [number, number, number] {
  let h = hex.replace("#", "").trim();
  if (h.length === 3)
    h = h
      .split("")
      .map((c) => c + c)
      .join("");
  if (h.length !== 6) return [1, 1, 1];
  const n = parseInt(h, 16);
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}

function compile(gl: WebGLRenderingContext, type: number, source: string) {
  const shader = gl.createShader(type);
  if (!shader) return null;
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  return gl.getShaderParameter(shader, gl.COMPILE_STATUS) ? shader : null;
}

export default function HorizonAurora({
  position = "bottom",
  horizon = 0,
  curvature = 0,
  reach = 1,
  speed = 1,
  intensity = 1,
  pull = 1,
  coreColor = "#e9d5ff",
  hazeColor = "#a855f7",
  skyColor = "#07060b",
  paused = false,
  reducedMotion = false,
  className = "",
}: HorizonAuroraProps) {
  const ref = useRef<HTMLDivElement>(null);
  const draw = useRef<((dt: number) => void) | null>(null);
  const sized = useRef<((w: number, h: number) => void) | null>(null);
  const fallback = useRef<HTMLDivElement>(null);

  const live = useRef({ position, horizon, curvature, reach, speed, intensity, pull, coreColor, hazeColor });
  live.current = { position, horizon, curvature, reach, speed, intensity, pull, coreColor, hazeColor };

  const loop = useAnimationLoop({
    target: ref,
    halted: paused || reducedMotion,
    dpr: 1,
    onResize: ({ bufferWidth, bufferHeight }) => sized.current?.(bufferWidth, bufferHeight),
    onFrame: ({ dt }) => (draw.current ? draw.current(reducedMotion ? 0 : dt) : false),
  });

  useEffect(() => {
    const host = ref.current;
    if (!host) return;
    const canvas = document.createElement("canvas");
    canvas.className = "absolute inset-0 size-full";
    const gl = canvas.getContext("webgl", { alpha: true, premultipliedAlpha: true, antialias: false });
    const vs = gl && compile(gl, gl.VERTEX_SHADER, VERTEX);
    const fs = gl && compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
    const program = gl?.createProgram();
    if (gl && vs && fs && program) {
      gl.attachShader(program, vs);
      gl.attachShader(program, fs);
      gl.linkProgram(program);
    }
    if (!gl || !program || !gl.getProgramParameter(program, gl.LINK_STATUS)) {
      fallback.current?.removeAttribute("hidden");
      return () => fallback.current?.setAttribute("hidden", "");
    }
    host.append(canvas);
    gl.useProgram(program);

    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
    const position = gl.getAttribLocation(program, "position");
    gl.enableVertexAttribArray(position);
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);

    const at = (name: string) => gl.getUniformLocation(program, name);
    const uRes = at("uRes");
    const uFlip = at("uFlip");
    const uTime = at("uTime");
    const uPointer = at("uPointer");
    const uCore = at("uCore");
    const uHaze = at("uHaze");
    const uHorizon = at("uHorizon");
    const uCurve = at("uCurve");
    const uReach = at("uReach");
    const uIntensity = at("uIntensity");

    const target = { x: 0, y: 0, pull: 0 };
    const eased = { x: 0, y: 0, pull: 0 };
    let time = 40;

    const onMove = (e: PointerEvent) => {
      const rect = host.getBoundingClientRect();
      if (!rect.height) return;
      const inside =
        e.pointerType !== "touch" &&
        e.clientX >= rect.left &&
        e.clientX <= rect.right &&
        e.clientY >= rect.top &&
        e.clientY <= rect.bottom;
      target.pull = inside ? 1 : 0;
      if (!inside) return;
      target.x = (e.clientX - rect.left) / rect.height;
      target.y = (live.current.position === "top" ? e.clientY - rect.top : rect.bottom - e.clientY) / rect.height;
      if (eased.pull < 0.01) Object.assign(eased, { x: target.x, y: target.y });
    };
    const onLeave = () => {
      target.pull = 0;
    };
    window.addEventListener("pointermove", onMove, { passive: true });
    document.documentElement.addEventListener("pointerleave", onLeave);

    sized.current = (w, h) => {
      canvas.width = w;
      canvas.height = h;
      gl.viewport(0, 0, w, h);
      gl.uniform2f(uRes, w, h);
    };
    draw.current = (dt) => {
      const l = live.current;
      time += dt * l.speed;
      const k = Math.min(1, dt * 2.2);
      eased.x += (target.x - eased.x) * k;
      eased.y += (target.y - eased.y) * k;
      const rate = target.pull > eased.pull ? 1.5 : 0.9;
      eased.pull += (target.pull - eased.pull) * Math.min(1, dt * rate);
      gl.uniform1f(uTime, time);
      gl.uniform1f(uFlip, l.position === "top" ? 1 : 0);
      gl.uniform3f(uPointer, eased.x, eased.y, eased.pull * l.pull);
      gl.uniform3fv(uCore, hexToRgb01(l.coreColor));
      gl.uniform3fv(uHaze, hexToRgb01(l.hazeColor));
      gl.uniform1f(uHorizon, l.horizon);
      gl.uniform1f(uCurve, l.curvature);
      gl.uniform1f(uReach, Math.max(0.05, l.reach));
      gl.uniform1f(uIntensity, l.intensity);
      gl.drawArrays(gl.TRIANGLES, 0, 3);
    };
    loop.resize();
    loop.start();

    return () => {
      window.removeEventListener("pointermove", onMove);
      document.documentElement.removeEventListener("pointerleave", onLeave);
      draw.current = null;
      sized.current = null;
      canvas.remove();
      gl.getExtension("WEBGL_lose_context")?.loseContext();
    };
  }, [loop]);

  useEffect(() => {
    loop.paint();
  }, [position, horizon, curvature, reach, intensity, pull, coreColor, hazeColor, loop]);

  return (
    <div
      ref={ref}
      aria-hidden
      className={`pointer-events-none relative h-full w-full overflow-hidden ${className}`.trim()}
      style={{ backgroundColor: skyColor }}
    >
      <div
        ref={fallback}
        hidden
        className="absolute inset-x-0"
        style={{
          [position]: `${horizon * 100}%`,
          height: "70%",
          background: `radial-gradient(60% 100% at 50% ${position === "top" ? "0%" : "100%"}, ${hazeColor}66, ${hazeColor}1a 55%, transparent)`,
        }}
      />
    </div>
  );
}
```

### 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 |
| --- | --- | --- | --- |
| `position` | `"bottom" | "top"` | `"bottom"` | Which edge the horizon lies along. Bottom rises off a footer; top flips the whole field so the light hangs down from a header, and the pointer pull follows it. |
| `horizon` | `number` | `0` | How far the horizon sits from its edge, as a fraction of the height. 0 lays it on the edge itself, so a border or hairline reads as the horizon; move it in and dark ground opens up behind it. Range 0–0.8. |
| `curvature` | `number` | `0` | How far the horizon bows down toward the corners. The light follows it, so the glow tapers off at the sides. Range 0–1. |
| `reach` | `number` | `1` | How high the smoke climbs off the horizon. Range 0.4–2 ×. |
| `speed` | `number` | `1` | Drift rate of the smoke. Accumulated per frame, so retuning it never jumps the field. Range 0–3 ×. |
| `intensity` | `number` | `1` | Density of the smoke, and with it the brightness. Range 0.2–2 ×. |
| `pull` | `number` | `1` | How hard the plume leans toward the pointer and climbs to meet it. 0 leaves it drifting on its own. Range 0–1. |
| `coreColor` | `string (hex)` | `"#e9d5ff"` | The dense heart of the smoke and the rim on the horizon. |
| `hazeColor` | `string (hex)` | `"#a855f7"` | The thin smoke at the edges, where the light fades into the sky. |
| `skyColor` | `string (hex)` | `"#07060b"` | The sky behind the light. The smoke blends mostly as light, so it wants a dark sky to read. |

## Usage

```tsx
import HorizonAurora from "@/components/registry/horizon-aurora/horizon-aurora";

<HorizonAurora
  position="bottom"
  horizon={0}
  curvature={0}
  reach={1}
  speed={1}
  intensity={1}
  pull={1}
  coreColor="#e9d5ff"
  hazeColor="#a855f7"
  skyColor="#07060b"
/>
```

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.
