# Seat view

> A cinema seat picker that flies you down into the seat you chose and shows the screen from there before you book.

A cinema booking screen with Classic seats, double reclining Lounge beds and Xtreme motion seats, as a phone app and desktop page. Compare screening darkness and house lights, locate surround and overhead speakers, and check the room temperature. On the phone you pick a seat on the map and press See the view: the map gives way to the hall in 3D, seen from straight above, and the camera drops into your seat and tilts up to the screen. A sheet rises with what the seat sees: how far the screen is, how wide it looks, how far off its middle, and Book. Drag the view to look around; Change seat flies back up to the map. On the desktop the map and the view sit side by side, and hovering a seat glides the camera to it, so seats can be compared before choosing one.

A React component by Bruno Delorence: https://brunodelorence.com/components/seat-view. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Mobile · Inputs.

## Anatomy

1. **Showings**: The times of the day, one chosen. A change of showing keeps the seat if it is still free.
2. **Seat map**: A button per seat, row by row, in blocks with the aisles between, under the curve of the screen. Taken seats are outlines; recliners are a darker rose.
3. **Chosen seat**: The accent green, with a soft glow. Pressing it again lets it go.
4. **Bar**: The seat and its price, and See the view, which only works once a seat is chosen.

## Properties

### Layout (`layout`)

1. **App (default)**: One thing at a time on a phone: the map, then the view from the chosen seat, then back.
2. **Desktop**: The map and the view side by side: hovering a seat shows its view, so seats can be compared at a glance.

Use the app below about 900 px wide, and the desktop above it: the view needs room beside the map to be worth hovering.

## When to use

- Booking a numbered seat where where you sit changes what you get: a cinema, a theatre, a concert hall, a stadium.
- A hall whose seats differ in more than price, such as distance, angle or a recliner row, so people can see the difference before they pay.
- A checkout people come back to, where a confident first choice saves a refund or a complaint.

## When not to use

- Unnumbered seating or a standing crowd: a ticket count is enough.
- A hall where every seat sees the same, such as a small screening room. The map alone is quicker.
- A very large venue, with thousands of seats: pick a section first, then show the seats of that section.
- A screen reader’s only way to choose: the view is a picture. The map and the numbers beside the view carry everything it shows.

### The flight

- **0 s**: See the view. The map fades and the hall appears behind it in 3D, seen from straight above, laid out as the map was.
- **0 to 1.5 s**: the camera drops towards the seat by equal ratios of height, so the fall reads as steady, and widens as it comes.
- **0.5 to 1.7 s**: low over the rows, it tilts up to the screen and settles at the eye of someone sitting, 1.2 m above the seat.
- **1.7 s**: the sheet rises. Drag the view to look around; it springs back when let go.
- **Change seat**: the same flight backwards, in 1.25 s, and the map fades back in.

### The numbers

- **Distance** is from the seat to the middle of the screen, along the floor.
- **Field of view** is how wide the screen looks from the seat: the angle between its two edges.
- **Off centre** is how far the seat is to the left or right of the screen’s middle; within 0.2 m it reads Centred.
- **The verdict** is from the distance: under 7.4 m Up close, under 11.6 m Sweet spot, further Full picture.

## Do’s and don’ts

- **Do**: On a desktop, let people hover seats freely before they choose: the view follows the pointer, and choosing is a separate click.
- **Do**: Put the numbers next to the picture. The view shows what it feels like; the numbers make seats comparable.
- **Don’t**: Make the view a step people have to go through. It is an offer: the map and its prices work on their own.

## Content

Short labels, in the words the ticket uses.

- **Seats** are named as on the ticket: `Row F, Seat 8`, or `F8` where space is short.
- **Prices** carry their currency and two decimals: `€12.50`.
- **Distances** are in metres with one decimal; angles are whole degrees.

## Installation

Install it with the shadcn CLI, into components/seat-view of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/seat-view.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/seat-view
```

Or copy all the source files below into one folder of your project. Either way it needs React 19.2 and a bundler with CSS Modules (Next.js, Vite).

Copy these media files to the same paths under your public folder:

The ZIP includes the code, poster, leather texture and provenance. Download the complete trailer from the MP4 address below into the same public path; the full video is kept outside the ZIP to keep the archive small. Its original captions are linked from the publisher in cinema-film-source.ts.

- https://brunodelorence.com/experiments/seat-view/spider-man-screen.webp
- https://brunodelorence.com/experiments/seat-view/media.json
- https://brunodelorence.com/experiments/seat-view/spider-man-trailer-full-3b0ca4312d7c.mp4
- https://brunodelorence.com/experiments/seat-view/materials/leather-pbr.webp
- https://brunodelorence.com/experiments/seat-view/materials/provenance.json

## Usage

```tsx
import { SeatView, type Booking } from './seat-view';

export function SeatPicker({ wide }: { wide: boolean }) {
  return (
    <SeatView
      layout={wide ? 'desktop' : 'app'}
      autoplay={false}
      onBook={(booking: Booking) =>
        fetch('/api/bookings', {
          method: 'POST',
          body: JSON.stringify({ room: booking.room, showing: booking.showtime.id, seat: booking.seat.id, capacity: booking.seat.capacity }),
        })
      }
    />
  );
}
```

## States

- **Nothing chosen**: The map, and See the view greyed out.
- **Seat chosen**: F8 in green, its price in the bar.
- **The view from F8**: The camera has landed in the seat: the screen, the rows in front, and the sheet with what the seat sees.
- **Cinema beds**: Twenty reclining loveseats for up to forty guests, with padded leather, shared footrests, side tables, a matching map and 22 degrees Celsius.
- **Xtreme motion**: Ninety-six motion seats; a film-timed demonstration track with a pause control and motion switch.
- **Sound sources**: Surround and overhead speakers marked in their 3D positions, with house lights on.
- **Up close**: From B4, 6.3 m away: the screen fills 86° of the view, 2.2 m left of its middle.
- **Desktop, no seat**: The hall from the back, and an invitation to hover a seat.
- **Desktop, seat chosen**: The view from F8 beside the map, with Book.

## How it works

- Three room plans share the map and the 3D renderer: Classic has 126 leather seats, Beds has 20 double reclining Lounge loveseats for up to 40 guests, with shared footrests, service tables and shaded reading lamps, and Xtreme has 96 motion seats on hydraulic bases. Each has its own spacing, availability, seat kinds and prices. Changing rooms clears the previous selection and booking.
- Screening mode turns the house lights down: the movie and safety LEDs light the room. House lights reveals the upholstery, acoustic walls and furniture. The sound map marks the actual screen, surround and overhead source positions in the same 3D camera. Temperature is a configurable venue value in degrees Celsius, with room defaults of 21, 22 and 20.
- Xtreme uses an authored demonstration cue track sampled against the actual native video time. The seats pitch, roll and heave on their fixed bases; the eye view follows gently. Pausing the film, switching motion off, leaving the viewport or requesting reduced motion stops the moving seats.
- A shared WebGL renderer builds the auditorium in real 3D: rounded leather seats with headrests, inset back panels, stitching, armrests, cup holders and recliner footrests; carpeted stadium terraces, illuminated aisle treads, timber acoustic panels, speakers and a suspended ceiling. The upholstery uses a CC0 leather normal/roughness texture, a GGX dielectric BRDF and ACES tone mapping. A rectangular screen light and a warm ceiling light cast filtered depth shadows from the actual geometry; a rough Fresnel reflection intersects the screen plane. The same decoded video frame displayed on screen is downsampled into a 320 × 136 texture on requestVideoFrameCallback. That texture drives the area light and rough reflections, including while seeking; pause retains the exact frame. Leather uses higher roughness and restrained reflectance, without a clearcoat-like shine.
- The cinema screen plays the complete public Columbia Pictures trailer (about 2 minutes 53 seconds) in a loop for Spider-Man: No Way Home, from a local MP4 through one native HTML video element. A CSS homography projects it into the exact screen plane of the WebGL camera. The same video supplies the light/reflection pixels and Xtreme clock. Play, pause, mute, loop, hidden views and reduced motion control that single source; the publisher’s full caption track is linked and media provenance is bundled.
- The flight is a function of time between two cameras: the plan, high above the hall with a long lens so it reads as a map, and the eye of someone sitting in the seat. The height falls by equal ratios, so the drop reads as steady, the lens widens, and only once low does the camera tilt up to the screen.
- Camera flights and dragging draw as they move. Actual decoded video frames repaint the auditorium; camera animation can draw between them. Paused films and hidden instances retain their last frame. All instances share one WebGL context and immutable geometry. Reduced motion starts the film paused, with an explicit Play control.
- What a seat sees is worked out from where it is: the distance to the screen’s middle, the screen’s width as an angle between its two edges, and the offset from its middle. The verdict (Up close, Sweet spot, Full picture) comes from the distance.
- Each layout is laid out at its design size, the phone at 430 by 902 px and the window at 1180 by 720, and scaled as one picture to fit its box; the canvas sizes its pixels to its size on screen, so it stays sharp.
- The seat map is a grid for the keyboard: one seat is in the tab order, and the arrow keys, Home and End move between seats. On the desktop, hovering or focusing a seat shows its view, and a click chooses it.
- While on screen and untouched, a pointer picks a seat near the screen, one in the middle and a recliner at the back, and looks from each; on the desktop it hovers across the hall, then chooses a seat.

## API reference

- **defaultRoom** (`'classic' | 'beds' | 'xtreme'`, default `'classic'`): The starting room. Its map, furniture, availability and price change together.
- **defaultHouseLights** (`boolean`, default `false`): Start with the house lights on, rather than screening darkness.
- **defaultSoundMap** (`boolean`, default `false`): Show the projected sound source markers on the speakers.
- **defaultMotion** (`boolean`, default `true`): Enable Xtreme’s demonstration motion track, while the film plays. Reduced motion always stops the moving seats.
- **temperature** (`number`, default `21 / 22 / 20 by room`): Venue-supplied degrees Celsius. The demo does not read a temperature sensor.
- **layout** (`'app' | 'desktop'`, default `'app'`): The phone, which flies into the seat; or the browser window, with the view always beside the map.
- **cinema** (`string`, default `'Meridian'`): The cinema’s name, over the map.
- **hall** (`string`, default `'Hall 3 · Fri 14 Nov'`): The line under it: the hall and the day.
- **showtimes** (`Showtime[]`, default `SHOWTIMES`): The showings, each with an id, a time and an optional format such as IMAX. The seats taken differ by showing.
- **defaultShowtime** (`string`, default `the second`): The id of the showing chosen at first.
- **defaultSeat** (`string`): The seat chosen at first, such as "F8", unless it is taken. Given, it turns the demo off.
- **defaultViewing** (`boolean`, default `false`): App only: opens on the view from defaultSeat, its sheet up.
- **onSeatChange** (`(seat: Seat | null) => void`): Called when a seat is chosen, or let go.
- **onBook** (`(booking: Booking) => void`): Called by Book, with the room, showing, seat and price.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a pointer picks seats and looks from them; never under reduced motion.
- **maxHeight** (`number`, default `640 (app), 900 (desktop)`): The tallest the layout is drawn, in px. It is also never wider than its box: it scales down as one picture.
- **className** (`string`): Added to the root.

## Accessibility

### Focus and keyboard

- The map is one stop in the tab order: the arrow keys move between seats, Home and End go to the ends of a row, Space or Enter chooses.
- On the desktop, moving the focus shows that seat’s view, as hovering does.

### Screen readers

- Each seat is a toggle button named by its row, number, kind and price, or taken.
- The canvas is hidden: the sheet, or the desktop’s card, says in words and numbers what the view shows.

### Motion

With reduced motion the camera cuts instead of flying, the sheet appears without rising, the demo stays still and the film starts paused. Play is an explicit choice.

### In this build

- Each seat is a toggle button named by its row, number, kind and price, or taken: “Row F, seat 8, standard, €12.50, toggle button, pressed”. Taken seats are aria-disabled.
- The map takes one stop in the tab order; the arrow keys, Home and End move between seats, and Space or Enter chooses one.
- The 3D view is a picture and is hidden from screen readers: the sheet, or the desktop’s card, gives what it shows in words and numbers.
- Showings and room types are radio groups. Lighting, sound-source markers and Xtreme motion are labelled toggle buttons; the temperature has a spoken Celsius label. Seat and price changes are announced.
- Under reduced motion the camera cuts to the seat, the sheet appears without rising, the film starts paused and Xtreme seats remain still even if the reader explicitly plays the film.

## Source

### seat-view/seat-view.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
  type RefObject,
} from 'react';
import { DemoPointer, runDemo, type Demo } from './demo-pointer';
import {
  ROOM_INFO,
  roomPlan,
  seatKindLabel,
  mapCamera,
  overviewCamera,
  seatCamera,
  seatStats,
  takenSeats,
  type Seat,
  type RoomKind,
} from './hall';
import { RoomContext, RoomPicker, RoomTools, useRoom } from './room-environment';
import styles from './seat-view.module.css';
import { useAutoplay } from './use-autoplay';
import { useHall } from './use-hall';
import { CinemaFilm } from './cinema-film';

/*
 * Seat view: a cinema's seat picker that shows the view from a seat before you book it. Two
 * layouts share the hall and its seats:
 *
 *   app      a phone. Pick a seat on the map and Continue: the map gives way to the hall in 3D,
 *            seen from straight above, and the camera drops into the seat and tilts up to the
 *            screen. A sheet rises with what the seat sees (how far the screen is, how wide it
 *            looks, how far off its middle) and Book. Drag the view to look around; Change seat
 *            flies back up to the map.
 *   desktop  a browser window. The map is on the left and the view on the right, live: hover a
 *            seat and the camera glides to it, so you can compare seats before choosing one.
 *
 * The hall uses the shared WebGL auditorium in cinema-gl.ts. The film is an official Sony
 * complete trailer projected into the same camera plane by cinema-film.tsx. Camera flights,
 * dragging and the seat map share the geometry in hall.ts.
 */

export type Showtime = { id: string; time: string; format?: string };

export const SHOWTIMES: Showtime[] = [
  { id: 'fri-1730', time: '17:30', format: '2D' },
  { id: 'fri-1945', time: '19:45', format: 'IMAX' },
  { id: 'fri-2215', time: '22:15', format: '2D' },
];

export type Booking = { showtime: Showtime; seat: Seat; price: number; room: RoomKind };

const PRICE = { standard: 12.5, recliner: 16, bed: 28, motion: 22 } as const;
const money = new Intl.NumberFormat('en-IE', { style: 'currency', currency: 'EUR' });
const metres = (m: number) => `${m.toFixed(1)} m`;

export type SeatViewProps = {
  /** Each room has its own physical plan, capacity and prices. */
  defaultRoom?: RoomKind;
  defaultHouseLights?: boolean;
  defaultSoundMap?: boolean;
  /** Xtreme's preview cue track follows the actual film timeline. */
  defaultMotion?: boolean;
  /** Degrees Celsius, supplied by the venue. */
  temperature?: number;
  /** 'app' is the phone; 'desktop' the browser window, with the view always beside the map. */
  layout?: 'app' | 'desktop';
  /** The cinema and the hall, over the map. */
  cinema?: string;
  hall?: string;
  showtimes?: Showtime[];
  /** The showing selected at first, by id. */
  defaultShowtime?: string;
  /** The seat chosen at first, such as "F8". */
  defaultSeat?: string;
  /** App only: opens on the view from defaultSeat, its sheet up. */
  defaultViewing?: boolean;
  /** Called when a seat is chosen, or let go (null). */
  onSeatChange?: (seat: Seat | null) => void;
  /** Called by Book. */
  onBook?: (booking: Booking) => void;
  /** While on screen and untouched, a pointer picks seats and looks from them. */
  autoplay?: boolean;
  /** The tallest the layout is drawn, in px; it is also never wider than its box. */
  maxHeight?: number;
  className?: string;
};

/* Pieces both layouts use. */

function Showtimes({
  showtimes,
  value,
  onChange,
}: {
  showtimes: Showtime[];
  value: string;
  onChange: (id: string) => void;
}) {
  return (
    <div className={styles.showtimes} role="radiogroup" aria-label="Showing" data-part="showtimes">
      {showtimes.map((showtime) => (
        <button
          key={showtime.id}
          type="button"
          role="radio"
          aria-checked={showtime.id === value}
          className={styles.showtime}
          data-showtime={showtime.id}
          onClick={() => onChange(showtime.id)}
        >
          {showtime.time}
          {showtime.format && <span className={styles.format}>{showtime.format}</span>}
        </button>
      ))}
    </div>
  );
}

function Legend() {
  const { room } = useRoom();
  const states =
    room === 'classic'
      ? (['available', 'taken', 'recliner', 'chosen'] as const)
      : (['available', 'taken', 'chosen'] as const);
  return (
    <ul className={styles.legend} aria-hidden="true">
      {states.map((state) => (
        <li key={state}>
          <span className={styles.swatch} data-state={state} />
          {state === 'chosen' ? 'Selected' : state[0].toUpperCase() + state.slice(1)}
        </li>
      ))}
    </ul>
  );
}

const seatLabel = (seat: Seat, taken: boolean) =>
  `Row ${seat.row}, seat ${seat.number}, ${seatKindLabel(seat.kind)}, ${taken ? 'taken' : money.format(PRICE[seat.kind])}`;

/**
 * The seat map: a row of buttons per row, in three blocks with aisles between them. One seat is
 * in the tab order at a time, and the arrow keys move between seats, as in a grid.
 */
function SeatMap({
  taken,
  chosen,
  shown,
  onChoose,
  onShow,
}: {
  taken: Set<string>;
  chosen: string | null;
  /** The seat whose view is shown, on the desktop: it is marked while hovered. */
  shown?: string | null;
  onChoose: (id: string) => void;
  onShow?: (id: string | null) => void;
}) {
  const { room } = useRoom();
  const { rows: ROWS, blocks: BLOCK_NUMBERS, byId: SEAT_BY_ID } = roomPlan(room);
  const [focus, setFocus] = useState(
    chosen ?? roomPlan(room).seats[Math.floor(roomPlan(room).seats.length / 2)].id,
  );
  const grid = useRef<HTMLDivElement>(null);
  const width = BLOCK_NUMBERS.flat().length;

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const seat = SEAT_BY_ID.get(focus);
    if (!seat) return;
    const moves: Record<string, [number, number]> = {
      ArrowLeft: [0, -1],
      ArrowRight: [0, 1],
      ArrowUp: [-1, 0],
      ArrowDown: [1, 0],
    };
    let next: string | null = null;
    if (event.key in moves) {
      const [dr, dn] = moves[event.key];
      const r = Math.min(ROWS.length - 1, Math.max(0, ROWS.indexOf(seat.row) + dr));
      const n = Math.min(width, Math.max(1, seat.number + dn));
      next = `${ROWS[r]}${n}`;
    } else if (event.key === 'Home') next = `${seat.row}1`;
    else if (event.key === 'End') next = `${seat.row}${width}`;
    if (!next) return;
    event.preventDefault();
    setFocus(next);
    onShow?.(next);
    grid.current?.querySelector<HTMLElement>(`[data-seat="${next}"]`)?.focus();
  };

  return (
    // The arrow keys are the grid's own: each seat inside is a button.
    // eslint-disable-next-line jsx-a11y/no-static-element-interactions
    <div
      ref={grid}
      className={styles.map}
      data-part="map"
      data-room={room}
      onKeyDown={onKeyDown}
      onPointerLeave={() => onShow?.(null)}
      onBlur={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget)) onShow?.(null);
      }}
    >
      <div className={styles.screenArc} aria-hidden="true">
        <span>Screen</span>
      </div>
      {ROWS.map((row) => (
        <div key={row} className={styles.row} role="group" aria-label={`Row ${row}`}>
          <span className={styles.rowLabel} aria-hidden="true">
            {row}
          </span>
          {BLOCK_NUMBERS.map((block, b) => (
            <div key={b} className={styles.block}>
              {block.map((number) => {
                const id = `${row}${number}`;
                const seat = SEAT_BY_ID.get(id)!;
                const isTaken = taken.has(id);
                return (
                  <button
                    key={id}
                    type="button"
                    className={styles.seat}
                    data-seat={id}
                    data-kind={seat.kind}
                    data-taken={isTaken || undefined}
                    data-shown={(shown === id && chosen !== id) || undefined}
                    aria-pressed={chosen === id}
                    aria-disabled={isTaken || undefined}
                    aria-label={seatLabel(seat, isTaken)}
                    tabIndex={focus === id ? 0 : -1}
                    onFocus={() => {
                      setFocus(id);
                      onShow?.(id);
                    }}
                    onPointerEnter={(event) => {
                      if (event.pointerType === 'mouse') onShow?.(id);
                    }}
                    onClick={() => {
                      if (!isTaken) onChoose(id);
                    }}
                  />
                );
              })}
            </div>
          ))}
          <span className={styles.rowLabel} aria-hidden="true">
            {row}
          </span>
        </div>
      ))}
    </div>
  );
}

/** What a seat sees, in three tiles. */
function Stats({ seat }: { seat: Seat }) {
  const stats = seatStats(seat);
  const side =
    stats.offset === 0
      ? ['Centred', 'on the screen']
      : [metres(Math.abs(stats.offset)), `${stats.offset < 0 ? 'left' : 'right'} of centre`];
  return (
    <dl className={styles.stats} data-part="stats">
      <div>
        <dt>to screen</dt>
        <dd>{metres(stats.distance)}</dd>
      </div>
      <div>
        <dt>field of view</dt>
        <dd>{Math.round(stats.fieldOfView)}°</dd>
      </div>
      <div>
        <dt>{side[1]}</dt>
        <dd>{side[0]}</dd>
      </div>
    </dl>
  );
}

/** The hall in miniature, the seat lit: where it is, at a glance. */
function MiniMap({ seat }: { seat: Seat }) {
  const { room } = useRoom();
  const { rows: ROWS, blocks: BLOCK_NUMBERS } = roomPlan(room);
  const count = BLOCK_NUMBERS.flat().length;
  return (
    <svg className={styles.mini} viewBox="0 0 64 52" aria-hidden="true">
      <path d="M8 6 Q32 1 56 6" className={styles.miniScreen} />
      {ROWS.map((row, r) =>
        BLOCK_NUMBERS.flat().map((number) => {
          const x = 7 + ((number - 1) * 50) / count;
          const on = seat.row === row && seat.number === number;
          return (
            <rect
              key={`${row}${number}`}
              x={x}
              y={12 + r * (36 / ROWS.length)}
              width="2.6"
              height="2.6"
              rx="0.6"
              className={on ? styles.miniOn : styles.miniSeat}
            />
          );
        }),
      )}
    </svg>
  );
}

/** Book, once a seat is chosen; Booked after. */
function BookButton({
  seat,
  booked,
  onBook,
  disabled,
  children,
}: {
  seat: Seat;
  booked: boolean;
  onBook: () => void;
  disabled?: boolean;
  children?: ReactNode;
}) {
  return (
    <button
      type="button"
      className={styles.primary}
      data-booked={booked || undefined}
      data-action="book"
      data-part="book"
      disabled={disabled}
      onClick={() => {
        if (!booked) onBook();
      }}
    >
      {booked ? (
        <>
          <svg viewBox="0 0 16 16" aria-hidden="true" className={styles.tick}>
            <path d="M3.5 8.5l3 3 6-7" />
          </svg>
          Booked
        </>
      ) : (
        (children ?? `Book · ${money.format(PRICE[seat.kind])}`)
      )}
    </button>
  );
}

/* Scaling: each layout is drawn at its design size and scaled to fit. */

function useFit(width: number, height: number, maxHeight: number) {
  const box = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(0);
  useLayoutEffect(() => {
    const element = box.current;
    if (!element) return;
    const measure = () => {
      const available = element.clientWidth;
      setScale(Math.min(1, available / width, maxHeight / height));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, [width, height, maxHeight]);
  return { box, scale };
}

/* The demo's helpers. */

/** The middle of `element`, in `stage`'s px. */
function middleOf(stage: HTMLElement, element: Element | null | undefined) {
  const s = stage.getBoundingClientRect();
  const r = element?.getBoundingClientRect();
  if (!r) return { x: s.width / 2, y: s.height / 2 };
  return { x: r.left - s.left + r.width / 2, y: r.top - s.top + r.height / 2 };
}

/** The first seat of `ids` that is free. */
const firstFree = (ids: string[], taken: Set<string>, room: RoomKind) =>
  ids.find((id) => roomPlan(room).byId.has(id) && !taken.has(id)) ??
  roomPlan(room).seats.find((s) => !taken.has(s.id))!.id;

/** The seats the demo picks: one near the screen, one in the middle, a recliner at the back. */
const DEMO_SEATS = [
  ['B4', 'B5', 'B3', 'C4'],
  ['F8', 'F7', 'E8', 'F9'],
  ['I12', 'I11', 'H12', 'I10'],
];

/* The app. */

const PHONE = { width: 430, height: 902 };
const APP_ZOOM = 1.25;
const APP_CENTRE = 0.33;
const FLIGHT_MS = 1700;
const LIFT_MS = 1250;

type Stage = 'map' | 'landing' | 'view' | 'lifting';

function AppLayout({
  cinema,
  hall,
  showtimes,
  defaultShowtime,
  defaultSeat,
  defaultViewing,
  onSeatChange,
  onBook,
  demoRef,
}: Required<Pick<SeatViewProps, 'cinema' | 'hall' | 'showtimes'>> &
  Pick<
    SeatViewProps,
    'defaultShowtime' | 'defaultSeat' | 'defaultViewing' | 'onSeatChange' | 'onBook'
  > & { demoRef: RefObject<DemoActions | null> }) {
  const [showtime, setShowtime] = useState(defaultShowtime ?? showtimes[1]?.id ?? showtimes[0].id);
  const { room } = useRoom();
  const { byId: SEAT_BY_ID } = roomPlan(room);
  const taken = useMemo(() => takenSeats(showtime, room), [showtime, room]);
  const [chosen, setChosen] = useState<string | null>(
    defaultSeat && SEAT_BY_ID.has(defaultSeat) && !taken.has(defaultSeat) ? defaultSeat : null,
  );
  const [stage, setStage] = useState<Stage>(defaultViewing && chosen ? 'view' : 'map');
  const [booked, setBooked] = useState(false);
  const seat = chosen ? SEAT_BY_ID.get(chosen)! : null;
  const plan = useMemo(() => mapCamera(room), [room]);
  const startCamera = useMemo(
    () => (stage === 'view' && seat ? seatCamera(seat, APP_ZOOM, APP_CENTRE) : plan),
    // The camera it starts from only.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );
  const hallView = useHall(startCamera);
  const drag = useRef<{ x: number; y: number; id: number } | null>(null);
  const reduced = useRef(false);

  useEffect(() => {
    reduced.current = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  }, []);

  useEffect(() => {
    hallView.setLook({ chosen });
  }, [chosen, hallView]);

  const choose = useCallback(
    (id: string | null) => {
      setChosen(id);
      setBooked(false);
      onSeatChange?.(id ? SEAT_BY_ID.get(id)! : null);
    },
    [onSeatChange, SEAT_BY_ID, setChosen, setBooked],
  );

  const pickShowtime = (id: string) => {
    setShowtime(id);
    if (chosen && takenSeats(id, room).has(chosen)) choose(null);
  };

  const land = useCallback(() => {
    if (!seat || stage !== 'map') return;
    setStage('landing');
    hallView.jump(plan);
    hallView
      .moveTo(seatCamera(seat, APP_ZOOM, APP_CENTRE), reduced.current ? 0 : FLIGHT_MS, 'land')
      .then(() => setStage('view'));
  }, [seat, stage, hallView, plan, setStage]);

  const lift = useCallback(() => {
    if (stage !== 'view') return;
    setStage('lifting');
    hallView.moveTo(plan, reduced.current ? 0 : LIFT_MS, 'lift').then(() => setStage('map'));
  }, [stage, hallView, plan, setStage]);

  const book = () => {
    if (!seat) return;
    setBooked(true);
    onBook?.({
      showtime: showtimes.find((s) => s.id === showtime)!,
      seat,
      price: PRICE[seat.kind],
      room,
    });
  };

  // The demo's hands on the controls.
  useLayoutEffect(() => {
    demoRef.current = { choose, land, lift, stage, taken };
  }, [demoRef, choose, land, lift, stage, taken]);

  const onPointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {
    if (stage !== 'view') return;
    event.currentTarget.setPointerCapture(event.pointerId);
    drag.current = { x: event.clientX, y: event.clientY, id: event.pointerId };
  };
  const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {
    const start = drag.current;
    if (!start || start.id !== event.pointerId) return;
    hallView.peekBy(event.clientX - start.x, event.clientY - start.y);
  };
  const onPointerUp = () => {
    if (!drag.current) return;
    drag.current = null;
    hallView.release();
  };

  const stats = seat ? seatStats(seat) : null;
  const time = showtimes.find((s) => s.id === showtime);

  return (
    <div className={styles.phone}>
      <div className={styles.screen} data-stage={stage}>
        <canvas
          ref={hallView.attach}
          className={styles.hall}
          data-part="view"
          aria-hidden="true"
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerUp}
        />
        <CinemaFilm hall={hallView} active={stage !== 'map'} />
        <canvas
          ref={hallView.attachSoundOverlay}
          className={styles.soundOverlay}
          aria-hidden="true"
        />
        <div className={styles.status} aria-hidden="true">
          <span>9:41</span>
          <span className={styles.island} />
          <StatusIcons />
        </div>

        {/* The map, over the hall. */}
        <div className={styles.mapLayer} inert={stage !== 'map'}>
          <header className={styles.appHeader}>
            <button type="button" className={styles.round} aria-label="Back">
              <Chevron />
            </button>
            <div className={styles.title}>
              <strong>{cinema}</strong>
              <span>{hall}</span>
            </div>
            <button type="button" className={styles.round} aria-label="About this hall">
              <Info />
            </button>
          </header>
          <Showtimes showtimes={showtimes} value={showtime} onChange={pickShowtime} />
          <RoomPicker />
          <div className={styles.mapArea}>
            <SeatMap
              taken={taken}
              chosen={chosen}
              onChoose={(id) => choose(id === chosen ? null : id)}
            />
            <Legend />
          </div>
          <div className={styles.bar} data-part="bar">
            <div className={styles.choice} aria-live="polite">
              {seat ? (
                <>
                  <span>
                    Row {seat.row} · Seat {seat.number}
                  </span>
                  <strong>{money.format(PRICE[seat.kind])}</strong>
                </>
              ) : (
                <>
                  <span>Choose your seat</span>
                  <strong aria-hidden="true">—</strong>
                </>
              )}
            </div>
            <button
              type="button"
              className={styles.continue}
              data-action="continue"
              disabled={!seat}
              onClick={land}
            >
              See the view
            </button>
          </div>
        </div>

        {/* The view, over the hall: its top bar and its sheet. */}
        <div className={styles.viewLayer} inert={stage !== 'view'}>
          <div className={styles.viewTop}>
            <button
              type="button"
              className={styles.round}
              aria-label="Back to the map"
              onClick={lift}
            >
              <Chevron />
            </button>
            {seat && (
              <span className={styles.pill}>
                <span className={styles.dot} />
                View from {seat.id}
              </span>
            )}
          </div>
          {seat && stats && (
            <section
              className={styles.sheet}
              data-part="sheet"
              aria-label={`Row ${seat.row}, seat ${seat.number}`}
            >
              <span className={styles.grabber} aria-hidden="true" />
              <div className={styles.sheetHead}>
                <div>
                  <span className={styles.eyebrow}>{stats.verdict}</span>
                  <h3 className={styles.seatTitle}>
                    Row {seat.row}, Seat {seat.number}
                  </h3>
                  <span className={styles.kind}>
                    {seatKindLabel(seat.kind)} · {money.format(PRICE[seat.kind])}
                    {time ? ` · ${time.time}` : ''}
                  </span>
                </div>
                <MiniMap seat={seat} />
              </div>
              <Stats seat={seat} />
              <RoomTools />
              <div className={styles.actions}>
                <button
                  type="button"
                  className={styles.secondary}
                  data-action="change"
                  onClick={lift}
                >
                  Change seat
                </button>
                <BookButton seat={seat} booked={booked} onBook={book} />
              </div>
              <span className={styles.home} aria-hidden="true" />
            </section>
          )}
        </div>
      </div>
    </div>
  );
}

/* The desktop. */

const WINDOW = { width: 1180, height: 720 };
const DESK_ZOOM = 1.3;
/** The view's middle sits above the card at the bottom of the viewer. */
const DESK_CENTRE = 0.34;
const GLIDE_MS = 700;

function DesktopLayout({
  cinema,
  hall,
  showtimes,
  defaultShowtime,
  defaultSeat,
  onSeatChange,
  onBook,
  demoRef,
}: Required<Pick<SeatViewProps, 'cinema' | 'hall' | 'showtimes'>> &
  Pick<SeatViewProps, 'defaultShowtime' | 'defaultSeat' | 'onSeatChange' | 'onBook'> & {
    demoRef: RefObject<DemoActions | null>;
  }) {
  const [showtime, setShowtime] = useState(defaultShowtime ?? showtimes[1]?.id ?? showtimes[0].id);
  const { room } = useRoom();
  const { byId: SEAT_BY_ID } = roomPlan(room);
  const taken = useMemo(() => takenSeats(showtime, room), [showtime, room]);
  const [chosen, setChosen] = useState<string | null>(
    defaultSeat && SEAT_BY_ID.has(defaultSeat) && !taken.has(defaultSeat) ? defaultSeat : null,
  );
  const [hovered, setHovered] = useState<string | null>(null);
  const [booked, setBooked] = useState(false);
  const shownId = hovered ?? chosen;
  const shown = shownId ? SEAT_BY_ID.get(shownId)! : null;
  const chosenSeat = chosen ? SEAT_BY_ID.get(chosen)! : null;
  const overview = useMemo(() => overviewCamera(DESK_ZOOM), []);
  const hallView = useHall(
    useMemo(() => (shown ? seatCamera(shown, DESK_ZOOM, DESK_CENTRE) : overview), []), // eslint-disable-line react-hooks/exhaustive-deps
  );
  const drag = useRef<{ x: number; y: number; id: number } | null>(null);
  const first = useRef(true);

  // The camera glides to the seat shown, or back to the overview.
  useEffect(() => {
    hallView.setLook({ chosen: shownId });
    if (first.current) {
      first.current = false;
      return;
    }
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    hallView.moveTo(
      shown ? seatCamera(shown, DESK_ZOOM, DESK_CENTRE) : overview,
      reduced ? 0 : GLIDE_MS,
    );
  }, [shownId, shown, overview, hallView]);

  const choose = useCallback(
    (id: string | null) => {
      setChosen(id);
      setBooked(false);
      onSeatChange?.(id ? SEAT_BY_ID.get(id)! : null);
    },
    [onSeatChange, SEAT_BY_ID, setChosen, setBooked],
  );

  const pickShowtime = (id: string) => {
    setShowtime(id);
    if (chosen && takenSeats(id, room).has(chosen)) choose(null);
  };

  const book = () => {
    if (!chosenSeat) return;
    setBooked(true);
    onBook?.({
      showtime: showtimes.find((s) => s.id === showtime)!,
      seat: chosenSeat,
      price: PRICE[chosenSeat.kind],
      room,
    });
  };

  useLayoutEffect(() => {
    demoRef.current = { choose, show: setHovered, taken };
  }, [demoRef, choose, taken]);

  const onPointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {
    event.currentTarget.setPointerCapture(event.pointerId);
    drag.current = { x: event.clientX, y: event.clientY, id: event.pointerId };
  };
  const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {
    const start = drag.current;
    if (!start || start.id !== event.pointerId) return;
    hallView.peekBy(event.clientX - start.x, event.clientY - start.y);
  };
  const onPointerUp = () => {
    if (!drag.current) return;
    drag.current = null;
    hallView.release();
  };

  const time = showtimes.find((s) => s.id === showtime);
  const stats = shown ? seatStats(shown) : null;

  return (
    <div className={styles.window}>
      <div className={styles.chrome} aria-hidden="true">
        <span className={styles.lights}>
          <i />
          <i />
          <i />
        </span>
        <span className={styles.address}>meridian.film/book/hall-3</span>
      </div>
      <div className={styles.desk}>
        <aside className={styles.panel} data-part="panel">
          <header className={styles.deskHeader}>
            <div>
              <span className={styles.eyebrow}>Fri 14 Nov</span>
              <h3 className={styles.deskTitle}>{cinema}</h3>
              <span className={styles.kind}>{hall}</span>
            </div>
            <Showtimes showtimes={showtimes} value={showtime} onChange={pickShowtime} />
            <RoomPicker />
            <RoomTools />
          </header>
          <SeatMap
            taken={taken}
            chosen={chosen}
            shown={shownId}
            onChoose={(id) => choose(id === chosen ? null : id)}
            onShow={setHovered}
          />
          <Legend />
        </aside>
        <section className={styles.viewer} aria-label="The view from the seat" data-part="viewer">
          <canvas
            ref={hallView.attach}
            className={styles.hall}
            data-part="view"
            aria-hidden="true"
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={onPointerUp}
          />
          <CinemaFilm hall={hallView} />
          <canvas
            ref={hallView.attachSoundOverlay}
            className={styles.soundOverlay}
            aria-hidden="true"
          />
          <span className={styles.pill} data-desk aria-live="polite">
            <span className={styles.dot} data-off={!shown || undefined} />
            {shown
              ? hovered && hovered !== chosen
                ? `Previewing ${shown.id}`
                : `View from ${shown.id}`
              : 'Hover a seat to see its view'}
          </span>
          <div className={styles.card} data-part="card" data-empty={!shown || undefined}>
            {shown && stats ? (
              <>
                <div className={styles.cardHead}>
                  <div>
                    <span className={styles.eyebrow}>{stats.verdict}</span>
                    <h3 className={styles.seatTitle}>
                      Row {shown.row}, Seat {shown.number}
                    </h3>
                    <span className={styles.kind}>
                      {seatKindLabel(shown.kind)} · {money.format(PRICE[shown.kind])}
                      {time ? ` · ${time.time}` : ''}
                    </span>
                  </div>
                  <Stats seat={shown} />
                </div>
                <div className={styles.actions} data-desk>
                  {chosenSeat && chosen === shownId ? (
                    <>
                      <button
                        type="button"
                        className={styles.secondary}
                        onClick={() => choose(null)}
                      >
                        Clear
                      </button>
                      <BookButton seat={chosenSeat} booked={booked} onBook={book}>
                        Book {chosenSeat.id} · {money.format(PRICE[chosenSeat.kind])}
                      </BookButton>
                    </>
                  ) : (
                    <span className={styles.hint}>Click the seat on the map to choose it</span>
                  )}
                </div>
              </>
            ) : (
              <span className={styles.hint}>
                Every seat shows its view: hover one on the map, or move with the arrow keys.
              </span>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}

/* The component. */

type DemoActions = {
  choose: (id: string | null) => void;
  land?: () => void;
  lift?: () => void;
  show?: (id: string | null) => void;
  stage?: Stage;
  taken: Set<string>;
};

export function SeatView({
  defaultRoom = 'classic',
  defaultHouseLights = false,
  defaultSoundMap = false,
  defaultMotion = true,
  temperature,
  layout = 'app',
  cinema = 'Meridian',
  hall = 'Hall 3 · Fri 14 Nov',
  showtimes = SHOWTIMES,
  defaultShowtime,
  defaultSeat,
  defaultViewing,
  onSeatChange,
  onBook,
  autoplay = true,
  maxHeight,
  className = '',
}: SeatViewProps) {
  const [room, setRoom] = useState<RoomKind>(defaultRoom);
  const [houseLights, setHouseLights] = useState(defaultHouseLights);
  const [soundMap, setSoundMap] = useState(defaultSoundMap);
  const [motion, setMotion] = useState(defaultMotion);
  const changeRoom = useCallback(
    (next: RoomKind) => {
      if (next === room) return;
      setRoom(next);
      onSeatChange?.(null);
    },
    [room, onSeatChange, setRoom],
  );
  const size = layout === 'app' ? PHONE : WINDOW;
  const { box, scale } = useFit(
    size.width,
    size.height,
    maxHeight ?? (layout === 'app' ? 640 : 900),
  );
  const { ref: stage, take, playing } = useAutoplay<HTMLDivElement>();
  const pointer = useRef<HTMLSpanElement>(null);
  const actions = useRef<DemoActions | null>(null);
  // Given a seat or a view to start on, it is a still: the demo stays off.
  const plays = autoplay && !defaultSeat && playing;

  useEffect(() => {
    const element = stage.current;
    const hand = pointer.current;
    if (!plays || !element || !hand || !scale) return;
    const find = (selector: string) => element.querySelector(selector);
    const glide = (d: Demo, selector: string, ms = 700) =>
      d.glide(middleOf(element, find(selector)), ms);
    return runDemo(element, hand, async (d) => {
      await d.wait(900);
      for (let round = 0; ; round += 1) {
        const act = () => actions.current!;
        if (layout === 'app') {
          for (const ids of DEMO_SEATS) {
            const id = firstFree(ids, act().taken, room);
            await glide(d, `[data-seat="${id}"]`, 800);
            act().choose(id);
            await d.wait(550);
            await glide(d, '[data-action="continue"]', 650);
            act().land?.();
            await d.wait(FLIGHT_MS + 1500);
            await glide(d, '[data-action="change"]', 700);
            act().lift?.();
            await d.wait(LIFT_MS + 700);
          }
        } else {
          for (const ids of [...DEMO_SEATS, ['E2', 'E1', 'D2']]) {
            const id = firstFree(ids, act().taken, room);
            await glide(d, `[data-seat="${id}"]`, 750);
            act().show?.(id);
            await d.wait(1500);
          }
          const pick = firstFree(DEMO_SEATS[1], act().taken, room);
          await glide(d, `[data-seat="${pick}"]`, 700);
          act().show?.(pick);
          await d.wait(400);
          act().choose(pick);
          await d.wait(500);
          await glide(d, '[data-action="book"]', 800);
          act().show?.(null);
          await d.wait(2200);
          act().choose(null);
        }
        if (round > 6) break;
      }
    });
  }, [plays, layout, scale, stage, room]);

  return (
    // The reader takes over from the demo by touching any of it.
    // eslint-disable-next-line jsx-a11y/no-static-element-interactions
    <RoomContext
      value={{
        room,
        setRoom: changeRoom,
        houseLights,
        setHouseLights,
        soundMap,
        setSoundMap,
        motion,
        setMotion,
        temperature: temperature ?? ROOM_INFO[room].temperature,
      }}
    >
      <div
        ref={stage}
        className={`${styles.root} ${className}`}
        data-layout={layout}
        data-room={room}
        onPointerDownCapture={(event) => {
          if (event.isTrusted) take();
        }}
        onKeyDownCapture={take}
        onWheelCapture={take}
      >
        <div
          ref={box}
          className={styles.fit}
          style={{
            height: scale ? size.height * scale : undefined,
            visibility: scale ? undefined : 'hidden',
          }}
        >
          <div
            className={styles.design}
            style={{
              width: size.width,
              height: size.height,
              transform: `translateX(-50%) scale(${scale || 1})`,
            }}
          >
            {layout === 'app' ? (
              <AppLayout
                key={room}
                cinema={cinema}
                hall={hall}
                showtimes={showtimes}
                defaultShowtime={defaultShowtime}
                defaultSeat={defaultSeat}
                defaultViewing={defaultViewing}
                onSeatChange={onSeatChange}
                onBook={onBook}
                demoRef={actions}
              />
            ) : (
              <DesktopLayout
                key={room}
                cinema={cinema}
                hall={hall}
                showtimes={showtimes}
                defaultShowtime={defaultShowtime}
                defaultSeat={defaultSeat}
                onSeatChange={onSeatChange}
                onBook={onBook}
                demoRef={actions}
              />
            )}
          </div>
        </div>
        <DemoPointer ref={pointer} className={styles.pointer} />
      </div>
    </RoomContext>
  );
}

/** The lab's demo: the app, or the desktop, on a dark stage, with a switch between them. */
export function SeatViewDemo({
  className = '',
  autoplay = true,
}: {
  className?: string;
  autoplay?: boolean;
}) {
  const [layout, setLayout] = useState<'app' | 'desktop'>('app');
  return (
    <div className={`${styles.stage} ${className}`}>
      <div className={styles.controls} role="radiogroup" aria-label="Layout">
        {(['app', 'desktop'] as const).map((value) => (
          <button
            key={value}
            type="button"
            role="radio"
            aria-checked={layout === value}
            onClick={() => setLayout(value)}
          >
            {value === 'app' ? 'App' : 'Desktop'}
          </button>
        ))}
      </div>
      <SeatView
        key={layout}
        layout={layout}
        autoplay={autoplay}
        maxHeight={layout === 'app' ? 610 : 560}
      />
    </div>
  );
}

/* Icons. */

function Chevron() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true" className={styles.icon}>
      <path d="M12 4.5L6.5 10l5.5 5.5" />
    </svg>
  );
}

function Info() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true" className={styles.icon}>
      <circle cx="10" cy="10" r="7" />
      <path d="M10 9v4.5M10 6.4v.1" />
    </svg>
  );
}

function StatusIcons() {
  return (
    <svg viewBox="0 0 66 12" className={styles.statusIcons}>
      <g fill="currentColor">
        <rect x="0" y="8" width="3" height="4" rx="1" />
        <rect x="4.5" y="5.5" width="3" height="6.5" rx="1" />
        <rect x="9" y="3" width="3" height="9" rx="1" />
        <rect x="13.5" y="0.5" width="3" height="11.5" rx="1" />
        <path d="M30 2.2a10 10 0 0 1 7.4 3.2l-1.3 1.3a8.2 8.2 0 0 0-12.2 0l-1.3-1.3A10 10 0 0 1 30 2.2zm0 3.6a6 6 0 0 1 4.4 1.9l-1.3 1.3a4.2 4.2 0 0 0-6.2 0l-1.3-1.3A6 6 0 0 1 30 5.8zm0 3.6a2 2 0 0 1 1.5.7L30 11.6l-1.5-1.5a2 2 0 0 1 1.5-.7z" />
        <rect
          x="42.5"
          y="1"
          width="21"
          height="10"
          rx="3"
          fill="none"
          stroke="currentColor"
          strokeOpacity="0.4"
        />
        <rect x="44.5" y="3" width="17" height="6" rx="1.6" />
        <path d="M65 4.5v3a1.6 1.6 0 0 0 0-3z" fillOpacity="0.4" />
      </g>
    </svg>
  );
}
```

### seat-view/seat-view.module.css

```css
/* Seat view (seat-view.tsx): a cinema's seat picker, dark as a cinema is, in two layouts. The app
   is a graphite phone; the desktop a browser window. Each is laid out at its design size (the
   phone 430 by 902 px, the window 1180 by 720) and scaled as one picture to fit its box, so every
   length below is a design px.

   Memory. Each layout has a hall canvas and a transparent sound-annotation canvas, drawn only when the view changes or its film plays. What moves is moved by
   transforms and opacity: the map and the hall cross-fade, the sheet rises, the pill fades. */

.root {
  /* The interface: its text, the quieter text and lines, the surfaces, and the accent (the chosen
     seat, the live dot, the call to action). */
  --ink: #f4f2ee;
  --muted: rgb(244 242 238 / 55%);
  --faint: rgb(244 242 238 / 32%);
  --line: rgb(255 255 255 / 8%);
  --fill: rgb(255 255 255 / 6%);
  --fill-strong: rgb(255 255 255 / 10%);
  --surface: #0b0b0d;
  --raised: #161619;
  --accent: #7fd39b;
  --accent-ink: #0c2615;
  --focus: #8ab4ff;
  /* The seats on the map. */
  --seat: #3b3b41;
  --seat-hover: #56565e;
  --recliner: #6e3a46;
  --recliner-hover: #8a4a58;
  /* The demo's pointer. */
  --pointer: #111;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 40%);
  position: relative;
  width: 100%;
  color: var(--ink);
  color-scheme: dark;
  font:
    400 14px/1.3 Inter,
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -webkit-tap-highlight-color: transparent;
}

:where(.root) button {
  font: inherit;
  color: inherit;
  cursor: pointer;
}

.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.fit {
  position: relative;
  width: 100%;
}

.design {
  position: absolute;
  top: 0;
  left: 50%;
  transform-origin: top center;
}

.pointer {
  width: 22px;
  height: 22px;
}

/* Only the arrow: nothing here takes text. */
.pointer > span + span {
  display: none !important;
}

/* The lab's stage, with the switch between the layouts (its controls, which a gallery card hides). */

.stage {
  position: relative;
  display: grid;
  align-content: center;
  min-height: 700px;
  padding: 64px 20px 28px;
  border-radius: 18px;
  background: radial-gradient(60% 50% at 50% 40%, rgb(127 211 155 / 5%), transparent 70%), #0a0a0c;
  box-shadow: inset 0 0 0 1px rgb(255 255 255 / 7%);
}

.controls {
  position: absolute;
  top: 18px;
  left: 50%;
  z-index: 3;
  display: flex;
  gap: 2px;
  padding: 3px;
  border-radius: 999px;
  background: rgb(255 255 255 / 7%);
  transform: translateX(-50%);
  font:
    600 12.5px/1 Inter,
    -apple-system,
    BlinkMacSystemFont,
    sans-serif;
}

.controls button {
  padding: 8px 16px;
  border: 0;
  border-radius: 999px;
  background: transparent;
  color: rgb(244 242 238 / 60%);
  cursor: pointer;
  transition:
    background 0.2s ease,
    color 0.2s ease;
}

.controls button[aria-checked='true'] {
  background: #f4f2ee;
  color: #111;
}

.controls button:focus-visible {
  outline: 2px solid #8ab4ff;
  outline-offset: 2px;
}

/* Shared pieces. */

.hall {
  position: absolute;
  inset: 0;
  display: block;
  width: 100%;
  height: 100%;
  touch-action: none;
  cursor: grab;
}

.hall:active {
  cursor: grabbing;
}

/* The movie shares the exact projected screen plane; dragging still reaches the hall. */
.projection {
  position: absolute;
  inset: 0;
  z-index: 1;
  overflow: hidden;
  pointer-events: none;
}
.filmPlane {
  position: absolute;
  top: 0;
  left: 0;
  width: 1280px;
  height: 544px;
  visibility: hidden;
  transform-origin: 0 0;
  background: #07080b;
  overflow: hidden;
  box-shadow: 0 0 55px 12px rgb(153 187 255 / 18%);
  backface-visibility: hidden;
}
.filmPoster,
.filmPlayer {
  top: -88px;
  height: 720px;
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  border: 0;
  object-fit: cover;
}
.filmPlayer {
  opacity: 0;
  transition: none;
}
.filmPlayer[data-playing] {
  opacity: 1;
}
.filmPlayer iframe {
  display: block;
  width: 100%;
  height: 100%;
  border: 0;
}
.screenGrain {
  position: absolute;
  inset: 0;
  background: repeating-linear-gradient(0deg, transparent 0 3px, rgb(0 0 0 / 4%) 3px 4px);
  box-shadow: inset 0 0 75px rgb(0 0 0 / 18%);
}
.filmControls {
  position: absolute;
  top: 122px;
  left: 22px;
  right: 22px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  pointer-events: auto;
  color: #eee;
}
.filmControls > span {
  display: flex;
  flex-direction: column;
  gap: 3px;
  color: rgb(255 255 255 / 48%);
  font-size: 8px;
  letter-spacing: 0.16em;
}
.filmControls strong {
  color: #fff;
  font-size: 10px;
  font-weight: 500;
  letter-spacing: 0;
}
.filmControls > div {
  display: flex;
  gap: 5px;
}
.filmControls button {
  height: 27px;
  min-width: 27px;
  padding: 0 8px;
  border: 1px solid rgb(255 255 255 / 13%);
  border-radius: 20px;
  background: rgb(9 11 16 / 76%);
  font-size: 9px;
  backdrop-filter: blur(8px);
}
.filmControls a {
  color: inherit;
  font-size: 10px;
}
.viewer .filmControls {
  top: 65px;
}

.round {
  display: grid;
  place-items: center;
  width: 38px;
  height: 38px;
  padding: 0;
  border: 0;
  border-radius: 50%;
  background: var(--fill-strong);
}

.icon {
  width: 18px;
  height: 18px;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.8;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.showtimes {
  display: flex;
  gap: 2px;
  margin: 10px auto 0;
  padding: 3px;
  border-radius: 999px;
  background: var(--fill);
}

.showtime {
  display: flex;
  align-items: baseline;
  gap: 4px;
  padding: 7px 14px;
  border: 0;
  border-radius: 999px;
  background: transparent;
  color: var(--muted);
  font-weight: 600;
  font-size: 13px;
  font-variant-numeric: tabular-nums;
  transition:
    background 0.2s ease,
    color 0.2s ease;
}

.showtime[aria-checked='true'] {
  background: var(--ink);
  color: #111;
}

.format {
  font-size: 8.5px;
  letter-spacing: 0.06em;
  opacity: 0.7;
}

.map {
  display: grid;
  justify-content: center;
  margin-top: 14px;
}

.screenArc {
  position: relative;
  width: 330px;
  height: 58px;
  margin: 0 auto;
}

.screenArc::before {
  content: '';
  position: absolute;
  inset: 0 0 auto;
  height: 46px;
  border-top: 2px solid rgb(255 255 255 / 85%);
  border-radius: 50% 50% 0 0 / 100% 100% 0 0;
  background: radial-gradient(70% 90% at 50% 0%, rgb(255 255 255 / 10%), transparent 70%);
  filter: drop-shadow(0 -2px 6px rgb(255 255 255 / 35%));
}

.screenArc span {
  position: absolute;
  top: 20px;
  left: 0;
  right: 0;
  color: var(--faint);
  font-size: 9px;
  font-weight: 600;
  letter-spacing: 0.3em;
  text-align: center;
  text-transform: uppercase;
}

.row {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 35px;
}

.rowLabel {
  width: 10px;
  color: var(--faint);
  font-size: 10px;
  font-weight: 600;
  text-align: center;
}

.block {
  display: flex;
  gap: 4px;
}

.seat {
  width: 19px;
  height: 19px;
  padding: 0;
  border: 0;
  border-radius: 6px 6px 5px 5px;
  background: var(--seat);
  transition:
    background 0.18s ease,
    box-shadow 0.18s ease,
    transform 0.18s ease;
}

.seat[data-kind='recliner'] {
  background: var(--recliner);
}

.seat[data-taken] {
  background: transparent;
  box-shadow: inset 0 0 0 1.5px var(--seat);
  cursor: not-allowed;
}

.seat[aria-pressed='true'] {
  background: var(--accent);
  box-shadow: 0 0 12px rgb(127 211 155 / 55%);
}

.seat[data-shown] {
  box-shadow: 0 0 0 2px var(--accent);
}

@media (hover: hover) {
  .seat:not([data-taken], [aria-pressed='true']):hover {
    background: var(--seat-hover);
    transform: translateY(-1px);
  }
  .seat[data-kind='recliner']:not([data-taken], [aria-pressed='true']):hover {
    background: var(--recliner-hover);
  }
}

.legend {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 18px 0 0;
  padding: 0;
  color: var(--muted);
  font-size: 11px;
  list-style: none;
}

.legend li {
  display: flex;
  align-items: center;
  gap: 6px;
}

.swatch {
  width: 10px;
  height: 10px;
  border-radius: 3px;
  background: var(--seat);
}

.swatch[data-state='taken'] {
  background: transparent;
  box-shadow: inset 0 0 0 1.5px var(--seat);
}

.swatch[data-state='recliner'] {
  background: var(--recliner);
}

.swatch[data-state='chosen'] {
  background: var(--accent);
}

.pill {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 8px 13px;
  border-radius: 999px;
  background: rgb(18 18 20 / 62%);
  backdrop-filter: blur(14px);
  font-size: 12.5px;
  font-weight: 500;
  white-space: nowrap;
}

.dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--accent);
  box-shadow: 0 0 8px var(--accent);
}

.dot[data-off] {
  background: var(--faint);
  box-shadow: none;
}

.eyebrow {
  color: var(--muted);
  font-size: 10.5px;
  font-weight: 600;
  letter-spacing: 0.14em;
  text-transform: uppercase;
}

.seatTitle {
  margin: 5px 0 3px;
  font-size: 25px;
  font-weight: 600;
  letter-spacing: -0.015em;
}

.kind {
  color: var(--muted);
  font-size: 12.5px;
}

.mini {
  width: 76px;
  height: 62px;
  padding: 6px;
  border-radius: 12px;
  background: var(--fill);
}

.miniScreen {
  fill: none;
  stroke: rgb(255 255 255 / 70%);
  stroke-width: 1;
}

.miniSeat {
  fill: rgb(255 255 255 / 16%);
}

.miniOn {
  fill: var(--accent);
}

.stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin: 18px 0;
}

.stats > div {
  display: flex;
  flex-direction: column-reverse;
  gap: 3px;
  padding: 12px 13px;
  border-radius: 14px;
  background: var(--fill);
}

.stats dd {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.stats dt {
  color: var(--muted);
  font-size: 11px;
}

.actions {
  display: grid;
  grid-template-columns: 1fr 1.25fr;
  gap: 10px;
}

.secondary,
.primary {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  height: 52px;
  padding: 0 22px;
  border-radius: 999px;
  font-size: 15px;
  font-weight: 600;
  white-space: nowrap;
  transition:
    background 0.2s ease,
    color 0.2s ease,
    opacity 0.2s ease,
    transform 0.12s ease;
}

.secondary {
  border: 1px solid rgb(255 255 255 / 18%);
  background: transparent;
}

.primary {
  border: 0;
  background: var(--ink);
  color: #111;
}

.primary[data-booked] {
  background: var(--accent);
  color: var(--accent-ink);
}

.secondary:active,
.primary:active {
  transform: scale(0.97);
}

.tick {
  width: 16px;
  height: 16px;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.hint {
  color: var(--muted);
  font-size: 13px;
}

/* The app. */

.phone {
  position: relative;
  width: 430px;
  height: 902px;
  border-radius: 68px;
  background: linear-gradient(160deg, #46474c, #1d1e21 45%, #2c2d31);
  box-shadow:
    0 40px 80px rgb(0 0 0 / 55%),
    0 0 0 1px rgb(0 0 0 / 60%),
    inset 0 0 0 1.5px rgb(255 255 255 / 14%);
}

.screen {
  position: absolute;
  inset: 14px;
  overflow: hidden;
  border-radius: 54px;
  background: var(--surface);
  isolation: isolate;
}

.status {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 54px;
  padding: 4px 30px 0 46px;
  font-size: 15.5px;
  font-weight: 600;
  pointer-events: none;
}

.island {
  position: absolute;
  top: 11px;
  left: 50%;
  width: 122px;
  height: 35px;
  margin-left: -61px;
  border-radius: 18px;
  background: #000;
}

.statusIcons {
  width: 66px;
  height: 12px;
}

.mapLayer,
.viewLayer {
  position: absolute;
  inset: 0;
  z-index: 2;
}

.mapLayer {
  display: flex;
  flex-direction: column;
  padding-top: 58px;
  background: var(--surface);
  transition: opacity 0.35s ease;
}

.screen[data-stage='landing'] .mapLayer,
.screen[data-stage='view'] .mapLayer,
.screen[data-stage='lifting'] .mapLayer {
  opacity: 0;
  transition-duration: 0.3s;
}

.screen[data-stage='map'] .hall {
  visibility: hidden;
}

.appHeader {
  display: grid;
  grid-template-columns: 38px 1fr 38px;
  align-items: center;
  padding: 6px 18px 0;
}

.title {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1px;
}

.title strong {
  font-size: 17px;
  font-weight: 600;
}

.title span {
  color: var(--muted);
  font-size: 12px;
}

.mapLayer .showtimes {
  margin-top: 14px;
}

/* The map and its legend, in the middle of the room the bar leaves. */
.mapArea {
  display: grid;
  flex: 1;
  align-content: center;
  padding-bottom: 128px;
}

.mapArea .map {
  margin-top: 0;
}

.bar {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 22px 44px;
  border-top: 1px solid var(--line);
  border-radius: 28px 28px 0 0;
  background: var(--raised);
}

.choice {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.choice span {
  color: var(--muted);
  font-size: 12px;
}

.choice strong {
  font-size: 21px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.continue {
  height: 50px;
  padding: 0 24px;
  border: 0;
  border-radius: 999px;
  background: var(--accent);
  color: var(--accent-ink);
  font-size: 15px;
  font-weight: 600;
  transition:
    background 0.2s ease,
    color 0.2s ease,
    transform 0.12s ease;
}

.continue:disabled {
  background: var(--fill-strong);
  color: var(--faint);
  cursor: default;
}

.continue:not(:disabled):active {
  transform: scale(0.97);
}

.viewLayer {
  pointer-events: none;
}

.viewLayer > * {
  pointer-events: auto;
}

.viewTop {
  position: absolute;
  top: 56px;
  left: 16px;
  right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.viewTop .round {
  position: absolute;
  left: 0;
  background: rgb(18 18 20 / 55%);
  backdrop-filter: blur(14px);
}

.screen[data-stage='view'] .viewTop {
  opacity: 1;
  transition-delay: 0.1s;
}

.sheet {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px 24px 40px;
  border-radius: 36px 36px 0 0;
  background: rgb(20 20 23 / 92%);
  backdrop-filter: blur(24px);
  box-shadow: 0 -1px 0 rgb(255 255 255 / 6%);
  transform: translateY(calc(100% + 12px));
  transition: transform 0.38s cubic-bezier(0.4, 0, 1, 1);
}

.screen[data-stage='view'] .sheet {
  transform: none;
  transition: transform 0.6s cubic-bezier(0.2, 0.95, 0.25, 1.04);
}

.grabber {
  display: block;
  width: 36px;
  height: 5px;
  margin: 0 auto 16px;
  border-radius: 3px;
  background: rgb(255 255 255 / 20%);
}

.sheetHead {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.sheetHead > div {
  display: flex;
  flex-direction: column;
}

.home {
  position: absolute;
  bottom: 8px;
  left: 50%;
  width: 134px;
  height: 5px;
  margin-left: -67px;
  border-radius: 3px;
  background: rgb(255 255 255 / 85%);
}

/* The desktop. */

.window {
  display: flex;
  flex-direction: column;
  width: 1180px;
  height: 720px;
  overflow: hidden;
  border-radius: 14px;
  background: var(--surface);
  box-shadow:
    0 40px 90px rgb(0 0 0 / 55%),
    0 0 0 1px rgb(255 255 255 / 10%);
}

.chrome {
  position: relative;
  display: flex;
  align-items: center;
  height: 42px;
  padding: 0 16px;
  border-bottom: 1px solid var(--line);
  background: #17171a;
}

.lights {
  display: flex;
  gap: 8px;
}

.lights i {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ff5f57;
}

.lights i:nth-child(2) {
  background: #febc2e;
}

.lights i:nth-child(3) {
  background: #28c840;
}

.address {
  position: absolute;
  left: 50%;
  width: 340px;
  margin-left: -170px;
  padding: 6px 0;
  border-radius: 8px;
  background: var(--fill);
  color: var(--muted);
  font-size: 12px;
  text-align: center;
}

.desk {
  display: grid;
  flex: 1;
  grid-template-columns: 440px 1fr;
  min-height: 0;
}

.panel {
  display: flex;
  flex-direction: column;
  padding: 24px 26px;
  border-right: 1px solid var(--line);
  background: #0e0e10;
}

.deskHeader {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.deskHeader > div:first-child {
  display: flex;
  flex-direction: column;
}

.deskHeader .showtimes {
  margin: 0;
  align-self: flex-start;
}

.deskTitle {
  margin: 6px 0 2px;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: -0.02em;
}

.panel .map {
  margin-top: 26px;
}

.panel .legend {
  margin-top: 22px;
}

.viewer {
  position: relative;
  overflow: hidden;
  background: var(--surface);
}

.pill[data-desk] {
  z-index: 2;
  position: absolute;
  top: 18px;
  left: 50%;
  transform: translateX(-50%);
}

.card {
  z-index: 2;
  position: absolute;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 18px 20px;
  border: 1px solid var(--line);
  border-radius: 22px;
  background: rgb(18 18 20 / 80%);
  backdrop-filter: blur(20px);
}

.card[data-empty] {
  text-align: center;
}

.cardHead {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 24px;
}

.cardHead > div:first-child {
  display: flex;
  flex-direction: column;
}

.cardHead .stats {
  width: 400px;
  margin: 0;
}

.actions[data-desk] {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 16px;
  min-height: 52px;
}

@media (prefers-reduced-motion: reduce) {
  .sheet,
  .screen[data-stage='view'] .sheet,
  .mapLayer,
  .viewTop {
    transition-duration: 0.01s;
  }
}

/* Room selection is part of booking, shared by the map and its physical auditorium. */
.roomPicker {
  margin: 16px 22px 0;
}
.roomPicker > div {
  display: flex;
  gap: 4px;
  padding: 4px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--fill);
}
.roomPicker button {
  flex: 1;
  padding: 10px 8px;
  border: 0;
  border-radius: 10px;
  background: transparent;
  color: var(--muted);
  font-size: 13px;
  font-weight: 600;
}
.roomPicker button[aria-checked='true'] {
  background: #e8e3d9;
  color: #1a1815;
  box-shadow: 0 2px 8px #0003;
}
.roomPicker p {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin: 10px 1px 0;
  color: var(--muted);
  font-size: 10px;
}
.roomPicker small {
  display: block;
  margin: 5px 1px 0;
  color: var(--faint);
  font-size: 10px;
}
.panel .roomPicker {
  margin: 2px 0 0;
}
.panel .map {
  margin-top: 12px;
}
.panel .screenArc {
  height: 44px;
}
.panel .row {
  height: 29px;
}
.panel .legend {
  margin-top: 12px;
  gap: 12px;
}
.roomTools {
  margin-top: 12px;
}
.roomTools > div {
  display: flex;
  align-items: center;
  gap: 6px;
}
.roomTools button,
.temperature {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  padding: 7px 9px;
  border: 1px solid var(--line);
  border-radius: 10px;
  background: #191a1ee8;
  color: #bcbcc0;
  font-size: 11px;
  white-space: nowrap;
}
.roomTools button[aria-pressed='true'] {
  border-color: #69ced64d;
  background: #18363b99;
  color: #b9f0ee;
}
.roomTools svg {
  width: 14px;
  height: 14px;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.4;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.temperature {
  margin-left: auto;
  color: #e8dcc6;
}
.roomTools .motionSwitch {
  display: flex;
  width: 100%;
  margin-top: 6px;
  justify-content: flex-start;
}
.motionSwitch > span:last-child {
  margin-left: auto;
  opacity: 0.6;
}
.motionDot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #6c6c70;
}
.motionDot[data-on] {
  background: #75dccf;
  box-shadow: 0 0 7px #75dccf66;
}
.soundLegend {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 7px 0 0;
  color: #8cd6e1;
  font-size: 9px;
}
.soundLegend i {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background: #8cd6e1;
}
.map[data-room='beds'] .seat {
  width: 62px;
  height: 40px;
  border-radius: 7px;
  background: linear-gradient(90deg, #78624b 48%, #493b31 48%, #493b31 52%, #78624b 52%);
  box-shadow:
    inset 0 8px 0 #ab9174,
    inset 0 -4px 0 #493b31;
}
.map[data-room='beds'] .row {
  height: 51px;
  gap: 12px;
}
.map[data-room='beds'] .block {
  gap: 6px;
}
.map[data-room='beds'] .seat[data-taken] {
  background: transparent;
  opacity: 0.4;
}
.map[data-room='beds'] .seat[aria-pressed='true'] {
  background: var(--accent);
  box-shadow:
    inset 0 7px 0 #c4f0cf,
    0 0 12px #7fd39b55;
}
.map[data-room='xtreme'] .seat {
  background: #345364;
  border-radius: 7px 7px 5px 5px;
  box-shadow: inset 0 -3px 0 #1c353e;
}
.map[data-room='xtreme'] .seat[data-taken] {
  background: transparent;
  box-shadow: inset 0 0 0 1.5px #345364;
}
.map[data-room='xtreme'] .seat[aria-pressed='true'] {
  background: var(--accent);
  box-shadow: 0 0 12px #7fd39b55;
}

/* Sound annotations sit above the projected film, including the screen channels. */
.soundOverlay {
  position: absolute;
  inset: 0;
  z-index: 2;
  width: 100%;
  height: 100%;
  pointer-events: none;
}
```

### seat-view/hall.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The cinema hall: its seats, what each one costs and sees, and a small 3D renderer that draws the
 * hall on a 2D canvas from any camera. No library: each seat is two boxes (the cushion and the
 * back), each box is up to six quads, and each quad is projected through a pinhole camera, cut at
 * the near plane and filled, far ones first. The film on the screen is painted once, by hand, into
 * an offscreen canvas and drawn onto the screen's quad in thin vertical strips, each its own
 * affine transform, so it keeps its perspective.
 *
 * The world is in metres: x to the right as you face the screen, y up, z from the screen towards
 * the back of the hall. The screen is at z = 0; row A is 4.8 m from it and each row behind is
 * 1.15 m further and 0.34 m higher, as in a stadium hall.
 */

export type SeatKind = 'standard' | 'recliner' | 'bed' | 'motion';
export type RoomKind = 'classic' | 'beds' | 'xtreme';

export type Seat = {
  /** "F8": the row's letter and the seat's number. */
  id: string;
  row: string;
  number: number;
  kind: SeatKind;
  /** Guests accommodated by one booking unit. */
  capacity: 1 | 2;
  /** Where it is: the middle of its cushion on the floor, in metres. */
  x: number;
  z: number;
  floor: number;
};

export const ROWS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
/** The rows of recliners, at the back. */
const RECLINERS = new Set(['H', 'I']);
/** Seats in each block, left to right: two aisles between them. */
const BLOCKS = [3, 8, 3];

const FIRST_ROW = 4.8;
const ROW_PITCH = 1.15;
const RISE = 0.34;
const SEAT_PITCH = 0.62;
const AISLE = 1.1;
/** Where the eye of someone sitting is, above the row's floor. */
const EYE = 1.2;

/** The screen: 11 m wide, 2.35:1, its bottom edge 2 m up. */
export const SCREEN = { width: 11, height: 4.68, bottom: 2 };
const SCREEN_MIDDLE = SCREEN.bottom + SCREEN.height / 2;
/** The side walls. */
const WALL = 6.6;
const BACK = FIRST_ROW + ROWS.length * ROW_PITCH + 1.2;

/** Every seat in the hall, row by row, left to right. */
export const SEATS: Seat[] = ROWS.flatMap((row, r) => {
  const count = BLOCKS.reduce((sum, n) => sum + n, 0);
  const width = (count - 1) * SEAT_PITCH + (BLOCKS.length - 1) * (AISLE - SEAT_PITCH);
  let x = -width / 2;
  let number = 1;
  const seats: Seat[] = [];
  BLOCKS.forEach((block, b) => {
    if (b > 0) x += AISLE - SEAT_PITCH;
    for (let i = 0; i < block; i += 1) {
      seats.push({
        id: `${row}${number}`,
        row,
        number,
        kind: RECLINERS.has(row) ? 'recliner' : 'standard',
        capacity: 1,
        x,
        z: FIRST_ROW + r * ROW_PITCH,
        floor: r * RISE,
      });
      x += SEAT_PITCH;
      number += 1;
    }
  });
  return seats;
});

export const SEAT_BY_ID = new Map(SEATS.map((seat) => [seat.id, seat]));

/** The blocks of a row, as the map lays them out: the seats' numbers, block by block. */
export const BLOCK_NUMBERS = BLOCKS.reduce<number[][]>((blocks, n) => {
  const start = blocks.flat().length + 1;
  blocks.push(Array.from({ length: n }, (_, i) => start + i));
  return blocks;
}, []);

/** Each room has its own physical plan. A Lounge loveseat is one booking unit for two guests. */
export const ROOM_INFO = {
  classic: { label: 'Classic', detail: 'Leather seats · recliners at the back', temperature: 21 },
  beds: { label: 'Beds', detail: 'Reclining loveseats · 2 guests per lounge', temperature: 22 },
  xtreme: { label: 'Xtreme', detail: 'Motion seats · synchronised movement', temperature: 20 },
} as const;

function makeRoom(kind: RoomKind) {
  if (kind === 'classic')
    return { rows: ROWS, blocks: BLOCK_NUMBERS, seats: SEATS, byId: SEAT_BY_ID, pitch: ROW_PITCH };
  const beds = kind === 'beds';
  const rows = Array.from({ length: beds ? 5 : 8 }, (_, i) => String.fromCharCode(65 + i));
  const counts = beds ? [2, 2] : [3, 6, 3];
  const pitch = beds ? 2.5 : 1.3;
  const seatPitch = beds ? 2.65 : 0.72;
  const aisle = beds ? 3.4 : 1.25;
  const count = counts.reduce((n, c) => n + c, 0);
  const width = (count - 1) * seatPitch + (counts.length - 1) * (aisle - seatPitch);
  const blocks = counts.reduce<number[][]>((out, c) => {
    const start = out.flat().length + 1;
    out.push(Array.from({ length: c }, (_, n) => start + n));
    return out;
  }, []);
  const seats: Seat[] = rows.flatMap((row, r) => {
    let x = -width / 2;
    return blocks.flatMap((block, b) => {
      if (b) x += aisle - seatPitch;
      return block.map((number) => {
        const seat: Seat = {
          id: `${row}${number}`,
          row,
          number,
          kind: beds ? 'bed' : 'motion',
          capacity: beds ? 2 : 1,
          x,
          z: FIRST_ROW + r * pitch,
          floor: r * (beds ? 0.4 : RISE),
        };
        x += seatPitch;
        return seat;
      });
    });
  });
  return { rows, blocks, seats, byId: new Map(seats.map((s) => [s.id, s])), pitch };
}
const ROOMS = { classic: makeRoom('classic'), beds: makeRoom('beds'), xtreme: makeRoom('xtreme') };
export const roomPlan = (room: RoomKind = 'classic') => ROOMS[room];
export const seatKindLabel = (kind: SeatKind) =>
  ({ standard: 'Standard', recliner: 'Recliner', bed: 'Lounge for two', motion: 'Xtreme motion' })[
    kind
  ];

/** A small seeded generator, so the taken seats of a showing are the same on every render. */
function seeded(text: string) {
  let a = [...text].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261);
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let x = Math.imul(a ^ (a >>> 15), 1 | a);
    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

/** The seats already sold for a showing: about a third, more of them in the middle. */
export function takenSeats(showing: string, room: RoomKind = 'classic'): Set<string> {
  const random = seeded(room === 'classic' ? showing : `${showing}:${room}`);
  const taken = new Set<string>();
  for (const seat of roomPlan(room).seats) {
    const middle = 1 - Math.min(1, Math.abs(seat.x) / 5);
    if (random() < 0.12 + 0.32 * middle) taken.add(seat.id);
  }
  return taken;
}

/** What a seat sees: how far the screen is, how wide it looks, and how far off its middle. */
export function seatStats(seat: Seat) {
  const distance = Math.hypot(seat.x, seat.z);
  const half = SCREEN.width / 2;
  const angle = Math.atan((half - seat.x) / seat.z) + Math.atan((half + seat.x) / seat.z);
  const offset = Math.abs(seat.x) < 0.2 ? 0 : seat.x;
  const verdict = distance < 7.4 ? 'Up close' : distance < 11.6 ? 'Sweet spot' : 'Full picture';
  return {
    distance,
    /** The screen's width as an angle, in degrees. */
    fieldOfView: (angle * 180) / Math.PI,
    /** Metres off the screen's middle: negative is left. */
    offset,
    verdict,
  };
}

/* The camera. */

export type Camera = {
  x: number;
  y: number;
  z: number;
  /** Turned right of the screen, in radians. */
  yaw: number;
  /** Up from level, in radians. */
  pitch: number;
  /** 1 / tan of half the horizontal field of view: bigger is narrower. */
  zoom: number;
  /** Where the middle of the view sits, as a share of the canvas's height. */
  centre: number;
};

/** The view from a seat, looking at the middle of the screen. */
export function seatCamera(seat: Seat, zoom: number, centre: number): Camera {
  const x = seat.x;
  const y = seat.floor + (seat.kind === 'bed' ? 1.12 : EYE);
  const z = seat.z + 0.08;
  return {
    x,
    y,
    z,
    yaw: Math.atan2(-x, z),
    // Most of the way up to the screen's middle: a person looks a little low, at the picture
    // rather than its top, and the seats in front stay in view.
    pitch: 0.6 * Math.atan2(SCREEN_MIDDLE - y, Math.hypot(x, z)),
    zoom,
    centre,
  };
}

/** Straight down on the hall from high above, the screen at the top: the seat map, in 3D. */
export function mapCamera(room: RoomKind = 'classic'): Camera {
  // Narrow, so it reads as a plan, and high enough that the seats span 82% of the canvas's width
  // with their middle row 53% of the way down, where the app's map draws them.
  const zoom = 7;
  const plan = roomPlan(room);
  const seats =
    plan.seats[plan.seats.length - 1].x - plan.seats[0].x + (room === 'beds' ? 2.45 : 0.56);
  return {
    x: 0,
    y: 1 + ((seats / 2) * zoom) / 0.82,
    z: FIRST_ROW + ((plan.rows.length - 1) / 2) * plan.pitch,
    yaw: 0,
    pitch: -Math.PI / 2,
    zoom,
    centre: 0.53,
  };
}

/** From the back of the hall, up high, looking at the screen over the seats. */
export function overviewCamera(zoom: number): Camera {
  const y = 5.4;
  const z = BACK + 0.6;
  return {
    x: 0,
    y,
    z,
    yaw: 0,
    pitch: Math.atan2(SCREEN_MIDDLE - y - 1.2, z),
    zoom,
    centre: 0.5,
  };
}

const lerp = (a: number, b: number, k: number) => a + (b - a) * k;
const clamp = (x: number) => Math.min(1, Math.max(0, x));
export const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
const smooth = (from: number, to: number, t: number) => {
  const k = clamp((t - from) / (to - from));
  return k * k * (3 - 2 * k);
};

/** A plain move between two cameras, every value eased together. */
export function blendCamera(a: Camera, b: Camera, t: number): Camera {
  const k = easeInOut(clamp(t));
  return {
    x: lerp(a.x, b.x, k),
    y: lerp(a.y, b.y, k),
    z: lerp(a.z, b.z, k),
    yaw: lerp(a.yaw, b.yaw, k),
    pitch: lerp(a.pitch, b.pitch, k),
    zoom: lerp(a.zoom, b.zoom, k),
    centre: lerp(a.centre, b.centre, k),
  };
}

/**
 * The flight from the plan down into a seat, at `t` from 0 to 1: it drops towards the seat (by
 * equal ratios of height, so the fall reads as steady), and only once low does it tilt up to the
 * screen, widening as it comes.
 */
export function flightCamera(plan: Camera, seat: Camera, t: number): Camera {
  const along = easeInOut(clamp(t));
  const height = Math.exp(lerp(Math.log(plan.y), Math.log(seat.y), smooth(0, 0.86, t)));
  const tilt = smooth(0.32, 1, t);
  return {
    x: lerp(plan.x, seat.x, along),
    y: height,
    z: lerp(plan.z, seat.z, smooth(0.05, 0.9, t)),
    yaw: lerp(plan.yaw, seat.yaw, tilt),
    pitch: lerp(plan.pitch, seat.pitch, tilt),
    zoom: Math.exp(lerp(Math.log(plan.zoom), Math.log(seat.zoom), smooth(0, 0.8, t))),
    centre: lerp(plan.centre, seat.centre, smooth(0.3, 1, t)),
  };
}

/* The renderer. */

type Vec = [number, number, number];

/** A camera's frame: its place, and its right, up and forward axes. */
function frame(camera: Camera) {
  const cp = Math.cos(camera.pitch);
  const forward: Vec = [
    Math.sin(camera.yaw) * cp,
    Math.sin(camera.pitch),
    -Math.cos(camera.yaw) * cp,
  ];
  const right: Vec = [Math.cos(camera.yaw), 0, Math.sin(camera.yaw)];
  // up = right × forward
  const up: Vec = [
    right[1] * forward[2] - right[2] * forward[1],
    right[2] * forward[0] - right[0] * forward[2],
    right[0] * forward[1] - right[1] * forward[0],
  ];
  return { eye: [camera.x, camera.y, camera.z] as Vec, forward, right, up };
}

const NEAR = 0.06;

export type Look = {
  /** The seat drawn in the accent colour. */
  chosen?: string | null;
  /** How bright the film is, 0 to 1: it comes up as the camera lands. */
  film?: number;
  /** Original-trailer seconds used by the Xtreme motion track. */
  filmTime?: number;
  /** Pixels from this instance's actual decoded video, shared with the screen light/reflection. */
  filmFrame?: { image: HTMLCanvasElement; version: number; mediaTime: number };
  room?: RoomKind;
  houseLights?: boolean;
  soundMap?: boolean;
  motion?: [number, number, number];
};

/** The seat's red, the floor, the walls, and the accent for the chosen seat. */
const RED: Vec = [176, 36, 30];
const RED_RECLINER: Vec = [150, 30, 34];
const ACCENT: Vec = [118, 206, 150];
const FLOOR: Vec = [34, 26, 26];
const WALLS: Vec = [26, 21, 22];
const BACKGROUND = '#09090b';

let film: HTMLCanvasElement | null = null;

/**
 * The still on the screen, painted once: a pale, hazy sky over dunes, a ridge in sunlight, and a
 * lone figure walking on it.
 */
function filmStill() {
  if (film) return film;
  const canvas = document.createElement('canvas');
  canvas.width = 640;
  canvas.height = 272;
  const ctx = canvas.getContext('2d');
  if (!ctx) return canvas;
  const sky = ctx.createLinearGradient(0, 0, 0, 180);
  sky.addColorStop(0, '#d9d1c6');
  sky.addColorStop(1, '#ece2d2');
  ctx.fillStyle = sky;
  ctx.fillRect(0, 0, 640, 272);
  const dune = (points: number[], top: string, bottom: string, y0: number) => {
    const gradient = ctx.createLinearGradient(0, y0, 0, 272);
    gradient.addColorStop(0, top);
    gradient.addColorStop(1, bottom);
    ctx.fillStyle = gradient;
    ctx.beginPath();
    ctx.moveTo(0, 272);
    for (let i = 0; i < points.length; i += 2) ctx.lineTo(points[i], points[i + 1]);
    ctx.lineTo(640, 272);
    ctx.closePath();
    ctx.fill();
  };
  // Far dunes, nearly lost in the haze, then nearer and warmer ones.
  dune([0, 170, 90, 160, 200, 166, 320, 156, 470, 164, 640, 158], '#d8c8b2', '#d2c0a6', 156);
  dune([0, 190, 120, 176, 260, 186, 380, 174, 520, 186, 640, 176], '#c9b293', '#bea482', 174);
  // The near dune: a long ridge rising to the right, lit on its far side and shaded on this one.
  dune([0, 232, 150, 212, 300, 204, 420, 188, 520, 170, 640, 150], '#b8976f', '#8f6f4c', 160);
  ctx.fillStyle = '#e6cfa8';
  ctx.beginPath();
  ctx.moveTo(300, 204);
  ctx.quadraticCurveTo(470, 182, 640, 150);
  ctx.lineTo(640, 196);
  ctx.quadraticCurveTo(520, 214, 420, 238);
  ctx.quadraticCurveTo(360, 226, 300, 204);
  ctx.fill();
  // The walker on the ridge.
  ctx.fillStyle = '#2a211b';
  ctx.fillRect(361, 184, 3, 9);
  ctx.beginPath();
  ctx.arc(362.5, 182, 2, 0, Math.PI * 2);
  ctx.fill();
  film = canvas;
  return canvas;
}

type Point = readonly [number, number];

/**
 * Draws the part of `image` inside the triangle `src` (image px) onto the triangle `dst` (canvas
 * px): the affine transform that takes the one onto the other, under a clip to `dst` grown by
 * nearly a pixel so that neighbours overlap. `cell` is the image's rectangle the triangle lies in,
 * the only part drawn.
 */
function texture(
  ctx: CanvasRenderingContext2D,
  image: HTMLCanvasElement,
  dst: [Point, Point, Point],
  src: [Point, Point, Point],
  cell: [number, number, number, number],
) {
  const [[x0, y0], [x1, y1], [x2, y2]] = dst;
  const [[u0, v0], [u1, v1], [u2, v2]] = src;
  const denom = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0);
  if (!denom) return;
  const a = ((x1 - x0) * (v2 - v0) - (x2 - x0) * (v1 - v0)) / denom;
  const b = ((y1 - y0) * (v2 - v0) - (y2 - y0) * (v1 - v0)) / denom;
  const c = ((x2 - x0) * (u1 - u0) - (x1 - x0) * (u2 - u0)) / denom;
  const d = ((y2 - y0) * (u1 - u0) - (y1 - y0) * (u2 - u0)) / denom;
  const mx = (x0 + x1 + x2) / 3;
  const my = (y0 + y1 + y2) / 3;
  const grow = (x: number, y: number) => {
    const len = Math.hypot(x - mx, y - my) || 1;
    return [x + ((x - mx) / len) * 0.9, y + ((y - my) / len) * 0.9] as const;
  };
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(...grow(x0, y0));
  ctx.lineTo(...grow(x1, y1));
  ctx.lineTo(...grow(x2, y2));
  ctx.closePath();
  ctx.clip();
  ctx.setTransform(a, b, c, d, x0 - a * u0 - c * v0, y0 - b * u0 - d * v0);
  // The cell and a margin round it, so that the grown edge is filled with the picture and not
  // with the soft edge of a cut-out.
  const [cx, cy, cw, ch] = cell;
  const { width, height } = image;
  const x = Math.max(0, cx - 2);
  const y = Math.max(0, cy - 2);
  const w = Math.min(width, cx + cw + 2) - x;
  const h = Math.min(height, cy + ch + 2) - y;
  ctx.drawImage(image, x, y, w, h, x, y, w, h);
  ctx.restore();
}

/**
 * Draws the hall on `ctx` (`w` by `h` canvas px) from `camera`. Everything is lit by the screen:
 * a face is brighter the more it faces the screen and the nearer it is, and fades into the dark
 * with distance.
 */
export function drawHall(
  ctx: CanvasRenderingContext2D,
  w: number,
  h: number,
  camera: Camera,
  look: Look = {},
) {
  const { eye, forward, right, up } = frame(camera);
  const f = (camera.zoom * w) / 2;
  const cx = w / 2;
  const cy = h * camera.centre;

  /** A world point in the camera's space: across, up, and depth ahead. */
  const view = (p: Vec): Vec => {
    const d: Vec = [p[0] - eye[0], p[1] - eye[1], p[2] - eye[2]];
    return [
      d[0] * right[0] + d[1] * right[1] + d[2] * right[2],
      d[0] * up[0] + d[1] * up[1] + d[2] * up[2],
      d[0] * forward[0] + d[1] * forward[1] + d[2] * forward[2],
    ];
  };

  /** Cuts a polygon (in camera space) at the near plane; what is left is all ahead. */
  const clip = (points: Vec[]) => {
    const out: Vec[] = [];
    for (let i = 0; i < points.length; i += 1) {
      const a = points[i];
      const b = points[(i + 1) % points.length];
      const aIn = a[2] >= NEAR;
      const bIn = b[2] >= NEAR;
      if (aIn) out.push(a);
      if (aIn !== bIn) {
        const k = (NEAR - a[2]) / (b[2] - a[2]);
        out.push([lerp(a[0], b[0], k), lerp(a[1], b[1], k), NEAR]);
      }
    }
    return out;
  };

  const fill = (world: Vec[], colour: string) => {
    const points = clip(world.map(view));
    if (points.length < 3) return;
    ctx.beginPath();
    points.forEach(([x, y, z], i) => {
      const sx = cx + (f * x) / z;
      const sy = cy - (f * y) / z;
      if (i === 0) ctx.moveTo(sx, sy);
      else ctx.lineTo(sx, sy);
    });
    ctx.closePath();
    ctx.fillStyle = colour;
    ctx.fill();
    // A hairline in the same colour closes the seams between neighbouring quads.
    ctx.strokeStyle = colour;
    ctx.lineWidth = 0.6;
    ctx.stroke();
  };

  const lit = (base: Vec, centre: Vec, normal: Vec, extra = 0) => {
    // Towards the middle of the screen, and how far.
    const to: Vec = [-centre[0], SCREEN_MIDDLE - centre[1], -centre[2]];
    const far = Math.hypot(to[0], to[1], to[2]);
    const facing = Math.max(0, (normal[0] * to[0] + normal[1] * to[1] + normal[2] * to[2]) / far);
    const fromEye = Math.hypot(centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]);
    const light = 0.28 + extra + (0.95 * facing + 0.22) * (9 / (9 + far));
    // Fog by distance beyond the nearest of the hall, so that the plan, seen from high up, is
    // as clear as the view from a seat.
    const fog = Math.min(0.7, Math.max(0, fromEye - Math.max(0, eye[1] - 2.5)) / 45);
    const c = base.map((v) => Math.round(Math.min(255, v * light) * (1 - fog) + 9 * fog));
    return `rgb(${c[0]} ${c[1]} ${c[2]})`;
  };

  /** A box from `a` to `b` (its two far corners), drawn face by face, those turned away left out. */
  const box = (a: Vec, b: Vec, base: Vec, extra = 0) => {
    const [x0, y0, z0] = a;
    const [x1, y1, z1] = b;
    const faces: [Vec, Vec[]][] = [
      [
        [0, 1, 0],
        [
          [x0, y1, z0],
          [x1, y1, z0],
          [x1, y1, z1],
          [x0, y1, z1],
        ],
      ],
      [
        [0, 0, 1],
        [
          [x0, y0, z1],
          [x1, y0, z1],
          [x1, y1, z1],
          [x0, y1, z1],
        ],
      ],
      [
        [0, 0, -1],
        [
          [x0, y0, z0],
          [x1, y0, z0],
          [x1, y1, z0],
          [x0, y1, z0],
        ],
      ],
      [
        [-1, 0, 0],
        [
          [x0, y0, z0],
          [x0, y0, z1],
          [x0, y1, z1],
          [x0, y1, z0],
        ],
      ],
      [
        [1, 0, 0],
        [
          [x1, y0, z0],
          [x1, y0, z1],
          [x1, y1, z1],
          [x1, y1, z0],
        ],
      ],
    ];
    for (const [normal, quad] of faces) {
      const c = quad[0];
      const toEye =
        (eye[0] - c[0]) * normal[0] + (eye[1] - c[1]) * normal[1] + (eye[2] - c[2]) * normal[2];
      if (toEye <= 0) continue;
      const middle: Vec = [(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2];
      fill(quad, lit(base, middle, normal, normal[1] > 0 ? 0.1 + extra : extra));
    }
  };

  ctx.fillStyle = BACKGROUND;
  ctx.fillRect(0, 0, w, h);

  // The room: the floor in front of the seats, the front wall and the side walls.
  const wallTop = 9.5;
  fill(
    [
      [-WALL, 0, 0],
      [WALL, 0, 0],
      [WALL, 0, FIRST_ROW - 0.7],
      [-WALL, 0, FIRST_ROW - 0.7],
    ],
    lit(FLOOR, [0, 0, 2], [0, 1, 0]),
  );
  fill(
    [
      [-WALL, 0, 0],
      [WALL, 0, 0],
      [WALL, wallTop, 0],
      [-WALL, wallTop, 0],
    ],
    'rgb(14 12 13)',
  );
  for (const side of [-1, 1]) {
    const x = side * WALL;
    for (let z = 0; z < BACK; z += 2) {
      fill(
        [
          [x, 0, z],
          [x, 0, z + 2],
          [x, wallTop, z + 2],
          [x, wallTop, z],
        ],
        lit(WALLS, [x, 3, z + 1], [-side, 0, 0]),
      );
    }
  }

  // The screen and its film: a grid of cells, each cut into two triangles, and each triangle the
  // still under the one affine transform that puts its three corners exactly where they project.
  // Neighbouring triangles share their edges, so no seam opens however steep the view.
  const still = look.filmFrame?.image ?? filmStill();
  const brightness = look.film ?? 1;
  const across = 24;
  const down = 2;
  const half = SCREEN.width / 2;
  const top = SCREEN.bottom + SCREEN.height;
  const project = (p: Vec) => {
    const [x, y, z] = view(p);
    return z < NEAR ? null : ([cx + (f * x) / z, cy - (f * y) / z] as const);
  };
  const corners: (readonly [number, number] | null)[][] = [];
  for (let j = 0; j <= down; j += 1) {
    corners.push([]);
    for (let i = 0; i <= across; i += 1) {
      corners[j].push(
        project([-half + (SCREEN.width * i) / across, top - (SCREEN.height * j) / down, 0.02]),
      );
    }
  }
  const cw = still.width / across;
  const ch = still.height / down;
  ctx.save();
  ctx.globalAlpha = 0.35 + 0.65 * brightness;
  // The screen in the film's own sand first: where two triangles' soft edges meet, it shows
  // through instead of the dark room.
  const a = corners[0][0];
  const b = corners[0][across];
  const c = corners[down][across];
  const d = corners[down][0];
  if (a && b && c && d) {
    ctx.fillStyle = '#d6c4a8';
    ctx.beginPath();
    ctx.moveTo(a[0], a[1]);
    ctx.lineTo(b[0], b[1]);
    ctx.lineTo(c[0], c[1]);
    ctx.lineTo(d[0], d[1]);
    ctx.closePath();
    ctx.fill();
  }
  for (let j = 0; j < down; j += 1) {
    for (let i = 0; i < across; i += 1) {
      const tl = corners[j][i];
      const tr = corners[j][i + 1];
      const bl = corners[j + 1][i];
      const br = corners[j + 1][i + 1];
      if (!tl || !tr || !bl || !br) continue;
      const u0 = i * cw;
      const v0 = j * ch;
      texture(
        ctx,
        still,
        [tl, tr, bl],
        [
          [u0, v0],
          [u0 + cw, v0],
          [u0, v0 + ch],
        ],
        [u0, v0, cw, ch],
      );
      texture(
        ctx,
        still,
        [tr, br, bl],
        [
          [u0 + cw, v0],
          [u0 + cw, v0 + ch],
          [u0, v0 + ch],
        ],
        [u0, v0, cw, ch],
      );
    }
  }
  ctx.restore();

  // The screen's light on the room, a soft glow from its middle.
  const middle = project([0, SCREEN_MIDDLE, 0.02]);
  const edge = project([half, SCREEN_MIDDLE, 0.02]);
  if (middle && edge) {
    const radius = Math.max(40, Math.abs(edge[0] - middle[0]) * 1.6);
    const glow = ctx.createRadialGradient(
      middle[0],
      middle[1],
      radius * 0.2,
      middle[0],
      middle[1],
      radius,
    );
    glow.addColorStop(0, `rgb(240 220 190 / ${0.1 * brightness})`);
    glow.addColorStop(1, 'rgb(240 220 190 / 0)');
    ctx.save();
    ctx.globalCompositeOperation = 'lighter';
    ctx.fillStyle = glow;
    ctx.fillRect(0, 0, w, h);
    ctx.restore();
  }

  // The rows, the farthest from the camera first; in each, its step and then its seats.
  const plan = roomPlan(look.room);
  const rows = plan.rows
    .map((row, r) => {
      const first = plan.seats.find((s) => s.row === row)!;
      const { z, floor } = first;
      return { row, r, z, floor, depth: Math.hypot(z - eye[2], floor - eye[1]) };
    })
    .sort((a, b) => b.depth - a.depth);

  for (const { row, z, floor } of rows) {
    const back = z + plan.pitch / 2;
    const front = z - plan.pitch / 2;
    // The tread, and the riser up to it from the row in front.
    fill(
      [
        [-WALL, floor, front],
        [WALL, floor, front],
        [WALL, floor, back],
        [-WALL, floor, back],
      ],
      lit(FLOOR, [0, floor, z], [0, 1, 0]),
    );
    if (floor > 0) {
      fill(
        [
          [-WALL, floor - RISE, front],
          [WALL, floor - RISE, front],
          [WALL, floor, front],
          [-WALL, floor, front],
        ],
        lit(FLOOR, [0, floor, front], [0, 0, -1]),
      );
    }
    const seats = plan.seats
      .filter((seat) => seat.row === row)
      .sort((a, b) => Math.abs(b.x - eye[0]) - Math.abs(a.x - eye[0]));
    for (const seat of seats) {
      const chosen = seat.id === look.chosen;
      const base = chosen ? ACCENT : seat.kind === 'recliner' ? RED_RECLINER : RED;
      const glow = chosen ? 0.35 : 0;
      if (seat.kind === 'bed') {
        const hide: Vec = chosen ? ACCENT : [73, 50, 36];
        box(
          [seat.x - 1.08, floor + 0.16, z - 1.32],
          [seat.x + 1.08, floor + 0.38, z + 0.7],
          hide,
          glow,
        );
        for (const side of [-1, 1]) {
          const x = seat.x + side * 0.43;
          box([x - 0.4, floor + 0.38, z - 1.3], [x + 0.4, floor + 0.57, z + 0.24], hide, glow);
          box([x - 0.4, floor + 0.57, z + 0.26], [x + 0.4, floor + 1.34, z + 0.7], hide, glow);
          box(
            [seat.x + side * 1.01 - 0.1, floor + 0.46, z - 1],
            [seat.x + side * 1.01 + 0.1, floor + 0.8, z + 0.6],
            hide,
            glow,
          );
        }
        box(
          [seat.x + 1.02, floor + 0.73, z - 0.62],
          [seat.x + 1.42, floor + 0.79, z - 0.17],
          [92, 61, 34],
        );
        continue;
      }
      const half = seat.kind === 'recliner' ? 0.29 : 0.27;
      const x0 = seat.x - half;
      const x1 = seat.x + half;
      const cushion: [Vec, Vec] = [
        [x0, floor + 0.28, z - 0.32],
        [x1, floor + 0.46, z + 0.18],
      ];
      const backrest: [Vec, Vec] = [
        [x0, floor + 0.28, z + 0.18],
        [x1, floor + 0.94, z + 0.32],
      ];
      // The nearer of the two goes on top.
      const order =
        Math.abs(eye[2] - (z - 0.07)) > Math.abs(eye[2] - (z + 0.26))
          ? [cushion, backrest]
          : [backrest, cushion];
      for (const [a, b] of order) box(a, b, base, glow);
    }
  }
}
```

### seat-view/cinema-gl.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import { SCREEN, roomPlan, type RoomKind, type Seat, type Camera, type Look } from './hall';
import { MATERIAL_FRAGMENT, SHADOW_FRAGMENT, loadCinemaTextures } from './cinema-materials';

/*
 * A real depth-tested WebGL auditorium. One shared GPU surface serves the visible instances;
 * their 2D canvases keep the last rendered bitmap. Geometry and GPU buffers are built once.
 * Coordinates, eye height and row elevations are the same metres used by the booking map.
 */
type V = [number, number, number];
const vertices: number[] = [];
let activeSeats: Seat[] = [];
const geometry = new Map<RoomKind, Float32Array>();
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));
const norm = (v: V): V => {
  const length = Math.hypot(...v) || 1;
  return v.map((n) => n / length) as V;
};
const W = 6.6;
const BACK = 16.35;
const red: V = [0.31, 0.035, 0.06];
const leather: V = [0.035, 0.038, 0.049];
const bronze: V = [0.19, 0.135, 0.085];

function vertex(p: V, n: V, color: V, material: number, seat: number) {
  const pivot = activeSeats[seat];
  vertices.push(
    ...p,
    ...n,
    ...color,
    material,
    seat,
    pivot?.x ?? 0,
    (pivot?.floor ?? 0) + 0.38,
    pivot?.z ?? 0,
  );
}

/** A bevelled box with smooth corner normals; lean tilts the backrest backwards. */
function box(c: V, size: V, radius: number, color: V, material = 0, seat = -1, lean = 0, puff = 0) {
  const steps = radius ? (puff ? 12 : 5) : 1;
  const half = size.map((n) => n / 2) as V;
  const inner = half.map((n) => Math.max(0, n - radius)) as V;
  const cosine = Math.cos(lean),
    sine = Math.sin(lean);
  const rotate = ([x, y, z]: V): V => [x, y * cosine - z * sine, y * sine + z * cosine];
  for (let axis = 0; axis < 3; axis++)
    for (const sign of [-1, 1]) {
      const a = (axis + 1) % 3,
        b = (axis + 2) % 3;
      const surface = (u: number, v: number) => {
        const raw: V = [0, 0, 0];
        raw[axis] = half[axis] * sign;
        raw[a] = (u * 2 - 1) * half[a];
        raw[b] = (v * 2 - 1) * half[b];
        const closest = raw.map((n, i) => clamp(n, -inner[i], inner[i])) as V;
        const normal = radius
          ? norm(raw.map((n, i) => n - closest[i]) as V)
          : ([0, 0, 0].map((_, i) => (i === axis ? sign : 0)) as V);
        const p = radius ? (closest.map((n, i) => n + normal[i] * radius) as V) : raw;
        if (puff) {
          p[axis] += sign * puff * Math.pow(Math.sin(Math.PI * u) * Math.sin(Math.PI * v), 1.4);
        }
        return { p, n: normal };
      };
      const point = (u: number, v: number) => {
        const point = surface(u, v);
        let normal = point.n;
        if (puff) {
          const l = surface(Math.max(0, u - 0.001), v).p,
            r = surface(Math.min(1, u + 0.001), v).p;
          const d = surface(u, Math.max(0, v - 0.001)).p,
            t = surface(u, Math.min(1, v + 0.001)).p;
          const a = r.map((n, i) => n - l[i]) as V,
            b = t.map((n, i) => n - d[i]) as V;
          normal = norm([
            a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0],
          ]);
          if (normal[axis] * sign < 0) normal = normal.map((n) => -n) as V;
        }
        const p = rotate(point.p);
        return { p: p.map((n, i) => n + c[i]) as V, n: rotate(normal) };
      };
      for (let u = 0; u < steps; u++)
        for (let v = 0; v < steps; v++) {
          const points = [
            point(u / steps, v / steps),
            point((u + 1) / steps, v / steps),
            point((u + 1) / steps, (v + 1) / steps),
            point(u / steps, (v + 1) / steps),
          ];
          for (const i of [0, 1, 2, 0, 2, 3])
            vertex(points[i].p, points[i].n, color, material, seat);
        }
    }
}

/** Round metalwork for lamp stems, pivots and hydraulic cylinders. */
function cylinder(
  c: V,
  bottom: number,
  top: number,
  height: number,
  color: V,
  material = 2,
  seat = -1,
) {
  const count = 16;
  for (let i = 0; i < count; i++) {
    const a = (i * Math.PI * 2) / count,
      b = ((i + 1) * Math.PI * 2) / count;
    const p = (angle: number, y: number, r: number): V => [
      c[0] + Math.cos(angle) * r,
      c[1] + y,
      c[2] + Math.sin(angle) * r,
    ];
    const na = norm([Math.cos(a), (bottom - top) / height, Math.sin(a)]),
      nb = norm([Math.cos(b), (bottom - top) / height, Math.sin(b)]);
    const points = [
      p(a, -height / 2, bottom),
      p(b, -height / 2, bottom),
      p(b, height / 2, top),
      p(a, height / 2, top),
    ];
    for (const k of [0, 1, 2, 0, 2, 3])
      vertex(points[k], k === 0 || k === 3 ? na : nb, color, material, seat);
    for (const sign of [-1, 1]) {
      const r = sign < 0 ? bottom : top,
        n: V = [0, sign, 0];
      for (const v of [
        [c[0], c[1] + (sign * height) / 2, c[2]] as V,
        p(a, (sign * height) / 2, r),
        p(b, (sign * height) / 2, r),
      ])
        vertex(v, n, color, material, seat);
    }
  }
}

/** Fine sewn diagonals follow a crowned backrest, rather than a flat painted texture. */
function quilt(
  c: V,
  width: number,
  height: number,
  depth: number,
  lean: number,
  color: V,
  id: number,
) {
  const hw = width / 2 - 0.035,
    hh = height / 2 - 0.045;
  const transform = (x: number, y: number): V => {
    const crown =
      0.024 *
      Math.pow(
        Math.max(
          0,
          Math.cos(((x / (width / 2)) * Math.PI) / 2) *
            Math.cos(((y / (height / 2)) * Math.PI) / 2),
        ),
        1.4,
      );
    const z = -depth / 2 - crown - 0.001;
    return [
      c[0] + x,
      c[1] + y * Math.cos(lean) - z * Math.sin(lean),
      c[2] + y * Math.sin(lean) + z * Math.cos(lean),
    ];
  };
  const line = (a: V, b: V) => {
    const delta = b.map((n, i) => n - a[i]) as V;
    const tangent = norm(delta),
      side = norm([tangent[1], -tangent[0], 0]);
    const radius = 0.0014;
    const points = [
      a.map((n, i) => n + side[i] * radius) as V,
      b.map((n, i) => n + side[i] * radius) as V,
      b.map((n, i) => n - side[i] * radius) as V,
      a.map((n, i) => n - side[i] * radius) as V,
    ];
    const normal: V = [0, Math.sin(lean), -Math.cos(lean)];
    for (const k of [0, 1, 2, 0, 2, 3]) vertex(points[k], normal, color, 0, id);
  };
  for (const slope of [-1, 1])
    for (let d = -1.5; d < 1.5; d += 0.22) {
      let previous: V | null = null;
      for (let step = 0; step <= 28; step++) {
        const x = -hw + (2 * hw * step) / 28,
          y = slope * x + d;
        if (y < -hh || y > hh) {
          previous = null;
          continue;
        }
        const p = transform(x, y);
        if (previous) line(previous, p);
        previous = p;
      }
    }
}

/** Horizontal cup-holder rim, with a dark recessed well underneath. */
function cup(x: number, y: number, z: number, seat = -1) {
  const rings = 14,
    tube = 5;
  const point = (a: number, b: number) => {
    const t = (a * Math.PI * 2) / rings,
      p = (b * Math.PI * 2) / tube;
    const n: V = [Math.cos(t) * Math.cos(p), Math.sin(p), Math.sin(t) * Math.cos(p)];
    return {
      p: [
        x + Math.cos(t) * (0.036 + Math.cos(p) * 0.006),
        y + Math.sin(p) * 0.006,
        z + Math.sin(t) * (0.036 + Math.cos(p) * 0.006),
      ] as V,
      n,
    };
  };
  for (let a = 0; a < rings; a++)
    for (let b = 0; b < tube; b++) {
      const ps = [point(a, b), point(a + 1, b), point(a + 1, b + 1), point(a, b + 1)];
      for (const i of [0, 1, 2, 0, 2, 3]) vertex(ps[i].p, ps[i].n, [0.13, 0.14, 0.16], 2, seat);
    }
  box([x, y - 0.014, z], [0.057, 0.013, 0.057], 0.005, [0.006, 0.007, 0.01], 2, seat);
}

function build(room: RoomKind) {
  const cached = geometry.get(room);
  if (cached) return cached;
  vertices.length = 0;
  const plan = roomPlan(room);
  activeSeats = plan.seats;
  // Front stage, black screen surround, deep reveal and a fine bronze edge.
  box([0, -0.15, 7.8], [W * 2, 0.3, 17], 0, [0.025, 0.024, 0.033], 1);
  box([0, 0.12, 0.5], [12.8, 0.24, 2.1], 0.04, [0.022, 0.021, 0.029], 1);
  box([0, 4.35, -0.32], [13.2, 8.7, 0.4], 0, [0.012, 0.012, 0.017], 1);
  box([0, 4.34, -0.075], [11.45, 5.13, 0.18], 0.06, [0.008, 0.009, 0.013]);
  box([0, 4.34, 0.025], [11.08, 4.76, 0.05], 0.01, bronze, 2);
  box([0, 4.34, 0.06], [11, 4.68, 0.018], 0, [0.33, 0.39, 0.5], 4);
  box([0, 4.2, 16.48], [13.3, 8.7, 0.28], 0, [0.035, 0.031, 0.029], 9);
  box([0, 5.7, 16.3], [2.2, 0.72, 0.08], 0.025, [0.075, 0.068, 0.055], 2);
  box([0, 5.7, 16.24], [2.02, 0.56, 0.04], 0.012, [0.012, 0.018, 0.025], 2);
  for (const px of [-0.38, 0.38])
    cylinder([px, 5.7, 16.18], 0.045, 0.045, 0.03, [0.035, 0.041, 0.046], 2);
  // Acoustic wall bays, timber ribs, concealed light coves, speakers and exit doors.
  for (const side of [-1, 1]) {
    box([side * (W + 0.12), 4.2, 7.6], [0.28, 8.8, 16.6], 0, [0.026, 0.028, 0.038], 1);
    for (let bay = 0; bay < 7; bay++) {
      const z = 1.3 + bay * 2.25;
      box([side * W, 4.55, z], [0.12, 5.9, 1.96], 0.025, [0.055, 0.057, 0.073], 1);
      for (let rib = 0; rib < 6; rib++)
        box(
          [side * (W - 0.075), 4.55, z - 0.84 + rib * 0.33],
          [0.06, 5.9, 0.023],
          0.006,
          [0.12, 0.086, 0.063],
          10,
        );
      box([side * (W - 0.14), 5.65, z + 1.03], [0.035, 2.9, 0.028], 0.008, [1, 0.47, 0.15], 3);
      if (bay % 2 === 1) {
        box([side * (W - 0.3), 5.35, z], [0.3, 0.72, 0.44], 0.045, [0.012, 0.014, 0.019], 7);
        box([side * (W - 0.47), 5.35, z], [0.025, 0.58, 0.32], 0.012, [0.04, 0.045, 0.054], 7);
      }
    }
    box([side * (W - 0.11), 7.65, 7.8], [0.07, 0.045, 15.6], 0.015, [1, 0.42, 0.11], 3);
    box([side * (W - 0.15), 1.15, 1.3], [0.07, 2.3, 1.0], 0.025, [0.06, 0.065, 0.078]);
    box([side * (W - 0.2), 2.45, 1.3], [0.04, 0.13, 0.42], 0.008, [0.12, 0.9, 0.52], 3);
  }
  // A suspended slat ceiling; open when the camera looks down from the plan.
  for (let z = 1; z < BACK; z += 0.65)
    box([0, 8.0, z], [13.2, 0.13, 0.16], 0.015, [0.027, 0.028, 0.035], 6);
  for (const x of [-4.9, 4.9]) box([x, 7.89, 7.3], [0.018, 0.018, 13], 0, [0.55, 0.65, 0.85], 3);
  for (const x of [-3, 3]) {
    for (const z of [6, 11]) box([x, 7.78, z], [0.62, 0.16, 0.62], 0.06, [0.035, 0.038, 0.045], 7);
    box([x, 5.35, 16.12], [0.6, 0.72, 0.3], 0.04, [0.025, 0.028, 0.035], 7);
  }
  const aisleXs = plan.blocks.slice(0, -1).map((block, index) => {
    const left = plan.seats.find(
      (seat) => seat.row === plan.rows[0] && seat.number === block.at(-1),
    )!;
    const right = plan.seats.find(
      (seat) => seat.row === plan.rows[0] && seat.number === plan.blocks[index + 1][0],
    )!;
    return (left.x + right.x) / 2;
  });
  // Carpeted terraces: LEDs follow each room's actual aisles.
  for (const row of plan.rows) {
    const { z, floor } = plan.seats.find((s) => s.row === row)!;
    box(
      [0, floor / 2 - 0.09, z + (room === 'beds' ? -0.25 : 0.1)],
      [13.1, floor + 0.18, plan.pitch],
      0,
      [0.025, 0.022, 0.027],
      1,
    );
    for (const x of [...aisleXs, -5.95, 5.95]) {
      box(
        [x, floor + 0.006, z - plan.pitch / 2 + (room === 'beds' ? -0.2 : 0.15)],
        [0.72, 0.012, 0.026],
        0.005,
        [1, 0.45, 0.12],
        3,
      );
      box([x - 0.4, floor + 0.012, z + 0.3], [0.018, 0.016, 0.92], 0.004, [0.7, 0.29, 0.08], 3);
    }
  }
  for (const [id, s] of plan.seats.entries()) {
    const { x, floor: y, z } = s;
    if (s.kind === 'bed') {
      // A reclining Lounge for two: shared body, paired padded seats, no fixed centre arm.
      const hide: V = [0.035, 0.022, 0.015],
        cushion: V = [0.055, 0.033, 0.022];
      box([x, y + 0.2, z - 0.25], [1.98, 0.32, 1.86], 0.11, [0.065, 0.052, 0.045], 0, id);
      box([x, y + 0.91, z + 0.66], [1.96, 0.93, 0.2], 0.1, hide, 0, id, 0.5, 0.015);
      for (const side of [-1, 1]) {
        const sx = x + side * 0.43;
        box([sx, y + 0.52, z - 0.05], [0.82, 0.25, 0.76], 0.11, cushion, 0, id, -0.09, 0.024);
        box([sx, y + 0.46, z - 0.76], [0.82, 0.22, 0.78], 0.1, cushion, 0, id, -0.12, 0.025);
        box([sx, y + 0.34, z - 1.19], [0.81, 0.16, 0.32], 0.065, hide, 0, id, -0.22, 0.012);
        const back: V = [sx, y + 0.94, z + 0.45];
        box(back, [0.81, 0.92, 0.24], 0.095, cushion, 8, id, 0.5, 0.024);
        quilt(back, 0.81, 0.92, 0.24, 0.5, [0.072, 0.05, 0.033], id);
        box([sx, y + 1.31, z + 0.65], [0.72, 0.23, 0.22], 0.085, hide, 0, id, 0.5, 0.02);
        box([x + side * 1.01, y + 0.63, z - 0.19], [0.21, 0.35, 1.44], 0.1, hide, 0, id, 0, 0.018);
        // Discreet service and reclining controls on the outside arm.
        box(
          [x + side * 1.012, y + 0.814, z - 0.35],
          [0.11, 0.013, 0.23],
          0.012,
          [0.035, 0.035, 0.037],
          2,
        );
        cylinder([x + side * 1.012, y + 0.825, z - 0.4], 0.018, 0.018, 0.009, [0.4, 0.43, 0.44], 2);
        cylinder(
          [x + side * 1.012, y + 0.825, z - 0.31],
          0.012,
          0.012,
          0.009,
          [0.85, 0.6, 0.25],
          11,
        );
      }
      // Wood service table, cup recess and a small shaded reading lamp.
      cylinder([x + 1.2, y + 0.37, z - 0.4], 0.022, 0.022, 0.72, [0.21, 0.22, 0.23], 2);
      cylinder([x + 1.2, y + 0.035, z - 0.4], 0.14, 0.14, 0.025, [0.06, 0.06, 0.065], 2);
      box([x + 1.2, y + 0.76, z - 0.4], [0.43, 0.045, 0.48], 0.05, [0.24, 0.15, 0.085], 10);
      cup(x + 1.28, y + 0.79, z - 0.48);
      cylinder([x + 1.12, y + 0.96, z + 0.27], 0.012, 0.012, 0.59, [0.26, 0.23, 0.18], 2);
      cylinder([x + 1.12, y + 1.29, z + 0.23], 0.078, 0.043, 0.12, [0.07, 0.065, 0.058], 2);
      cylinder([x + 1.12, y + 1.226, z + 0.23], 0.067, 0.067, 0.006, [1, 0.7, 0.32], 11);
      continue;
    }
    if (s.kind === 'motion') {
      const shell: V = [0.018, 0.026, 0.035],
        cushion: V = [0.025, 0.038, 0.052];
      // The hydraulic base stays fixed. The bucket, restraints and footplate move together.
      box([x, y + 0.12, z + 0.06], [0.55, 0.2, 0.6], 0.04, [0.05, 0.055, 0.06], 2);
      for (const side of [-1, 1]) {
        cylinder([x + side * 0.18, y + 0.26, z + 0.1], 0.052, 0.052, 0.27, [0.065, 0.07, 0.075], 2);
        cylinder([x + side * 0.18, y + 0.38, z + 0.1], 0.025, 0.025, 0.18, [0.48, 0.5, 0.52], 2);
        for (let ring = 0; ring < 4; ring++)
          cylinder(
            [x + side * 0.18, y + 0.18 + ring * 0.04, z + 0.1],
            0.06,
            0.06,
            0.012,
            [0.035, 0.038, 0.042],
            0,
          );
      }
      box([x, y + 0.5, z], [0.57, 0.22, 0.62], 0.085, cushion, 0, id, 0, 0.022);
      box([x, y + 0.99, z + 0.25], [0.57, 1.05, 0.24], 0.105, shell, 0, id, 0.11, 0.022);
      box([x, y + 1.35, z + 0.26], [0.42, 0.24, 0.21], 0.08, cushion, 0, id, 0.11, 0.018);
      box([x, y + 0.95, z + 0.1], [0.35, 0.62, 0.08], 0.035, cushion, 0, id, 0.11, 0.024);
      for (const side of [-1, 1]) {
        box(
          [x + side * 0.27, y + 0.85, z + 0.17],
          [0.1, 0.7, 0.3],
          0.04,
          shell,
          0,
          id,
          side * 0.05,
        );
        box([x + side * 0.3, y + 0.65, z - 0.05], [0.08, 0.13, 0.64], 0.025, shell, 0, id);
        box(
          [x + side * 0.22, y + 1.05, z + 0.39],
          [0.02, 0.57, 0.014],
          0.004,
          [0.045, 0.23, 0.3],
          0,
          id,
        );
      }
      box([x, y + 0.25, z - 0.5], [0.5, 0.09, 0.36], 0.025, [0.08, 0.1, 0.12], 2, id, -0.2);
      box([x, y + 0.303, z - 0.49], [0.46, 0.013, 0.3], 0.012, [0.014, 0.017, 0.019], 12, id, -0.2);
      cup(x + 0.3, y + 0.72, z - 0.22, id);
      continue;
    }
    const recliner = s.kind === 'recliner';
    const fabric: V = recliner ? [0.23, 0.032, 0.06] : red;
    box([x, y + 0.22, z + 0.1], [0.32, 0.32, 0.34], 0.025, leather);
    box([x, y + 0.46, z - 0.04], [0.49, 0.19, 0.56], 0.065, fabric, 0, id, -0.045);
    box([x, y + 0.82, z + 0.24], [0.51, 0.8, 0.2], 0.085, fabric, 0, id, 0.095);
    box([x, y + 1.13, z + 0.27], [0.43, 0.22, 0.16], 0.065, fabric, 0, id, 0.095);
    // Separate upholstered lumbar inset, double piping, and stitched vertical seams.
    box(
      [x, y + 0.79, z + 0.115],
      [0.34, 0.45, 0.045],
      0.02,
      fabric.map((n) => n * 1.13) as V,
      0,
      id,
      0.095,
    );
    for (const side of [-1, 1]) {
      box(
        [x + side * 0.19, y + 0.82, z + 0.128],
        [0.008, 0.59, 0.012],
        0.003,
        [0.4, 0.11, 0.13],
        0,
        id,
        0.095,
      );
      box([x + side * 0.27, y + 0.57, z + 0.01], [0.075, 0.105, 0.64], 0.026, leather);
      box([x + side * 0.27, y + 0.3, z + 0.19], [0.038, 0.42, 0.038], 0.009, [0.12, 0.12, 0.14], 2);
    }
    cup(x + 0.27, y + 0.626, z - 0.18);
    // Rear upholstery, inset panels and stitched piping visible from the row behind.
    box(
      [x, y + 0.82, z + 0.36],
      [0.39, 0.57, 0.025],
      0.018,
      fabric.map((n) => n * 0.8) as V,
      0,
      id,
      0.095,
    );
    for (const side of [-1, 1])
      box(
        [x + side * 0.18, y + 0.82, z + 0.383],
        [0.006, 0.53, 0.007],
        0.002,
        [0.28, 0.085, 0.105],
        0,
        id,
        0.095,
      );
    box([x, y + 1.09, z + 0.39], [0.14, 0.025, 0.008], 0.005, bronze, 2);
    if (recliner) box([x, y + 0.34, z - 0.43], [0.47, 0.13, 0.32], 0.045, fabric, 0, id, -0.25);
  }
  const data = new Float32Array(vertices);
  geometry.set(room, data);
  vertices.length = 0;
  return data;
}

const VERTEX = `
attribute vec3 position;
attribute vec3 normal;
attribute vec3 color;
attribute float material;
attribute float seat;
attribute vec3 pivot;
uniform vec3 eye, right, up, forward;
uniform vec3 projection;
uniform vec2 clipRange;
uniform vec3 motion;
uniform float room;
varying vec3 vPosition, vNormal, vColor;
varying float vMaterial, vSeat, vDistance;
void main() {
  vec3 p=position, n=normal;
  if(room>1.5 && seat>=0.0) {
    float cp=cos(motion.y),sp=sin(motion.y),cr=cos(motion.z),sr=sin(motion.z);
    mat3 pitch=mat3(1.,0.,0.,0.,cp,sp,0.,-sp,cp);
    mat3 roll=mat3(cr,sr,0.,-sr,cr,0.,0.,0.,1.);
    p=roll*pitch*(p-pivot)+pivot+vec3(0.,motion.x,0.);
    n=roll*pitch*n;
  }
  vec3 relative = p - eye;
  float depth = dot(relative, forward);
  float near = clipRange.x, far = clipRange.y;
  gl_Position = vec4(dot(relative,right)*projection.x,
    dot(relative,up)*projection.y + projection.z*depth,
    (far+near)/(far-near)*depth - 2.0*far*near/(far-near), depth);
  vPosition=p; vNormal=n; vColor=color;
  vMaterial=material; vSeat=seat; vDistance=length(relative);
}`;

function lightCamera(eye: V, target: V, zoom: number): Camera {
  const dx = target[0] - eye[0],
    dy = target[1] - eye[1],
    dz = target[2] - eye[2];
  return {
    x: eye[0],
    y: eye[1],
    z: eye[2],
    yaw: Math.atan2(dx, -dz),
    pitch: Math.atan2(dy, Math.hypot(dx, dz)),
    zoom,
    centre: 0.5,
  };
}
function cameraBasis(camera: Camera) {
  const cp = Math.cos(camera.pitch),
    sp = Math.sin(camera.pitch),
    cy = Math.cos(camera.yaw),
    sy = Math.sin(camera.yaw);
  return {
    right: [cy, 0, sy] as V,
    up: [-sy * sp, cp, cy * sp] as V,
    forward: [sy * cp, sp, -cy * cp] as V,
  };
}
function uploadCamera(
  gl: WebGLRenderingContext,
  u: Record<string, WebGLUniformLocation | null>,
  camera: Camera,
  aspect: number,
  shadow = false,
) {
  const basis = cameraBasis(camera);
  gl.uniform2f(u.clipRange, shadow ? 0.6 : 0.08, shadow ? 40 : 160);
  gl.uniform3f(u.eye, camera.x, camera.y, camera.z);
  gl.uniform3fv(u.right, basis.right);
  gl.uniform3fv(u.up, basis.up);
  gl.uniform3fv(u.forward, basis.forward);
  gl.uniform3f(u.projection, camera.zoom, camera.zoom * aspect, 1 - camera.centre * 2);
}
function lightMatrix(camera: Camera) {
  const { right: r, up: u, forward: f } = cameraBasis(camera),
    q = camera.zoom;
  const a = (40 + 0.6) / (40 - 0.6),
    b = (2 * 40 * 0.6) / (40 - 0.6),
    eye: V = [camera.x, camera.y, camera.z];
  const dot = (v: V) => v.reduce((sum, n, i) => sum + n * eye[i], 0);
  return new Float32Array([
    r[0] * q,
    u[0] * q,
    f[0] * a,
    f[0],
    r[1] * q,
    u[1] * q,
    f[1] * a,
    f[1],
    r[2] * q,
    u[2] * q,
    f[2] * a,
    f[2],
    -dot(r) * q,
    -dot(u) * q,
    -dot(f) * a - b,
    -dot(f),
  ]);
}

let gpu: ReturnType<typeof createGPU> | null = null;
function createGPU() {
  const surface = document.createElement('canvas');
  const gl = surface.getContext('webgl', {
    antialias: true,
    alpha: false,
    preserveDrawingBuffer: true,
  });
  if (!gl) return null;
  const shader = (type: number, source: string) => {
    const s = gl.createShader(type)!;
    gl.shaderSource(s, source);
    gl.compileShader(s);
    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
      throw new Error(gl.getShaderInfoLog(s) ?? 'Cinema shader');
    return s;
  };
  const compileProgram = (fragment: string) => {
    const program = gl.createProgram()!;
    const vs = shader(gl.VERTEX_SHADER, VERTEX),
      fs = shader(gl.FRAGMENT_SHADER, fragment);
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    for (const [index, name] of [
      'position',
      'normal',
      'color',
      'material',
      'seat',
      'pivot',
    ].entries())
      gl.bindAttribLocation(program, index, name);
    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS))
      throw new Error(gl.getProgramInfoLog(program) ?? 'Cinema program');
    gl.deleteShader(vs);
    gl.deleteShader(fs);
    return program;
  };
  const program = compileProgram(MATERIAL_FRAGMENT),
    shadowProgram = compileProgram(SHADOW_FRAGMENT);
  gl.useProgram(program);
  const buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  let offset = 0;
  for (const [name, size] of [
    ['position', 3],
    ['normal', 3],
    ['color', 3],
    ['material', 1],
    ['seat', 1],
    ['pivot', 3],
  ] as const) {
    const location = gl.getAttribLocation(program, name);
    gl.enableVertexAttribArray(location);
    gl.vertexAttribPointer(location, size, gl.FLOAT, false, 56, offset * 4);
    offset += size;
  }
  gl.enable(gl.DEPTH_TEST);
  gl.disable(gl.CULL_FACE);
  // Dithering corrupts packed depth values and causes banded self-shadow artifacts.
  gl.disable(gl.DITHER);
  const uniforms = Object.fromEntries(
    [
      'eye',
      'right',
      'up',
      'forward',
      'projection',
      'clipRange',
      'selected',
      'brightness',
      'houseLights',
      'soundMap',
      'room',
      'motion',
      'layout',
      'shadowXs[0]',
      'leatherMap',
      'filmMap',
      'screenShadow',
      'houseShadow',
      'screenMatrix',
      'houseMatrix',
    ].map((name) => [name, gl.getUniformLocation(program, name)]),
  );
  surface.addEventListener('webglcontextlost', (event) => {
    event.preventDefault();
    gpu = null;
  });
  const textures = loadCinemaTextures(gl, () =>
    window.dispatchEvent(new Event('seat-view:materials-ready')),
  );
  const shadowUniforms = Object.fromEntries(
    ['eye', 'right', 'up', 'forward', 'projection', 'clipRange', 'motion', 'room'].map((name) => [
      name,
      gl.getUniformLocation(shadowProgram, name),
    ]),
  );
  const shadowSize = 1024;
  const shadows = [
    lightCamera([0, 4.34, 0.25], [0, 1.5, 10], 0.43),
    lightCamera([-3, 7.5, 8], [0, 1, 8], 0.56),
  ].map((camera) => {
    const texture = gl.createTexture()!;
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      gl.RGBA,
      shadowSize,
      shadowSize,
      0,
      gl.RGBA,
      gl.UNSIGNED_BYTE,
      null,
    );
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    const frame = gl.createFramebuffer()!,
      depth = gl.createRenderbuffer()!;
    gl.bindFramebuffer(gl.FRAMEBUFFER, frame);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
    gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, shadowSize, shadowSize);
    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
    const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
    gl.clearColor(1, 1, 1, 1);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    return { texture, frame, depth, camera, matrix: lightMatrix(camera), complete };
  });
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  const filmTexture = gl.createTexture()!;
  gl.bindTexture(gl.TEXTURE_2D, filmTexture);
  gl.texImage2D(
    gl.TEXTURE_2D,
    0,
    gl.RGBA,
    1,
    1,
    0,
    gl.RGBA,
    gl.UNSIGNED_BYTE,
    new Uint8Array([0, 0, 0, 255]),
  );
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  return {
    filmTexture,
    filmOwner: null as HTMLCanvasElement | null,
    filmVersion: -1,
    surface,
    gl,
    program,
    shadowProgram,
    shadowUniforms,
    shadowSize,
    shadows,
    textures,
    buffer,
    uniforms,
    count: 0,
    room: '' as string,
    shadowKey: '',
  };
}

/** Returns false only on devices without WebGL, so the low-detail fallback can still work. */
export function drawCinema(
  ctx: CanvasRenderingContext2D,
  w: number,
  h: number,
  camera: Camera,
  look: Look,
) {
  gpu ??= createGPU();
  if (!gpu) return false;
  const { surface, gl, program, uniforms: u } = gpu;
  const room = look.room ?? 'classic';
  if (gpu.room !== room) {
    const data = build(room);
    gl.bindBuffer(gl.ARRAY_BUFFER, gpu.buffer);
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
    gpu.room = room;
    gpu.count = data.length / 14;
  }
  if (surface.width !== w || surface.height !== h) {
    surface.width = w;
    surface.height = h;
  }
  const movement = look.motion ?? [0, 0, 0];
  const shadowKey = room + movement.map((value) => Math.round(value * 150)).join(',');
  if (shadowKey !== gpu.shadowKey) {
    gl.useProgram(gpu.shadowProgram);
    const su = gpu.shadowUniforms;
    gl.uniform1f(su.room, room === 'xtreme' ? 2 : room === 'beds' ? 1 : 0);
    gl.uniform3fv(su.motion, movement);
    for (const shadow of gpu.shadows) {
      if (!shadow.complete) continue;
      gl.bindFramebuffer(gl.FRAMEBUFFER, shadow.frame);
      gl.viewport(0, 0, gpu.shadowSize, gpu.shadowSize);
      gl.clearColor(1, 1, 1, 1);
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      uploadCamera(gl, su, shadow.camera, 1, true);
      gl.drawArrays(gl.TRIANGLES, 0, gpu.count);
    }
    gpu.shadowKey = shadowKey;
  }
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0, 0, w, h);
  gl.useProgram(program);
  gl.clearColor(0.016, 0.018, 0.025, 1);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  uploadCamera(gl, u, camera, w / h);
  const film = look.filmFrame;
  if (film && (gpu.filmOwner !== film.image || gpu.filmVersion !== film.version)) {
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, gpu.filmTexture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, film.image);
    gpu.filmOwner = film.image;
    gpu.filmVersion = film.version;
  }
  for (const [index, texture] of [
    gpu.textures.leather,
    film ? gpu.filmTexture : gpu.textures.screen,
    ...gpu.shadows.map((s) => s.texture),
  ].entries()) {
    gl.activeTexture(gl.TEXTURE0 + index);
    gl.bindTexture(gl.TEXTURE_2D, texture);
  }
  gl.uniform1i(u.leatherMap, 0);
  gl.uniform1i(u.filmMap, 1);
  gl.uniform1i(u.screenShadow, 2);
  gl.uniform1i(u.houseShadow, 3);
  gl.uniformMatrix4fv(u.screenMatrix, false, gpu.shadows[0].matrix);
  gl.uniformMatrix4fv(u.houseMatrix, false, gpu.shadows[1].matrix);
  gl.uniform1f(
    u.selected,
    roomPlan(room).seats.findIndex((s) => s.id === look.chosen),
  );
  gl.uniform1f(u.brightness, look.film ?? 1);
  gl.uniform1f(u.houseLights, look.houseLights ? 1 : 0);
  gl.uniform1f(u.soundMap, look.soundMap ? 1 : 0);
  gl.uniform1f(u.room, room === 'xtreme' ? 2 : room === 'beds' ? 1 : 0);
  gl.uniform3fv(u.motion, look.motion ?? [0, 0, 0]);
  const plan = roomPlan(room),
    firstRow = plan.seats.filter((seat) => seat.row === plan.rows[0]);
  gl.uniform3f(u.layout, firstRow.length, plan.pitch, room === 'beds' ? 0.4 : 0.34);
  gl.uniform1fv(
    u['shadowXs[0]'],
    new Float32Array(Array.from({ length: 14 }, (_, i) => firstRow[i]?.x ?? 0)),
  );
  gl.drawArrays(gl.TRIANGLES, 0, gpu.count);
  ctx.drawImage(surface, 0, 0, w, h);
  return true;
}

/** Awaited by native artwork exports, while paused runtime views redraw on texture readiness. */
export async function cinemaMaterialsReady() {
  await gpu?.textures.ready;
}

const SOUND_SOURCES: { point: V; label: string; group: string }[] = [
  { point: [0, 4.35, 0.12], label: 'Screen L / C / R', group: 'screen' },
  ...[-1, 1].flatMap((side) =>
    [3.55, 8.05, 12.55].map((z) => ({
      point: [side * 6.12, 5.35, z] as V,
      label: side < 0 ? 'Left surround' : 'Right surround',
      group: side < 0 ? 'left' : 'right',
    })),
  ),
  ...[-3, 3].map((x) => ({ point: [x, 5.35, 15.94] as V, label: 'Rear surround', group: 'rear' })),
  ...[-3, 3].flatMap((x) =>
    [6, 11].map((z) => ({ point: [x, 7.66, z] as V, label: 'Overhead', group: 'ceiling' })),
  ),
];
function projectWorld(camera: Camera, width: number, height: number, point: V) {
  const cp = Math.cos(camera.pitch),
    sp = Math.sin(camera.pitch),
    cy = Math.cos(camera.yaw),
    sy = Math.sin(camera.yaw);
  const dx = point[0] - camera.x,
    dy = point[1] - camera.y,
    dz = point[2] - camera.z;
  const depth = dx * sy * cp + dy * sp - dz * cy * cp;
  if (depth < 0.1) return null;
  return [
    width / 2 + ((dx * cy + dz * sy) * width * camera.zoom) / 2 / depth,
    height * camera.centre -
      ((-dx * sy * sp + dy * cp + dz * cy * sp) * width * camera.zoom) / 2 / depth,
  ];
}
export function drawSoundSources(
  ctx: CanvasRenderingContext2D,
  w: number,
  h: number,
  camera: Camera,
) {
  const ratio = w / Math.max(1, ctx.canvas.clientWidth || w),
    shown = new Set<string>();
  ctx.save();
  ctx.font = `500 ${Math.max(10, 12 * ratio)}px Inter,Arial,sans-serif`;
  for (const source of SOUND_SOURCES) {
    const p = projectWorld(camera, w, h, source.point);
    if (
      !p ||
      p[0] < 16 * ratio ||
      p[0] > w - 16 * ratio ||
      p[1] < 18 * ratio ||
      p[1] > h - 30 * ratio
    )
      continue;
    const [x, y] = p;
    ctx.strokeStyle = '#6fdfec';
    ctx.fillStyle = '#a4f3ff';
    ctx.lineWidth = 1.5 * ratio;
    for (const r of [8, 14]) {
      ctx.beginPath();
      ctx.arc(x, y, r * ratio, 0, Math.PI * 2);
      ctx.globalAlpha = r === 8 ? 0.9 : 0.45;
      ctx.stroke();
    }
    ctx.globalAlpha = 1;
    ctx.beginPath();
    ctx.arc(x, y, 2.5 * ratio, 0, Math.PI * 2);
    ctx.fill();
    if (shown.has(source.group)) continue;
    shown.add(source.group);
    const text = source.label,
      tw = ctx.measureText(text).width + 18 * ratio;
    const bx = Math.max(4, Math.min(w - tw - 4, x - tw / 2)),
      by = y + 20 * ratio;
    ctx.fillStyle = 'rgba(4,19,25,.9)';
    ctx.beginPath();
    ctx.roundRect(bx, by, tw, 24 * ratio, 6 * ratio);
    ctx.fill();
    ctx.fillStyle = '#b5f4ff';
    ctx.fillText(text, bx + 9 * ratio, by + 16 * ratio);
  }
  ctx.restore();
}

/** The same perspective, as a CSS homography for the real movie player on the screen plane. */
export function projectScreen(camera: Camera, width: number, height: number) {
  const cp = Math.cos(camera.pitch),
    sp = Math.sin(camera.pitch),
    cy = Math.cos(camera.yaw),
    sy = Math.sin(camera.yaw);
  const point = (x: number, y: number) => {
    const dx = x - camera.x,
      dy = y - camera.y,
      dz = 0.078 - camera.z;
    const z = dx * sy * cp + dy * sp - dz * cy * cp;
    if (z < 0.1) return null;
    return [
      width / 2 + ((dx * cy + dz * sy) * width * camera.zoom) / 2 / z,
      height * camera.centre -
        ((-dx * sy * sp + dy * cp + dz * cy * sp) * width * camera.zoom) / 2 / z,
    ];
  };
  const p = [
    point(-SCREEN.width / 2, SCREEN.bottom + SCREEN.height),
    point(SCREEN.width / 2, SCREEN.bottom + SCREEN.height),
    point(SCREEN.width / 2, SCREEN.bottom),
    point(-SCREEN.width / 2, SCREEN.bottom),
  ];
  if (p.some((v) => !v)) return null;
  const [a, b, c, d] = p as number[][];
  const dx1 = b[0] - c[0],
    dx2 = d[0] - c[0],
    dx3 = a[0] - b[0] + c[0] - d[0];
  const dy1 = b[1] - c[1],
    dy2 = d[1] - c[1],
    dy3 = a[1] - b[1] + c[1] - d[1];
  const determinant = dx1 * dy2 - dx2 * dy1;
  if (Math.abs(determinant) < 0.01) return null;
  const g = (dx3 * dy2 - dx2 * dy3) / determinant,
    h = (dx1 * dy3 - dx3 * dy1) / determinant;
  const m = [
    (b[0] - a[0] + g * b[0]) / 1280,
    (b[1] - a[1] + g * b[1]) / 1280,
    0,
    g / 1280,
    (d[0] - a[0] + h * d[0]) / 544,
    (d[1] - a[1] + h * d[1]) / 544,
    0,
    h / 544,
    0,
    0,
    1,
    0,
    a[0],
    a[1],
    0,
    1,
  ];
  return `matrix3d(${m.join(',')})`;
}
```

### seat-view/cinema-materials.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/** Packed CC0 Leather027 maps: OpenGL normal XY, roughness, albedo variation. */
export function loadCinemaTextures(gl: WebGLRenderingContext, redraw: () => void) {
  const load = (url: string, pixel: number[], repeat: boolean) => {
    const texture = gl.createTexture()!;
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      gl.RGBA,
      1,
      1,
      0,
      gl.RGBA,
      gl.UNSIGNED_BYTE,
      new Uint8Array(pixel),
    );
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    const ready = new Promise<void>((resolve) => {
      const image = new Image();
      image.onload = () => {
        if (!gl.isContextLost()) {
          gl.bindTexture(gl.TEXTURE_2D, texture);
          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
          if (repeat) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
            gl.generateMipmap(gl.TEXTURE_2D);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
          }
        }
        resolve();
        redraw();
      };
      image.onerror = () => {
        resolve();
        redraw();
      };
      image.src = url;
    });
    return { texture, ready };
  };
  const leather = load(
    '/experiments/seat-view/materials/leather-pbr.webp',
    [128, 128, 115, 128],
    true,
  );
  const screen = load('/experiments/seat-view/spider-man-screen.webp', [153, 128, 83, 255], false);
  return {
    leather: leather.texture,
    screen: screen.texture,
    ready: Promise.all([leather.ready, screen.ready]),
  };
}

export const SHADOW_FRAGMENT = `
precision highp float;
varying float vMaterial;
void main(){
  if((vMaterial>3.5 && vMaterial<4.5) || (vMaterial>5.5 && vMaterial<6.5) || (vMaterial>8.5 && vMaterial<9.5)) discard;
  vec4 encodedDepth=fract(gl_FragCoord.z*vec4(1.0,255.0,65025.0,16581375.0));
  encodedDepth-=encodedDepth.yzww*vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);
  gl_FragColor=encodedDepth;
}`;

/** Linear lighting, GGX dielectric leather, a rectangular film light and filtered depth shadows. */
export const MATERIAL_FRAGMENT = `
precision highp float;
uniform vec3 eye;
uniform float selected, brightness, houseLights, soundMap, room;
uniform vec3 layout;
uniform float shadowXs[14];
uniform sampler2D leatherMap, filmMap, screenShadow, houseShadow;
uniform mat4 screenMatrix, houseMatrix;
varying vec3 vPosition, vNormal, vColor;
varying float vMaterial, vSeat, vDistance;
const float PI=3.14159265;
float noise(vec3 p){return fract(sin(dot(p,vec3(127.1,311.7,74.7)))*43758.5453);}
float depthAt(sampler2D map,vec2 uv){return dot(texture2D(map,uv),vec4(1.,1./255.,1./65025.,1./16581375.));}
float visibility(sampler2D map,mat4 matrix,vec3 p,vec3 n,vec3 light){
  vec4 q=matrix*vec4(p+n*0.009,1.);vec3 ndc=q.xyz/q.w;vec2 uv=ndc.xy*.5+.5;
  if(q.w<0. || any(lessThan(uv,vec2(.004))) || any(greaterThan(uv,vec2(.996))))return 1.;
  float depth=ndc.z*.5+.5, bias=max(.0007,.0015*(1.-max(dot(n,light),0.))), sum=0.;
  for(int x=-1;x<=1;x++)for(int y=-1;y<=1;y++){
    float stored=depthAt(map,uv+vec2(float(x),float(y))*.0009);
    sum+=smoothstep(depth-bias-.00006,depth-bias+.00006,stored);
  }
  return mix(.12,1.,sum/9.);
}
vec3 brdf(vec3 n,vec3 v,vec3 l,vec3 base,float rough,vec3 f0){
  vec3 h=normalize(l+v);float nl=max(dot(n,l),0.), nv=max(dot(n,v),.001), nh=max(dot(n,h),0.), vh=max(dot(v,h),0.);
  float a=rough*rough,a2=a*a,d=nh*nh*(a2-1.)+1.;
  float distribution=a2/(PI*d*d+.00001), k=(rough+1.)*(rough+1.)/8.;
  float geometry=nl/(nl*(1.-k)+k)*nv/(nv*(1.-k)+k);
  vec3 fresnel=f0+(1.-f0)*pow(1.-vh,5.);
  vec3 spec=distribution*geometry*fresnel/max(.004,4.*nv*nl);
  return ((1.-fresnel)*base/PI+spec)*nl;
}
vec4 leatherSample(vec3 p,vec3 n){
  vec3 weights=pow(abs(n),vec3(6.));weights/=max(dot(weights,vec3(1.)),.001);
  return texture2D(leatherMap,p.zy*3.0)*weights.x+texture2D(leatherMap,p.xz*3.0)*weights.y+texture2D(leatherMap,p.xy*3.0)*weights.z;
}
vec3 filmColor(vec2 uv){return pow(texture2D(filmMap,clamp(uv,vec2(.01),vec2(.99))).rgb,vec3(2.2));}
vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);}
void main(){
  if(vMaterial>5.5 && vMaterial<6.5 && eye.y>7.5)discard;
  if(vPosition.z>16.1 && eye.z>16.25)discard;
  vec3 p=vPosition, n=normalize(vNormal), geometric=n, v=normalize(eye-p);
  bool upholstered=vMaterial<.5 || (vMaterial>7.5 && vMaterial<8.5);
  bool metal=vMaterial>1.5 && vMaterial<2.5;
  bool fabric=vMaterial>.5 && vMaterial<1.5;
  float rough=metal?.25:fabric?.95:.62;
  if(vMaterial>11.5 && vMaterial<12.5)rough=.90;
  vec3 base=vColor, f0=metal?mix(vec3(.09),base,.65):vec3(.035);
  if(upholstered){
    vec4 material=leatherSample(p,n);
    vec3 tangent=normalize(abs(n.y)>.8?cross(vec3(0.,0.,1.),n):cross(vec3(0.,1.,0.),n));
    vec3 bitangent=normalize(cross(n,tangent));
    vec2 detail=(material.rg*2.-1.)*.80;
    // Micro-normal detail follows the surface; roughness breaks up the broad screen highlight.
    n=normalize(n+tangent*detail.x+bitangent*detail.y);
    rough=clamp(.52+material.b*.28+(material.a-.5)*.10,.56,.76);
    f0=vec3(.028);
    base*=.70+material.a*.40;
    float folds=sin(p.x*96.+sin(p.z*17.)*2.)*sin(p.y*61.+p.z*23.);
    base*=.97+.03*folds;
  }
  if(fabric)base*=.76+noise(floor(p*180.))*.24;
  if(vMaterial>11.5 && vMaterial<12.5)base*=.65+.35*smoothstep(.35,.5,fract(p.z*48.));
  if(vMaterial>9.5 && vMaterial<10.5)base*=.90+.10*sin(p.z*110.+sin(p.x*11.)*2.);
  if(vSeat>=0. && abs(vSeat-selected)<.3)base=mix(base,vec3(.07,.21,.12),.06);
  vec3 ambient=vec3(.007,.009,.015)+houseLights*vec3(.055,.048,.038);
  float sky=.35+.65*max(n.y,0.);
  vec3 lit=base*ambient*sky;
  vec3 toScreen=vec3(0.,4.34,.25)-p;
  vec3 screenDirection=normalize(toScreen);
  float screenVisible=visibility(screenShadow,screenMatrix,p,geometric,screenDirection);
  // The luminous screen is an 11 x 4.68 metre area, rather than a single point light.
  for(int x=0;x<3;x++)for(int y=0;y<2;y++){
    vec2 uv=(vec2(float(x),float(y))+vec2(.5))/vec2(3.,2.);
    vec3 source=vec3((uv.x-.5)*11.,2.+uv.y*4.68,.25),delta=source-p;
    float distance2=dot(delta,delta);
    vec3 radiance=filmColor(uv)*70./(distance2+14.);
    lit+=brdf(n,v,normalize(delta),base,rough,f0)*radiance*screenVisible*brightness;
  }
  // A broad warm ceiling source, with shadows from the actual cushions, arms and tables.
  vec3 ceilingDelta=vec3(-3.,7.5,8.)-p;
  float houseVisible=visibility(houseShadow,houseMatrix,p,geometric,normalize(ceilingDelta));
  lit+=brdf(n,v,normalize(ceilingDelta),base,rough,f0)*vec3(3.0,2.5,1.9)*houseLights*houseVisible;
  lit+=brdf(n,v,normalize(vec3(4.,7.5,5.)-p),base,.7,f0)*vec3(.6,.56,.52)*houseLights;
  float wall=pow(clamp(abs(p.x)/6.7,0.,1.),5.);
  lit+=base*vec3(.35,.13,.035)*wall*mix(.12,.55,houseLights);
  if(upholstered || metal){
    // Fresnel reflection intersects the real screen plane. Roughness spreads the film image.
    vec3 ray=reflect(-v,n);float t=(.078-p.z)/min(ray.z,-.0001);
    if(ray.z<-.01 && t>0.){
      vec3 hit=p+ray*t;vec2 uv=vec2(hit.x/11.+.5,(hit.y-2.)/4.68);
      float edge=smoothstep(0.,.06,uv.x)*smoothstep(0.,.06,uv.y)*smoothstep(0.,.06,1.-uv.x)*smoothstep(0.,.06,1.-uv.y);
      float blur=rough*.24;
      vec3 reflection=filmColor(uv)*.4;
      reflection+=(filmColor(uv+vec2(blur,0.))+filmColor(uv-vec2(blur,0.))+filmColor(uv+vec2(0.,blur))+filmColor(uv-vec2(0.,blur)))*.15;
      vec3 fresnel=f0+(1.-f0)*pow(1.-max(dot(n,v),0.),5.);
      lit+=reflection*fresnel*edge*screenVisible*brightness*(upholstered?.55:2.5);
    }
  }
  // Occlusion at the floor, the centre seam, and the seat/back junction keeps upholstery grounded.
  if(fabric && geometric.y>.65 && p.z>3.1){
    float dx=100.;for(int i=0;i<14;i++)if(float(i)<layout.x)dx=min(dx,abs(p.x-shadowXs[i]));
    float rowIndex=clamp(floor((p.z-4.8)/layout.y+.5),0.,room>.5 && room<1.5?4.:room>1.5?7.:8.);
    float dz=p.z-(4.8+rowIndex*layout.y)+(room>.5 && room<1.5?.25:0.);
    vec2 footprint=vec2(dx/(room>.5 && room<1.5?1.12:.37),dz/(room>.5 && room<1.5?1.20:.47));
    lit*=1.-(1.-smoothstep(.28,1.4,length(footprint)))*.7;
  }
  if(vSeat>=0. && upholstered){
    float rowIndex=floor((p.z-4.8)/layout.y+.5),floorY=max(0.,rowIndex)*layout.z;
    float localZ=p.z-(4.8+rowIndex*layout.y),localY=p.y-floorY;
    float junction=exp(-pow((localZ-.24)*10.,2.))*exp(-pow((localY-.60)*6.,2.));
    lit*=1.-junction*.45;
  }
  if(vMaterial>2.5 && vMaterial<3.5)lit=base*mix(.20,1.3,houseLights);
  if(vMaterial>3.5 && vMaterial<4.5)lit=vec3(.27,.32,.42)*brightness;
  if(vMaterial>10.5 && vMaterial<11.5)lit=base*mix(.08,2.0,houseLights);
  if(vMaterial>6.5 && vMaterial<7.5 && soundMap>.5)lit=vec3(.03,.6,.8);
  float fog=1.-exp(-vDistance*.003);
  lit=mix(lit,vec3(.003,.004,.007),fog);
  gl_FragColor=vec4(pow(aces(lit*1.5),vec3(1./2.2)),1.);
}`;
```

### seat-view/cinema-film.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.
'use client';

import { useEffect, useRef, useState } from 'react';
import type { useHall } from './use-hall';
import { CINEMA_FILM } from './cinema-film-source';
import styles from './seat-view.module.css';

/** One native video supplies both the projected picture and the actual decoded light frames. */
export function CinemaFilm({
  hall,
  active = true,
}: {
  hall: ReturnType<typeof useHall>;
  active?: boolean;
}) {
  const container = useRef<HTMLDivElement>(null);
  const video = useRef<HTMLVideoElement>(null);
  const [visible, setVisible] = useState(false);
  const [paused, setPaused] = useState(false);
  const [sound, setSound] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [reduced, setReduced] = useState(false);
  const [unavailable, setUnavailable] = useState(false);
  const canPlay = active && visible && !paused && !reduced && !unavailable;

  useEffect(() => {
    const element = container.current;
    if (!element) return;
    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));
    observer.observe(element);
    const media = matchMedia('(prefers-reduced-motion: reduce)');
    const change = () => {
      setReduced(media.matches);
      if (media.matches) setPaused(true);
    };
    change();
    media.addEventListener('change', change);
    return () => {
      observer.disconnect();
      media.removeEventListener('change', change);
    };
  }, []);

  useEffect(() => {
    const element = video.current;
    if (!element) return;
    const sync = () => {
      if (canPlay && !document.hidden) void element.play().catch(() => setPaused(true));
      else {
        element.pause();
        hall.setPlaying(false);
      }
    };
    sync();
    document.addEventListener('visibilitychange', sync);
    return () => {
      document.removeEventListener('visibilitychange', sync);
      element.pause();
      hall.setPlaying(false);
    };
  }, [canPlay, hall]);

  useEffect(() => {
    const element = video.current;
    if (!element) return;
    let frame = 0,
      raf = 0,
      disposed = false,
      lastTime = -1;
    const copy = (time = element.currentTime) => {
      if (element.readyState < 2 || disposed) return;
      // The projected <video> and this texture are the very same decoded media source.
      hall.setFilmFrame(element, CINEMA_FILM.sourceStart + time);
      lastTime = time;
      setLoaded(true);
    };
    const seek = () => copy();
    element.addEventListener('loadeddata', seek);
    element.addEventListener('seeked', seek);
    if (typeof element.requestVideoFrameCallback === 'function') {
      const next: VideoFrameRequestCallback = (_now, metadata) => {
        if (disposed) return;
        copy(metadata.mediaTime);
        frame = element.requestVideoFrameCallback(next);
      };
      frame = element.requestVideoFrameCallback(next);
    } else {
      const next = () => {
        raf = 0;
        if (element.paused || document.hidden || disposed) return;
        if (element.currentTime !== lastTime) copy();
        raf = requestAnimationFrame(next);
      };
      const start = () => {
        if (!raf && !disposed) raf = requestAnimationFrame(next);
      };
      element.addEventListener('playing', start);
      start();
      return () => {
        disposed = true;
        cancelAnimationFrame(raf);
        element.removeEventListener('playing', start);
        element.removeEventListener('loadeddata', seek);
        element.removeEventListener('seeked', seek);
      };
    }
    copy();
    return () => {
      disposed = true;
      if (frame) element.cancelVideoFrameCallback(frame);
      cancelAnimationFrame(raf);
      element.removeEventListener('loadeddata', seek);
      element.removeEventListener('seeked', seek);
    };
  }, [hall]);

  return (
    <div ref={container} className={styles.projection} data-part="projection">
      <div ref={hall.attachFilmPlane} className={styles.filmPlane} aria-hidden="true">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={CINEMA_FILM.poster}
          width={960}
          height={408}
          alt=""
          className={styles.filmPoster}
        />
        <video
          ref={video}
          src={active ? CINEMA_FILM.src : undefined}
          poster={CINEMA_FILM.poster}
          className={styles.filmPlayer}
          data-playing={loaded || undefined}
          data-part="film-video"
          muted={!sound}
          loop
          playsInline
          crossOrigin="anonymous"
          preload={active ? (visible ? 'auto' : 'metadata') : 'none'}
          aria-hidden="true"
          onPlaying={() => hall.setPlaying(true)}
          onPause={() => hall.setPlaying(false)}
          onWaiting={() => hall.setPlaying(false)}
          onTimeUpdate={(event) =>
            hall.setFilmTime(CINEMA_FILM.sourceStart + event.currentTarget.currentTime)
          }
          onError={() => {
            setUnavailable(true);
            setLoaded(false);
            hall.setPlaying(false);
          }}
        >
          <track kind="captions" src={CINEMA_FILM.captions} srcLang="en" label="English" />
        </video>
        <div className={styles.screenGrain} />
      </div>
      {active && (
        <div className={styles.filmControls}>
          <span>
            NOW SHOWING <strong>{CINEMA_FILM.title}</strong>
          </span>
          <div>
            <button
              type="button"
              aria-label={paused || reduced ? 'Play film' : 'Pause film'}
              onClick={() => {
                const play = paused || reduced;
                setReduced(false);
                setPaused(!play);
                if (play) void video.current?.play().catch(() => setPaused(true));
                else video.current?.pause();
              }}
            >
              {paused || reduced ? '▶' : 'Ⅱ'}
            </button>
            <button
              type="button"
              aria-label={sound ? 'Mute film' : 'Unmute film'}
              aria-pressed={sound}
              onClick={() => setSound(!sound)}
            >
              {sound ? 'Sound on' : 'Sound off'}
            </button>
          </div>
          {unavailable && (
            <a href={CINEMA_FILM.sourcePage} target="_blank" rel="noreferrer">
              Watch trailer ↗
            </a>
          )}
        </div>
      )}
    </div>
  );
}
```

### seat-view/cinema-film-source.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/** The complete local Columbia Pictures trailer; screen and light share one native player. */
export const CINEMA_FILM = {
  title: 'Spider-Man: No Way Home',
  src: '/experiments/seat-view/spider-man-trailer-full-3b0ca4312d7c.mp4',
  captions:
    'https://vs-prodamdfandango.akamaized.net/NBCU_Fandango/244/971/source_1BD18461-FCEA-4FA7-835E-0C8A351848F2nowayhome_tr2_19748716195_en.vtt',
  poster: '/experiments/seat-view/spider-man-screen.webp',
  sourcePage: 'https://www.rottentomatoes.com/m/spider_man_no_way_home/videos/ww8kAAMF00Ss',
  /** The player, light texture and Xtreme cue track share the full trailer timeline. */
  sourceStart: 0,
} as const;
```

### seat-view/room-environment.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.
'use client';

import { createContext, useContext } from 'react';
import { ROOM_INFO, roomPlan, type RoomKind } from './hall';
import styles from './seat-view.module.css';

export type RoomEnvironment = {
  room: RoomKind;
  setRoom: (room: RoomKind) => void;
  houseLights: boolean;
  setHouseLights: (on: boolean) => void;
  soundMap: boolean;
  setSoundMap: (on: boolean) => void;
  motion: boolean;
  setMotion: (on: boolean) => void;
  temperature: number;
};
export const RoomContext = createContext<RoomEnvironment | null>(null);
export function useRoom() {
  const room = useContext(RoomContext);
  if (!room) throw new Error('Room controls belong inside SeatView.');
  return room;
}

export function RoomPicker() {
  const { room, setRoom, temperature } = useRoom();
  const kinds = Object.keys(ROOM_INFO) as RoomKind[];
  const plan = roomPlan(room);
  const change = (kind: RoomKind, element: HTMLElement) => {
    const root = element.closest('[data-layout]');
    setRoom(kind);
    // The room remounts its map, so restore focus to the new room's selected radio.
    requestAnimationFrame(() =>
      root?.querySelector<HTMLElement>('[data-part="room-picker"] [aria-checked="true"]')?.focus(),
    );
  };
  return (
    <div className={styles.roomPicker} data-part="room-picker">
      <div
        role="radiogroup"
        tabIndex={-1}
        aria-label="Cinema room"
        onKeyDown={(event) => {
          const directions: Record<string, number> = {
            ArrowRight: 1,
            ArrowDown: 1,
            ArrowLeft: -1,
            ArrowUp: -1,
          };
          const step = directions[event.key];
          if (step === undefined && event.key !== 'Home' && event.key !== 'End') return;
          event.preventDefault();
          const next =
            event.key === 'Home'
              ? 0
              : event.key === 'End'
                ? kinds.length - 1
                : (kinds.indexOf(room) + (step ?? 0) + kinds.length) % kinds.length;
          change(kinds[next], event.currentTarget);
        }}
      >
        {kinds.map((kind) => (
          <button
            type="button"
            role="radio"
            key={kind}
            aria-checked={kind === room}
            tabIndex={kind === room ? 0 : -1}
            onClick={(event) => change(kind, event.currentTarget)}
          >
            {ROOM_INFO[kind].label}
          </button>
        ))}
      </div>
      <p>
        <span>
          {plan.seats.length}{' '}
          {room === 'beds'
            ? `lounges · ${plan.seats.reduce((sum, seat) => sum + seat.capacity, 0)} places`
            : 'seats'}
        </span>
        <span>{temperature}°C · Climate controlled</span>
      </p>
      <small>{ROOM_INFO[room].detail}</small>
    </div>
  );
}

export function RoomTools() {
  const {
    room,
    houseLights,
    setHouseLights,
    soundMap,
    setSoundMap,
    motion,
    setMotion,
    temperature,
  } = useRoom();
  return (
    <div className={styles.roomTools} data-part="room-environment">
      <div>
        <button
          type="button"
          aria-label={houseLights ? 'Switch to screening darkness' : 'Turn house lights on'}
          aria-pressed={houseLights}
          onClick={() => setHouseLights(!houseLights)}
        >
          <span aria-hidden="true">{houseLights ? '☀' : '☾'}</span>
          {houseLights ? 'House lights' : 'Screening'}
        </button>
        <button
          type="button"
          aria-label="Show sound sources"
          aria-pressed={soundMap}
          onClick={() => setSoundMap(!soundMap)}
        >
          <SpeakerIcon />
          Sound map
        </button>
        <span
          className={styles.temperature}
          aria-label={`Room temperature ${temperature} degrees Celsius`}
        >
          <ThermometerIcon />
          {temperature}°C
        </span>
      </div>
      {room === 'xtreme' && (
        <button
          type="button"
          className={styles.motionSwitch}
          aria-pressed={motion}
          aria-label="Xtreme motion preview"
          onClick={() => setMotion(!motion)}
        >
          <span className={styles.motionDot} data-on={motion || undefined} />
          {motion ? 'Motion preview on' : 'Motion preview off'}
          <span>3-axis seats</span>
        </button>
      )}
      {soundMap && (
        <p className={styles.soundLegend} role="status">
          <i />
          Screen L/C/R · side & rear surround · overhead
        </p>
      )}
    </div>
  );
}

function SpeakerIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <path d="M9 4 5 7H2v6h3l4 3V4Zm4 3c2 2 2 4 0 6m3-9c4 3.5 4 8.5 0 12" />
    </svg>
  );
}
function ThermometerIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <path d="M8 11V4a2 2 0 0 1 4 0v7a4 4 0 1 1-4 0Zm2-5v7m4-9h3m-3 4h2" />
    </svg>
  );
}

/** A small authored preview track sampled against the actual player's time, in seconds. */
const CUES: [number, number, number, number][] = [
  [0, 0, 0, 0],
  [5, 0, 0, 0],
  [13, 0.01, 0.02, -0.012],
  [20, 0, 0, 0],
  [32, 0.012, -0.018, 0.014],
  [43, 0, 0, 0],
  [62, -0.008, 0.02, -0.012],
  [79, 0, 0, 0],
  [90, 0, 0, 0],
  [96, 0.018, 0.035, -0.025],
  [103, -0.008, -0.03, 0.025],
  [114, 0.012, 0.02, 0],
  [128, 0, 0, 0],
  [143, 0.012, 0.025, -0.02],
  [155, 0.022, -0.045, 0.035],
  [164, -0.008, 0.025, -0.018],
  [171, 0, 0, 0],
  [174, 0, 0, 0],
];
export function motionAt(time: number): [number, number, number] {
  const next = CUES.findIndex((c) => c[0] > time);
  if (next <= 0) return [0, 0, 0];
  const a = CUES[next - 1],
    b = CUES[next];
  const t = (time - a[0]) / (b[0] - a[0]),
    k = t * t * (3 - 2 * t);
  return [1, 2, 3].map((i) => a[i] + (b[i] - a[i]) * k) as [number, number, number];
}
```

### seat-view/use-hall.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useMemo, useRef } from 'react';
import { blendCamera, drawHall, flightCamera, type Camera, type Look } from './hall';
import { drawCinema, drawSoundSources, projectScreen } from './cinema-gl';
import { motionAt, useRoom } from './room-environment';

/*
 * The canvas the hall is drawn on, and the moves of its camera. The hall is drawn only when
 * something changes: a move plays frame by frame and stops, a drag to look around draws as the
 * pointer moves and springs back, and a resize or a new look draws once. Between them the canvas
 * holds its last frame. New decoded video frames schedule the room's light and reflections;
 * hidden instances and paused films keep their last frame.
 *
 * Moves: `blend` eases every value of the camera together (the desktop's glide from seat to
 * seat); `land` is the app's flight from the plan down into a seat, and `lift` the same flight
 * played backwards. A move started during another starts from wherever the camera is.
 */

export type Move = 'blend' | 'land' | 'lift';

type Running = {
  from: Camera;
  to: Camera;
  move: Move;
  start: number;
  ms: number;
  done: () => void;
};

/** How far a drag can turn the view, in radians, sideways and up or down. */
const PEEK_YAW = 0.5;
const PEEK_PITCH = 0.18;
const PEEK_BACK_MS = 520;

export function useHall(initial: Camera) {
  const environment = useRoom();
  const roomOptions = useRef({
    room: environment.room,
    houseLights: environment.houseLights,
    soundMap: environment.soundMap,
    motion: environment.motion,
  });
  const filmClock = useRef({ time: 0, at: 0 });
  const filmFrame = useRef<Look['filmFrame']>(undefined);
  const reduced = useRef(false);
  const canvas = useRef<HTMLCanvasElement>(null);
  const camera = useRef(initial);
  const look = useRef<Look>({});
  const running = useRef<Running | null>(null);
  const peek = useRef({ yaw: 0, pitch: 0 });
  const peekBack = useRef<{ yaw: number; pitch: number; start: number } | null>(null);
  const frame = useRef(0);
  const filmPlane = useRef<HTMLDivElement>(null);
  const soundOverlay = useRef<HTMLCanvasElement>(null);
  const playing = useRef(false);
  const visible = useRef(false);

  const paint = useCallback(() => {
    const element = canvas.current;
    if (!element) return;
    // The canvas may sit in a scaled box: its pixels follow its size on screen.
    const rect = element.getBoundingClientRect();
    const ratio = Math.min(2, window.devicePixelRatio || 1);
    const w = Math.max(1, Math.round(rect.width * ratio));
    const h = Math.max(1, Math.round(rect.height * ratio));
    if (element.width !== w || element.height !== h) {
      element.width = w;
      element.height = h;
    }
    const ctx = element.getContext('2d');
    if (!ctx) return;
    const view = camera.current;
    const options = roomOptions.current;
    const moves =
      options.room === 'xtreme' && options.motion && playing.current && !reduced.current;
    const time = filmFrame.current?.mediaTime ?? filmClock.current.time;
    const motion = moves ? motionAt(time) : ([0, 0, 0] as [number, number, number]);
    const seatedMotion = look.current.chosen ? motion : [0, 0, 0];
    const projected = {
      ...view,
      y: view.y + seatedMotion[0] * 0.3,
      yaw: view.yaw + peek.current.yaw + seatedMotion[2] * 0.08,
      pitch: view.pitch + peek.current.pitch + seatedMotion[1] * 0.12,
    };
    const appearance = {
      ...look.current,
      ...options,
      motion,
      filmTime: time,
      filmFrame: filmFrame.current,
    };
    element.dataset.room = options.room;
    element.dataset.motion = moves ? 'on' : 'off';
    element.dataset.lighting = options.houseLights ? 'house' : 'screening';
    element.dataset.filmTime = time.toFixed(2);
    element.dataset.filmLight = filmFrame.current ? 'video' : 'poster';
    element.dataset.filmFrame = String(filmFrame.current?.version ?? 0);
    element.dataset.filmFrameTime = String(filmFrame.current?.mediaTime ?? 0);
    if (!drawCinema(ctx, w, h, projected, appearance)) drawHall(ctx, w, h, projected, appearance);
    const overlay = soundOverlay.current;
    if (overlay) {
      overlay.style.visibility = options.soundMap ? 'visible' : 'hidden';
      if (overlay.width !== w || overlay.height !== h) {
        overlay.width = w;
        overlay.height = h;
      }
      const overlayContext = overlay.getContext('2d');
      if (overlayContext) {
        overlayContext.clearRect(0, 0, w, h);
        if (options.soundMap) drawSoundSources(overlayContext, w, h, projected);
      }
    }
    if (filmPlane.current) {
      const transform = projectScreen(projected, element.clientWidth, element.clientHeight);
      filmPlane.current.style.visibility = transform ? 'visible' : 'hidden';
      if (transform) filmPlane.current.style.transform = transform;
    }
  }, []);

  const tick = useCallback(
    function tickFrame(now: number) {
      frame.current = 0;
      let again = false;
      const move = running.current;
      if (move) {
        const t = move.ms <= 0 ? 1 : Math.min(1, (now - move.start) / move.ms);
        camera.current =
          move.move === 'land'
            ? flightCamera(move.from, move.to, t)
            : move.move === 'lift'
              ? flightCamera(move.to, move.from, 1 - t)
              : blendCamera(move.from, move.to, t);
        if (t >= 1) {
          running.current = null;
          move.done();
        } else again = true;
      }
      const back = peekBack.current;
      if (back) {
        const t = Math.min(1, (now - back.start) / PEEK_BACK_MS);
        const k = 1 - (1 - t) ** 3;
        peek.current = { yaw: back.yaw * (1 - k), pitch: back.pitch * (1 - k) };
        if (t >= 1) peekBack.current = null;
        else again = true;
      }
      // Decoded frames schedule their own paint. Camera movement can still run at display rate.
      // A paused or buffering movie has no synthetic light clock to keep the room animating.
      paint();
      if (again) frame.current = requestAnimationFrame(tickFrame);
    },
    [paint],
  );

  const schedule = useCallback(() => {
    if (!frame.current) frame.current = requestAnimationFrame(tick);
  }, [tick]);

  useEffect(() => {
    roomOptions.current = {
      room: environment.room,
      houseLights: environment.houseLights,
      soundMap: environment.soundMap,
      motion: environment.motion,
    };
    schedule();
  }, [
    environment.room,
    environment.houseLights,
    environment.soundMap,
    environment.motion,
    schedule,
  ]);
  useEffect(() => {
    const media = matchMedia('(prefers-reduced-motion: reduce)');
    const change = () => {
      reduced.current = media.matches;
      schedule();
    };
    change();
    media.addEventListener('change', change);
    return () => media.removeEventListener('change', change);
  }, [schedule]);

  /**
   * Moves the camera to `to` in `ms`. For `lift`, `to` is the plan it rises to. Resolves once it
   * gets there; a move cut short by another never resolves, and the newer one takes over.
   */
  const moveTo = useCallback(
    (to: Camera, ms: number, move: Move = 'blend') =>
      new Promise<void>((resolve) => {
        const from = camera.current;
        running.current = { from, to, move, start: performance.now(), ms, done: resolve };
        // A move lets go of any look around.
        if (peek.current.yaw || peek.current.pitch) {
          peekBack.current = { ...peek.current, start: performance.now() };
        }
        schedule();
      }),
    [schedule],
  );

  /** Puts the camera at `to` at once. */
  const jump = useCallback(
    (to: Camera) => {
      running.current = null;
      camera.current = to;
      schedule();
    },
    [schedule],
  );

  const setLook = useCallback(
    (next: Look) => {
      look.current = next;
      schedule();
    },
    [schedule],
  );

  /** Turns the view by a drag of `dx`, `dy` px; `release` lets it spring back. */
  const peekBy = useCallback(
    (dx: number, dy: number) => {
      const width = canvas.current?.clientWidth || 400;
      peekBack.current = null;
      peek.current = {
        yaw: Math.max(-PEEK_YAW, Math.min(PEEK_YAW, (-dx / width) * 1.1)),
        pitch: Math.max(-PEEK_PITCH, Math.min(PEEK_PITCH, (dy / width) * 0.6)),
      };
      schedule();
    },
    [schedule],
  );

  const release = useCallback(() => {
    peekBack.current = { ...peek.current, start: performance.now() };
    schedule();
  }, [schedule]);

  const setPlaying = useCallback(
    (value: boolean) => {
      playing.current = value;
      schedule();
    },
    [schedule],
  );
  const setFilmTime = useCallback(
    (time: number) => {
      filmClock.current = { time, at: performance.now() };
      schedule();
    },
    [schedule],
  );

  const setFilmFrame = useCallback(
    (source: HTMLVideoElement, mediaTime: number) => {
      let frame = filmFrame.current;
      if (!frame) {
        const image = document.createElement('canvas');
        image.width = 320;
        image.height = 136;
        frame = { image, version: 0, mediaTime };
        filmFrame.current = frame;
      }
      const context = frame.image.getContext('2d');
      if (!context || source.readyState < 2) return;
      const aspect = 320 / 136,
        sourceAspect = source.videoWidth / source.videoHeight;
      const width = sourceAspect > aspect ? source.videoHeight * aspect : source.videoWidth;
      const height = sourceAspect > aspect ? source.videoHeight : source.videoWidth / aspect;
      context.drawImage(
        source,
        (source.videoWidth - width) / 2,
        (source.videoHeight - height) / 2,
        width,
        height,
        0,
        0,
        320,
        136,
      );
      frame.version += 1;
      frame.mediaTime = mediaTime;
      filmClock.current = { time: mediaTime, at: performance.now() };
      schedule();
    },
    [schedule],
  );

  // Drawn again when the canvas changes size, and the frame cancelled on the way out.
  useEffect(() => {
    const element = canvas.current;
    if (!element) return;
    const observer = new ResizeObserver(() => schedule());
    observer.observe(element);
    const intersection = new IntersectionObserver(([entry]) => {
      visible.current = entry.isIntersecting;
      if (entry.isIntersecting) schedule();
    });
    intersection.observe(element);
    const wake = () => {
      if (!document.hidden) schedule();
    };
    document.addEventListener('visibilitychange', wake);
    window.addEventListener('seat-view:materials-ready', schedule);
    return () => {
      observer.disconnect();
      intersection.disconnect();
      document.removeEventListener('visibilitychange', wake);
      window.removeEventListener('seat-view:materials-ready', schedule);
      cancelAnimationFrame(frame.current);
      frame.current = 0;
    };
  }, [schedule]);

  /** The canvas's ref: a callback, so a layout can hand it straight to its <canvas>. */
  const attach = useCallback((element: HTMLCanvasElement | null) => {
    canvas.current = element;
  }, []);
  const attachFilmPlane = useCallback((element: HTMLDivElement | null) => {
    filmPlane.current = element;
  }, []);

  const attachSoundOverlay = useCallback((element: HTMLCanvasElement | null) => {
    soundOverlay.current = element;
  }, []);

  return useMemo(
    () => ({
      attach,
      moveTo,
      jump,
      setLook,
      peekBy,
      release,
      redraw: schedule,
      attachFilmPlane,
      attachSoundOverlay,
      setPlaying,
      setFilmTime,
      setFilmFrame,
    }),
    [
      attach,
      moveTo,
      jump,
      setLook,
      peekBy,
      release,
      schedule,
      setPlaying,
      setFilmTime,
      setFilmFrame,
      attachFilmPlane,
      attachSoundOverlay,
    ],
  );
}
```

### seat-view/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the text cursor are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the text cursor a field shows. */
  glyph: (name: 'arrow' | 'text') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (seat-view.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, and so is the text cursor: a dark line over a wider white one. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const BEAM = 'M7 3c1.8 0 3 .7 3 2v10c0 1.3-1.2 2-3 2M13 3c-1.8 0-3 .7-3 2v10c0 1.3 1.2 2 3 2';

/**
 * The pointer the demo moves around: an arrow, or a text cursor over a field. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  textClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  textClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={textClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The middle of the cursor sits where the arrow's tip is. */}
          <g fill="none" strokeLinecap="round" transform="translate(-7 -8)">
            <path d={BEAM} stroke="var(--pointer-edge)" strokeWidth="3" />
            <path d={BEAM} stroke="var(--pointer)" strokeWidth="1.3" />
          </g>
        </svg>
      </span>
    </span>
  );
}
```

### seat-view/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```