# Metaverse WebXR Controls

This guide covers the dedicated WebXR integration shipped for VR/AR headset
support inside the metaverse canvas.

## React Hook: `useWebXRSession`

The hook at `web/src/hooks/use-webxr-session.ts` centralises session lifecycle
management:

- Detects feature support for `immersive-vr` and `immersive-ar` via the active
  `WebXRManager` instance.
- Exposes `startVR`, `startAR`, and `stopXR` helpers that proxy to the manager
  while tracking session state.
- Surfaces structured support and session status data (`support`, `session`)
  that UI components can consume for enablement/feedback.

Example usage:

```ts
const managerRef = useRef<WebXRManager | null>(null);
const xr = useWebXRSession(managerRef);

await xr.startVR();
if (xr.session.active) {
  // update UI, attach teleportation controls, etc.
}
```

Vitest coverage lives in `web/src/hooks/__tests__/use-webxr-session.test.tsx`
and validates WebGL2/1 detection, success/failure paths, and teardown behaviour.

## UI Layer: `WebXRControls`

`web/src/components/WebXRControls.tsx` renders an accessible control surface for
toggling VR/AR sessions:

- Shows "Enter VR"/"Enter AR" buttons when the corresponding modals are allowed
  and supported.
- Provides an "Exit XR" action while a session is active and surfaces error
  messaging when session handshakes fail.
- Disables buttons automatically when support checks report `false` or a session
  is already active.

Component-level tests in `web/src/components/__tests__/WebXRControls.test.tsx`
exercise button enablement, start handlers, and exit flow.

## Composable Panel: `MetaverseXRPanel`

`web/src/components/MetaverseXRPanel.tsx` encapsulates both hook + UI wiring so
parent experiences can drop in full WebXR controls with minimal code:

```tsx
<MetaverseXRPanel
  managerRef={webXRManagerRef}
  allowVR
  allowAR
  className="absolute top-6 right-6 z-20 w-48"
/>
```

The panel is embedded inside `MetaverseCanvas`, ensuring the primary metaverse
surface now exposes headset entry/exit affordances without duplicating the hook
logic. `web/src/components/__tests__/MetaverseXRPanel.test.tsx` asserts the
panel pipes hook results through to `WebXRControls`.

## Lifecycle During Canvas Cleanup

`MetaverseCanvas` now calls `endSession()` on the underlying `WebXRManager`
during teardown, guaranteeing headset sessions terminate when the canvas
unmounts or reinitialises. This avoids dangling browser sessions and keeps the
hook state in sync with manager lifecycle events.

## Next Steps

- Wire the panel into the R3F-based metaverse entry point
  (`web/src/components/metaverse/MetaverseCanvas.tsx`) to offer mirrored
  controls in React Three Fiber scenes.
- Expand integration tests to simulate headset connect/disconnect once
  Playwright environments expose WebXR emulation APIs.
