# Integrate `RubiksCube` from Motion Garden

You are helping me add the **RubiksCube** 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:** RubiksCube
- **Category:** Power-User Systems
- **Summary:** A Rubik's cube that scrambles and solves itself on an endless loop while spinning like a planet. Two independent rotation layers, and every quarter-turn is quantised back to exact integers, so an hour of turns drifts by nothing at all.
- **Reference:** https://motion-garden.netlify.app/components/rubiks-cube
- **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 three @react-three/fiber clsx tailwind-merge
```

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

```tsx
"use client";

import { Canvas, useFrame, useThree } from "@react-three/fiber";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { cn } from "@/lib/utils";

export type CubeFace = "up" | "down" | "right" | "left" | "front" | "back";
export type CubePalette = "classic" | "amethyst" | "mono" | "neon";

export interface RubiksCubeProps {
  autoRotate?: boolean;
  rotationSpeed?: number;
  moveDuration?: number;
  scrambleMoveCount?: number;
  pauseBetweenCycles?: number;
  cameraDistance?: number;
  gap?: number;
  palette?: CubePalette;
  colors?: Partial<Record<CubeFace, string>>;
  bodyColor?: string;
  background?: string;
  transparent?: boolean;
  glossy?: boolean;
  glow?: boolean;
  paused?: boolean;
  reducedMotion?: boolean;
  onReady?: () => void;
  className?: string;
}

type Axis = 0 | 1 | 2;
type Layer = -1 | 0 | 1;
type Dir = 1 | -1;
interface Move {
  axis: Axis;
  layer: Layer;
  dir: Dir;
}

const QUARTER = Math.PI / 2;
const DEG = Math.PI / 180;

const ORBIT_AZIMUTH = 0.7;
const ORBIT_ELEVATION = 0.42;

function orbitPosition(radius: number): [number, number, number] {
  const ce = Math.cos(ORBIT_ELEVATION);
  return [
    radius * ce * Math.sin(ORBIT_AZIMUTH),
    radius * Math.sin(ORBIT_ELEVATION),
    radius * ce * Math.cos(ORBIT_AZIMUTH),
  ];
}
const BASE_SPIN = 13;
const SWIPE_MIN = 2;
const AXIS_EASE = 3;
const STICKER_SCALE = 0.86;
const AXIS_KEY = ["x", "y", "z"] as const;
const AXIS_VEC = [
  new THREE.Vector3(1, 0, 0),
  new THREE.Vector3(0, 1, 0),
  new THREE.Vector3(0, 0, 1),
] as const;

interface FaceSpec {
  face: CubeFace;
  axis: Axis;
  sign: Dir;
  normal: [number, number, number];
  rotation: [number, number, number];
}

const FACES: readonly FaceSpec[] = [
  { face: "right", axis: 0, sign: 1, normal: [1, 0, 0], rotation: [0, QUARTER, 0] },
  { face: "left", axis: 0, sign: -1, normal: [-1, 0, 0], rotation: [0, -QUARTER, 0] },
  { face: "up", axis: 1, sign: 1, normal: [0, 1, 0], rotation: [-QUARTER, 0, 0] },
  { face: "down", axis: 1, sign: -1, normal: [0, -1, 0], rotation: [QUARTER, 0, 0] },
  { face: "front", axis: 2, sign: 1, normal: [0, 0, 1], rotation: [0, 0, 0] },
  { face: "back", axis: 2, sign: -1, normal: [0, 0, -1], rotation: [0, Math.PI, 0] },
];

const PALETTES: Record<CubePalette, Record<CubeFace, string>> = {
  classic: {
    up: "#f4f4f2",
    down: "#ffd500",
    right: "#c41e3a",
    left: "#ff5800",
    front: "#009b48",
    back: "#0051ba",
  },
  amethyst: {
    up: "#f3e9ff",
    down: "#a855f7",
    right: "#7c3aed",
    left: "#d2abfd",
    front: "#5b21b6",
    back: "#2e1065",
  },
  mono: {
    up: "#fafafa",
    down: "#16161a",
    right: "#8a8a94",
    left: "#4a4a52",
    front: "#c9c9d1",
    back: "#2a2a30",
  },
  neon: {
    up: "#eafcff",
    down: "#ffe600",
    right: "#ff2d78",
    left: "#ff8a00",
    front: "#00ffa3",
    back: "#00c8ff",
  },
};

interface CubieSpec {
  key: string;
  coord: [number, number, number];
  stickers: { face: CubeFace; position: [number, number, number]; rotation: [number, number, number] }[];
}

const CUBIES: readonly CubieSpec[] = (() => {
  const out: CubieSpec[] = [];
  for (let x = -1; x <= 1; x++) {
    for (let y = -1; y <= 1; y++) {
      for (let z = -1; z <= 1; z++) {
        const stickers = FACES.filter((f) => (f.axis === 0 ? x : f.axis === 1 ? y : z) === f.sign).map(
          (f) => ({
            face: f.face,
            position: [f.normal[0] * 0.501, f.normal[1] * 0.501, f.normal[2] * 0.501] as [
              number,
              number,
              number,
            ],
            rotation: f.rotation,
          }),
        );
        out.push({ key: `${x}:${y}:${z}`, coord: [x, y, z], stickers });
      }
    }
  }
  return out;
})();

function easeTurn(t: number): number {
  const c1 = 1.12;
  const c3 = c1 + 1;
  const u = t - 1;
  return 1 + c3 * u * u * u + c1 * u * u;
}

function makeScramble(count: number): Move[] {
  const out: Move[] = [];
  let lastAxis = -1;
  for (let i = 0; i < count; i++) {
    let axis: Axis;
    do {
      axis = Math.floor(Math.random() * 3) as Axis;
    } while (axis === lastAxis);
    lastAxis = axis;
    out.push({
      axis,
      layer: (Math.floor(Math.random() * 3) - 1) as Layer,
      dir: Math.random() < 0.5 ? 1 : -1,
    });
  }
  return out;
}

function invert(moves: Move[]): Move[] {
  return moves
    .slice()
    .reverse()
    .map((m) => ({ axis: m.axis, layer: m.layer, dir: -m.dir as Dir }));
}

const GLOW_VERT =  `
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const GLOW_FRAG =  `
uniform vec3 uColor;
uniform float uIntensity;
varying vec2 vUv;
void main() {
  float r = clamp(length(vUv - 0.5) * 2.0, 0.0, 1.0);
  float d = 1.0 - r;
  float a = pow(d, 2.6) * 0.8 + pow(d, 1.15) * 0.28;
  gl_FragColor = vec4(uColor * a * uIntensity, 1.0);
}
`;

const DOME_HEIGHT = 0.08;

function makeStickerGeometry(): THREE.BufferGeometry {
  const g = new THREE.PlaneGeometry(1, 1, 20, 20);
  const pos = g.attributes.position;
  for (let i = 0; i < pos.count; i++) {
    const x = Math.abs(pos.getX(i)) * 2;
    const y = Math.abs(pos.getY(i)) * 2;
    const r = Math.min(1, Math.pow(x ** 4 + y ** 4, 0.25));
    pos.setZ(i, Math.cos(r * Math.PI * 0.5) * DOME_HEIGHT);
  }
  pos.needsUpdate = true;
  g.computeVertexNormals();
  return g;
}

const SKY_VERT =  `
varying vec3 vPos;
void main() {
  vPos = position;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const SKY_FRAG =  `
uniform vec3 uTop;
uniform vec3 uBottom;
varying vec3 vPos;
void main() {
  float t = clamp(normalize(vPos).y * 0.5 + 0.5, 0.0, 1.0);
  gl_FragColor = vec4(mix(uBottom, uTop, t), 1.0);
}
`;

function buildEnvScene(): { scene: THREE.Scene; dispose: () => void } {
  const scene = new THREE.Scene();
  const geo = new THREE.PlaneGeometry(1, 1);
  const mats: THREE.Material[] = [];
  const strip = (
    color: string,
    intensity: number,
    position: [number, number, number],
    scale: [number, number],
    lookAt: [number, number, number],
  ) => {
    const mat = new THREE.MeshBasicMaterial({ color, toneMapped: false });
    mat.color.multiplyScalar(intensity);
    mats.push(mat);
    const mesh = new THREE.Mesh(geo, mat);
    mesh.position.set(...position);
    mesh.scale.set(scale[0], scale[1], 1);
    mesh.lookAt(...lookAt);
    scene.add(mesh);
  };

  const skyGeo = new THREE.SphereGeometry(40, 32, 16);
  const skyMat = new THREE.ShaderMaterial({
    uniforms: {
      uTop: { value: new THREE.Color("#6e6e88") },
      uBottom: { value: new THREE.Color("#2c2c3a") },
    },
    vertexShader: SKY_VERT,
    fragmentShader: SKY_FRAG,
    side: THREE.BackSide,
    depthWrite: false,
    toneMapped: false,
  });
  scene.add(new THREE.Mesh(skyGeo, skyMat));

  strip("#ffffff", 5, [0, 8, 1], [11, 4], [0, 0, 0]);
  strip("#c9b8ff", 3.4, [-8, 1, 4], [3, 11], [0, 0, 0]);
  strip("#8fd0ff", 2.6, [8, -1, -4], [3, 11], [0, 0, 0]);
  strip("#7d8398", 1.1, [0, -7, -1], [10, 4], [0, 0, 0]);

  return {
    scene,
    dispose: () => {
      geo.dispose();
      skyGeo.dispose();
      skyMat.dispose();
      for (const m of mats) m.dispose();
    },
  };
}

function StudioEnvironment({ intensity }: { intensity: number }) {
  const gl = useThree((s) => s.gl);
  const scene = useThree((s) => s.scene);
  const invalidate = useThree((s) => s.invalidate);

  useEffect(() => {
    const pmrem = new THREE.PMREMGenerator(gl);
    const env = buildEnvScene();
    const target = pmrem.fromScene(env.scene, 0.04);
    scene.environment = target.texture;
    env.dispose();
    pmrem.dispose();
    invalidate();
    return () => {
      scene.environment = null;
      target.texture.dispose();
    };
  }, [gl, scene, invalidate]);

  useEffect(() => {
    scene.environmentIntensity = intensity;
    invalidate();
  }, [intensity, scene, invalidate]);

  return null;
}

const GLOW_TINT: Record<CubePalette, string> = {
  classic: "#a855f7",
  amethyst: "#a855f7",
  mono: "#8b9cff",
  neon: "#00d9ff",
};

function GlowHalo({ extent, tint }: { extent: number; tint: string }) {
  const ref = useRef<THREE.Mesh>(null);
  const geo = useMemo(() => new THREE.PlaneGeometry(1, 1), []);
  const mat = useMemo(
    () =>
      new THREE.ShaderMaterial({
        uniforms: {
          uColor: { value: new THREE.Color("#ffffff") },
          uIntensity: { value: 1.05 },
        },
        vertexShader: GLOW_VERT,
        fragmentShader: GLOW_FRAG,
        transparent: true,
        blending: THREE.AdditiveBlending,
        depthWrite: false,
        toneMapped: false,
      }),
    [],
  );
  useEffect(() => {
    mat.uniforms.uColor.value.set(tint);
  }, [tint, mat]);
  useEffect(() => {
    return () => {
      geo.dispose();
      mat.dispose();
    };
  }, [geo, mat]);
  useFrame((state) => {
    const mesh = ref.current;
    if (!mesh) return;
    mesh.quaternion.copy(state.camera.quaternion);
    mesh.position.copy(state.camera.position).normalize().multiplyScalar(-extent * 0.34);
  });
  return <mesh ref={ref} geometry={geo} material={mat} scale={extent} frustumCulled={false} />;
}

const _snapMatrix = new THREE.Matrix4();
function snapQuaternion(q: THREE.Quaternion): void {
  _snapMatrix.makeRotationFromQuaternion(q);
  const e = _snapMatrix.elements;
  for (let i = 0; i < 16; i++) e[i] = Math.round(e[i]);
  q.setFromRotationMatrix(_snapMatrix);
}

function CameraRig({
  distance,
  onDrag,
}: {
  distance: number;
  onDrag: (dx: number, dy: number, camera: THREE.Camera) => void;
}) {
  const gl = useThree((s) => s.gl);
  const camera = useThree((s) => s.camera);
  const invalidate = useThree((s) => s.invalidate);
  const azimuth = useRef({ current: ORBIT_AZIMUTH, target: ORBIT_AZIMUTH });
  const elevation = useRef({
    current: ORBIT_ELEVATION,
    target: ORBIT_ELEVATION,
  });
  const radius = useRef(distance);
  const dragRef = useRef(onDrag);
  dragRef.current = onDrag;

  useEffect(() => invalidate(), [distance, invalidate]);

  useEffect(() => {
    const el = gl.domElement;
    let dragging = false;
    let lastX = 0;
    let lastY = 0;
    const down = (e: PointerEvent) => {
      if (e.pointerType === "mouse" && e.button !== 0) return;
      dragging = true;
      lastX = e.clientX;
      lastY = e.clientY;
      el.setPointerCapture(e.pointerId);
    };
    const move = (e: PointerEvent) => {
      if (!dragging) return;
      const dx = e.clientX - lastX;
      const dy = e.clientY - lastY;
      azimuth.current.target -= dx * 0.006;
      elevation.current.target = THREE.MathUtils.clamp(
        elevation.current.target + dy * 0.005,
        -1.35,
        1.35,
      );
      lastX = e.clientX;
      lastY = e.clientY;
      dragRef.current(dx, dy, camera);
      invalidate();
    };
    const up = (e: PointerEvent) => {
      dragging = false;
      if (el.hasPointerCapture(e.pointerId)) el.releasePointerCapture(e.pointerId);
    };
    el.addEventListener("pointerdown", down);
    el.addEventListener("pointermove", move);
    el.addEventListener("pointerup", up);
    el.addEventListener("pointercancel", up);
    return () => {
      el.removeEventListener("pointerdown", down);
      el.removeEventListener("pointermove", move);
      el.removeEventListener("pointerup", up);
      el.removeEventListener("pointercancel", up);
    };
  }, [gl, camera, invalidate]);

  useFrame((state, delta) => {
    const az = azimuth.current;
    const el = elevation.current;
    const ease = Math.min(1, delta * 8);
    az.current += (az.target - az.current) * ease;
    el.current += (el.target - el.current) * ease;
    radius.current += (distance - radius.current) * ease;
    if (
      Math.abs(az.target - az.current) > 0.0004 ||
      Math.abs(el.target - el.current) > 0.0004 ||
      Math.abs(distance - radius.current) > 0.005
    ) {
      invalidate();
    }
    const r = radius.current;
    const ce = Math.cos(el.current);
    state.camera.position.set(
      r * ce * Math.sin(az.current),
      r * Math.sin(el.current),
      r * ce * Math.cos(az.current),
    );
    state.camera.lookAt(0, 0, 0);
  });

  return null;
}

const _basisRight = new THREE.Vector3();
const _basisUp = new THREE.Vector3();
const _basisFwd = new THREE.Vector3();
const _swipeAxis = new THREE.Vector3();
const _spinDelta = new THREE.Quaternion();

function CubeScene({
  autoRotate = true,
  rotationSpeed = 1,
  moveDuration = 380,
  scrambleMoveCount = 12,
  pauseBetweenCycles = 700,
  cameraDistance = 11,
  gap = 0.06,
  palette = "classic",
  colors,
  bodyColor = "#16161c",
  background = "#0b0d14",
  transparent = false,
  glossy = true,
  glow = false,
  paused = false,
  reducedMotion = false,
}: Omit<RubiksCubeProps, "className">) {
  const invalidate = useThree((s) => s.invalidate);
  const halted = paused || reducedMotion;

  const spinRef = useRef<THREE.Group>(null);
  const rootRef = useRef<THREE.Group>(null);
  const pivotRef = useRef<THREE.Group>(null);
  const cubieRefs = useRef<(THREE.Group | null)[]>([]);

  const live = useRef({
    autoRotate,
    rotationSpeed,
    moveDuration,
    scrambleMoveCount,
    pauseBetweenCycles,
    gap,
    halted,
  });
  live.current = {
    autoRotate,
    rotationSpeed,
    moveDuration,
    scrambleMoveCount,
    pauseBetweenCycles,
    gap,
    halted,
  };

  const coords = useRef<THREE.Vector3[]>(
    CUBIES.map((c) => new THREE.Vector3(c.coord[0], c.coord[1], c.coord[2])),
  );

  const sched = useRef<{
    mode: "scramble" | "solve";
    scramble: Move[];
    queue: Move[];
    active: Move | null;
    members: THREE.Object3D[];
    t: number;
    hold: number;
  }>({ mode: "scramble", scramble: [], queue: [], active: null, members: [], t: 0, hold: 0 });

  const spin = useRef({
    axis: new THREE.Vector3(0.32, 1, 0.16).normalize(),
    target: new THREE.Vector3(0.32, 1, 0.16).normalize(),
  });

  const boxGeo = useMemo(() => new THREE.BoxGeometry(1, 1, 1), []);
  const planeGeo = useMemo(() => makeStickerGeometry(), []);
  useEffect(() => {
    return () => {
      boxGeo.dispose();
      planeGeo.dispose();
    };
  }, [boxGeo, planeGeo]);

  const plasticMat = useMemo(
    () => new THREE.MeshPhysicalMaterial({ color: "#16161c", roughness: 0.68, metalness: 0.05 }),
    [],
  );
  const faceMats = useMemo(() => {
    const out = {} as Record<CubeFace, THREE.MeshPhysicalMaterial>;
    for (const f of FACES) {
      out[f.face] = new THREE.MeshPhysicalMaterial({
        roughness: 0.38,
        metalness: 0,
        toneMapped: false,
      });
    }
    return out;
  }, []);
  useEffect(() => {
    return () => {
      plasticMat.dispose();
      for (const m of Object.values(faceMats)) m.dispose();
    };
  }, [plasticMat, faceMats]);

  useEffect(() => {
    plasticMat.color.set(bodyColor);
    invalidate();
  }, [bodyColor, plasticMat, invalidate]);

  useEffect(() => {
    const scheme = PALETTES[palette] ?? PALETTES.classic;
    for (const f of FACES) {
      const hex = colors?.[f.face] ?? scheme[f.face];
      const mat = faceMats[f.face];
      mat.color.set(hex);
      mat.emissive.set(hex).multiplyScalar(glow ? 0.45 : 0.12);
    }
    invalidate();
  }, [palette, colors, glow, faceMats, invalidate]);

  useEffect(() => {
    for (const f of FACES) {
      const mat = faceMats[f.face];
      mat.roughness = glossy ? 0.2 : 0.42;
      mat.clearcoat = glossy ? 1 : 0;
      mat.clearcoatRoughness = glossy ? 0.03 : 0.5;
      mat.iridescence = glossy ? 0.45 : 0;
      mat.iridescenceIOR = 1.32;
      mat.iridescenceThicknessRange = [130, 420];
      mat.needsUpdate = true;
    }
    plasticMat.roughness = glossy ? 0.42 : 0.68;
    plasticMat.clearcoat = glossy ? 0.7 : 0;
    plasticMat.clearcoatRoughness = glossy ? 0.22 : 0.5;
    plasticMat.needsUpdate = true;
    invalidate();
  }, [glossy, faceMats, plasticMat, invalidate]);

  useEffect(() => {
    const step = 1 + gap;
    for (let i = 0; i < CUBIES.length; i++) {
      const obj = cubieRefs.current[i];
      if (!obj || obj.parent !== rootRef.current) continue;
      const c = coords.current[i];
      obj.position.set(c.x * step, c.y * step, c.z * step);
    }
    invalidate();
  }, [gap, invalidate]);

  const finalizeTurn = useCallback(() => {
    const s = sched.current;
    const move = s.active;
    const pivot = pivotRef.current;
    const root = rootRef.current;
    if (!move || !pivot || !root) return;

    pivot.rotation[AXIS_KEY[move.axis]] = move.dir * QUARTER;
    pivot.updateMatrixWorld(true);
    for (const obj of s.members) root.attach(obj);
    pivot.rotation.set(0, 0, 0);
    pivot.updateMatrixWorld(true);

    const step = 1 + live.current.gap;
    const angle = move.dir * QUARTER;
    for (const obj of s.members) {
      const index = obj.userData.cubieIndex as number;
      const c = coords.current[index];
      c.applyAxisAngle(AXIS_VEC[move.axis], angle);
      c.set(Math.round(c.x), Math.round(c.y), Math.round(c.z));
      obj.position.set(c.x * step, c.y * step, c.z * step);
      snapQuaternion(obj.quaternion);
    }

    s.members = [];
    s.active = null;
    s.t = 0;
  }, []);

  const startTurn = useCallback((move: Move) => {
    const s = sched.current;
    const pivot = pivotRef.current;
    if (!pivot) return;
    pivot.rotation.set(0, 0, 0);
    pivot.updateMatrixWorld(true);
    s.members = [];
    for (let i = 0; i < CUBIES.length; i++) {
      const c = coords.current[i];
      const slot = move.axis === 0 ? c.x : move.axis === 1 ? c.y : c.z;
      if (slot !== move.layer) continue;
      const obj = cubieRefs.current[i];
      if (!obj) continue;
      pivot.attach(obj);
      s.members.push(obj);
    }
    s.active = move;
    s.t = 0;
  }, []);

  useEffect(() => {
    if (!halted) return;
    if (sched.current.active) finalizeTurn();
    invalidate();
  }, [halted, finalizeTurn, invalidate]);

  const handleDrag = useCallback((dx: number, dy: number, camera: THREE.Camera) => {
    if (Math.hypot(dx, dy) < SWIPE_MIN) return;
    camera.matrixWorld.extractBasis(_basisRight, _basisUp, _basisFwd);
    _swipeAxis.copy(_basisUp).multiplyScalar(dx).addScaledVector(_basisRight, dy);
    if (_swipeAxis.lengthSq() < 1e-6) return;
    spin.current.target.copy(_swipeAxis).normalize();
  }, []);

  useFrame((_state, delta) => {
    const L = live.current;
    if (L.halted) return;
    const dt = Math.min(delta, 0.05);

    if (L.autoRotate && spinRef.current) {
      const st = spin.current;
      st.axis.lerp(st.target, Math.min(1, dt * AXIS_EASE));
      if (st.axis.lengthSq() < 1e-6) st.axis.copy(st.target);
      st.axis.normalize();
      _spinDelta.setFromAxisAngle(st.axis, BASE_SPIN * DEG * L.rotationSpeed * dt);
      spinRef.current.quaternion.premultiply(_spinDelta);
    }

    const s = sched.current;
    const pivot = pivotRef.current;
    if (!pivot) return;

    if (s.active) {
      s.t += (dt * 1000) / Math.max(1, L.moveDuration);
      if (s.t >= 1) {
        finalizeTurn();
      } else {
        pivot.rotation[AXIS_KEY[s.active.axis]] = easeTurn(s.t) * s.active.dir * QUARTER;
      }
    } else if (s.hold > 0) {
      s.hold -= dt * 1000;
    } else if (s.queue.length > 0) {
      startTurn(s.queue.shift() as Move);
    } else if (s.mode === "scramble" && s.scramble.length > 0) {
      s.mode = "solve";
      s.queue = invert(s.scramble);
      s.hold = L.pauseBetweenCycles;
    } else {
      s.mode = "scramble";
      s.scramble = makeScramble(Math.max(1, Math.round(L.scrambleMoveCount)));
      s.queue = s.scramble.slice();
      s.hold = s.scramble.length > 0 ? L.pauseBetweenCycles : 0;
    }
  });

  const haloExtent = 3 * (1 + gap) * 3.6;

  return (
    <>
      <CameraRig distance={cameraDistance} onDrag={handleDrag} />
      {transparent ? null : <color attach="background" args={[background]} />}
      <StudioEnvironment intensity={glossy ? 1.25 : 0.55} />
      {glow ? (
        <GlowHalo extent={haloExtent} tint={GLOW_TINT[palette] ?? GLOW_TINT.classic} />
      ) : null}

      <ambientLight intensity={0.55} />
      <directionalLight position={[5, 7, 6]} intensity={2.1} />
      <directionalLight position={[-6, 2, 4]} intensity={0.85} color="#cfd6ff" />
      <directionalLight position={[-3, -5, -5]} intensity={0.7} color="#a855f7" />

      <group ref={spinRef}>
        <group ref={rootRef}>
          <group ref={pivotRef} />
          {CUBIES.map((cubie, i) => (
            <group
              key={cubie.key}
              ref={(el) => {
                if (el) el.userData.cubieIndex = i;
                cubieRefs.current[i] = el;
              }}
            >
              <mesh geometry={boxGeo} material={plasticMat} />
              {cubie.stickers.map((sticker) => (
                <mesh
                  key={sticker.face}
                  geometry={planeGeo}
                  material={faceMats[sticker.face]}
                  position={sticker.position}
                  rotation={sticker.rotation}
                  scale={STICKER_SCALE}
                />
              ))}
            </group>
          ))}
        </group>
      </group>
    </>
  );
}

function FitGate({
  hostRef,
  onFit,
}: {
  hostRef: { current: HTMLDivElement | null };
  onFit: () => void;
}) {
  const width = useThree((s) => s.size.width);
  useEffect(() => {
    const host = hostRef.current;
    if (!host) return;
    const hostWidth = host.getBoundingClientRect().width;
    if (hostWidth > 0 && Math.abs(width - hostWidth) <= 2) onFit();
  }, [width, hostRef, onFit]);
  return null;
}

function ReadySignal({ onReady }: { onReady?: () => void }) {
  const fired = useRef(false);
  useFrame(() => {
    if (fired.current) return;
    fired.current = true;
    onReady?.();
  });
  return null;
}

export default function RubiksCube({
  className,
  paused = false,
  reducedMotion = false,
  transparent = false,
  cameraDistance = 11,
  onReady,
  ...props
}: RubiksCubeProps) {
  const [canvasEpoch, setCanvasEpoch] = useState(0);
  useEffect(() => () => setCanvasEpoch((e) => e + 1), []);
  const hostRef = useRef<HTMLDivElement>(null);

  const [fitEpoch, setFitEpoch] = useState(-1);
  const fitted = fitEpoch === canvasEpoch;
  const markFitted = useCallback(() => setFitEpoch(canvasEpoch), [canvasEpoch]);

  const halted = paused || reducedMotion;

  return (
    <div
      ref={hostRef}
      className={cn(
        "relative h-full w-full select-none [&_canvas]:cursor-grab [&_canvas]:touch-none [&_canvas:active]:cursor-grabbing",
        "[&_canvas]:transition-opacity [&_canvas]:duration-700 [&_canvas]:ease-out",
        fitted ? "[&_canvas]:opacity-100" : "[&_canvas]:opacity-0",
        className,
      )}
    >
      <Canvas
        key={canvasEpoch}
        flat
        dpr={[1, 1.75]}
        frameloop={halted ? "demand" : "always"}
        camera={{ position: orbitPosition(cameraDistance), fov: 42 }}
        gl={{ antialias: true, alpha: true }}
        resize={{ scroll: false }}
      >
        <FitGate hostRef={hostRef} onFit={markFitted} />
        <ReadySignal onReady={onReady} />
        <CubeScene
          paused={paused}
          reducedMotion={reducedMotion}
          transparent={transparent}
          cameraDistance={cameraDistance}
          {...props}
        />
      </Canvas>
    </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 |
| --- | --- | --- | --- |
| `autoRotate` | `boolean` | `true` | Spin the whole cube on its own axis, independently of the solve loop. Off leaves the cube still while it keeps scrambling and solving. |
| `rotationSpeed` | `number` | `1` | Multiplier on the ambient spin rate. A drag re-aims the spin axis but never changes this — direction is yours, speed is the component's. Range 0–3 ×. Ignored while `autoRotate` is `false`. |
| `moveDuration` | `number` | `380` | How long one quarter-turn takes. The ease overshoots slightly and settles back, which is the mechanical click a real cube makes. Range 120–1200 ms. |
| `scrambleMoveCount` | `number` | `12` | Quarter-turns per scramble. The solve is this sequence replayed backwards and negated, so a longer scramble buys a longer solve for free. Range 1–30. |
| `pauseBetweenCycles` | `number` | `700` | Beat of stillness between scramble and solve. Zero runs the two together into one continuous churn. Range 0–3000 ms. |
| `cameraDistance` | `number` | `11` | Orbit radius, which is what sets the cube's apparent size. Drag anywhere to orbit; elevation stops short of the poles so the cube never tumbles sideways. Range 6–22. |
| `gap` | `number` | `0.06` | Space between cubies, in cubie widths. Widen it and the black core shows through the seams, exactly as a real cube's does. Range 0–0.3. |
| `palette` | `"classic" | "amethyst" | "mono" | "neon"` | `"classic"` | Named sticker scheme. The component also takes a `colors` record to override any individual face. |
| `bodyColor` | `string (hex)` | `"#16161c"` | Plastic behind the stickers, and the core seen through the seams. |
| `background` | `string (hex)` | `"#0b0d14"` | The dark field the cube turns in. |
| `glossy` | `boolean` | `true` | Wet-lacquer clearcoat plus a faint oil-slick sheen, lit by a small studio environment. Off leaves flat matte plastic. |
| `glow` | `boolean` | `false` | Emissive stickers plus an additive amethyst halo at the silhouette. Off by default: it is a flourish, not the point. |

## Usage

```tsx
import RubiksCube from "@/components/registry/rubiks-cube/rubiks-cube";

<RubiksCube
  autoRotate={true}
  rotationSpeed={1}
  moveDuration={380}
  scrambleMoveCount={12}
  pauseBetweenCycles={700}
  cameraDistance={11}
  gap={0.06}
  palette="classic"
  bodyColor="#16161c"
  background="#0b0d14"
  glossy={true}
  glow={false}
/>
```

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 `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- `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. 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.
