{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "aperture-dive",
  "title": "Aperture dive",
  "description": "Aperture dive is a production-ready heroes component from BJORK UI, packaged for shadcn registries.",
  "dependencies": [
    "clsx",
    "next-themes",
    "tailwind-merge",
    "three"
  ],
  "files": [
    {
      "path": "components/bjork-ui/heroes/aperture-dive.tsx",
      "content": "\"use client\";\n\n// Aperture Dive: a hero that starts straight above a ring of screens (an eclipse), dives\n// into the ring on native scroll, lands square on one screen, then hands that screen to a\n// real DOM element in the next section. WebGL first, CSS 3D when WebGL is missing, a still\n// poster under reduced motion.\n\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type CSSProperties,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport * as THREE from \"three\";\nimport { CSS3DObject, CSS3DRenderer } from \"three/examples/jsm/renderers/CSS3DRenderer.js\";\nimport { cn } from \"@/lib/utils\";\nimport { cubicBezier } from \"../_core/motion\";\nimport { useBjorkTone } from \"../_core/tone\";\nimport { useVisibleLoop } from \"../_core/loop\";\nimport { LiveRegion } from \"../_core/a11y\";\nimport { angleDelta, clamp01, smoothstep } from \"../_core/scene-states\";\nimport {\n  ApertureDiveScene,\n  DIVE_PROFILES,\n  PANEL_H,\n  PANEL_W,\n  applyDiveCamera,\n  createDiveFrame,\n  createDiveSampler,\n  panelPlacement,\n  projectPanelCorners,\n  quadToMatrix3d,\n  ringRadius,\n  type DiveFrame,\n  type DiveQuality,\n  type DiveSceneMedia,\n} from \"./aperture-dive-scene\";\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface ApertureDiveMedia {\n  type: \"image\" | \"video\";\n  src: string;\n  poster?: string;\n  /** `cover` fills the screen; `contain` floats the media on `backdrop`. Default cover. */\n  fit?: \"cover\" | \"contain\";\n  backdrop?: string;\n  /** Contain only: inset as a fraction of the screen height. */\n  inset?: number;\n  /** Contain only: corner radius as a fraction of the screen height. */\n  radius?: number;\n  /** Width / height of the media. Lets contained media lay out before it loads. */\n  aspect?: number;\n}\n\nexport interface ApertureDivePanel {\n  id: string;\n  media: ApertureDiveMedia;\n  title?: string;\n  meta?: string;\n}\n\nexport type ApertureDivePhase = \"overhead\" | \"dive\" | \"landed\" | \"handoff\";\n\nexport interface ApertureDiveProps {\n  /** 6–12 screens. More than 12 are ignored. */\n  panels: ApertureDivePanel[];\n  /** The screen the dive lands on and hands off. */\n  focusIndex?: number;\n  headline?: ReactNode;\n  eyebrowLeft?: ReactNode;\n  eyebrowRight?: ReactNode;\n  scrollHint?: string;\n  /** Scroll length of the dive, in viewport heights beyond the first. 140 desktop, 110 mobile. */\n  travel?: number;\n  /** Element that receives the landed screen. Defaults to `<ApertureDiveTarget />` or any `[data-aperture-target]` inside `children`. */\n  handoffTarget?: RefObject<HTMLElement | null>;\n  /** Where the target's centre sits in the viewport when the handoff completes, 0..1. */\n  handoffAlign?: number;\n  haze?: boolean;\n  ground?: \"sand\" | \"none\";\n  tone?: \"light\" | \"dark\";\n  /** `auto` picks `low` on small or touch screens. */\n  quality?: \"auto\" | \"high\" | \"low\";\n  /** Force a renderer. `auto` uses WebGL and falls back to CSS 3D. */\n  renderer?: \"auto\" | \"webgl\" | \"css\";\n  /** Page background the scene fades into. Defaults to the BJORK background for the tone. */\n  background?: string;\n  /** Scroll container, when the page does not scroll on the window. */\n  scrollRoot?: RefObject<HTMLElement | null>;\n  /** Freeze at a progress (0..1). For posters and docs. */\n  staticProgress?: number;\n  onPhaseChange?: (phase: ApertureDivePhase) => void;\n  className?: string;\n  /** The section after the hero. Put `<ApertureDiveTarget />` in it. */\n  children?: ReactNode;\n}\n\nconst HANDOFF_START = 0.92;\nconst easeHandoff = cubicBezier(0.65, 0, 0.35, 1);\nconst DISPLAY_FONT = '\"Bjork Grotesk Display\", \"Bjork Grotesk Alpha\", var(--font-geist-sans), sans-serif';\nconst MONO_FONT = \"var(--font-geist-mono), ui-monospace, SFMono-Regular, Menlo, monospace\";\n\nconst TONES = {\n  dark: { bg: \"#111111\", ink: \"#f2eee7\", soft: \"rgba(242,238,231,0.56)\", faint: \"rgba(242,238,231,0.32)\", line: \"rgba(242,238,231,0.18)\", stage: \"#070707\" },\n  light: { bg: \"#f7f3ea\", ink: \"#1a1815\", soft: \"rgba(26,24,21,0.58)\", faint: \"rgba(26,24,21,0.34)\", line: \"rgba(26,24,21,0.16)\", stage: \"#f2ede3\" },\n} as const;\n\n// ─── Media ────────────────────────────────────────────────────────────────────\n\nfunction normalizeMedia(media: ApertureDiveMedia): DiveSceneMedia & { aspect?: number } {\n  return {\n    type: media.type,\n    src: media.src,\n    poster: media.poster,\n    fit: media.fit ?? \"cover\",\n    backdrop: media.backdrop ?? \"#000000\",\n    inset: media.fit === \"contain\" ? (media.inset ?? 0) : 0,\n    radius: media.fit === \"contain\" ? (media.radius ?? 0) : 0,\n    aspect: media.aspect,\n  };\n}\n\n/** Inline styles for the media element, shared by React and imperative paths. */\nfunction mediaElementStyle(m: ReturnType<typeof normalizeMedia>): Partial<CSSStyleDeclaration> & CSSProperties {\n  if (m.fit === \"cover\") {\n    return { position: \"absolute\", inset: \"0\", width: \"100%\", height: \"100%\", objectFit: \"cover\", display: \"block\" };\n  }\n  return {\n    position: \"absolute\",\n    left: \"50%\",\n    top: `${m.inset * 100}%`,\n    height: `${(1 - 2 * m.inset) * 100}%`,\n    width: m.aspect ? \"auto\" : \"auto\",\n    aspectRatio: m.aspect ? String(m.aspect) : undefined,\n    maxWidth: `calc(100% - ${m.inset * 200}cqh)`,\n    objectFit: \"contain\",\n    transform: \"translateX(-50%)\",\n    borderRadius: `calc(${m.radius} * 100cqh)`,\n    display: \"block\",\n  } as Partial<CSSStyleDeclaration> & CSSProperties;\n}\n\nexport interface ApertureMediaProps {\n  media: ApertureDiveMedia;\n  title?: string;\n  className?: string;\n  style?: CSSProperties;\n  /** Reuse an existing <video> (the WebGL texture source) instead of creating one. */\n  sharedVideo?: HTMLVideoElement | null;\n}\n\n/** Renders a panel's media exactly as the WebGL screen draws it. */\nexport function ApertureMedia({ media, title, className, style, sharedVideo }: ApertureMediaProps) {\n  const m = normalizeMedia(media);\n  const slotRef = useRef<HTMLDivElement>(null);\n  const elStyle = mediaElementStyle(m) as CSSProperties;\n\n  useEffect(() => {\n    const slot = slotRef.current;\n    if (!slot || !sharedVideo) return;\n    Object.assign(sharedVideo.style, mediaElementStyle(m));\n    slot.appendChild(sharedVideo);\n    // Re-attaching pauses a media element; keep it running.\n    sharedVideo.play().catch(() => {});\n    return () => {\n      if (sharedVideo.parentNode === slot) slot.removeChild(sharedVideo);\n      sharedVideo.play().catch(() => {});\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [sharedVideo, m.fit, m.inset, m.radius, m.aspect]);\n\n  return (\n    <div\n      className={cn(\"relative overflow-hidden\", className)}\n      style={{ background: m.backdrop, containerType: \"size\", ...style }}\n    >\n      {m.type === \"image\" ? (\n        // eslint-disable-next-line @next/next/no-img-element\n        <img src={m.src} alt={title ?? \"\"} draggable={false} style={elStyle} />\n      ) : sharedVideo ? (\n        <div ref={slotRef} className=\"absolute inset-0\" />\n      ) : (\n        <video\n          src={m.src}\n          poster={m.poster}\n          muted\n          loop\n          playsInline\n          autoPlay\n          preload=\"metadata\"\n          aria-label={title}\n          style={elStyle}\n        />\n      )}\n    </div>\n  );\n}\n\n// ─── Handoff target ───────────────────────────────────────────────────────────\n\ninterface DiveContextValue {\n  panel: ApertureDivePanel;\n  registerTarget: (el: HTMLElement | null) => void;\n}\n\nconst DiveContext = createContext<DiveContextValue | null>(null);\n\nexport interface ApertureDiveTargetProps {\n  className?: string;\n  style?: CSSProperties;\n  children?: ReactNode;\n}\n\n/**\n * The DOM element the landed screen becomes. Render it anywhere inside <ApertureDive>'s\n * children. It keeps the screen's aspect ratio so the morph only moves and scales.\n */\nexport function ApertureDiveTarget({ className, style, children }: ApertureDiveTargetProps) {\n  const ctx = useContext(DiveContext);\n  const register = ctx?.registerTarget;\n  const ref = useCallback((el: HTMLDivElement | null) => register?.(el), [register]);\n  if (!ctx) return null;\n  return (\n    <div\n      ref={ref}\n      data-aperture-target=\"\"\n      className={cn(\"relative w-full overflow-hidden\", className)}\n      style={{ aspectRatio: `${PANEL_W} / ${PANEL_H}`, ...style }}\n    >\n      <ApertureMedia media={ctx.panel.media} title={ctx.panel.title} className=\"absolute inset-0\" />\n      {children}\n    </div>\n  );\n}\n\n// ─── Environment ──────────────────────────────────────────────────────────────\n\nfunction useMedia(query: string) {\n  return useSyncExternalStore(\n    (cb) => {\n      if (typeof window === \"undefined\") return () => {};\n      const mq = window.matchMedia(query);\n      mq.addEventListener(\"change\", cb);\n      return () => mq.removeEventListener(\"change\", cb);\n    },\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n\nconst noopSubscribe = () => () => {};\n\nfunction hasWebGL() {\n  try {\n    const c = document.createElement(\"canvas\");\n    return Boolean(c.getContext(\"webgl2\") || c.getContext(\"webgl\"));\n  } catch {\n    return false;\n  }\n}\n\nfunction saveData() {\n  const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;\n  return Boolean(conn?.saveData);\n}\n\n// ─── CSS 3D fallback ──────────────────────────────────────────────────────────\n\nconst CSS_UNIT = 200; // px per world unit inside CSS3DObjects\n\nfunction createMediaElement(media: ReturnType<typeof normalizeMedia>, play: boolean) {\n  const el = document.createElement(\"div\");\n  el.style.cssText = `width:${PANEL_W * CSS_UNIT}px;height:${PANEL_H * CSS_UNIT}px;overflow:hidden;background:${media.backdrop};container-type:size;backface-visibility:hidden;`;\n  const inner = document.createElement(\"div\");\n  inner.style.cssText = \"position:absolute;inset:0;transform-origin:50% 50%;\";\n  let node: HTMLImageElement | HTMLVideoElement;\n  if (media.type === \"video\" && play) {\n    const v = document.createElement(\"video\");\n    v.src = media.src;\n    if (media.poster) v.poster = media.poster;\n    v.muted = true;\n    v.loop = true;\n    v.playsInline = true;\n    v.setAttribute(\"muted\", \"\");\n    v.setAttribute(\"playsinline\", \"\");\n    v.play().catch(() => {});\n    node = v;\n  } else {\n    const img = document.createElement(\"img\");\n    img.src = media.type === \"image\" ? media.src : (media.poster ?? \"\");\n    img.alt = \"\";\n    img.draggable = false;\n    node = img;\n  }\n  Object.assign(node.style, mediaElementStyle(media));\n  inner.appendChild(node);\n  el.appendChild(inner);\n  return { el, inner, video: node instanceof HTMLVideoElement ? node : null };\n}\n\nclass CssWorld {\n  readonly renderer = new CSS3DRenderer();\n  readonly camera = new THREE.PerspectiveCamera(15, 1, 0.05, 200);\n  private scene = new THREE.Scene();\n  private group = new THREE.Group();\n  private panels: { obj: CSS3DObject; el: HTMLElement; inner: HTMLElement; video: HTMLVideoElement | null }[] = [];\n  private interior: HTMLDivElement;\n  private corona: HTMLDivElement;\n  private width = 1;\n  private height = 1;\n  readonly ring: number;\n\n  constructor(\n    container: HTMLElement,\n    panels: ReturnType<typeof normalizeMedia>[],\n    private focusIndex: number,\n    tone: \"light\" | \"dark\",\n  ) {\n    const count = panels.length;\n    this.ring = ringRadius(count);\n    container.appendChild(this.renderer.domElement);\n    this.renderer.domElement.style.position = \"absolute\";\n    this.renderer.domElement.style.inset = \"0\";\n    this.scene.add(this.group);\n\n    // Ground: a disc with the corona painted on, and an interior glow that fills in.\n    const size = 18;\n    const px = size * CSS_UNIT * 0.25;\n    const ground = document.createElement(\"div\");\n    const r = (this.ring / (size / 2)) * 100; // % of the disc radius (closest-side)\n    ground.style.cssText = `width:${px}px;height:${px}px;border-radius:50%;position:relative;`;\n    this.corona = document.createElement(\"div\");\n    this.corona.style.cssText =\n      tone === \"dark\"\n        ? `position:absolute;inset:0;border-radius:50%;background:radial-gradient(circle closest-side, transparent ${r * 0.98}%, rgba(255,233,204,.55) ${r * 1.02}%, rgba(255,233,204,.12) ${r * 1.35}%, transparent ${r * 2.4}%);`\n        : `position:absolute;inset:0;border-radius:50%;background:radial-gradient(circle closest-side, transparent ${r * 0.98}%, rgba(96,80,58,.42) ${r * 1.03}%, rgba(96,80,58,.08) ${r * 1.45}%, transparent ${r * 2.4}%);`;\n    this.interior = document.createElement(\"div\");\n    this.interior.style.cssText =\n      tone === \"dark\"\n        ? `position:absolute;inset:0;border-radius:50%;opacity:0;background:radial-gradient(circle closest-side, rgba(236,170,120,.28) 0%, rgba(236,140,90,.16) ${r * 0.7}%, transparent ${r}%);`\n        : `position:absolute;inset:0;border-radius:50%;opacity:0;background:radial-gradient(circle closest-side, rgba(60,50,40,.12) 0%, rgba(60,50,40,.06) ${r * 0.7}%, transparent ${r}%);`;\n    ground.append(this.interior, this.corona);\n    const groundObj = new CSS3DObject(ground);\n    groundObj.rotation.x = -Math.PI / 2;\n    groundObj.scale.setScalar(size / px);\n    this.scene.add(groundObj);\n\n    panels.forEach((media, i) => {\n      const { el, inner, video } = createMediaElement(media, i === focusIndex);\n      const obj = new CSS3DObject(el);\n      const place = panelPlacement(i, count, focusIndex);\n      obj.position.set(place.x, place.y, place.z);\n      obj.rotation.y = place.rotationY;\n      obj.scale.setScalar(1 / CSS_UNIT);\n      this.group.add(obj);\n      this.panels.push({ obj, el, inner, video });\n    });\n  }\n\n  get focusVideo() {\n    return this.panels[this.focusIndex]?.video ?? null;\n  }\n\n  resize(w: number, h: number) {\n    this.width = Math.max(1, w);\n    this.height = Math.max(1, h);\n    this.renderer.setSize(this.width, this.height);\n    this.camera.aspect = this.width / this.height;\n    this.camera.updateProjectionMatrix();\n  }\n\n  render(frame: DiveFrame) {\n    this.group.rotation.y = frame.ringSpin;\n    applyDiveCamera(this.camera, frame);\n    this.panels.forEach((p, i) => {\n      p.obj.scale.set(frame.scaleX / CSS_UNIT, 1 / CSS_UNIT, 1 / CSS_UNIT);\n      p.inner.style.transform = `scaleX(${1 / Math.max(0.01, frame.scaleX)})`;\n      p.el.style.filter = frame.saturation < 0.999 ? `saturate(${frame.saturation.toFixed(3)})` : \"\";\n      p.el.style.opacity = i === this.focusIndex && frame.focusOut > 0.5 ? \"0.06\" : \"1\";\n    });\n    this.interior.style.opacity = frame.interior.toFixed(3);\n    this.corona.style.opacity = frame.corona.toFixed(3);\n    this.renderer.domElement.style.opacity = (1 - frame.fade).toFixed(3);\n    this.renderer.render(this.scene, this.camera);\n  }\n\n  projectFocus(scaleX: number) {\n    const p = this.panels[this.focusIndex];\n    if (!p) return [];\n    p.obj.updateWorldMatrix(true, false);\n    // The CSS object is scaled to px; rebuild the unit-size panel matrix for projection.\n    const m = new THREE.Matrix4().compose(\n      p.obj.getWorldPosition(new THREE.Vector3()),\n      p.obj.getWorldQuaternion(new THREE.Quaternion()),\n      new THREE.Vector3(1, 1, 1),\n    );\n    return projectPanelCorners(m, this.camera, scaleX, this.width, this.height);\n  }\n\n  setVideosPlaying(playing: boolean) {\n    const v = this.focusVideo;\n    if (!v) return;\n    if (playing && v.paused) v.play().catch(() => {});\n    if (!playing && !v.paused) v.pause();\n  }\n\n  dispose() {\n    this.panels.forEach((p) => p.video?.pause());\n    this.renderer.domElement.remove();\n  }\n}\n\n// ─── Component ────────────────────────────────────────────────────────────────\n\ntype Mode = \"webgl\" | \"css\";\n\ninterface Runtime {\n  scene: ApertureDiveScene | null;\n  css: CssWorld | null;\n  sampler: ReturnType<typeof createDiveSampler>;\n  goal: DiveFrame;\n  cur: DiveFrame;\n  out: DiveFrame;\n  primed: boolean;\n  mouse: { x: number; y: number; tx: number; ty: number };\n  width: number;\n  height: number;\n  ghostShown: boolean;\n  targetShown: boolean | null;\n  videosPlaying: boolean | null;\n  text: Record<string, string>;\n  wake: () => void;\n}\n\nfunction createRuntime(count: number): Runtime {\n  return {\n    scene: null,\n    css: null,\n    sampler: createDiveSampler(ringRadius(Math.max(1, count))),\n    goal: createDiveFrame(),\n    cur: createDiveFrame(),\n    out: createDiveFrame(),\n    primed: false,\n    mouse: { x: 0, y: 0, tx: 0, ty: 0 },\n    width: 1,\n    height: 1,\n    ghostShown: false,\n    targetShown: null,\n    videosPlaying: null,\n    text: {},\n    wake: () => {},\n  };\n}\n\nfunction copyFrame(from: DiveFrame, to: DiveFrame) {\n  to.pose.target[0] = from.pose.target[0];\n  to.pose.target[1] = from.pose.target[1];\n  to.pose.target[2] = from.pose.target[2];\n  to.pose.radius = from.pose.radius;\n  to.pose.phi = from.pose.phi;\n  to.pose.theta = from.pose.theta;\n  to.fov = from.fov;\n  to.scaleX = from.scaleX;\n  to.saturation = from.saturation;\n  to.haze = from.haze;\n  to.interior = from.interior;\n  to.corona = from.corona;\n  to.look = from.look;\n  to.ringSpin = from.ringSpin;\n  to.focusOut = from.focusOut;\n  to.focusDim = from.focusDim;\n  to.fade = from.fade;\n}\n\n/** Frame-rate independent approach, `1 - e^(-9dt)`. Returns the largest remaining gap. */\nfunction dampFrame(cur: DiveFrame, goal: DiveFrame, dt: number) {\n  const k = 1 - Math.exp(-9 * dt);\n  let gap = 0;\n  const step = (a: number, b: number) => {\n    gap = Math.max(gap, Math.abs(b - a));\n    return a + (b - a) * k;\n  };\n  for (let i = 0; i < 3; i++) cur.pose.target[i] = step(cur.pose.target[i], goal.pose.target[i]);\n  // Radius damps in log space so the dolly feels even at both ends.\n  const lr = step(Math.log(cur.pose.radius), Math.log(goal.pose.radius));\n  cur.pose.radius = Math.exp(lr);\n  cur.pose.phi = step(cur.pose.phi, goal.pose.phi);\n  const dTheta = angleDelta(cur.pose.theta, goal.pose.theta);\n  gap = Math.max(gap, Math.abs(dTheta));\n  cur.pose.theta += dTheta * k;\n  cur.fov = step(cur.fov, goal.fov);\n  cur.scaleX = step(cur.scaleX, goal.scaleX);\n  cur.saturation = step(cur.saturation, goal.saturation);\n  cur.haze = step(cur.haze, goal.haze);\n  cur.interior = step(cur.interior, goal.interior);\n  cur.corona = step(cur.corona, goal.corona);\n  cur.look = step(cur.look, goal.look);\n  return gap;\n}\n\nexport function ApertureDive({\n  panels: panelsProp,\n  focusIndex: focusProp = 0,\n  headline,\n  eyebrowLeft,\n  eyebrowRight,\n  scrollHint = \"Scroll to dive\",\n  travel: travelProp,\n  handoffTarget,\n  handoffAlign = 0.5,\n  haze = true,\n  ground = \"sand\",\n  tone: toneProp,\n  quality: qualityProp = \"auto\",\n  renderer: rendererProp = \"auto\",\n  background,\n  scrollRoot,\n  staticProgress,\n  onPhaseChange,\n  className,\n  children,\n}: ApertureDiveProps) {\n  const tone = useBjorkTone(toneProp);\n  const reducedMotion = useMedia(\"(prefers-reduced-motion: reduce)\");\n  const smallScreen = useMedia(\"(max-width: 767px), (pointer: coarse)\");\n  const quality: DiveQuality = qualityProp === \"auto\" ? (smallScreen ? \"low\" : \"high\") : qualityProp;\n  const isStatic = reducedMotion || staticProgress != null;\n  const travel = travelProp ?? (quality === \"low\" ? 110 : 140);\n  const palette = TONES[tone];\n  const pageBg = background ?? palette.bg;\n\n  const panels = useMemo(() => panelsProp.slice(0, 12), [panelsProp]);\n  const focusIndex = Math.min(Math.max(0, focusProp), Math.max(0, panels.length - 1));\n  const focusPanel = panels[focusIndex];\n  const media = useMemo(() => panels.map((p) => normalizeMedia(p.media)), [panels]);\n\n  const [mode, setMode] = useState<Mode>(\"webgl\");\n  const [sharedVideo, setSharedVideo] = useState<HTMLVideoElement | null>(null);\n  const [phase, setPhase] = useState<ApertureDivePhase>(\"overhead\");\n  const mounted = useSyncExternalStore(\n    noopSubscribe,\n    () => true,\n    () => false,\n  );\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const trackRef = useRef<HTMLElement>(null);\n  const stageRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const cssHostRef = useRef<HTMLDivElement>(null);\n  const ghostRef = useRef<HTMLDivElement>(null);\n  const headlineRef = useRef<HTMLDivElement>(null);\n  const hintRef = useRef<HTMLDivElement>(null);\n  const altRef = useRef<HTMLSpanElement>(null);\n  const hudRef = useRef<HTMLDivElement>(null);\n  const titleRef = useRef<HTMLDivElement>(null);\n  const childrenRef = useRef<HTMLDivElement>(null);\n  const registeredTarget = useRef<HTMLElement | null>(null);\n  const phaseRef = useRef<ApertureDivePhase>(\"overhead\");\n  const onPhaseRef = useRef(onPhaseChange);\n  useEffect(() => {\n    onPhaseRef.current = onPhaseChange;\n  }, [onPhaseChange]);\n\n  // Mutable per-instance runtime. Allocated each render but only the first is kept.\n  const rt = useRef<Runtime>(createRuntime(panels.length));\n\n  const registerTarget = useCallback((el: HTMLElement | null) => {\n    registeredTarget.current = el;\n  }, []);\n  const ctx = useMemo<DiveContextValue | null>(\n    () => (focusPanel ? { panel: focusPanel, registerTarget } : null),\n    [focusPanel, registerTarget],\n  );\n\n  const resolveTarget = useCallback((): HTMLElement | null => {\n    if (handoffTarget?.current) return handoffTarget.current;\n    if (registeredTarget.current?.isConnected) return registeredTarget.current;\n    return childrenRef.current?.querySelector<HTMLElement>(\"[data-aperture-target]\") ?? null;\n  }, [handoffTarget]);\n\n  // ── Build the renderer ────────────────────────────────────────────────────\n  useEffect(() => {\n    const r = rt.current;\n    const canvas = canvasRef.current;\n    const stage = stageRef.current;\n    if (!canvas || !stage || panels.length === 0) return;\n    r.sampler = createDiveSampler(ringRadius(panels.length));\n    r.primed = false;\n    r.ghostShown = false;\n    r.targetShown = null;\n    r.videosPlaying = null;\n\n    const wantCss = rendererProp === \"css\" || (rendererProp === \"auto\" && (!hasWebGL() || saveData()));\n    let nextMode: Mode = wantCss ? \"css\" : \"webgl\";\n    if (!wantCss) {\n      try {\n        r.scene = new ApertureDiveScene({\n          canvas,\n          panels: media,\n          focusIndex,\n          tone,\n          quality,\n          haze: haze && quality === \"high\" && !isStatic,\n          ground: ground === \"sand\",\n          background: pageBg,\n        });\n        setSharedVideo(r.scene.focusVideo);\n      } catch {\n        r.scene = null;\n        nextMode = \"css\";\n      }\n    }\n    if (nextMode === \"css\" && cssHostRef.current) {\n      r.css = new CssWorld(cssHostRef.current, media, focusIndex, tone);\n      setSharedVideo(null);\n    }\n    setMode(nextMode);\n\n    const resize = () => {\n      const rect = stage.getBoundingClientRect();\n      r.width = rect.width;\n      r.height = rect.height;\n      const dpr = Math.min(window.devicePixelRatio || 1, quality === \"high\" ? 1.75 : 1.5);\n      r.scene?.resize(rect.width, rect.height, dpr);\n      r.css?.resize(rect.width, rect.height);\n      rt.current.wake();\n    };\n    const ro = new ResizeObserver(resize);\n    ro.observe(stage);\n    resize();\n\n    return () => {\n      ro.disconnect();\n      r.scene?.dispose();\n      r.scene = null;\n      r.css?.dispose();\n      r.css = null;\n      setSharedVideo(null);\n    };\n  }, [panels, media, focusIndex, tone, quality, haze, ground, rendererProp, pageBg, isStatic]);\n\n  // ── Per-frame ─────────────────────────────────────────────────────────────\n  const write = (key: string, el: HTMLElement | null, prop: \"opacity\" | \"transform\" | \"filter\", value: string) => {\n    const r = rt.current;\n    const k = `${key}.${prop}`;\n    if (!el || r.text[k] === value) return;\n    r.text[k] = value;\n    el.style[prop] = value;\n  };\n\n  const frame = useCallback(\n    (dt: number) => {\n      const r = rt.current;\n      const track = trackRef.current;\n      const stage = stageRef.current;\n      if (!track || !stage || (!r.scene && !r.css)) return false;\n\n      const root = scrollRoot?.current ?? null;\n      const rootTop = root ? root.getBoundingClientRect().top : 0;\n      const vh = root ? root.clientHeight : window.innerHeight;\n      const tr = track.getBoundingClientRect();\n      const scrolled = rootTop - tr.top;\n      const range = Math.max(1, tr.height - vh);\n      const p = staticProgress != null ? clamp01(staticProgress) : isStatic ? 0 : clamp01(scrolled / range);\n\n      // Handoff progress: from p = HANDOFF_START until the target sits at `handoffAlign`.\n      const target = isStatic ? null : resolveTarget();\n      let h = 0;\n      let tRect: DOMRect | null = null;\n      if (target) {\n        tRect = target.getBoundingClientRect();\n        const s0 = HANDOFF_START * range;\n        const align = scrolled + (tRect.top + tRect.height / 2 - rootTop) - vh * handoffAlign;\n        const s1 = Math.max(align, s0 + 0.3 * vh);\n        h = clamp01((scrolled - s0) / (s1 - s0));\n      }\n\n      // Keyframes → goal, then damp the current frame toward it.\n      const aspect = r.width / Math.max(1, r.height);\n      r.sampler(p, aspect, DIVE_PROFILES[quality], r.goal);\n      let gap = 0;\n      if (!r.primed || isStatic) {\n        copyFrame(r.goal, r.cur);\n        r.primed = true;\n      } else {\n        gap = dampFrame(r.cur, r.goal, dt);\n      }\n\n      // Pointer parallax, desktop only; fades out of the overhead ring spin by p = .3.\n      const m = r.mouse;\n      const km = 1 - Math.exp(-4 * dt);\n      m.x += (m.tx - m.x) * km;\n      m.y += (m.ty - m.y) * km;\n      gap = Math.max(gap, Math.abs(m.tx - m.x), Math.abs(m.ty - m.y));\n      copyFrame(r.cur, r.out);\n      const overhead = 1 - smoothstep(clamp01(p / 0.3));\n      r.out.pose.theta += m.x * 0.03;\n      r.out.pose.phi = Math.min(Math.PI - 1e-4, Math.max(1e-4, r.out.pose.phi + m.y * 0.02));\n      r.out.ringSpin = m.x * 0.2 * Math.PI * 0.4 * overhead;\n      r.out.focusOut = h > 0 ? 1 : 0;\n      r.out.focusDim = smoothstep(clamp01(h / 0.3));\n      r.out.fade = target ? smoothstep(clamp01((h - 0.02) / 0.5)) : smoothstep(clamp01((p - 0.9) / 0.1));\n\n      const sr = stage.getBoundingClientRect();\n      const stageVisible = sr.bottom > rootTop && sr.top < rootTop + vh;\n      const flying = h > 0 && h < 1;\n\n      if (stageVisible && r.out.fade < 0.999) {\n        if (r.scene) r.scene.render(r.out, dt);\n        else r.css?.render(r.out);\n      }\n\n      // Videos only decode while someone can see them.\n      const wantVideos = stageVisible || flying;\n      if (wantVideos !== r.videosPlaying) {\n        r.videosPlaying = wantVideos;\n        r.scene?.setVideosPlaying(wantVideos, !wantVideos);\n        r.css?.setVideosPlaying(wantVideos);\n      }\n\n      // Ghost: the landed screen as a DOM element, flown from its projected quad to the target.\n      const ghost = ghostRef.current;\n      if (ghost && target && tRect && flying) {\n        const corners = r.scene ? r.scene.projectFocus() : (r.css?.projectFocus(r.out.scaleX) ?? []);\n        if (corners.length === 4) {\n          const top = Math.max(sr.top, rootTop); // floats free once the stage scrolls away\n          const e = easeHandoff(h);\n          const tq: [number, number][] = [\n            [tRect.left, tRect.top],\n            [tRect.right, tRect.top],\n            [tRect.right, tRect.bottom],\n            [tRect.left, tRect.bottom],\n          ];\n          const q = corners.map(([x, y], i) => [\n            x + sr.left + (tq[i][0] - x - sr.left) * e,\n            y + top + (tq[i][1] - y - top) * e,\n          ]) as [number, number][];\n          const w = Math.max(1, tRect.width);\n          const hh = Math.max(1, tRect.height);\n          ghost.style.width = `${w}px`;\n          ghost.style.height = `${hh}px`;\n          ghost.style.transform = quadToMatrix3d(w, hh, q);\n          const radius = parseFloat(getComputedStyle(target).borderTopLeftRadius) || 0;\n          ghost.style.borderRadius = `${radius * e}px`;\n          if (!r.ghostShown) {\n            r.ghostShown = true;\n            ghost.style.visibility = \"visible\";\n            const from = r.css?.focusVideo ?? target.querySelector(\"video\");\n            const to = ghost.querySelector(\"video\");\n            if (from && to && from !== to && Number.isFinite(from.currentTime)) to.currentTime = from.currentTime;\n          }\n        }\n      } else if (ghost && r.ghostShown) {\n        r.ghostShown = false;\n        ghost.style.visibility = \"hidden\";\n      }\n\n      if (target) {\n        const show = h >= 1;\n        if (show !== r.targetShown) {\n          const ghostVideo = ghost?.querySelector(\"video\");\n          const targetVideo = target.querySelector(\"video\");\n          if (show && ghostVideo && targetVideo) {\n            targetVideo.currentTime = ghostVideo.currentTime;\n            targetVideo.play().catch(() => {});\n          }\n          r.targetShown = show;\n          target.style.opacity = show ? \"\" : \"0\";\n        }\n      }\n\n      // DOM chrome, written only when a value changes.\n      const headlineK = smoothstep(clamp01((p - 0.1) / 0.2));\n      write(\"headline\", headlineRef.current, \"opacity\", (1 - headlineK).toFixed(3));\n      write(\n        \"headline\",\n        headlineRef.current,\n        \"transform\",\n        `translate3d(0, ${(-headlineK * 18).toFixed(2)}px, 0) scale(${(1 + headlineK * 0.06).toFixed(4)})`,\n      );\n      write(\"headline\", headlineRef.current, \"filter\", headlineK > 0.001 ? `blur(${(headlineK * 8).toFixed(2)}px)` : \"none\");\n      write(\"hint\", hintRef.current, \"opacity\", (1 - smoothstep(clamp01(p / 0.08))).toFixed(3));\n      const hudK = (1 - smoothstep(clamp01((p - 0.86) / 0.06))) * (1 - smoothstep(clamp01(h / 0.1)));\n      write(\"hud\", hudRef.current, \"opacity\", isStatic ? \"0\" : hudK.toFixed(3));\n      if (altRef.current) {\n        const alt = r.out.pose.target[1] + r.out.pose.radius * Math.cos(r.out.pose.phi);\n        const text = alt.toFixed(1).padStart(4, \"0\");\n        if (r.text.alt !== text) {\n          r.text.alt = text;\n          altRef.current.textContent = text;\n        }\n      }\n      const titleEl = titleRef.current;\n      if (titleEl) {\n        const k = smoothstep(clamp01((p - 0.78) / 0.08)) * (1 - smoothstep(clamp01(h / 0.12)));\n        write(\"title\", titleEl, \"opacity\", k.toFixed(3));\n        if (k > 0.001) {\n          const corners = r.scene ? r.scene.projectFocus() : (r.css?.projectFocus(r.out.scaleX) ?? []);\n          if (corners.length === 4) {\n            const cx = (corners[2][0] + corners[3][0]) / 2;\n            const by = Math.max(corners[2][1], corners[3][1]);\n            write(\"title\", titleEl, \"transform\", `translate3d(${cx.toFixed(1)}px, ${(by + 22 + (1 - k) * 8).toFixed(1)}px, 0) translateX(-50%)`);\n          }\n        }\n      }\n\n      const nextPhase: ApertureDivePhase = h > 0 ? \"handoff\" : p < 0.08 ? \"overhead\" : p < 0.8 ? \"dive\" : \"landed\";\n      if (nextPhase !== phaseRef.current) {\n        phaseRef.current = nextPhase;\n        setPhase(nextPhase);\n        onPhaseRef.current?.(nextPhase);\n      }\n\n      if (isStatic) return false;\n      // Idle once nothing moves and the stage is out of sight.\n      const settled = gap < 1e-4;\n      if (!stageVisible && !flying && settled) return false;\n      return true;\n    },\n    [scrollRoot, staticProgress, isStatic, resolveTarget, handoffAlign, quality],\n  );\n\n  const { wake } = useVisibleLoop(rootRef, frame, { enabled: mounted && !isStatic });\n  useEffect(() => {\n    rt.current.wake = isStatic ? () => requestAnimationFrame(() => frame(0)) : wake;\n  }, [wake, isStatic, frame]);\n\n  // Static: one frame after the renderer exists (and again on resize via rt.current.wake).\n  useEffect(() => {\n    if (!isStatic) return;\n    const id = requestAnimationFrame(() => frame(0));\n    const t = window.setTimeout(() => frame(0), 600);\n    return () => {\n      cancelAnimationFrame(id);\n      window.clearTimeout(t);\n    };\n  }, [isStatic, frame, mode, tone, quality]);\n\n  // Wake on scroll and pointer.\n  useEffect(() => {\n    if (isStatic) return;\n    const target: HTMLElement | Window = scrollRoot?.current ?? window;\n    const onScroll = () => wake();\n    const onPointer = (e: PointerEvent) => {\n      if (quality !== \"high\" || e.pointerType !== \"mouse\") return;\n      const m = rt.current.mouse;\n      m.tx = (e.clientX / window.innerWidth - 0.5) * 2;\n      m.ty = (e.clientY / window.innerHeight - 0.5) * 2;\n      wake();\n    };\n    target.addEventListener(\"scroll\", onScroll, { passive: true });\n    window.addEventListener(\"resize\", onScroll);\n    window.addEventListener(\"pointermove\", onPointer, { passive: true });\n    return () => {\n      target.removeEventListener(\"scroll\", onScroll);\n      window.removeEventListener(\"resize\", onScroll);\n      window.removeEventListener(\"pointermove\", onPointer);\n    };\n  }, [wake, scrollRoot, quality, isStatic]);\n\n  // Reduced motion: the next section crossfades in over 200 ms instead of a handoff.\n  useEffect(() => {\n    const el = childrenRef.current;\n    if (!el || !reducedMotion || staticProgress != null) return;\n    el.style.opacity = \"0\";\n    el.style.transition = \"opacity 200ms ease-out\";\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting) {\n          el.style.opacity = \"1\";\n          io.disconnect();\n        }\n      },\n      { threshold: 0.05 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      el.style.opacity = \"\";\n      el.style.transition = \"\";\n    };\n  }, [reducedMotion, staticProgress]);\n\n  // Targets are visible until the dive takes them over, so no-JS and reduced motion still show them.\n  useEffect(() => {\n    if (!isStatic) return;\n    const t = resolveTarget();\n    if (t) t.style.opacity = \"\";\n  }, [isStatic, resolveTarget]);\n\n  const trackHeight = isStatic ? \"100svh\" : `calc(100svh * ${(1 + travel / 100).toFixed(3)})`;\n  const announce =\n    phase === \"landed\" || phase === \"handoff\" ? `Now showing ${focusPanel?.title ?? `screen ${focusIndex + 1}`}` : \"\";\n  const label = (i: number) => String(i + 1).padStart(2, \"0\");\n\n  return (\n    <div ref={rootRef} className={cn(\"relative\", className)} style={{ background: pageBg }}>\n      <style>{`\n        @keyframes bjork-aperture-hint { 0% { transform: scaleY(0); transform-origin: top; } 45% { transform: scaleY(1); transform-origin: top; } 55% { transform: scaleY(1); transform-origin: bottom; } 100% { transform: scaleY(0); transform-origin: bottom; } }\n        @media (prefers-reduced-motion: reduce) { [data-aperture-hint-line] { animation: none !important; } }\n      `}</style>\n      <section\n        ref={trackRef}\n        aria-label=\"Featured work\"\n        className=\"relative\"\n        style={{ height: trackHeight }}\n        data-aperture-dive=\"\"\n        data-phase={phase}\n      >\n        <div\n          ref={stageRef}\n          className=\"sticky top-0 w-full overflow-hidden\"\n          style={{ height: \"100svh\", background: palette.stage }}\n        >\n          <canvas\n            ref={canvasRef}\n            aria-hidden=\"true\"\n            className=\"absolute inset-0 block h-full w-full\"\n            style={{ display: mode === \"webgl\" ? \"block\" : \"none\" }}\n          />\n          <div\n            ref={cssHostRef}\n            aria-hidden=\"true\"\n            className=\"absolute inset-0\"\n            style={{ display: mode === \"css\" ? \"block\" : \"none\" }}\n          />\n          {mode === \"css\" ? (\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-0 opacity-[0.07] mix-blend-overlay\"\n              style={{\n                backgroundImage:\n                  \"url(\\\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\\\")\",\n              }}\n            />\n          ) : null}\n\n          {/* Chrome */}\n          <div className=\"pointer-events-none absolute inset-x-0 top-0 flex items-start justify-between px-5 pt-5 sm:px-8 sm:pt-7\">\n            <div className=\"text-[11px] uppercase tracking-[0.16em]\" style={{ color: palette.soft, fontFamily: MONO_FONT }}>\n              {eyebrowLeft}\n            </div>\n            <div className=\"text-right text-[11px] uppercase tracking-[0.16em]\" style={{ color: palette.soft, fontFamily: MONO_FONT }}>\n              {eyebrowRight}\n            </div>\n          </div>\n\n          {headline ? (\n            <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center px-6\">\n              <div\n                ref={headlineRef}\n                className=\"max-w-[16ch] text-balance text-center will-change-transform\"\n                style={{\n                  color: palette.ink,\n                  fontFamily: DISPLAY_FONT,\n                  fontSize: \"clamp(34px, 6.2vw, 96px)\",\n                  lineHeight: 0.98,\n                  letterSpacing: \"-0.035em\",\n                  fontWeight: 500,\n                }}\n              >\n                {headline}\n              </div>\n            </div>\n          ) : null}\n\n          <div\n            ref={hintRef}\n            className=\"pointer-events-none absolute inset-x-0 bottom-7 flex flex-col items-center gap-3\"\n            style={{ color: palette.soft }}\n          >\n            <span className=\"text-[11px] uppercase tracking-[0.18em]\" style={{ fontFamily: MONO_FONT }}>\n              {scrollHint}\n            </span>\n            <span className=\"relative block h-7 w-px overflow-hidden\" style={{ background: palette.line }}>\n              <span\n                data-aperture-hint-line=\"\"\n                className=\"absolute inset-0 block\"\n                style={{ background: palette.ink, animation: \"bjork-aperture-hint 1.8s cubic-bezier(0.77,0,0.175,1) infinite\" }}\n              />\n            </span>\n          </div>\n\n          <div\n            ref={hudRef}\n            className=\"pointer-events-none absolute inset-x-0 bottom-0 flex items-end justify-between px-5 pb-5 text-[10px] uppercase tracking-[0.16em] sm:px-8 sm:pb-7\"\n            style={{ color: palette.faint, fontFamily: MONO_FONT, opacity: isStatic ? 0 : undefined }}\n          >\n            <span>\n              Alt <span ref={altRef} className=\"tabular-nums\" style={{ color: palette.soft }}>34.0</span>\n            </span>\n            <span className=\"tabular-nums\">\n              {label(focusIndex)} / {label(panels.length - 1)}\n            </span>\n          </div>\n\n          <div\n            ref={titleRef}\n            className=\"pointer-events-none absolute left-0 top-0 whitespace-nowrap text-center\"\n            style={{ opacity: 0, color: palette.ink }}\n          >\n            {focusPanel?.title ? (\n              <div className=\"text-[15px] tracking-[-0.01em]\" style={{ fontFamily: DISPLAY_FONT, fontWeight: 500 }}>\n                {focusPanel.title}\n              </div>\n            ) : null}\n            {focusPanel?.meta ? (\n              <div className=\"mt-1 text-[10px] uppercase tracking-[0.16em]\" style={{ color: palette.soft, fontFamily: MONO_FONT }}>\n                {focusPanel.meta}\n              </div>\n            ) : null}\n          </div>\n\n          <ul className=\"sr-only\">\n            {panels.map((p, i) => (\n              <li key={p.id}>\n                {p.title ?? `Screen ${i + 1}`}\n                {p.meta ? `, ${p.meta}` : \"\"}\n              </li>\n            ))}\n          </ul>\n          <LiveRegion message={announce} />\n        </div>\n      </section>\n\n      <DiveContext.Provider value={ctx}>\n        <div ref={childrenRef}>{children}</div>\n      </DiveContext.Provider>\n\n      {mounted && focusPanel && !isStatic\n        ? createPortal(\n            <div\n              ref={ghostRef}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none fixed left-0 top-0 overflow-hidden\"\n              style={{ visibility: \"hidden\", transformOrigin: \"0 0\", zIndex: 30, willChange: \"transform\" }}\n            >\n              <ApertureMedia\n                media={focusPanel.media}\n                className=\"absolute inset-0\"\n                sharedVideo={mode === \"webgl\" ? sharedVideo : null}\n              />\n            </div>,\n            document.body,\n          )\n        : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/heroes/aperture-dive.tsx"
    },
    {
      "path": "lib/utils.ts",
      "content": "import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n",
      "type": "registry:lib",
      "target": "@lib/utils.ts"
    },
    {
      "path": "components/bjork-ui/_core/motion.ts",
      "content": "// Shared springs, easings and durations. Components import these instead of inventing values.\n\nexport const springs = {\n  press: { type: \"spring\", stiffness: 500, damping: 30, mass: 0.6 },\n  snappy: { type: \"spring\", stiffness: 400, damping: 25, mass: 1 },\n  standard: { type: \"spring\", stiffness: 300, damping: 30, mass: 0.8 },\n  soft: { type: \"spring\", stiffness: 200, damping: 25, mass: 1.2 },\n  settle: { type: \"spring\", stiffness: 380, damping: 30, mass: 0.8 },\n  blurIn: { type: \"spring\", stiffness: 400, damping: 28, mass: 0.6 },\n} as const;\n\nexport const ease = {\n  out: [0.23, 1, 0.32, 1],\n  inOut: [0.77, 0, 0.175, 1],\n  drawer: [0.32, 0.72, 0, 1],\n} as const;\n\nexport const easeCss = {\n  out: \"cubic-bezier(0.23,1,0.32,1)\",\n  inOut: \"cubic-bezier(0.77,0,0.175,1)\",\n  drawer: \"cubic-bezier(0.32,0.72,0,1)\",\n} as const;\n\nexport const durations = { press: 140, tooltip: 160, menu: 200, panel: 280 } as const; // ms\n\n// Cubic bezier easing for canvas and rAF code. Returns progress y for input x in [0, 1].\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {\n  const cx = 3 * x1;\n  const bx = 3 * (x2 - x1) - cx;\n  const ax = 1 - cx - bx;\n  const cy = 3 * y1;\n  const by = 3 * (y2 - y1) - cy;\n  const ay = 1 - cy - by;\n  const sampleX = (s: number) => ((ax * s + bx) * s + cx) * s;\n  const sampleY = (s: number) => ((ay * s + by) * s + cy) * s;\n  const sampleDX = (s: number) => (3 * ax * s + 2 * bx) * s + cx;\n\n  const solveX = (x: number) => {\n    let s = x;\n    for (let i = 0; i < 8; i++) {\n      const err = sampleX(s) - x;\n      if (Math.abs(err) < 1e-6) return s;\n      const d = sampleDX(s);\n      if (Math.abs(d) < 1e-6) break;\n      s -= err / d;\n    }\n    let lo = 0;\n    let hi = 1;\n    s = x;\n    while (lo < hi) {\n      const v = sampleX(s);\n      if (Math.abs(v - x) < 1e-6) return s;\n      if (x > v) lo = s;\n      else hi = s;\n      s = (lo + hi) / 2;\n      if (hi - lo < 1e-7) break;\n    }\n    return s;\n  };\n\n  return (t: number) => {\n    if (t <= 0) return 0;\n    if (t >= 1) return 1;\n    return sampleY(solveX(t));\n  };\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/motion.ts"
    },
    {
      "path": "components/bjork-ui/_core/tone.ts",
      "content": "\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport type { BjorkTone } from \"./palette\";\n\nconst subscribeNoop = () => () => {};\nconst getMounted = () => true;\nconst getServerMounted = () => false;\n\n/**\n * Resolves the tone for a component. An explicit `tone` always wins.\n * Otherwise it follows next-themes' resolved theme, but only after mount,\n * so the server render and first client render agree on dark.\n */\nexport function useBjorkTone(tone?: BjorkTone): BjorkTone {\n  const { resolvedTheme } = useTheme();\n  const mounted = useSyncExternalStore(subscribeNoop, getMounted, getServerMounted);\n  if (tone) return tone;\n  if (!mounted) return \"dark\";\n  return resolvedTheme === \"light\" ? \"light\" : \"dark\";\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/tone.ts"
    },
    {
      "path": "components/bjork-ui/_core/palette.ts",
      "content": "export type BjorkTone = \"dark\" | \"light\";\n\n// Canvas, WebGL and SVG attribute colours. DOM code uses the CSS tokens with these as fallbacks.\nexport const BJORK_PALETTE = {\n  dark: {\n    bg: \"#050505\", stage: \"#111111\", surface: \"#121212\", raised: \"#161616\", active: \"#202020\",\n    border: \"#232323\", borderStrong: \"#343434\",\n    text: \"#ededed\", textMedium: \"rgba(237,237,237,0.72)\", textMuted: \"rgba(237,237,237,0.6)\",\n    textSoft: \"rgba(237,237,237,0.5)\", textFaint: \"rgba(237,237,237,0.22)\", hair: \"rgba(237,237,237,0.12)\",\n    accent: \"#ec5c13\", accentInk: \"#ec5c13\", accentFill: \"#b84a12\", accentSoft: \"rgba(236,92,19,0.12)\", accentMuted: \"rgba(236,92,19,0.24)\",\n    accentFg: \"#fff2ea\", success: \"#4cc38a\", warning: \"#f2b544\", error: \"#ff5c4d\",\n  },\n  light: {\n    bg: \"#f7f5ef\", stage: \"#f7f5ef\", surface: \"#fffcf6\", raised: \"#f5efe3\", active: \"#efe7d8\",\n    border: \"#eee6db\", borderStrong: \"#e1d7c8\",\n    text: \"#171717\", textMedium: \"rgba(23,23,23,0.78)\", textMuted: \"rgba(23,23,23,0.68)\",\n    textSoft: \"rgba(23,23,23,0.62)\", textFaint: \"rgba(23,23,23,0.22)\", hair: \"rgba(23,23,23,0.10)\",\n    accent: \"#ec7d43\", accentInk: \"#b4531f\", accentFill: \"#ec7d43\", accentSoft: \"rgba(236,125,67,0.10)\", accentMuted: \"rgba(236,125,67,0.20)\",\n    accentFg: \"#3f2112\", success: \"#1f8a55\", warning: \"#a86b00\", error: \"#c8361f\",\n  },\n} as const;\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/palette.ts"
    },
    {
      "path": "components/bjork-ui/_core/loop.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, type RefObject } from \"react\";\n\nexport interface VisibleLoopOptions {\n  enabled?: boolean;\n  fpsCap?: number;\n  rootMargin?: string;\n}\n\n/**\n * Runs `frame(dt, t)` on requestAnimationFrame while the element is near the viewport,\n * the tab is visible and `enabled` is not false. Return `false` from `frame` to go idle\n * until `wake()` is called. Writes `data-loop` on the element: running, idle or paused.\n */\nexport function useVisibleLoop(\n  ref: RefObject<HTMLElement | null>,\n  frame: (dt: number, t: number) => boolean | void,\n  opts?: VisibleLoopOptions,\n): { wake: () => void } {\n  const enabled = opts?.enabled !== false;\n  const fpsCap = opts?.fpsCap ?? 0;\n  const rootMargin = opts?.rootMargin ?? \"96px\";\n\n  const frameRef = useRef(frame);\n  useEffect(() => {\n    frameRef.current = frame;\n  }, [frame]);\n\n  const wakeRef = useRef<() => void>(() => {});\n  const wake = useCallback(() => wakeRef.current(), []);\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof window === \"undefined\") return;\n\n    let wants = true; // false once the frame callback returns false\n    let inView = false;\n    let raf = 0;\n    let last = 0;\n    let t = 0;\n    const minFrame = fpsCap > 0 ? 1000 / fpsCap : 0;\n\n    const canRun = () => enabled && inView && document.visibilityState === \"visible\";\n    const stop = () => {\n      if (raf) cancelAnimationFrame(raf);\n      raf = 0;\n    };\n\n    const update = () => {\n      if (!enabled) {\n        stop();\n        el.dataset.loop = \"paused\";\n        return;\n      }\n      if (!wants) {\n        stop();\n        el.dataset.loop = \"idle\";\n        return;\n      }\n      if (!canRun()) {\n        stop();\n        el.dataset.loop = \"paused\";\n        return;\n      }\n      el.dataset.loop = \"running\";\n      if (!raf) {\n        last = performance.now();\n        raf = requestAnimationFrame(tick);\n      }\n    };\n\n    const tick = (now: number) => {\n      raf = 0;\n      if (!canRun() || !wants) {\n        update();\n        return;\n      }\n      const elapsed = now - last;\n      if (minFrame && elapsed < minFrame - 0.5) {\n        raf = requestAnimationFrame(tick);\n        return;\n      }\n      last = now;\n      const dt = Math.min(0.05, Math.max(0, elapsed / 1000));\n      t += dt;\n      const keep = frameRef.current(dt, t);\n      if (keep === false) {\n        wants = false;\n        update();\n        return;\n      }\n      raf = requestAnimationFrame(tick);\n    };\n\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        inView = entry.isIntersecting;\n        update();\n      },\n      { rootMargin },\n    );\n    observer.observe(el);\n\n    const onVisibility = () => update();\n    document.addEventListener(\"visibilitychange\", onVisibility);\n\n    wakeRef.current = () => {\n      wants = true;\n      update();\n    };\n\n    update();\n\n    return () => {\n      stop();\n      observer.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      wakeRef.current = () => {};\n    };\n  }, [ref, enabled, fpsCap, rootMargin]);\n\n  return useMemo(() => ({ wake }), [wake]);\n}\n\n// matchMedia based check. False on the server.\nexport function isCoarsePointer(): boolean {\n  if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return false;\n  return window.matchMedia(\"(pointer: coarse)\").matches;\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/loop.ts"
    },
    {
      "path": "components/bjork-ui/_core/a11y.tsx",
      "content": "import type { ReactNode } from \"react\";\n\n// Text for assistive tech only.\nexport function VisuallyHidden({ children }: { children: ReactNode }) {\n  return <span className=\"sr-only\">{children}</span>;\n}\n\n// Announces `message` when it changes. Same text re-rendered does not re-announce.\nexport function LiveRegion({\n  message,\n  politeness = \"polite\",\n}: {\n  message: string;\n  politeness?: \"polite\" | \"assertive\";\n}) {\n  return (\n    <span role=\"status\" aria-live={politeness} aria-atomic=\"true\" className=\"sr-only\">\n      {message}\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/a11y.tsx"
    },
    {
      "path": "components/bjork-ui/_core/scene-states.ts",
      "content": "\"use client\";\n\n// Scene States: DOM sections declare camera poses, scroll blends between them.\n//\n//   <section data-scene-state=\"overview\" />\n//   <section data-scene-state=\"detail\" data-scene-lead=\"0.4\" />\n//   <div data-scene-state=\"pinned\" data-scene-hold />   // holds through a sticky span\n//\n// The engine knows nothing about three.js. It returns a blended pose and params,\n// and a small rig damps toward them frame-rate independently. Add `?scene-debug`\n// to the URL to draw every anchor and the probe.\n\nimport { useEffect, useMemo, useRef } from \"react\";\n\nexport type Vec3 = [number, number, number];\n\nexport interface Pose {\n  target: Vec3;\n  radius: number;\n  /** Polar angle from +Y. 0 looks straight down. */\n  phi: number;\n  /** Azimuth around +Y. `null` keeps whatever the previous state had. */\n  theta: number | null;\n}\n\nexport type SceneParams = Record<string, number>;\n\nexport interface StateDef<P extends SceneParams = SceneParams> {\n  pose: Pose;\n  params: P;\n  /** Per-frame damping at 60 fps, 0..1. Defaults to 0.1. */\n  damp?: number;\n  mobile?: { pose?: Partial<Pose>; params?: Partial<P>; damp?: number };\n}\n\nexport interface SceneSample<P extends SceneParams = SceneParams> {\n  pose: Pose & { theta: number };\n  params: P;\n  activeKey: string | null;\n  fromKey: string | null;\n  toKey: string | null;\n  /** Raw blend 0..1 between `fromKey` and `toKey`. */\n  t: number;\n  damp: number;\n  /** True when the active section asked to snap (data-scene-immediate). */\n  immediate: boolean;\n  /** Document-space probe line, useful for debugging. */\n  probe: number;\n}\n\nexport interface SceneStatesOptions<P extends SceneParams = SceneParams> {\n  /** Element to scan for `[data-scene-state]`. Defaults to document.body. */\n  root?: HTMLElement | null;\n  /** Element that scrolls. Defaults to the window. */\n  scrollRoot?: HTMLElement | null;\n  /** Mobile overrides apply while this matches. */\n  mobileQuery?: string;\n  /** Params that blend with easeOutQuad so lights die before the camera arrives. */\n  fadeKeys?: (keyof P & string)[];\n  /** Fallback when no section is registered. */\n  initialKey?: string;\n  /** Force the debug overlay regardless of the URL. */\n  debug?: boolean;\n}\n\nexport interface SceneStates<P extends SceneParams = SceneParams> {\n  sample(scrollY?: number, vh?: number, maxScroll?: number): SceneSample<P>;\n  rescan(): void;\n  destroy(): void;\n  readonly keys: string[];\n}\n\ninterface Entry {\n  el: HTMLElement;\n  key: string;\n  anchorY: number;\n  lead: number | null;\n  immediate: boolean;\n}\n\nconst DEFAULT_DAMP = 0.1;\nconst TAU = Math.PI * 2;\n\nexport const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);\nexport const smoothstep = (t: number) => t * t * (3 - 2 * t);\nexport const easeOutQuad = (t: number) => t * (2 - t);\nexport const lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\n/** Shortest signed difference b - a on the circle. */\nexport function angleDelta(a: number, b: number) {\n  let d = (b - a) % TAU;\n  if (d > Math.PI) d -= TAU;\n  if (d < -Math.PI) d += TAU;\n  return d;\n}\n\n/**\n * Converts a per-frame damping factor (tuned at 60 fps) into the factor for `dt` seconds,\n * so the rig settles the same on a 120 Hz display as on a 60 Hz one.\n */\nexport function dampFactor(damp: number, dt: number) {\n  if (damp >= 1) return 1;\n  return 1 - Math.pow(1 - damp, dt * 60);\n}\n\n/** Exponential approach with rate `lambda` per second. `1 - e^(-9dt)` is the house default. */\nexport function expDamp(current: number, target: number, lambda: number, dt: number) {\n  return lerp(current, target, 1 - Math.exp(-lambda * dt));\n}\n\n/** World-space camera position for a pose: target + r·(sinφ sinθ, cosφ, sinφ cosθ). */\nexport function poseToPosition(pose: Pose, out: Vec3 = [0, 0, 0], theta = pose.theta ?? 0): Vec3 {\n  const s = Math.sin(pose.phi);\n  out[0] = pose.target[0] + pose.radius * s * Math.sin(theta);\n  out[1] = pose.target[1] + pose.radius * Math.cos(pose.phi);\n  out[2] = pose.target[2] + pose.radius * s * Math.cos(theta);\n  return out;\n}\n\n/** Blends two poses. Theta takes the shortest arc; a null theta keeps `fallbackTheta`. */\nexport function blendPose(a: Pose, b: Pose, t: number, fallbackTheta: number, out?: Pose & { theta: number }) {\n  const res = out ?? { target: [0, 0, 0] as Vec3, radius: 0, phi: 0, theta: 0 };\n  res.target[0] = lerp(a.target[0], b.target[0], t);\n  res.target[1] = lerp(a.target[1], b.target[1], t);\n  res.target[2] = lerp(a.target[2], b.target[2], t);\n  res.radius = lerp(a.radius, b.radius, t);\n  res.phi = lerp(a.phi, b.phi, t);\n  const ta = a.theta ?? fallbackTheta;\n  const tb = b.theta ?? fallbackTheta;\n  res.theta = ta + angleDelta(ta, tb) * t;\n  return res;\n}\n\nfunction resolveDef<P extends SceneParams>(def: StateDef<P>, mobile: boolean): StateDef<P> {\n  if (!mobile || !def.mobile) return def;\n  return {\n    pose: { ...def.pose, ...def.mobile.pose },\n    params: { ...def.params, ...def.mobile.params } as P,\n    damp: def.mobile.damp ?? def.damp,\n  };\n}\n\nfunction readScroll(scrollRoot: HTMLElement | null | undefined) {\n  if (scrollRoot) {\n    return {\n      y: scrollRoot.scrollTop,\n      vh: scrollRoot.clientHeight,\n      max: Math.max(0, scrollRoot.scrollHeight - scrollRoot.clientHeight),\n    };\n  }\n  const vh = window.innerHeight;\n  const doc = document.scrollingElement ?? document.documentElement;\n  return { y: window.scrollY, vh, max: Math.max(0, doc.scrollHeight - vh) };\n}\n\n/**\n * Builds the engine. `defs` maps a state key to its pose and params. Every def should\n * carry the same param keys; missing ones fall back to the first def's value.\n */\nexport function createSceneStates<P extends SceneParams>(\n  defs: Record<string, StateDef<P>>,\n  opts: SceneStatesOptions<P> = {},\n): SceneStates<P> {\n  const keys = Object.keys(defs);\n  const fadeKeys = new Set<string>(opts.fadeKeys ?? []);\n  const paramKeys = Array.from(new Set(keys.flatMap((k) => Object.keys(defs[k].params))));\n  const fallbackKey = opts.initialKey && defs[opts.initialKey] ? opts.initialKey : keys[0];\n  const mq =\n    typeof window !== \"undefined\" && opts.mobileQuery ? window.matchMedia(opts.mobileQuery) : null;\n\n  let entries: Entry[] = [];\n  let lastTheta = defs[fallbackKey]?.pose.theta ?? 0;\n  const out: SceneSample<P> = {\n    pose: { target: [0, 0, 0], radius: 0, phi: 0, theta: 0 },\n    params: {} as P,\n    activeKey: null,\n    fromKey: null,\n    toKey: null,\n    t: 0,\n    damp: DEFAULT_DAMP,\n    immediate: false,\n    probe: 0,\n  };\n\n  const def = (key: string) => {\n    const d = defs[key] ?? defs[fallbackKey];\n    return resolveDef(d, Boolean(mq?.matches));\n  };\n\n  const measure = () => {\n    if (typeof window === \"undefined\") return;\n    const root = opts.root ?? document.body;\n    const { y, vh } = readScroll(opts.scrollRoot);\n    const rootTop = opts.scrollRoot ? opts.scrollRoot.getBoundingClientRect().top : 0;\n    const portrait = vh > (opts.scrollRoot?.clientWidth ?? window.innerWidth);\n    const next: Entry[] = [];\n    root.querySelectorAll<HTMLElement>(\"[data-scene-state]\").forEach((el) => {\n      const key = el.dataset.sceneState;\n      if (!key || !defs[key]) return;\n      const rect = el.getBoundingClientRect();\n      const top = rect.top - rootTop + y;\n      const lead = el.dataset.sceneLead != null ? parseFloat(el.dataset.sceneLead) : NaN;\n      const base = {\n        el,\n        key,\n        lead: Number.isFinite(lead) && lead > 0 ? lead : null,\n        immediate: el.hasAttribute(\"data-scene-immediate\"),\n      };\n      if (el.hasAttribute(\"data-scene-hold\") && rect.height > vh) {\n        // Two anchors with the same key: the blend stays flat across the sticky span.\n        next.push({ ...base, anchorY: top + vh / 2 });\n        next.push({ ...base, lead: null, anchorY: top + rect.height - vh / 2 });\n        return;\n      }\n      next.push({ ...base, anchorY: portrait ? top : top + rect.height / 2 });\n    });\n    next.sort((a, b) => a.anchorY - b.anchorY);\n    entries = next;\n    debug?.draw(entries);\n  };\n\n  // Rescans are coalesced to one per frame.\n  let raf = 0;\n  const schedule = () => {\n    if (typeof window === \"undefined\") return;\n    cancelAnimationFrame(raf);\n    raf = requestAnimationFrame(measure);\n  };\n\n  let mo: MutationObserver | null = null;\n  let ro: ResizeObserver | null = null;\n  const debug =\n    typeof window !== \"undefined\" &&\n    (opts.debug || new URLSearchParams(window.location.search).has(\"scene-debug\"))\n      ? createDebugOverlay(opts.scrollRoot ?? null)\n      : null;\n\n  if (typeof window !== \"undefined\") {\n    const root = opts.root ?? document.body;\n    mo = new MutationObserver(schedule);\n    mo.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: [\"data-scene-state\", \"data-scene-lead\", \"data-scene-hold\"] });\n    ro = new ResizeObserver(schedule);\n    ro.observe(root);\n    mq?.addEventListener?.(\"change\", schedule);\n    window.addEventListener(\"resize\", schedule);\n    measure();\n  }\n\n  const blendParams = (a: P, b: P, t: number, tf: number) => {\n    const base = defs[fallbackKey].params;\n    const res = out.params as SceneParams;\n    for (const k of paramKeys) {\n      const va = a[k] ?? base[k] ?? 0;\n      const vb = b[k] ?? base[k] ?? 0;\n      res[k] = lerp(va, vb, fadeKeys.has(k) ? tf : t);\n    }\n  };\n\n  const sample = (scrollY?: number, vh?: number, maxScroll?: number): SceneSample<P> => {\n    const live = typeof window !== \"undefined\" ? readScroll(opts.scrollRoot) : { y: 0, vh: 1, max: 0 };\n    const y = scrollY ?? live.y;\n    const h = vh ?? live.vh;\n    const max = maxScroll ?? live.max;\n\n    if (entries.length === 0) {\n      const d = def(fallbackKey);\n      blendPose(d.pose, d.pose, 0, lastTheta, out.pose);\n      blendParams(d.params, d.params, 0, 0);\n      out.activeKey = out.fromKey = out.toKey = fallbackKey;\n      out.t = 0;\n      out.damp = d.damp ?? DEFAULT_DAMP;\n      out.immediate = false;\n      out.probe = y + h / 2;\n      return out;\n    }\n\n    // Edge-corrected probe: the first and last sections stay reachable.\n    const half = h / 2;\n    const i = 1 - smoothstep(clamp01(y / half));\n    const s = 1 - smoothstep(clamp01((max - y) / half));\n    const c = y + half * (1 - i + s);\n\n    let idx = 0;\n    while (idx < entries.length - 1 && entries[idx + 1].anchorY <= c) idx++;\n    const from = entries[idx];\n    const to = entries[Math.min(idx + 1, entries.length - 1)];\n    const start = to.lead != null ? Math.max(from.anchorY, to.anchorY - to.lead * h) : from.anchorY;\n    const span = to.anchorY - start;\n    const t = span > 0 ? clamp01((c - start) / span) : 0;\n\n    const a = def(from.key);\n    const b = def(to.key);\n    blendPose(a.pose, b.pose, smoothstep(t), lastTheta, out.pose);\n    lastTheta = out.pose.theta;\n    blendParams(a.params, b.params, smoothstep(t), easeOutQuad(t));\n\n    const active = t < 0.5 ? from : to;\n    out.activeKey = active.key;\n    out.fromKey = from.key;\n    out.toKey = to.key;\n    out.t = t;\n    out.damp = def(active.key).damp ?? DEFAULT_DAMP;\n    out.immediate = active.immediate;\n    out.probe = c;\n    debug?.probe(c, y);\n    return out;\n  };\n\n  return {\n    sample,\n    rescan: measure,\n    destroy() {\n      cancelAnimationFrame(raf);\n      mo?.disconnect();\n      ro?.disconnect();\n      mq?.removeEventListener?.(\"change\", schedule);\n      if (typeof window !== \"undefined\") window.removeEventListener(\"resize\", schedule);\n      debug?.destroy();\n      entries = [];\n    },\n    get keys() {\n      return keys;\n    },\n  };\n}\n\n/**\n * A damped follower for poses and params. `update` moves toward the sample using\n * frame-rate independent damping and returns the smoothed values.\n */\nexport function createSceneRig<P extends SceneParams>(initial: { pose: Pose; params: P }) {\n  const pose: Pose & { theta: number } = {\n    target: [...initial.pose.target] as Vec3,\n    radius: initial.pose.radius,\n    phi: initial.pose.phi,\n    theta: initial.pose.theta ?? 0,\n  };\n  const params = { ...initial.params } as P;\n  return {\n    pose,\n    params,\n    update(sample: { pose: Pose; params: P; damp?: number; immediate?: boolean }, dt: number) {\n      const k = sample.immediate ? 1 : dampFactor(sample.damp ?? DEFAULT_DAMP, dt);\n      for (let i = 0; i < 3; i++) pose.target[i] += (sample.pose.target[i] - pose.target[i]) * k;\n      pose.radius += (sample.pose.radius - pose.radius) * k;\n      pose.phi += (sample.pose.phi - pose.phi) * k;\n      if (sample.pose.theta != null) pose.theta += angleDelta(pose.theta, sample.pose.theta) * k;\n      const p = params as SceneParams;\n      for (const key in sample.params) p[key] = (p[key] ?? 0) + (sample.params[key] - (p[key] ?? 0)) * k;\n      return { pose, params };\n    },\n    /** True once every value is within `eps` of the sample. */\n    settled(sample: { pose: Pose; params: P }, eps = 1e-4) {\n      if (Math.abs(sample.pose.radius - pose.radius) > eps) return false;\n      if (Math.abs(sample.pose.phi - pose.phi) > eps) return false;\n      if (sample.pose.theta != null && Math.abs(angleDelta(pose.theta, sample.pose.theta)) > eps) return false;\n      for (let i = 0; i < 3; i++) if (Math.abs(sample.pose.target[i] - pose.target[i]) > eps) return false;\n      for (const key in sample.params) if (Math.abs(sample.params[key] - (params as SceneParams)[key]) > eps) return false;\n      return true;\n    },\n  };\n}\n\n/**\n * React binding. The engine is created once per mount; pass stable `defs`.\n * Returns a ref whose `current` is the engine (null before mount).\n */\nexport function useSceneStates<P extends SceneParams>(\n  defs: Record<string, StateDef<P>>,\n  opts?: SceneStatesOptions<P>,\n) {\n  const ref = useRef<SceneStates<P> | null>(null);\n  const root = opts?.root ?? null;\n  const scrollRoot = opts?.scrollRoot ?? null;\n  const mobileQuery = opts?.mobileQuery;\n  const fadeKey = (opts?.fadeKeys ?? []).join(\",\");\n  const initialKey = opts?.initialKey;\n  const debug = opts?.debug;\n  const stableOpts = useMemo(\n    () => ({\n      root,\n      scrollRoot,\n      mobileQuery,\n      fadeKeys: fadeKey ? (fadeKey.split(\",\") as (keyof P & string)[]) : [],\n      initialKey,\n      debug,\n    }),\n    [root, scrollRoot, mobileQuery, fadeKey, initialKey, debug],\n  );\n\n  useEffect(() => {\n    const engine = createSceneStates(defs, stableOpts);\n    ref.current = engine;\n    return () => {\n      engine.destroy();\n      ref.current = null;\n    };\n  }, [defs, stableOpts]);\n\n  return ref;\n}\n\n// ─── ?scene-debug overlay ─────────────────────────────────────────────────────\n\nfunction createDebugOverlay(scrollRoot: HTMLElement | null) {\n  const layer = document.createElement(\"div\");\n  layer.setAttribute(\"aria-hidden\", \"true\");\n  layer.style.cssText =\n    \"position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:11px/1.2 ui-monospace,monospace;\";\n  const probeLine = document.createElement(\"div\");\n  probeLine.style.cssText =\n    \"position:absolute;left:0;right:0;height:0;border-top:1px dashed #ec5c13;\";\n  const probeLabel = document.createElement(\"span\");\n  probeLabel.style.cssText =\n    \"position:absolute;right:8px;top:-16px;color:#ec5c13;background:rgba(0,0,0,.6);padding:1px 4px;border-radius:3px;\";\n  probeLabel.textContent = \"probe\";\n  probeLine.appendChild(probeLabel);\n  layer.appendChild(probeLine);\n  document.body.appendChild(layer);\n\n  let marks: { el: HTMLDivElement; y: number }[] = [];\n  let lastY = 0;\n  const place = (scrollY: number) => {\n    const offset = scrollRoot ? scrollRoot.getBoundingClientRect().top : 0;\n    for (const m of marks) m.el.style.transform = `translateY(${m.y - scrollY + offset}px)`;\n  };\n\n  return {\n    draw(entries: Entry[]) {\n      marks.forEach((m) => m.el.remove());\n      marks = entries.map((e) => {\n        const el = document.createElement(\"div\");\n        el.style.cssText =\n          \"position:absolute;left:0;right:0;top:0;height:0;border-top:1px solid rgba(80,180,255,.8);\";\n        const label = document.createElement(\"span\");\n        label.style.cssText =\n          \"position:absolute;left:8px;top:-16px;color:#7cc4ff;background:rgba(0,0,0,.6);padding:1px 4px;border-radius:3px;\";\n        label.textContent = `${e.key}${e.lead ? ` lead ${e.lead}` : \"\"}${e.immediate ? \" immediate\" : \"\"}`;\n        el.appendChild(label);\n        layer.appendChild(el);\n        return { el, y: e.anchorY };\n      });\n      place(lastY);\n    },\n    probe(c: number, scrollY: number) {\n      lastY = scrollY;\n      const offset = scrollRoot ? scrollRoot.getBoundingClientRect().top : 0;\n      probeLine.style.transform = `translateY(${c - scrollY + offset}px)`;\n      place(scrollY);\n    },\n    destroy() {\n      layer.remove();\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/scene-states.ts"
    },
    {
      "path": "components/bjork-ui/heroes/aperture-dive-scene.ts",
      "content": "// Aperture Dive scene: a ring of screens standing in sand, seen first from straight above\n// (the eclipse), then from inside. Vanilla three, no post-processing dependency.\n//\n// Everything is shaded in display (sRGB) space on purpose: the landed panel has to match\n// the DOM element it morphs into pixel for pixel, so textures are sampled raw and written\n// raw. A half-float target plus an output dither keeps the dark gradients clean.\n\nimport * as THREE from \"three\";\nimport { poseToPosition, type Pose, type Vec3 } from \"../_core/scene-states\";\n\nexport const PANEL_W = 1.61;\nexport const PANEL_H = 0.98;\nexport const PANEL_D = 0.05;\nexport const PANEL_ASPECT = PANEL_W / PANEL_H;\nconst MAX_PANELS = 12;\n\nexport type DiveTone = \"light\" | \"dark\";\nexport type DiveQuality = \"high\" | \"low\";\n\nexport interface DiveSceneMedia {\n  type: \"image\" | \"video\";\n  src: string;\n  poster?: string;\n  fit: \"cover\" | \"contain\";\n  /** CSS color drawn around contained media. */\n  backdrop: string;\n  /** Contained media inset, as a fraction of the panel height. */\n  inset: number;\n  /** Corner radius of contained media, as a fraction of the panel height. */\n  radius: number;\n}\n\nexport interface DiveFrame {\n  pose: Pose & { theta: number };\n  fov: number;\n  /** Panel width multiplier: narrow slabs overhead, a closed wall when landed. */\n  scaleX: number;\n  saturation: number;\n  haze: number;\n  /** Screen light falling inside the ring. */\n  interior: number;\n  /** Rim light outside the ring: the eclipse. */\n  corona: number;\n  /** 1 adds screen sheen and vignette; 0 is the untouched media the DOM will show. */\n  look: number;\n  ringSpin: number;\n  /** 1 switches the focus screen off: its picture is out in the DOM. */\n  focusOut: number;\n  /** 0..1, how much of the focus screen's light on the sand has gone with it. */\n  focusDim: number;\n  /** 0..1 fade of the whole canvas to the page background. */\n  fade: number;\n}\n\nexport interface DiveSceneOptions {\n  canvas: HTMLCanvasElement;\n  panels: DiveSceneMedia[];\n  focusIndex: number;\n  tone: DiveTone;\n  quality: DiveQuality;\n  haze: boolean;\n  ground: boolean;\n  /** Page background the canvas fades into. */\n  background: string;\n}\n\ninterface Palette {\n  world: THREE.Color;\n  sand: THREE.Color;\n  reliefLow: THREE.Color;\n  reliefHigh: THREE.Color;\n  body: THREE.Color;\n  bodyTop: THREE.Color;\n  corona: THREE.Color;\n  off: THREE.Color;\n}\n\n// Colours are kept in display space: no sRGB → linear conversion anywhere.\nfunction col(value: string) {\n  return new THREE.Color().setStyle(value, THREE.LinearSRGBColorSpace);\n}\n\nfunction palette(tone: DiveTone): Palette {\n  return tone === \"light\"\n    ? {\n        world: col(\"#f2ede3\"),\n        sand: col(\"#e9e1d2\"),\n        reliefLow: col(\"#cdbfa6\"),\n        reliefHigh: col(\"#f6f0e4\"),\n        body: col(\"#d9d1c3\"),\n        bodyTop: col(\"#fbf8f2\"),\n        corona: col(\"#4a3f31\"),\n        off: col(\"#e2dacb\"),\n      }\n    : {\n        world: col(\"#070707\"),\n        sand: col(\"#8a8072\"),\n        reliefLow: col(\"#3a352f\"),\n        reliefHigh: col(\"#fff3e0\"),\n        body: col(\"#0c0c0c\"),\n        bodyTop: col(\"#262422\"),\n        corona: col(\"#ffe9cc\"),\n        off: col(\"#050505\"),\n      };\n}\n\nexport function ringRadius(count: number) {\n  return (count * 1.7) / (Math.PI * 2);\n}\n\n/** Where panel `i` stands: the focus panel sits at -Z, facing the ring centre. */\nexport function panelPlacement(i: number, count: number, focusIndex: number) {\n  const ring = ringRadius(count);\n  const angle = (i - focusIndex) * ((Math.PI * 2) / count);\n  return {\n    angle,\n    x: ring * Math.sin(angle),\n    y: PANEL_H / 2,\n    z: -ring * Math.cos(angle),\n    rotationY: -angle,\n  };\n}\n\n// ─── Shaders ──────────────────────────────────────────────────────────────────\n\nconst COMMON = /* glsl */ `\n  const vec3 LUMA = vec3(0.299, 0.587, 0.114);\n  float hash12(vec2 p) {\n    vec3 p3 = fract(vec3(p.xyx) * 0.1031);\n    p3 += dot(p3, p3.yzx + 33.33);\n    return fract((p3.x + p3.y) * p3.z);\n  }\n`;\n\nconst panelVertex = /* glsl */ `\n  attribute float aFront;\n  uniform float uScaleX;\n  varying vec2 vUv;\n  varying float vFront;\n  varying vec3 vNormal;\n  void main() {\n    vUv = uv;\n    vFront = aFront;\n    vNormal = normalize(mat3(modelMatrix) * normal);\n    vec3 p = vec3(position.x * uScaleX, position.y, position.z);\n    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(p, 1.0);\n  }\n`;\n\nconst panelFragment = /* glsl */ `\n  ${COMMON}\n  uniform sampler2D uMap;\n  uniform float uHasMap;\n  uniform float uMediaAspect;\n  uniform float uPanelAspect;\n  uniform float uFit;\n  uniform float uInset;\n  uniform float uRadius;\n  uniform vec3 uBackdrop;\n  uniform float uScaleX;\n  uniform float uSaturation;\n  uniform float uLook;\n  uniform float uOff;\n  uniform float uLight;\n  uniform vec3 uOffColor;\n  uniform vec3 uBody;\n  uniform vec3 uBodyTop;\n  varying vec2 vUv;\n  varying float vFront;\n  varying vec3 vNormal;\n\n  float roundedBox(vec2 p, vec2 b, float r) {\n    vec2 q = abs(p) - b + r;\n    return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;\n  }\n\n  vec3 media(vec2 uv) {\n    // The visible window narrows with uScaleX: the picture crops, it never squashes.\n    vec2 st = vec2(0.5 + (uv.x - 0.5) * uScaleX, uv.y);\n    if (uFit < 0.5) {\n      vec2 m = st;\n      if (uMediaAspect > uPanelAspect) m.x = 0.5 + (st.x - 0.5) * uPanelAspect / uMediaAspect;\n      else m.y = 0.5 + (st.y - 0.5) * uMediaAspect / uPanelAspect;\n      return texture2D(uMap, m).rgb;\n    }\n    // Contain: a box of height (1 - 2 inset), centred, on the backdrop. Units: panel heights.\n    vec2 p = vec2((st.x - 0.5) * uPanelAspect, st.y - 0.5);\n    float bh = 1.0 - 2.0 * uInset;\n    float bw = bh * uMediaAspect;\n    if (bw > uPanelAspect - 2.0 * uInset) { bw = uPanelAspect - 2.0 * uInset; bh = bw / uMediaAspect; }\n    vec2 hb = vec2(bw, bh) * 0.5;\n    float d = roundedBox(p, hb, uRadius);\n    vec2 m = p / (2.0 * hb) + 0.5;\n    vec3 c = texture2D(uMap, clamp(m, 0.0, 1.0)).rgb;\n    float aa = fwidth(d) * 0.75;\n    return mix(c, uBackdrop, smoothstep(-aa, aa, d));\n  }\n\n  void main() {\n    if (vFront < 0.5) {\n      // Slab body: lit from above, so overhead the ring reads as a thin bright outline.\n      float up = clamp(vNormal.y, 0.0, 1.0);\n      vec3 c = mix(uBody, uBodyTop, up);\n      gl_FragColor = vec4(c, 1.0);\n      return;\n    }\n    vec3 c = uHasMap > 0.5 ? media(vUv) : uBackdrop;\n    c = mix(vec3(dot(c, LUMA)), c, uSaturation);\n    // Screen look (sheen + edge falloff) fades to nothing as the panel lands.\n    if (uLook > 0.001) {\n      float edge = smoothstep(0.0, 0.18, vUv.x) * smoothstep(1.0, 0.82, vUv.x) * smoothstep(0.0, 0.2, vUv.y) * smoothstep(1.0, 0.8, vUv.y);\n      c *= mix(1.0, 0.55 + 0.45 * edge, uLook);\n      c += uLook * 0.05 * smoothstep(0.35, 1.0, vUv.y) * (1.0 - vUv.x);\n    }\n    c *= uLight;\n    c = mix(c, uOffColor, uOff);\n    gl_FragColor = vec4(c, 1.0);\n  }\n`;\n\nconst haloVertex = /* glsl */ `\n  varying vec2 vUv;\n  void main() {\n    vUv = uv;\n    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n  }\n`;\n\nconst haloFragment = /* glsl */ `\n  uniform vec3 uColor;\n  uniform float uStrength;\n  uniform float uScaleX;\n  uniform vec2 uSize;\n  varying vec2 vUv;\n  void main() {\n    vec2 p = (vUv - 0.5) * uSize;\n    vec2 b = vec2(${PANEL_W.toFixed(3)} * 0.5 * uScaleX, ${PANEL_H.toFixed(3)} * 0.5);\n    vec2 q = abs(p) - b;\n    float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);\n    float g = exp(-max(d, 0.0) * 7.0) * step(0.0, d);\n    gl_FragColor = vec4(uColor * g * uStrength, 1.0);\n  }\n`;\n\nconst groundVertex = /* glsl */ `\n  varying vec3 vWorld;\n  varying vec3 vNormal;\n  void main() {\n    vec4 w = modelMatrix * vec4(position, 1.0);\n    vWorld = w.xyz;\n    vNormal = normalize(mat3(modelMatrix) * normal);\n    gl_Position = projectionMatrix * viewMatrix * w;\n  }\n`;\n\nconst groundFragment = /* glsl */ `\n  ${COMMON}\n  #define MAX_PANELS ${MAX_PANELS}\n  uniform int uCount;\n  uniform vec2 uPanelPos[MAX_PANELS];\n  uniform vec2 uPanelNrm[MAX_PANELS];\n  uniform vec3 uPanelCol[MAX_PANELS];\n  uniform float uPanelOn[MAX_PANELS];\n  uniform float uHalfLen;\n  uniform float uInterior;\n  uniform float uCorona;\n  uniform float uSaturation;\n  uniform float uLightMode;\n  uniform float uSparkle;\n  uniform float uTime;\n  uniform float uRing;\n  uniform vec3 uSand;\n  uniform vec3 uReliefLow;\n  uniform vec3 uReliefHigh;\n  uniform vec3 uCoronaColor;\n  uniform vec3 uWorld;\n  varying vec3 vWorld;\n  varying vec3 vNormal;\n\n  void main() {\n    vec2 g = vWorld.xz;\n    // Fine sand normal from hashed value noise; cheap and texture-free.\n    vec2 cell = floor(g * 90.0);\n    float n1 = hash12(cell);\n    float n2 = hash12(cell + 7.13);\n    vec3 nrm = normalize(vNormal + vec3(n1 - 0.5, 0.0, n2 - 0.5) * 0.16);\n    vec3 key = normalize(vec3(-0.6, 0.55, -0.35));\n    float ndl = clamp(dot(nrm, key), 0.0, 1.0);\n    vec3 relief = mix(uReliefLow, uReliefHigh, ndl);\n    float ni = clamp(dot(nrm, vec3(0.0, 1.0, 0.0)) * 1.03, 0.0, 1.0);\n    float facing = ni * ni * ni;\n\n    vec3 screen = vec3(0.0);\n    float rim = 0.0;\n    vec3 rimTint = vec3(0.0);\n    for (int i = 0; i < MAX_PANELS; i++) {\n      if (i >= uCount) break;\n      vec2 d = g - uPanelPos[i];\n      vec2 nv = uPanelNrm[i];\n      float v = dot(d, nv);\n      float u = abs(dot(d, vec2(nv.y, -nv.x)));\n      float lx = max(u - uHalfLen, 0.0);\n      float r = sqrt(lx * lx + v * v) + 1e-4;\n      float cosv = v / r; // 1 straight in front, -1 straight behind\n      if (v > 0.0) {\n        float L = pow(1.0 + r / 0.55, -2.6) * pow(1.0 - min(lx / r, 1.0), 0.6);\n        screen += uPanelCol[i] * L * uPanelOn[i];\n      }\n      // Behind the slab: a tight rim plus a wide halo. Overhead this is the corona.\n      // Weighted by angle so nothing cuts off along the slab's plane.\n      float back = smoothstep(-0.6, 0.6, -cosv);\n      float tight = exp(-r / 0.16) * pow(1.0 - min(lx / r, 1.0), 0.45) * (0.35 + 0.65 * back);\n      float wide = (exp(-r / 1.1) * 0.42 + exp(-r / 3.0) * 0.08) * back;\n      rim += tight + wide;\n      rimTint += uPanelCol[i] * (tight + wide);\n    }\n    screen = mix(vec3(dot(screen, LUMA)), screen, uSaturation);\n    float rimSafe = max(rim, 1e-4);\n    vec3 coronaColor = mix(uCoronaColor, rimTint / rimSafe * 1.6, 0.18 * uSaturation);\n\n    float dist = length(g);\n    float far = smoothstep(uRing * 1.6, uRing * 5.5, dist);\n    vec3 c;\n    if (uLightMode < 0.5) {\n      vec3 sand = uSand * relief;\n      vec3 lit = sand * screen * 9.0 * facing * uInterior;\n      vec3 halo = coronaColor * rim * uCorona * (0.35 + 0.65 * ndl) * 0.9;\n      vec3 ambient = sand * (0.02 + 0.05 * uInterior * ndl) * (1.0 - far);\n      c = ambient + lit + halo;\n      // Grain, gated by how lit the sand is.\n      float grain = hash12(floor(g * 260.0));\n      c *= 1.0 + (grain - 0.5) * 0.3 * clamp(dot(c, LUMA) * 30.0, 0.0, 1.0);\n      if (uSparkle > 0.5) {\n        vec2 sc = g * 140.0;\n        vec2 sCell = floor(sc);\n        float h = hash12(sCell);\n        float pick = step(0.986, h);\n        vec2 j = vec2(hash12(sCell + 17.31), hash12(sCell + 53.17)) - 0.5;\n        float pt = smoothstep(0.3, 0.0, length(fract(sc) - 0.5 - j * 0.5));\n        float tw = sin(uTime * 2.5 + h * 100.0) * 0.5 + 0.5;\n        tw *= tw; tw *= tw; tw *= tw;\n        c += vec3(1.0, 0.97, 0.9) * pick * pt * tw * clamp(dot(c, LUMA) * 4.0, 0.0, 1.2) * 2.5;\n      }\n    } else {\n      // Daylight eclipse: screens throw coloured shadow, the corona is a soft ink ring.\n      vec3 sand = uSand * mix(vec3(1.0), relief, 0.55);\n      float shade = clamp(rim * uCorona * 1.05, 0.0, 0.82);\n      c = sand * (1.0 - shade * (1.0 - uCoronaColor / max(uSand, vec3(0.01))));\n      // The disc inside the ring reads as paper-bright against the ink corona.\n      float inside = 1.0 - smoothstep(uRing * 0.82, uRing * 1.02, dist);\n      c = mix(c, vec3(0.985, 0.975, 0.955), inside * 0.55 * uCorona);\n      float L = clamp(dot(screen, vec3(0.333)) * 2.4 * uInterior, 0.0, 1.0);\n      vec3 tint = mix(vec3(1.0), clamp(screen / max(dot(screen, vec3(0.333)), 1e-3) * 0.55, 0.0, 1.0), 0.75);\n      c *= mix(vec3(1.0), tint, L * facing);\n      float grain = hash12(floor(g * 260.0));\n      c *= 1.0 + (grain - 0.5) * 0.08;\n    }\n    c = mix(c, uWorld, far);\n    gl_FragColor = vec4(c, 1.0);\n  }\n`;\n\nconst postVertex = /* glsl */ `\n  varying vec2 vUv;\n  void main() {\n    vUv = position.xy * 0.5 + 0.5;\n    gl_Position = vec4(position.xy, 0.0, 1.0);\n  }\n`;\n\nconst postFragment = /* glsl */ `\n  ${COMMON}\n  uniform sampler2D tScene;\n  uniform float uHaze;\n  uniform float uTime;\n  uniform float uVignette;\n  uniform float uLightMode;\n  uniform float uFade;\n  uniform vec3 uFadeColor;\n  uniform vec2 uResolution;\n  varying vec2 vUv;\n\n  float vnoise(vec2 p) {\n    vec2 i = floor(p);\n    vec2 f = fract(p);\n    f = f * f * (3.0 - 2.0 * f);\n    float a = hash12(i);\n    float b = hash12(i + vec2(1.0, 0.0));\n    float c = hash12(i + vec2(0.0, 1.0));\n    float d = hash12(i + vec2(1.0, 1.0));\n    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);\n  }\n\n  void main() {\n    vec2 uv = vUv;\n    if (uHaze > 0.001) {\n      // Heat shimmer: strongest low in the frame where the sand is.\n      float low = smoothstep(0.75, 0.0, uv.y);\n      float n = vnoise(vec2(uv.x * 7.0, uv.y * 22.0 - uTime * 1.3)) - 0.5;\n      float heat = sin(uv.y * 64.0 + uTime * 2.2) * cos(uv.x * 11.0 - uTime * 1.1);\n      float w = (n + heat * 0.35) * low * 0.0028 * uHaze;\n      uv += vec2(w, w * 2.2);\n    }\n    vec3 c = texture2D(tScene, uv).rgb;\n    vec2 q = vUv - 0.5;\n    q.x *= uResolution.x / uResolution.y;\n    float vig = smoothstep(0.35, 1.05, length(q));\n    if (uLightMode < 0.5) c *= 1.0 - vig * 0.55 * uVignette;\n    else c = mix(c, c * vec3(0.93, 0.9, 0.85), vig * 0.6 * uVignette);\n    c = mix(c, uFadeColor, uFade);\n    // ±1/2 LSB dither: the half-float scene lands in an 8-bit canvas.\n    c += (hash12(gl_FragCoord.xy + fract(uTime) * 61.0) - 0.5) / 255.0;\n    gl_FragColor = vec4(c, 1.0);\n  }\n`;\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction hash2(x: number, y: number) {\n  const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;\n  return s - Math.floor(s);\n}\n\nfunction valueNoise(x: number, y: number) {\n  const xi = Math.floor(x);\n  const yi = Math.floor(y);\n  const xf = x - xi;\n  const yf = y - yi;\n  const u = xf * xf * (3 - 2 * xf);\n  const v = yf * yf * (3 - 2 * yf);\n  const a = hash2(xi, yi);\n  const b = hash2(xi + 1, yi);\n  const c = hash2(xi, yi + 1);\n  const d = hash2(xi + 1, yi + 1);\n  return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;\n}\n\nfunction buildGround(ring: number, segments: number) {\n  const geo = new THREE.PlaneGeometry(44, 44, segments, segments);\n  geo.rotateX(-Math.PI / 2);\n  const pos = geo.attributes.position as THREE.BufferAttribute;\n  for (let i = 0; i < pos.count; i++) {\n    const x = pos.getX(i);\n    const z = pos.getZ(i);\n    const r = Math.hypot(x, z);\n    // Dunes rise away from the ring; inside it the floor stays near flat.\n    const mask = THREE.MathUtils.smoothstep(r, ring + 0.4, ring + 5);\n    const dune =\n      (valueNoise(x * 0.16 + 3.1, z * 0.22) - 0.5) * 1.0 + (valueNoise(x * 0.42, z * 0.38 + 7.7) - 0.5) * 0.35;\n    const ripple = Math.sin(x * 3.1 + z * 1.4 + valueNoise(x * 0.6, z * 0.6) * 4) * 0.012;\n    pos.setY(i, dune * 0.35 * 2 * mask + ripple + mask * 0.06);\n  }\n  geo.computeVertexNormals();\n  return geo;\n}\n\nfunction buildPanelGeometry() {\n  const geo = new THREE.BoxGeometry(PANEL_W, PANEL_H, PANEL_D);\n  const count = geo.attributes.position.count;\n  const front = new Float32Array(count);\n  // BoxGeometry face order: px, nx, py, ny, pz, nz. pz (index 4) is the screen.\n  for (let v = 16; v < 20; v++) front[v] = 1;\n  geo.setAttribute(\"aFront\", new THREE.BufferAttribute(front, 1));\n  return geo;\n}\n\nfunction cssColor(value: string) {\n  try {\n    return col(value);\n  } catch {\n    return col(\"#000000\");\n  }\n}\n\ninterface PanelRuntime {\n  media: DiveSceneMedia;\n  mesh: THREE.Mesh<THREE.BufferGeometry, THREE.ShaderMaterial>;\n  halo: THREE.Mesh<THREE.PlaneGeometry, THREE.ShaderMaterial> | null;\n  texture: THREE.Texture | null;\n  video: HTMLVideoElement | null;\n  source: CanvasImageSource | null;\n  avg: THREE.Color;\n  avgTarget: THREE.Color;\n  lastSample: number;\n  angle: number;\n}\n\n// ─── Scene ────────────────────────────────────────────────────────────────────\n\nexport class ApertureDiveScene {\n  readonly renderer: THREE.WebGLRenderer;\n  readonly camera: THREE.PerspectiveCamera;\n  readonly ring: number;\n  private scene = new THREE.Scene();\n  private ringGroup = new THREE.Group();\n  private panels: PanelRuntime[] = [];\n  private shared: Record<string, THREE.IUniform>;\n  private ground: THREE.Mesh<THREE.BufferGeometry, THREE.ShaderMaterial> | null = null;\n  private target: THREE.WebGLRenderTarget;\n  private post: THREE.Mesh<THREE.BufferGeometry, THREE.ShaderMaterial>;\n  private postScene = new THREE.Scene();\n  private postCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);\n  private sampleCanvas: HTMLCanvasElement;\n  private sampleCtx: CanvasRenderingContext2D | null;\n  private opts: DiveSceneOptions;\n  private pal: Palette;\n  private width = 1;\n  private height = 1;\n  private disposed = false;\n  private pos: Vec3 = [0, 0, 0];\n  private time = 0;\n  private onFrame?: () => void;\n\n  constructor(opts: DiveSceneOptions, onFrame?: () => void) {\n    this.opts = opts;\n    this.onFrame = onFrame;\n    this.pal = palette(opts.tone);\n    const count = Math.min(opts.panels.length, MAX_PANELS);\n    this.ring = ringRadius(count);\n\n    this.renderer = new THREE.WebGLRenderer({\n      canvas: opts.canvas,\n      antialias: true,\n      alpha: false,\n      powerPreference: \"high-performance\",\n      preserveDrawingBuffer: false,\n    });\n    this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;\n    this.renderer.toneMapping = THREE.NoToneMapping;\n\n    this.camera = new THREE.PerspectiveCamera(15, 1, 0.05, 220);\n    this.target = new THREE.WebGLRenderTarget(1, 1, {\n      type: THREE.HalfFloatType,\n      depthBuffer: true,\n      samples: opts.quality === \"high\" ? 4 : 0,\n    });\n\n    this.shared = {\n      uScaleX: { value: 0.5 },\n      uSaturation: { value: 0 },\n      uLook: { value: 1 },\n      uPanelAspect: { value: PANEL_ASPECT },\n      uOffColor: { value: this.pal.off.clone() },\n      uBody: { value: this.pal.body.clone() },\n      uBodyTop: { value: this.pal.bodyTop.clone() },\n    };\n\n    this.sampleCanvas = document.createElement(\"canvas\");\n    this.sampleCanvas.width = 6;\n    this.sampleCanvas.height = 4;\n    this.sampleCtx = this.sampleCanvas.getContext(\"2d\", { willReadFrequently: true });\n\n    this.scene.background = this.pal.world.clone();\n    this.scene.add(this.ringGroup);\n    this.buildPanels(count);\n    if (opts.ground) this.buildGround(count);\n\n    const tri = new THREE.BufferGeometry();\n    tri.setAttribute(\"position\", new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));\n    this.post = new THREE.Mesh(\n      tri,\n      new THREE.ShaderMaterial({\n        vertexShader: postVertex,\n        fragmentShader: postFragment,\n        uniforms: {\n          tScene: { value: this.target.texture },\n          uHaze: { value: 0 },\n          uTime: { value: 0 },\n          uVignette: { value: 1 },\n          uLightMode: { value: opts.tone === \"light\" ? 1 : 0 },\n          uFade: { value: 0 },\n          uFadeColor: { value: cssColor(opts.background) },\n          uResolution: { value: new THREE.Vector2(1, 1) },\n        },\n        depthTest: false,\n        depthWrite: false,\n      }),\n    );\n    this.post.frustumCulled = false;\n    this.postScene.add(this.post);\n    // Compile every program now so the first scroll does not stall on it.\n    this.renderer.compile(this.scene, this.camera);\n    this.renderer.compile(this.postScene, this.postCamera);\n  }\n\n  private buildPanels(count: number) {\n    const geo = buildPanelGeometry();\n    const haloGeo = new THREE.PlaneGeometry(PANEL_W * 2.1, PANEL_H * 2.6);\n    for (let i = 0; i < count; i++) {\n      const media = this.opts.panels[i];\n      const place = panelPlacement(i, count, this.opts.focusIndex);\n      const angle = place.angle;\n      const uniforms: Record<string, THREE.IUniform> = {\n        ...this.shared,\n        uMap: { value: null },\n        uHasMap: { value: 0 },\n        uMediaAspect: { value: 1 },\n        uFit: { value: media.fit === \"contain\" ? 1 : 0 },\n        uInset: { value: media.inset },\n        uRadius: { value: media.radius },\n        uBackdrop: { value: cssColor(media.backdrop) },\n        uOff: { value: 0 },\n        uLight: { value: 1 },\n      };\n      const mat = new THREE.ShaderMaterial({ vertexShader: panelVertex, fragmentShader: panelFragment, uniforms });\n      const mesh = new THREE.Mesh(geo, mat);\n      mesh.position.set(place.x, place.y, place.z);\n      mesh.rotation.y = place.rotationY;\n      this.ringGroup.add(mesh);\n\n      let halo: PanelRuntime[\"halo\"] = null;\n      if (this.opts.tone === \"dark\") {\n        const haloMat = new THREE.ShaderMaterial({\n          vertexShader: haloVertex,\n          fragmentShader: haloFragment,\n          uniforms: {\n            uColor: { value: new THREE.Color(0, 0, 0) },\n            uStrength: { value: 0 },\n            uScaleX: this.shared.uScaleX,\n            uSize: { value: new THREE.Vector2(PANEL_W * 2.1, PANEL_H * 2.6) },\n          },\n          blending: THREE.AdditiveBlending,\n          transparent: true,\n          depthWrite: false,\n        });\n        halo = new THREE.Mesh(haloGeo, haloMat);\n        // Just behind the slab so the glow only shows around its edges.\n        halo.position.set(0, 0, -PANEL_D * 0.6);\n        mesh.add(halo);\n      }\n\n      const runtime: PanelRuntime = {\n        media,\n        mesh,\n        halo,\n        texture: null,\n        video: null,\n        source: null,\n        avg: new THREE.Color(0.25, 0.25, 0.25),\n        avgTarget: new THREE.Color(0.25, 0.25, 0.25),\n        lastSample: -1,\n        angle,\n      };\n      this.panels.push(runtime);\n      this.loadMedia(runtime, i === this.opts.focusIndex);\n    }\n  }\n\n  private buildGround(count: number) {\n    const geo = buildGround(this.ring, this.opts.quality === \"high\" ? 180 : 110);\n    const mat = new THREE.ShaderMaterial({\n      vertexShader: groundVertex,\n      fragmentShader: groundFragment,\n      uniforms: {\n        uCount: { value: count },\n        uPanelPos: { value: Array.from({ length: MAX_PANELS }, () => new THREE.Vector2()) },\n        uPanelNrm: { value: Array.from({ length: MAX_PANELS }, () => new THREE.Vector2()) },\n        uPanelCol: { value: Array.from({ length: MAX_PANELS }, () => new THREE.Color()) },\n        uPanelOn: { value: new Array(MAX_PANELS).fill(1) },\n        uHalfLen: { value: PANEL_W * 0.25 },\n        uInterior: { value: 0 },\n        uCorona: { value: 1 },\n        uSaturation: { value: 0 },\n        uLightMode: { value: this.opts.tone === \"light\" ? 1 : 0 },\n        uSparkle: { value: this.opts.quality === \"high\" && this.opts.tone === \"dark\" ? 1 : 0 },\n        uTime: { value: 0 },\n        uRing: { value: this.ring },\n        uSand: { value: this.pal.sand.clone() },\n        uReliefLow: { value: this.pal.reliefLow.clone() },\n        uReliefHigh: { value: this.pal.reliefHigh.clone() },\n        uCoronaColor: { value: this.pal.corona.clone() },\n        uWorld: { value: this.pal.world.clone() },\n      },\n    });\n    this.ground = new THREE.Mesh(geo, mat);\n    this.scene.add(this.ground);\n  }\n\n  private setImage(p: PanelRuntime, img: TexImageSource & { width: number; height: number }, w: number, h: number) {\n    if (this.disposed) return;\n    const tex = new THREE.Texture(img as unknown as HTMLImageElement);\n    this.configureTexture(tex);\n    tex.needsUpdate = true;\n    this.applyTexture(p, tex, w / h);\n    p.source = img as CanvasImageSource;\n    this.sampleColor(p, true);\n  }\n\n  private configureTexture(tex: THREE.Texture) {\n    tex.colorSpace = THREE.NoColorSpace;\n    tex.minFilter = THREE.LinearMipmapLinearFilter;\n    tex.magFilter = THREE.LinearFilter;\n    tex.generateMipmaps = true;\n    tex.anisotropy = Math.min(8, this.renderer.capabilities.getMaxAnisotropy());\n  }\n\n  private applyTexture(p: PanelRuntime, tex: THREE.Texture, aspect: number) {\n    const u = p.mesh.material.uniforms;\n    if (p.texture && p.texture !== tex) p.texture.dispose();\n    p.texture = tex;\n    u.uMap.value = tex;\n    u.uHasMap.value = 1;\n    u.uMediaAspect.value = aspect;\n  }\n\n  private loadImage(src: string) {\n    return new Promise<HTMLImageElement>((resolve, reject) => {\n      const img = new Image();\n      img.crossOrigin = \"anonymous\";\n      img.decoding = \"async\";\n      img.onload = () => resolve(img);\n      img.onerror = reject;\n      img.src = src;\n    });\n  }\n\n  private loadMedia(p: PanelRuntime, isFocus: boolean) {\n    const { media } = p;\n    const playVideo = media.type === \"video\" && (isFocus || this.opts.quality === \"high\");\n    const still = media.type === \"image\" ? media.src : media.poster;\n    if (still) {\n      this.loadImage(still)\n        .then((img) => {\n          // A video that already delivered frames wins over its poster.\n          if (p.video && p.video.readyState >= 2) return;\n          this.setImage(p, img, img.naturalWidth, img.naturalHeight);\n        })\n        .catch(() => {});\n    }\n    if (!playVideo) return;\n    const video = document.createElement(\"video\");\n    video.crossOrigin = \"anonymous\";\n    video.muted = true;\n    video.loop = true;\n    video.playsInline = true;\n    video.preload = \"auto\";\n    video.setAttribute(\"muted\", \"\");\n    video.setAttribute(\"playsinline\", \"\");\n    video.src = media.src;\n    p.video = video;\n    const onData = () => {\n      if (this.disposed) return;\n      const tex = new THREE.VideoTexture(video);\n      tex.colorSpace = THREE.NoColorSpace;\n      tex.minFilter = THREE.LinearFilter;\n      tex.magFilter = THREE.LinearFilter;\n      tex.generateMipmaps = false;\n      this.applyTexture(p, tex, video.videoWidth / Math.max(1, video.videoHeight));\n      p.source = video;\n      this.sampleColor(p, true);\n    };\n    video.addEventListener(\"loadeddata\", onData, { once: true });\n    video.play().catch(() => {});\n  }\n\n  /** Average colour of a panel's media, mixed with its backdrop by area. */\n  private sampleColor(p: PanelRuntime, immediate = false) {\n    if (!this.sampleCtx || !p.source) return;\n    try {\n      this.sampleCtx.drawImage(p.source, 0, 0, 6, 4);\n      const data = this.sampleCtx.getImageData(0, 0, 6, 4).data;\n      let r = 0;\n      let g = 0;\n      let b = 0;\n      for (let i = 0; i < data.length; i += 4) {\n        r += data[i];\n        g += data[i + 1];\n        b += data[i + 2];\n      }\n      const n = (data.length / 4) * 255;\n      const c = new THREE.Color(r / n, g / n, b / n);\n      if (p.media.fit === \"contain\") {\n        const aspect = p.mesh.material.uniforms.uMediaAspect.value as number;\n        const bh = 1 - 2 * p.media.inset;\n        const area = Math.min(1, (bh * bh * aspect) / PANEL_ASPECT);\n        c.lerp(cssColor(p.media.backdrop), 1 - area);\n      }\n      // Lift dim content so every screen still throws light; push chroma a little.\n      const lum = c.r * 0.299 + c.g * 0.587 + c.b * 0.114;\n      const gain = 0.55 / Math.max(0.08, Math.sqrt(lum));\n      const sat = 1.5;\n      c.setRGB(\n        Math.min(1.4, (lum + (c.r - lum) * sat) * gain),\n        Math.min(1.4, (lum + (c.g - lum) * sat) * gain),\n        Math.min(1.4, (lum + (c.b - lum) * sat) * gain),\n      );\n      p.avgTarget.copy(c);\n      if (immediate) p.avg.copy(c);\n    } catch {\n      // Tainted source: keep the neutral grey.\n    }\n  }\n\n  resize(width: number, height: number, dpr: number) {\n    this.width = Math.max(1, width);\n    this.height = Math.max(1, height);\n    this.renderer.setPixelRatio(dpr);\n    this.renderer.setSize(this.width, this.height, false);\n    this.target.setSize(Math.round(this.width * dpr), Math.round(this.height * dpr));\n    (this.post.material.uniforms.uResolution.value as THREE.Vector2).set(this.width, this.height);\n    this.camera.aspect = this.width / this.height;\n    this.camera.updateProjectionMatrix();\n  }\n\n  get focusVideo() {\n    return this.panels[this.opts.focusIndex]?.video ?? null;\n  }\n\n  /** Pauses every video except the focus one (or all, with `all`). */\n  setVideosPlaying(playing: boolean, all = false) {\n    this.panels.forEach((p, i) => {\n      if (!p.video) return;\n      const keep = !all && i === this.opts.focusIndex;\n      if (playing || keep) {\n        if (p.video.paused) p.video.play().catch(() => {});\n      } else if (!p.video.paused) p.video.pause();\n    });\n  }\n\n  /** Screen-space corners (CSS px, canvas-relative) of the focus screen: TL, TR, BR, BL. */\n  projectFocus(): [number, number][] {\n    const p = this.panels[this.opts.focusIndex];\n    if (!p) return [];\n    p.mesh.updateWorldMatrix(true, false);\n    return projectPanelCorners(p.mesh.matrixWorld, this.camera, this.shared.uScaleX.value as number, this.width, this.height);\n  }\n\n  render(frame: DiveFrame, dt: number) {\n    if (this.disposed) return;\n    this.time += dt;\n    const s = this.shared;\n    s.uScaleX.value = frame.scaleX;\n    s.uSaturation.value = frame.saturation;\n    s.uLook.value = frame.look;\n\n    this.ringGroup.rotation.y = frame.ringSpin;\n    this.ringGroup.updateMatrixWorld(true);\n\n    applyDiveCamera(this.camera, frame, this.pos);\n\n    const now = performance.now();\n    const k = 1 - Math.exp(-dt * 6);\n    const gu = this.ground?.material.uniforms;\n    const spin = frame.ringSpin;\n    // One video colour readback per frame at most, each video about twice a second.\n    let sampled = false;\n    this.panels.forEach((p, i) => {\n      if (!sampled && p.video && !p.video.paused && now - p.lastSample > 450) {\n        p.lastSample = now;\n        sampled = true;\n        this.sampleColor(p);\n      }\n      p.avg.lerp(p.avgTarget, k);\n      const isFocus = i === this.opts.focusIndex;\n      const off = isFocus ? frame.focusOut : 0;\n      const u = p.mesh.material.uniforms;\n      u.uOff.value = off;\n      if (p.halo) {\n        p.halo.material.uniforms.uColor.value.copy(p.avg);\n        p.halo.material.uniforms.uStrength.value = (0.06 + 0.22 * frame.interior) * (1 - off) * frame.saturation;\n      }\n      if (gu) {\n        // Group yaw `spin` moves a panel at angle a to a - spin.\n        const a = p.angle - spin;\n        (gu.uPanelPos.value[i] as THREE.Vector2).set(this.ring * Math.sin(a), -this.ring * Math.cos(a));\n        (gu.uPanelNrm.value[i] as THREE.Vector2).set(-Math.sin(a), Math.cos(a));\n        (gu.uPanelCol.value[i] as THREE.Color).copy(p.avg);\n        gu.uPanelOn.value[i] = isFocus ? 1 - frame.focusDim : 1;\n      }\n    });\n    if (gu) {\n      gu.uHalfLen.value = PANEL_W * 0.5 * frame.scaleX;\n      gu.uInterior.value = frame.interior;\n      gu.uCorona.value = frame.corona;\n      gu.uSaturation.value = frame.saturation;\n      gu.uTime.value = this.time;\n    }\n\n    const pu = this.post.material.uniforms;\n    pu.uHaze.value = this.opts.haze ? frame.haze * (this.opts.tone === \"light\" ? 0.5 : 1) : 0;\n    pu.uTime.value = this.time;\n    pu.uFade.value = frame.fade;\n    pu.uVignette.value = 0.35 + 0.65 * frame.look;\n\n    this.renderer.setRenderTarget(this.target);\n    this.renderer.render(this.scene, this.camera);\n    this.renderer.setRenderTarget(null);\n    this.renderer.render(this.postScene, this.postCamera);\n    this.onFrame?.();\n  }\n\n  dispose() {\n    this.disposed = true;\n    this.panels.forEach((p) => {\n      p.texture?.dispose();\n      p.mesh.material.dispose();\n      p.halo?.material.dispose();\n      if (p.video) {\n        p.video.pause();\n        p.video.removeAttribute(\"src\");\n        p.video.load();\n      }\n    });\n    this.panels[0]?.mesh.geometry.dispose();\n    this.panels[0]?.halo?.geometry.dispose();\n    this.ground?.geometry.dispose();\n    this.ground?.material.dispose();\n    this.post.geometry.dispose();\n    this.post.material.dispose();\n    this.target.dispose();\n    this.renderer.dispose();\n  }\n}\n\nconst cornerTmp = new THREE.Vector3();\n\n/** Projects a panel's screen face (TL, TR, BR, BL) to CSS px in a w×h viewport. */\nexport function projectPanelCorners(\n  matrixWorld: THREE.Matrix4,\n  camera: THREE.Camera,\n  scaleX: number,\n  width: number,\n  height: number,\n): [number, number][] {\n  const sx = scaleX * PANEL_W * 0.5;\n  const hy = PANEL_H * 0.5;\n  const z = PANEL_D * 0.5;\n  const out: [number, number][] = [];\n  for (const [x, y] of [\n    [-sx, hy],\n    [sx, hy],\n    [sx, -hy],\n    [-sx, -hy],\n  ]) {\n    cornerTmp.set(x, y, z).applyMatrix4(matrixWorld).project(camera);\n    out.push([(cornerTmp.x * 0.5 + 0.5) * width, (-cornerTmp.y * 0.5 + 0.5) * height]);\n  }\n  return out;\n}\n\n/** Places a camera on a dive frame. Shared by the WebGL scene and the CSS fallback. */\nexport function applyDiveCamera(camera: THREE.PerspectiveCamera, frame: DiveFrame, out: Vec3 = [0, 0, 0]) {\n  poseToPosition(frame.pose, out, frame.pose.theta);\n  camera.position.set(out[0], out[1], out[2]);\n  camera.up.set(0, 1, 0);\n  camera.lookAt(frame.pose.target[0], frame.pose.target[1], frame.pose.target[2]);\n  if (Math.abs(camera.fov - frame.fov) > 1e-4) {\n    camera.fov = frame.fov;\n    camera.updateProjectionMatrix();\n  }\n  camera.updateMatrixWorld(true);\n}\n\n// ─── Keyframes ────────────────────────────────────────────────────────────────\n\n/**\n * Monotone cubic (Fritsch–Carlson) through authored keyframes: velocity is continuous\n * across keys, nothing overshoots, and flat holds stay flat.\n */\nexport function monotoneTrack(times: number[], values: number[]) {\n  const n = times.length;\n  const d: number[] = [];\n  const m: number[] = new Array(n).fill(0);\n  for (let i = 0; i < n - 1; i++) d.push((values[i + 1] - values[i]) / (times[i + 1] - times[i]));\n  m[0] = d[0];\n  m[n - 1] = d[n - 2];\n  for (let i = 1; i < n - 1; i++) m[i] = d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2;\n  for (let i = 0; i < n - 1; i++) {\n    if (d[i] === 0) {\n      m[i] = 0;\n      m[i + 1] = 0;\n      continue;\n    }\n    const a = m[i] / d[i];\n    const b = m[i + 1] / d[i];\n    const s = a * a + b * b;\n    if (s > 9) {\n      const t = 3 / Math.sqrt(s);\n      m[i] = t * a * d[i];\n      m[i + 1] = t * b * d[i];\n    }\n  }\n  // Ease out of the first key and into the last: the dive starts and lands at rest.\n  m[0] = 0;\n  m[n - 1] = 0;\n  return (x: number) => {\n    if (x <= times[0]) return values[0];\n    if (x >= times[n - 1]) return values[n - 1];\n    let i = 0;\n    while (i < n - 2 && x > times[i + 1]) i++;\n    const h = times[i + 1] - times[i];\n    const t = (x - times[i]) / h;\n    const t2 = t * t;\n    const t3 = t2 * t;\n    return (\n      (2 * t3 - 3 * t2 + 1) * values[i] +\n      (t3 - 2 * t2 + t) * h * m[i] +\n      (-2 * t3 + 3 * t2) * values[i + 1] +\n      (t3 - t2) * h * m[i + 1]\n    );\n  };\n}\n\nexport interface DiveProfile {\n  overheadRadius: number;\n  /** Fraction of the viewport the landed screen may fill: [width, height]. */\n  landedFill: [number, number];\n  /** How far past the ring centre the camera lands, in ring radii. */\n  landedDistance: number;\n  haze: boolean;\n}\n\nexport const DIVE_PROFILES: Record<DiveQuality, DiveProfile> = {\n  high: { overheadRadius: 34, landedFill: [0.5, 0.56], landedDistance: 1.36, haze: true },\n  low: { overheadRadius: 56, landedFill: [0.86, 0.36], landedDistance: 1.34, haze: false },\n};\n\n/** The landed camera: distance from the ring's far side and the fov that frames the screen. */\nexport function landedFraming(ring: number, aspect: number, profile: DiveProfile) {\n  const dist = ring * profile.landedDistance;\n  const [fw, fh] = profile.landedFill;\n  const half = Math.max(PANEL_W / (fw * aspect), PANEL_H / fh) / (2 * dist);\n  const fov = THREE.MathUtils.radToDeg(2 * Math.atan(half));\n  return { dist, fov: Math.min(68, Math.max(18, fov)) };\n}\n\nexport const DIVE_KEYS = {\n  //            overhead  begin   descend  rim     landed  hold\n  p: /*     */ [0, 0.15, 0.38, 0.58, 0.8, 0.92],\n  phi: /*   */ [0.0001, 0.09, 0.52, 1.06, 1.475, 1.475],\n  theta: /* */ [-0.42, -0.34, -0.17, -0.05, 0, 0],\n  scaleX: /**/ [0.5, 0.54, 0.7, 0.9, 1, 1],\n  sat: /*   */ [0, 0.08, 0.42, 0.82, 1, 1],\n  haze: /*  */ [0.6, 0.9, 1.5, 1.2, 0.35, 0],\n  interior: [0, 0.04, 0.32, 0.78, 1, 1],\n  corona: /**/ [1, 0.95, 0.62, 0.34, 0.2, 0.2],\n  look: /*  */ [1, 1, 0.85, 0.45, 0, 0],\n};\n\nexport function createDiveSampler(ring: number) {\n  const k = DIVE_KEYS;\n  const tracks = {\n    phi: monotoneTrack(k.p, k.phi),\n    theta: monotoneTrack(k.p, k.theta),\n    scaleX: monotoneTrack(k.p, k.scaleX),\n    sat: monotoneTrack(k.p, k.sat),\n    haze: monotoneTrack(k.p, k.haze),\n    interior: monotoneTrack(k.p, k.interior),\n    corona: monotoneTrack(k.p, k.corona),\n    look: monotoneTrack(k.p, k.look),\n    // 0 → 1 travel from the ring centre to the focus screen, front-loaded so the camera\n    // drifts toward the far wall while it is still high.\n    pan: monotoneTrack(k.p, [0, 0.08, 0.38, 0.72, 1, 1]),\n    // 0 → 1 between overhead radius and the landed distance, in log space (a dolly).\n    zoom: monotoneTrack(k.p, [0, 0.12, 0.45, 0.8, 1, 1]),\n    // 0 → 1 between the overhead fov and the landed fov.\n    lens: monotoneTrack(k.p, [0, 0.02, 0.18, 0.62, 1, 1]),\n  };\n\n  return (p: number, aspect: number, profile: DiveProfile, out: DiveFrame): DiveFrame => {\n    const framing = landedFraming(ring, aspect, profile);\n    const pan = tracks.pan(p);\n    const zoom = tracks.zoom(p);\n    out.pose.target[0] = 0;\n    out.pose.target[1] = THREE.MathUtils.lerp(0, PANEL_H / 2, pan);\n    out.pose.target[2] = THREE.MathUtils.lerp(0, -ring, pan);\n    out.pose.radius = Math.exp(THREE.MathUtils.lerp(Math.log(profile.overheadRadius), Math.log(framing.dist), zoom));\n    out.pose.phi = tracks.phi(p);\n    out.pose.theta = tracks.theta(p);\n    out.fov = THREE.MathUtils.lerp(15, framing.fov, tracks.lens(p));\n    out.scaleX = tracks.scaleX(p);\n    out.saturation = tracks.sat(p);\n    out.haze = profile.haze ? tracks.haze(p) : 0;\n    out.interior = tracks.interior(p);\n    out.corona = tracks.corona(p);\n    out.look = tracks.look(p);\n    return out;\n  };\n}\n\nexport function createDiveFrame(): DiveFrame {\n  return {\n    pose: { target: [0, 0, 0], radius: 34, phi: 0.0001, theta: 0 },\n    fov: 15,\n    scaleX: 0.5,\n    saturation: 0,\n    haze: 0.6,\n    interior: 0,\n    corona: 1,\n    look: 1,\n    ringSpin: 0,\n    focusOut: 0,\n    focusDim: 0,\n    fade: 0,\n  };\n}\n\n/** CSS matrix3d that maps a w×h box onto four screen points (TL, TR, BR, BL). */\nexport function quadToMatrix3d(w: number, h: number, q: [number, number][]) {\n  const [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = q;\n  // Square → quad homography (Heckbert), then pre-scale the box to the unit square.\n  const dx1 = x1 - x2;\n  const dx2 = x3 - x2;\n  const dy1 = y1 - y2;\n  const dy2 = y3 - y2;\n  const sx = x0 - x1 + x2 - x3;\n  const sy = y0 - y1 + y2 - y3;\n  let g = 0;\n  let hh = 0;\n  if (Math.abs(sx) > 1e-9 || Math.abs(sy) > 1e-9) {\n    const den = dx1 * dy2 - dx2 * dy1 || 1e-9;\n    g = (sx * dy2 - dx2 * sy) / den;\n    hh = (dx1 * sy - sx * dy1) / den;\n  }\n  const a = x1 - x0 + g * x1;\n  const b = x3 - x0 + hh * x3;\n  const c = x0;\n  const d = y1 - y0 + g * y1;\n  const e = y3 - y0 + hh * y3;\n  const f = y0;\n  const A = a / w;\n  const B = b / h;\n  const D = d / w;\n  const E = e / h;\n  const G = g / w;\n  const H = hh / h;\n  // Column-major for CSS matrix3d.\n  return `matrix3d(${A},${D},0,${G},${B},${E},0,${H},0,0,1,0,${c},${f},0,1)`;\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/heroes/aperture-dive-scene.ts"
    }
  ],
  "cssVars": {
    "light": {
      "bjork-bg": "#f7f3ea",
      "bjork-surface": "#fffcf6",
      "bjork-surface-muted": "rgba(250, 246, 237, 0.94)",
      "bjork-surface-hover": "#f5efe3",
      "bjork-surface-active": "#efe7d8",
      "bjork-panel": "#f8f2e7",
      "bjork-menu": "rgba(255, 252, 246, 0.98)",
      "bjork-field": "rgba(255, 252, 246, 0.96)",
      "bjork-field-muted": "rgba(248, 242, 231, 0.82)",
      "bjork-field-inset": "rgba(239, 231, 216, 0.72)",
      "bjork-error-bg": "#fff0e8",
      "bjork-text": "#171717",
      "bjork-text-strong": "rgba(23, 23, 23, 0.9)",
      "bjork-text-medium": "rgba(23, 23, 23, 0.78)",
      "bjork-text-muted": "rgba(23, 23, 23, 0.68)",
      "bjork-text-soft": "rgba(23, 23, 23, 0.62)",
      "bjork-text-faint": "rgba(23, 23, 23, 0.22)",
      "bjork-inverted-text": "#fff8f0",
      "bjork-border": "#eee6db",
      "bjork-border-muted": "#f5ede2",
      "bjork-border-strong": "#e1d7c8",
      "bjork-thumb": "#a49b8e",
      "bjork-track": "#ded6ca",
      "bjork-accent": "#ec7d43",
      "bjork-accent-hover": "#f0935f",
      "bjork-accent-soft": "rgba(236, 125, 67, 0.1)",
      "bjork-accent-muted": "rgba(236, 125, 67, 0.2)",
      "bjork-accent-badge": "rgba(236, 125, 67, 0.16)",
      "bjork-accent-badge-foreground": "#8d421d",
      "bjork-accent-foreground": "#3f2112",
      "bjork-accent-fill": "#ec7d43",
      "bjork-accent-fill-hover": "#f0935f",
      "bjork-shadow-surface": "inset 0 7px 14px rgba(88, 72, 49, 0.045), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.92), inset 1px 0 0 rgba(88, 72, 49, 0.026), inset -1px 0 0 rgba(255, 255, 255, 0.68), 0 14px 22px -9px rgba(66, 52, 33, 0.11)",
      "bjork-shadow-soft": "inset 0 1px 0 rgba(88, 72, 49, 0.045), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.86)",
      "bjork-shadow-panel": "inset 0 1px 0 rgba(88, 72, 49, 0.04), inset 1px 0 0 rgba(88, 72, 49, 0.024), inset -1px 0 0 rgba(255, 255, 255, 0.64), 0 18px 38px -30px rgba(66, 52, 33, 0.2)",
      "bjork-shadow-menu": "inset 0 1px 0 rgba(88, 72, 49, 0.04), inset 0 12px 24px rgba(88, 72, 49, 0.022), inset 1px 0 0 rgba(88, 72, 49, 0.024), inset -1px 0 0 rgba(255, 255, 255, 0.62), 0 22px 44px -26px rgba(66, 52, 33, 0.22)",
      "bjork-shadow-inset": "inset 0 1px 10px rgba(88, 72, 49, 0.12), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.72)",
      "bjork-ring-offset": "#f7f3ea"
    },
    "dark": {
      "bjork-bg": "#111111",
      "bjork-surface": "#121212",
      "bjork-surface-muted": "rgba(22, 22, 22, 0.92)",
      "bjork-surface-hover": "#161616",
      "bjork-surface-active": "#202020",
      "bjork-panel": "#0d0d0d",
      "bjork-menu": "rgba(18, 18, 18, 0.98)",
      "bjork-field": "rgba(18, 18, 18, 0.95)",
      "bjork-field-muted": "rgba(18, 18, 18, 0.55)",
      "bjork-field-inset": "rgba(9, 9, 9, 0.75)",
      "bjork-error-bg": "#130d0a",
      "bjork-text": "#ededed",
      "bjork-text-strong": "rgba(237, 237, 237, 0.9)",
      "bjork-text-medium": "rgba(237, 237, 237, 0.72)",
      "bjork-text-muted": "rgba(237, 237, 237, 0.6)",
      "bjork-text-soft": "rgba(237, 237, 237, 0.5)",
      "bjork-text-faint": "rgba(237, 237, 237, 0.22)",
      "bjork-inverted-text": "#080808",
      "bjork-border": "#232323",
      "bjork-border-muted": "#1c1c1c",
      "bjork-border-strong": "#343434",
      "bjork-thumb": "#626262",
      "bjork-track": "#090909",
      "bjork-accent": "#ec5c13",
      "bjork-accent-hover": "#f07832",
      "bjork-accent-soft": "rgba(236, 92, 19, 0.12)",
      "bjork-accent-muted": "rgba(236, 92, 19, 0.24)",
      "bjork-accent-badge": "#b84a12",
      "bjork-accent-badge-foreground": "#fff2ea",
      "bjork-accent-foreground": "#fff2ea",
      "bjork-accent-fill": "#b84a12",
      "bjork-accent-fill-hover": "#a84a14",
      "bjork-shadow-surface": "inset 0 7px 14px rgba(255, 255, 255, 0.03), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.06), 0 14px 20px -6px rgba(0, 0, 0, 0.45)",
      "bjork-shadow-soft": "inset 0 1px 0 rgba(255, 255, 255, 0.045)",
      "bjork-shadow-panel": "inset 0 1px 0 rgba(255, 255, 255, 0.035), 0 18px 36px -28px rgba(0, 0, 0, 0.9)",
      "bjork-shadow-menu": "inset 0 1px 0 rgba(255, 255, 255, 0.055), inset 0 12px 24px rgba(255, 255, 255, 0.018), inset 0 -18px 26px rgba(0, 0, 0, 0.24), 0 22px 42px -22px rgba(0, 0, 0, 0.9)",
      "bjork-shadow-inset": "inset 0 1px 10px rgba(0, 0, 0, 0.45)",
      "bjork-ring-offset": "#080808"
    }
  },
  "css": {
    ".bjork-range": {
      "box-shadow": "inset 0 1px 1px rgba(255, 255, 255, 0.04), 0 0 14px rgba(189, 69, 20, 0.06)"
    },
    ".bjork-range::-webkit-slider-thumb": {
      "appearance": "none",
      "width": "16px",
      "height": "8px",
      "border": "0",
      "border-radius": "999px",
      "background": "var(--bjork-thumb)",
      "box-shadow": "inset 0 1px 0 rgba(255, 255, 255, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.42)"
    },
    ".bjork-range::-moz-range-thumb": {
      "width": "16px",
      "height": "8px",
      "border": "0",
      "border-radius": "999px",
      "background": "var(--bjork-thumb)",
      "box-shadow": "inset 0 1px 0 rgba(255, 255, 255, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.42)"
    },
    ".bjork-layered-button-accent, .bjork-layered-button-raised": {
      "position": "relative",
      "isolation": "isolate",
      "appearance": "none",
      "overflow": "hidden",
      "border": "0",
      "border-radius": "13px",
      "box-shadow": "inset 0 1px 0 #ffffff38, 0 4px 6px -1px #0000001a, 0 2px 4px -2px #0000001a",
      "transition": "filter 150ms ease-out, box-shadow 150ms ease-out"
    },
    ".bjork-layered-button-accent::after, .bjork-layered-button-raised::after": {
      "position": "absolute",
      "inset": "0",
      "pointer-events": "none",
      "content": "\"\"",
      "border": "1.5px solid transparent",
      "border-radius": "inherit",
      "background": "linear-gradient(#ffffffb8, #0000003d 41% 75%, #ffffff47) border-box",
      "mix-blend-mode": "overlay",
      "-webkit-mask-image": "linear-gradient(#000, #000), linear-gradient(#000, #000)",
      "mask-image": "linear-gradient(#000, #000), linear-gradient(#000, #000)",
      "-webkit-mask-clip": "padding-box, border-box",
      "mask-clip": "padding-box, border-box",
      "-webkit-mask-origin": "padding-box, border-box",
      "mask-origin": "padding-box, border-box",
      "-webkit-mask-composite": "xor",
      "mask-composite": "exclude"
    },
    ".bjork-layered-button-accent": {
      "color": "oklch(100% 0 0)",
      "text-shadow": "0 -1px #00000040",
      "background": "radial-gradient(ellipse at -20px top, rgba(255, 255, 255, 0.14), transparent), linear-gradient(180deg, #ec5c13 0%, #ec5c13 62%, color-mix(in oklab, #ec5c13 84%, black 16%) 100%)"
    },
    ".bjork-layered-button-raised": {
      "color": "oklch(100% 0 0)",
      "text-shadow": "0 -1px #00000026",
      "background": "radial-gradient(ellipse at -20px top, #ffffff38, #fff0), linear-gradient(180deg, oklch(0.1881 0.006 265), oklch(0.5493 0.0081 265))"
    },
    ".dark .bjork-layered-button-raised": {
      "color": "oklch(0.2574 0.0056 265)",
      "text-shadow": "0 -1px #00000026",
      "background": "radial-gradient(ellipse at -20px top, #ffffff38, #fff0), linear-gradient(180deg, color-mix(in oklab, oklch(0.9674 0.0013 265) 80%, oklch(0.2574 0.0056 265) 20%), color-mix(in oklab, oklch(0.669 0.0107 265) 80%, oklch(0.2574 0.0056 265) 20%))"
    },
    "@media (hover: hover)": {
      ".bjork-layered-button-accent:hover": {
        "filter": "brightness(1.08) saturate(1.04)"
      },
      ".bjork-layered-button-raised:hover": {
        "filter": "brightness(1.08) contrast(0.9)"
      }
    }
  },
  "meta": {
    "collection": "Heroes",
    "registryUrl": "https://ui.isaiahbjork.com/aperture-dive.json",
    "installCommand": "npx shadcn@latest add https://ui.isaiahbjork.com/aperture-dive.json"
  },
  "type": "registry:component"
}