@seatlayer/js 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channelsMode-33ZLORVF.js +13 -0
- package/dist/channelsMode-33ZLORVF.js.map +1 -0
- package/dist/chunk-CF5MS7UR.js +2543 -0
- package/dist/chunk-CF5MS7UR.js.map +1 -0
- package/dist/chunk-DMEFXZIL.js +3198 -0
- package/dist/chunk-DMEFXZIL.js.map +1 -0
- package/dist/chunk-X2R4AQSZ.js +323 -0
- package/dist/chunk-X2R4AQSZ.js.map +1 -0
- package/dist/index.cjs +9517 -9416
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -1382
- package/dist/index.d.ts +6 -1382
- package/dist/index.js +48 -5958
- package/dist/index.js.map +1 -1
- package/dist/manager-CAIPkUYl.d.cts +1419 -0
- package/dist/manager-CAIPkUYl.d.ts +1419 -0
- package/dist/manager.cjs +6069 -0
- package/dist/manager.cjs.map +1 -0
- package/dist/manager.d.cts +2 -0
- package/dist/manager.d.ts +2 -0
- package/dist/manager.js +14 -0
- package/dist/manager.js.map +1 -0
- package/package.json +20 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/SeatingChart.ts","../src/buyerRealtime.ts","../src/api.ts","../src/buyerAccess.ts","../src/seatLayerBrand.ts","../src/EmbeddedDesigner.ts","../src/SeatPicker.ts","../src/attachPickerFrame.ts","../src/SeatManager.ts","../src/channelPlan.ts","../src/manageApi.ts","../src/channelsMode.ts"],"sourcesContent":["/**\n * SeatingChart — the embeddable buyer picker.\n *\n * A thin wrapper over the shared PickerController (src/picker/PickerController):\n * it owns the mount <div> + the public embed contract (hold-only — the SDK hands\n * the holdId to the host page for a server-side book) and delegates all transport\n * + booking to the controller, so the SDK inherits every fix made for the live\n * buyer page and the demo picker.\n */\nimport {\n PickerController,\n loadLocale,\n setStringOverrides,\n t,\n type PickerSeat,\n type RendererViewMode,\n type SeatHoverDetails,\n} from '@seatlayer/core';\nimport { PubApi, type BestAvailableResult, type HoldResult } from './api';\nimport {\n createBuyerAccessContext,\n type BuyerAccessContext,\n type BuyerAccessExpiredEvent,\n type BuyerAccessToken,\n type BuyerAccessTokenProvider,\n type BuyerAccessUnavailableEvent,\n type SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, createControllerSink } from './buyerRealtime';\nimport { SEATLAYER_ATTRIBUTION_MARK_SVG } from './seatLayerBrand';\n\nconst DEFAULT_API_BASE = 'https://api.seatlayer.io';\nconst DEFAULT_MAX_SELECTION = 10;\n\n/** A seat as surfaced to the host page (prices resolved from the chart's categories). */\nexport type SelectedSeat = PickerSeat;\nexport interface GAAreaAvailability {\n id: string; label: string; capacity: number; available: number; categoryKey: string; price: number; currency: string;\n /** Buyer-facing copy authored separately from stable inventory identity. */\n displayLabel?: string;\n displayType?: string;\n tiers?: Array<{ id: string; name: string; price: number }>;\n}\n\nexport interface SeatingChartOptions {\n /** CSS selector or an HTMLElement to render into. */\n container: string | HTMLElement;\n /** Event key, e.g. `ev_xxx`. */\n event: string;\n /** API origin. Defaults to https://api.seatlayer.io. */\n apiBase?: string;\n /** Reserved for future authenticated rendering — accepted + stored, not yet sent.\n * NOT the channel-access credential: a buyer access session is a different\n * thing with different authority, and uses the two options below. */\n publicKey?: string;\n /**\n * Buyer access session provider — the recommended way to render private\n * channel inventory (Sales Channels guide §6).\n *\n * Called with a `reason` whenever the SDK needs a bearer: first acquisition,\n * a near/actual expiry, a 401 `buyer_access_expired`, a realtime reconnect,\n * or `refreshAccess()`. It should POST to YOUR backend, which mints the\n * session with your secret key and returns `{ token, expiresAt }`.\n *\n * The token lives in memory for the widget's lifetime and nowhere else: never\n * in storage, never in a URL, never in a log or an error message. Refresh\n * returns the same or a narrower scope — the SDK never widens to Public sale\n * on its own, and a failed refresh stops the scoped operation rather than\n * retrying it anonymously.\n */\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n /**\n * One-shot escape hatch for hosts that already own the session lifecycle.\n * Cannot be renewed — when it lapses the widget reports `onAccessExpired`\n * and then `onAccessUnavailable`. Prefer `buyerAccessTokenProvider`.\n */\n buyerAccessToken?: string | BuyerAccessToken;\n /** Max seats selectable at once (default 10). */\n maxSelection?: number;\n /**\n * BCP 47 language for the widget UI — `'de'`, `'es-MX'`, etc. Falls back to\n * the browser language, then English. Built-in: en, es, de, fr. The German\n * bundle (etc.) is fetched on demand so unused languages cost nothing.\n */\n locale?: string;\n /**\n * Per-key string overrides layered over the active locale — white-label copy\n * without shipping a whole bundle, e.g. `{ 'map.fromPrice': 'ab {price}' }`.\n */\n messages?: Record<string, string>;\n /** ISO 4217 currency for on-map prices (default USD). */\n currency?: string;\n /**\n * Colorblind-safe rendering: category hues switch to an Okabe-Ito palette\n * and booked seats render hollow, so state never relies on hue alone.\n * Toggleable later with setColorblindSafe().\n */\n colorblindSafe?: boolean;\n /** Initial canvas projection.\n * @deprecated `'isometric'` and `'perspective'` are retired in favour of the\n * real 3D venue view (`setBuyerView('venue3d')`); they remain accepted for\n * source compatibility and will be removed in the next major. Use `'flat'`. */\n initialView?: RendererViewMode;\n /**\n * Built-in seat tooltip on mouse hover (seat · category · price · status).\n * Rendered inside the widget so every host gets it; default true. Turn off\n * to draw your own popover from onSeatHover.\n */\n seatTooltip?: boolean;\n /**\n * Seat hover with everything a popover needs (category label/color, resolved\n * tier-aware price, live status, currency); null on hover-out. Fires whether\n * or not the built-in tooltip is enabled.\n */\n onSeatHover?: (details: SeatHoverDetails | null) => void;\n onSelectionChange?: (seats: SelectedSeat[]) => void;\n onHold?: (result: HoldResult) => void;\n /** A prior active hold was restored with resumeHold(). */\n onHoldRestored?: (result: HoldResult) => void;\n onHoldExpired?: () => void;\n onGAClick?: (area: GAAreaAvailability) => void;\n /**\n * The buyer access session lapsed. `refreshed` says whether the provider\n * already recovered it — false means private inventory is now unavailable and\n * `onAccessUnavailable` follows. Distinct from `onError` on purpose: this is\n * never a network failure (guide §10).\n */\n onAccessExpired?: (event: BuyerAccessExpiredEvent) => void;\n /**\n * Private inventory is unavailable and refreshing will not fix it — revoked,\n * paused, wrong origin/event/mode, or the provider failed. Carries a reason,\n * never a channel name, id, colour or count.\n */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /**\n * Selected-but-unheld units stopped being selectable — someone else took\n * them, or an allocation change moved them out of this buyer's scope. The\n * widget has already dropped them from the selection.\n */\n onSelectedObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n onError?: (err: unknown) => void;\n /**\n * What the BUYER sees when the chart cannot load.\n *\n * `'message'` (the default) renders a plain, styleable notice with a Try\n * again button. This used to be silent unconditionally: `render()` returned\n * with an EMPTY mounted div and only `onError` fired, so a host that had not\n * wired `onError` — or had wired it to a logger — showed buyers a blank\n * rectangle where the seat map belongs, on the host's own domain, which\n * reads as a broken website rather than a temporary fault. `SeatPicker` has\n * always failed loud with a retry; this is the embed class catching up.\n *\n * `'none'` restores the silent behaviour for hosts that render their own\n * failure UI from `onError`.\n */\n errorDisplay?: 'message' | 'none';\n /**\n * Multi-floor charts only: fires when the buyer taps a deck in the stacked\n * 3D view, after the picker switches to that floor — lets the host page sync\n * its own floor UI (tabs, labels) with the map.\n */\n onDeckTap?: (floorId: string) => void;\n /**\n * Non-blocking, localized selection advice — currently the orphan-seat hint\n * (the selection would strand a single free seat between taken neighbors).\n * `null` clears it. Purely informational; nothing is ever prevented.\n */\n onHint?: (message: string | null) => void;\n}\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container === 'string') {\n const el = document.querySelector(container);\n if (!el) throw new Error(`seatmap: container \"${container}\" not found`);\n return el as HTMLElement;\n }\n if (!(container instanceof HTMLElement)) {\n throw new Error('seatmap: container must be a CSS selector or an HTMLElement');\n }\n return container;\n}\n\nexport class SeatingChart {\n private readonly opts: SeatingChartOptions;\n private readonly controller: PickerController;\n /** Reserved for future authenticated rendering — stored, not yet sent on any request. */\n readonly publicKey?: string;\n\n private mount: HTMLElement | null = null;\n private hostEl: HTMLDivElement | null = null;\n private rendered = false;\n private retryBtn: HTMLButtonElement | null = null;\n private mode_: 'live' | 'test' | null = null;\n private tipEl: HTMLDivElement | null = null;\n private tipPos = { x: 0, y: 0 };\n private onTipMove: ((e: MouseEvent) => void) | null = null;\n /** Null for the ordinary public chart — the tokenless path is untouched. */\n private readonly access: BuyerAccessContext | null;\n private readonly api: PubApi;\n private realtime: BuyerRealtimeClient | null = null;\n\n constructor(options: SeatingChartOptions) {\n if (!options || typeof options !== 'object') throw new Error('seatmap: options object is required');\n if (!options.container) throw new Error('seatmap: `container` is required');\n if (!options.event || typeof options.event !== 'string') throw new Error('seatmap: `event` key is required');\n\n this.opts = options;\n this.publicKey = options.publicKey;\n this.access = createBuyerAccessContext(options, {\n onExpired: (event) => this.opts.onAccessExpired?.(event),\n onUnavailable: (event) => this.opts.onAccessUnavailable?.(event),\n });\n const api = new PubApi((options.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, ''), {\n access: this.access ?? undefined,\n onObjectUnavailable: (event) => this.opts.onSelectedObjectUnavailable?.(event),\n });\n this.api = api;\n this.controller = new PickerController({\n transport: api,\n eventKey: options.event,\n maxSelection: options.maxSelection ?? DEFAULT_MAX_SELECTION,\n currency: options.currency,\n onSelectionChange: (seats) => this.opts.onSelectionChange?.(seats),\n onHold: (h) => this.opts.onHold?.({ holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items }),\n onHoldRestored: (h) => this.opts.onHoldRestored?.({ holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items }),\n onHoldExpired: () => this.opts.onHoldExpired?.(),\n onGAClick: (areaId) => {\n const area = this.controller.getGAAreas().find((candidate) => candidate.id === areaId);\n if (area) this.opts.onGAClick?.(area);\n },\n onError: (err) => this.opts.onError?.(err),\n onDeckTap: (floorId) => this.opts.onDeckTap?.(floorId),\n onHint: (message) => this.opts.onHint?.(message),\n // Live-activity cue: pulse seats that other buyers take while the map is\n // open — the WS feed already streams the status change, this makes it felt.\n flashOnLiveChange: true,\n onSeatHover: (details) => {\n this.opts.onSeatHover?.(details);\n if (this.opts.seatTooltip !== false) this.updateTooltip(details);\n },\n colorblindSafe: options.colorblindSafe,\n });\n }\n\n /** Fetch the chart, mount the renderer, seed statuses and go live. Idempotent. */\n async render(): Promise<this> {\n if (this.rendered) return this;\n this.rendered = true;\n\n // Resolve + load the UI language before the first paint so on-map labels\n // (\"N LEFT\", \"FROM …\", the map aria-label) render translated. English and\n // already-loaded locales resolve synchronously; others fetch one small chunk.\n await loadLocale(this.opts.locale);\n if (this.opts.messages) setStringOverrides(this.opts.messages);\n\n // Mount an owned <div> inside the caller's container so we never fight their\n // layout and can cleanly remove it on destroy().\n this.mount = resolveContainer(this.opts.container);\n const host = document.createElement('div');\n host.style.width = '100%';\n host.style.height = '100%';\n host.style.position = 'relative';\n this.mount.appendChild(host);\n this.hostEl = host;\n\n const info = await this.controller.render(host);\n if (!info) {\n this.rendered = false;\n if (this.opts.errorDisplay !== 'none') this.showLoadFailure(host);\n return this;\n }\n this.controller.setViewMode(this.opts.initialView ?? 'flat');\n this.startRealtime();\n // The served event's mode. Anything the API does not explicitly mark as a\n // test event is a live one — the same rule the test-mode ribbon below uses.\n this.mode_ = info.mode === 'test' ? 'test' : 'live';\n\n // Tooltip element + cursor tracking (mouse only — touch selects directly and\n // reviews seats in the host tray). Positioned at the cursor, flipped at edges.\n // Appended AFTER controller.render — mounting the canvas replaces the host's\n // prior children, so anything added earlier would be wiped.\n if (this.opts.seatTooltip !== false) {\n const tip = document.createElement('div');\n tip.setAttribute('role', 'tooltip');\n tip.style.cssText =\n 'position:absolute;z-index:7;pointer-events:none;display:none;max-width:240px;' +\n 'background:#10162a;color:#fff;border-radius:10px;padding:9px 12px;' +\n 'font:500 12px/1.45 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;' +\n 'box-shadow:0 10px 30px -10px rgba(0,0,0,.5);';\n host.appendChild(tip);\n this.tipEl = tip;\n this.onTipMove = (e: MouseEvent) => {\n const r = host.getBoundingClientRect();\n this.tipPos = { x: e.clientX - r.left, y: e.clientY - r.top };\n if (this.tipEl && this.tipEl.style.display !== 'none') this.placeTooltip();\n };\n host.addEventListener('mousemove', this.onTipMove);\n }\n if (info.mode === 'test') {\n host.style.overflow = 'hidden';\n const ribbon = document.createElement('div');\n ribbon.textContent = t('picker.testMode');\n ribbon.setAttribute('aria-label', t('picker.testMode'));\n ribbon.style.cssText =\n 'position:absolute;top:18px;right:-34px;z-index:6;transform:rotate(45deg);' +\n 'width:140px;text-align:center;padding:4px 0;background:#f4b740;color:#1a1200;' +\n 'font:800 10.5px/1.4 -apple-system,BlinkMacSystemFont,sans-serif;letter-spacing:.12em;' +\n 'box-shadow:0 2px 8px rgba(0,0,0,.25);pointer-events:none;';\n host.appendChild(ribbon);\n }\n\n // \"Powered by SeatLayer\" attribution — the SDK embed is canvas-only, so\n // (unlike the full SeatPicker widget) nothing else renders this badge; no\n // duplication guard is needed. Shown by default; hidden only when the SERVED\n // chart doc's theme sets hideBadge (the API forces that false for orgs\n // without the white-label entitlement, so the client can trust the flag).\n this.buildBadge(host);\n return this;\n }\n\n /**\n * Attribution badge pinned to the embed's bottom-right, linking to\n * seatlayer.io. Rendered as an absolutely-positioned overlay with\n * self-contained inline styles — the SDK embed ships no widget CSS, and an\n * overlay keeps it out of the layout flow so it never disturbs the SDK v0.22\n * fill-height resize contract. Mirrors the full widget's mark + wordmark and\n * reuses the `picker.poweredBy` i18n string.\n */\n private buildBadge(host: HTMLDivElement): void {\n if (this.controller.doc?.theme?.hideBadge) return;\n const badge = document.createElement('a');\n badge.href = 'https://seatlayer.io';\n badge.target = '_blank';\n badge.rel = 'noopener noreferrer';\n badge.setAttribute('aria-label', t('picker.poweredBy'));\n badge.style.cssText =\n 'position:absolute;bottom:10px;right:12px;z-index:5;' +\n 'display:inline-flex;align-items:center;gap:6px;padding:5px 9px;border-radius:999px;' +\n 'background:rgba(255,255,255,.92);color:#4a5163;text-decoration:none;' +\n 'font:600 11px/1 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;letter-spacing:.02em;' +\n 'box-shadow:0 2px 8px rgba(0,0,0,.12);';\n badge.innerHTML =\n '<span aria-hidden=\"true\" style=\"width:16px;height:16px;border-radius:4px;flex:none;' +\n 'display:flex;align-items:center;justify-content:center;background:#0c1220;color:#fcf7ee\">' +\n SEATLAYER_ATTRIBUTION_MARK_SVG + '</span>' +\n `<span>${t('picker.poweredBy')}</span>`;\n host.appendChild(badge);\n }\n\n private placeTooltip(): void {\n if (!this.tipEl || !this.hostEl) return;\n const hw = this.hostEl.clientWidth;\n const tw = this.tipEl.offsetWidth;\n const th = this.tipEl.offsetHeight;\n let x = this.tipPos.x + 14;\n let y = this.tipPos.y - th - 12;\n if (x + tw > hw - 8) x = this.tipPos.x - tw - 14;\n if (y < 8) y = this.tipPos.y + 18;\n this.tipEl.style.left = `${Math.max(8, x)}px`;\n this.tipEl.style.top = `${Math.max(8, y)}px`;\n }\n\n private updateTooltip(details: SeatHoverDetails | null): void {\n if (!this.tipEl) return;\n if (!details) {\n this.tipEl.style.display = 'none';\n return;\n }\n const money = (() => {\n try {\n return new Intl.NumberFormat(undefined, { style: 'currency', currency: details.currency }).format(details.price);\n } catch {\n return `${details.price} ${details.currency}`;\n }\n })();\n const statusLine =\n details.status === 'free'\n ? ''\n : `<div style=\"margin-top:5px;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;color:#fca5a5;font-weight:700\">${\n details.status === 'held' ? t('map.statusHeld') : t('map.statusTaken')\n }</div>`;\n this.tipEl.innerHTML =\n `<div style=\"font-weight:700;font-size:13px\">${details.label}</div>` +\n `<div style=\"display:flex;align-items:center;gap:6px;margin-top:4px;color:#c7cddc\">` +\n `<span style=\"width:9px;height:9px;border-radius:50%;flex:none;background:${details.categoryColor}\"></span>` +\n `<span>${details.categoryLabel}</span>` +\n `<span style=\"margin-left:auto;font-weight:700;color:#fff\">${money}</span></div>` +\n statusLine;\n this.tipEl.style.display = 'block';\n this.placeTooltip();\n }\n\n /**\n * Whether the SERVED event is a live or a test event (`sk_test_` keys create\n * test events, which never book real inventory). `null` before render()\n * resolves — the mode comes from the server with the chart, not from options.\n *\n * The widget already surfaces this visually with the test-mode ribbon; this\n * getter is for hosts that draw their own chrome — notably a native WebView\n * wrapper, which must be able to tell an integrator that the build they are\n * about to ship is pointed at a test event.\n */\n getMode(): 'live' | 'test' | null {\n return this.mode_;\n }\n\n /** Current selection with prices resolved from the chart categories. */\n getSelection(): SelectedSeat[] {\n return this.controller.getSelection();\n }\n\n /** Hold the current selection. Resolves the hold, or null on a 409 conflict. */\n async hold(options: { ttlMs?: number } = {}): Promise<HoldResult | null> {\n try {\n return await this.holdOrThrow(options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /**\n * @internal Like {@link hold} but RE-THROWS the structured API error (409\n * `reason`/`code` + `conflicts`) instead of swallowing it into `onError` +\n * `null`. The native WebView host adapter needs the throw so it can answer the\n * originating command with a correlated error carrying the SPECIFIC reason\n * (`sold_out` vs `not_enough_together`); the public method above keeps the\n * catch-and-onError contract that direct web consumers rely on. Not a stable\n * part of the embed API.\n */\n async holdOrThrow(options: { ttlMs?: number } = {}): Promise<HoldResult | null> {\n const h = await this.controller.hold(undefined, options.ttlMs);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /** Restore an active hold by its opaque id without extending its expiry. */\n async resumeHold(holdId: string): Promise<HoldResult | null> {\n try {\n return await this.resumeHoldOrThrow(holdId);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link resumeHold} for the native host adapter. See {@link holdOrThrow}. */\n async resumeHoldOrThrow(holdId: string): Promise<HoldResult | null> {\n const h = await this.controller.resumeHold(holdId);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /**\n * Push the OPEN hold's expiry out (\"need more time?\"). Resolves the refreshed\n * hold, or `null` when there is nothing held or the server refused (the hold\n * is gone, already expired, or at its renewal cap) — refusal is a normal\n * outcome, not an error, so the host decides the copy. The client-side expiry\n * timer is re-armed to match, so `onHoldExpired` won't fire early.\n */\n async extendHold(ttlMs?: number): Promise<HoldResult | null> {\n try {\n const h = await this.controller.extendHold(ttlMs);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** Current active hold known to this chart, if any. */\n getCurrentHold(): HoldResult | null {\n const h = this.controller.currentHold();\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n getGAAreas(): GAAreaAvailability[] {\n return this.controller.getGAAreas();\n }\n\n async holdGA(\n areaId: string,\n qty: number,\n options: { tierId?: string | null; ttlMs?: number } = {},\n ): Promise<HoldResult | null> {\n try {\n return await this.holdGAOrThrow(areaId, qty, options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link holdGA} for the native host adapter. See {@link holdOrThrow}. */\n async holdGAOrThrow(\n areaId: string,\n qty: number,\n options: { tierId?: string | null; ttlMs?: number } = {},\n ): Promise<HoldResult | null> {\n const h = await this.controller.holdGA(areaId, qty, options);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /**\n * Ask the server for the `qty` best free seats and hold them atomically.\n * `options.ttlMs` sets the checkout window exactly like {@link hold}; omit it\n * and the server falls back to the event setting, then its own default.\n */\n async bestAvailable(\n qty: number,\n categoryKey?: string,\n options: { zoneId?: string; preferPremium?: boolean; ttlMs?: number } = {},\n ): Promise<BestAvailableResult | null> {\n try {\n return await this.bestAvailableOrThrow(qty, categoryKey, options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link bestAvailable} for the native host adapter. See {@link holdOrThrow}. */\n async bestAvailableOrThrow(\n qty: number,\n categoryKey?: string,\n options: { zoneId?: string; preferPremium?: boolean; ttlMs?: number } = {},\n ): Promise<BestAvailableResult | null> {\n const h = await this.controller.bestAvailable(qty, categoryKey, options);\n return h ? {\n holdId: h.holdId,\n expiresAt: h.expiresAt,\n labels: h.labels,\n seats: h.seats,\n items: h.items,\n ...(options.zoneId ? { zoneId: options.zoneId } : {}),\n } : null;\n }\n\n /**\n * Choose a ticket tier for a selected seat (e.g. Adult → Child). The seat's\n * available `tiers` are on each `SelectedSeat` from `getSelection()` /\n * `onSelectionChange`. Re-emits the selection with the new tier + price, and\n * the tier rides along in the next `hold()` / `onHold` per seat. `tierId=null`\n * reverts to the default tier.\n */\n setSeatTier(seatId: string, tierId: string | null): void {\n this.controller.setSeatTier(seatId, tierId);\n }\n\n /**\n * Floors of a multi-floor chart — `[{ id, name }]` (single-floor charts\n * return one entry; empty before render()). Pair with setFloor() to build a\n * host-side floor switcher.\n */\n getFloors(): { id: string; name: string }[] {\n return this.controller.getFloors();\n }\n\n /** Switch the shown floor (2D). Warns + no-ops on single-floor charts. */\n setFloor(floorId: string): void {\n if (this.controller.getFloors().length <= 1) {\n console.warn('seatmap: setFloor() ignored — this chart has a single floor');\n return;\n }\n this.controller.setFloor(floorId);\n }\n\n /** Toggle colorblind-safe rendering at runtime (see options.colorblindSafe). */\n setColorblindSafe(on: boolean): void {\n this.controller.setColorblindSafe(on);\n }\n\n /** Switch the 2D canvas projection.\n * @deprecated `'isometric'` and `'perspective'` are retired in favour of the\n * real 3D venue view (`setBuyerView('venue3d')`); accepted for source\n * compatibility until the next major. */\n setViewMode(mode: RendererViewMode): void {\n this.controller.setViewMode(mode);\n }\n\n /** Current canvas projection. */\n getViewMode(): RendererViewMode {\n return this.controller.getViewMode();\n }\n\n /** Zoom in one step (same increment as the wheel/pinch gesture). */\n zoomIn(): void {\n this.controller.zoomIn();\n }\n\n /** Zoom out one step. */\n zoomOut(): void {\n this.controller.zoomOut();\n }\n\n /** Reset the camera so the whole chart fits the container. */\n zoomToFit(): void {\n this.controller.zoomToFit();\n }\n\n /** Release the current hold (if any). No-op when nothing is held. */\n async release(): Promise<void> {\n await this.controller.release();\n }\n\n /** Release selected labels from the current hold while keeping the remainder. */\n async releaseLabels(labels: string[]): Promise<boolean> {\n return this.controller.releaseLabels(labels);\n }\n\n /** Tear everything down: close the socket, stop timers, drop the canvas. */\n /**\n * Realtime for an access-scoped chart.\n *\n * A tokenless chart never gets here: `access` is null, `PubApi.socketUrl()`\n * returns the URL it always has, and PickerController keeps its own socket\n * and its own legacy frames. Nothing about the public path changes.\n */\n private startRealtime(): void {\n if (!this.access?.configured || this.realtime) return;\n this.realtime = new BuyerRealtimeClient({\n url: this.api.subscribeUrl(this.opts.event),\n mintTicket: () => this.api.subscribeTicket(this.opts.event),\n onAccessUnavailable: (event) => this.opts.onAccessUnavailable?.(event),\n sink: createControllerSink(this.controller, {\n flashOnLiveChange: true,\n onSelectedObjectUnavailable: (labels, reason) =>\n this.opts.onSelectedObjectUnavailable?.({ labels, reason }),\n }),\n });\n this.realtime.start();\n }\n\n /**\n * Re-acquire the buyer access session — call after your app has re-authorized\n * the buyer (a revoked session cannot be recovered any other way). Resolves\n * true when a fresh bearer is held; the realtime feed restarts with it.\n */\n async refreshAccess(): Promise<boolean> {\n if (!this.access?.configured) return false;\n const ok = await this.access.refresh('manual');\n if (ok) {\n await this.controller.refresh();\n this.realtime?.restart();\n if (!this.realtime) this.startRealtime();\n }\n return ok;\n }\n\n /**\n * The visible failure state. Deliberately inline-styled and dependency-free:\n * this renders on a stranger's website, where our stylesheet may not have\n * loaded (the chart fetch just failed) and where inheriting the host's own\n * styles is likelier to produce something unreadable than something on-brand.\n */\n private showLoadFailure(host: HTMLDivElement): void {\n const box = document.createElement('div');\n box.setAttribute('role', 'status');\n box.style.cssText =\n 'display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;' +\n 'width:100%;height:100%;min-height:180px;box-sizing:border-box;padding:24px;text-align:center;' +\n 'font:500 14px/1.5 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;color:#3b4256;';\n\n const text = document.createElement('div');\n // No error detail: a buyer cannot act on it, and it can carry internals.\n text.textContent = 'The seat map didn’t load.';\n box.appendChild(text);\n\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.textContent = 'Try again';\n btn.style.cssText =\n 'appearance:none;border:1px solid #c9cede;background:#fff;color:#10162a;border-radius:8px;' +\n 'padding:8px 16px;font:600 13px/1 inherit;cursor:pointer;';\n btn.addEventListener('click', () => {\n // Full remount: the controller holds no partial state worth salvaging\n // after a failed render, and this is the same recovery SeatPicker uses.\n this.destroy();\n void this.render().catch((err) => this.opts.onError?.(err));\n });\n box.appendChild(btn);\n this.retryBtn = btn;\n host.appendChild(box);\n }\n\n destroy(): void {\n this.realtime?.stop();\n this.realtime = null;\n this.access?.clear();\n this.retryBtn = null;\n if (this.hostEl && this.onTipMove) this.hostEl.removeEventListener('mousemove', this.onTipMove);\n this.tipEl = null;\n this.onTipMove = null;\n this.controller.destroy();\n if (this.hostEl && this.hostEl.parentNode) this.hostEl.parentNode.removeChild(this.hostEl);\n this.hostEl = null;\n this.mount = null;\n this.rendered = false;\n this.mode_ = null;\n }\n}\n","/**\n * BuyerRealtimeClient — the client half of `docs/realtime-protocol-2026-08-01.md`.\n *\n * Why this exists as a separate socket rather than inside PickerController:\n * a private scope authenticates with a one-use **subscribe ticket** carried in\n * `Sec-WebSocket-Protocol`, and a browser can only set that at construction —\n * `new WebSocket(url, protocols)`. The controller's socket is built from a URL\n * alone (`PickerTransport.socketUrl`), and a bearer must never travel in a URL\n * because URLs are routinely logged. So an access-scoped picker asks the\n * transport for an empty `socketUrl()` (the controller then skips its own\n * connection entirely) and this client owns the wire instead.\n *\n * A tokenless public picker never reaches this file. It keeps the controller's\n * original socket, offers no subprotocol, and therefore receives byte-for-byte\n * the frames it received before this module existed (protocol doc §1).\n *\n * What it implements:\n * - protocol negotiation: offer `seatlayer.v1`, believe the 101 echo, and fall\n * back to legacy frame handling when the server (or a proxy) does not echo;\n * - the ticket exchange, one mint per connection attempt, ticket in the\n * subprotocol list and never in the URL;\n * - compact `{default, exceptions}` snapshot reconstruction;\n * - `sv.<n>` resume, handling BOTH outcomes (a `resumed` delta or a full\n * snapshot) on every reconnect;\n * - close code 4401 as a typed access-revoked state, never a reconnect loop;\n * - liveness by ping/pong only. Silence is normal and carries no information\n * (protocol doc §5) — a quiet socket is never treated as a dead one.\n */\nimport type { BuyerAccessUnavailableEvent } from './buyerAccess';\n\n/** The projected status of one unit, as the server words it on the wire. */\nexport type WireStatus = string;\n\n/** A scope's projection: one default plus the units that differ from it. */\nexport interface Projection {\n default: WireStatus;\n exceptions: Record<string, WireStatus>;\n}\n\nexport interface StatusChange {\n label: string;\n status: WireStatus;\n}\n\n/** Where reconstructed inventory goes. Implemented over PickerController. */\nexport interface RealtimeSink {\n /** Apply a batch of label→status changes. Implementations must paint this as\n * ONE pass, not one pass per label (motion system §4 rule 2). */\n applyStatuses(changes: StatusChange[]): void;\n /** Re-pull authoritative state over the scoped HTTP route. Used when a frame\n * cannot be diffed against what we hold (first snapshot, or the scope's\n * default itself changed, which redefines every unit we were never told\n * about). */\n resync(): void | Promise<void>;\n /** Section availability changed (channel-agnostic; identical for every scope). */\n onSections?(hidden: string[], closed: string[]): void;\n /** Scope-projected presence counters. */\n onPresence?(counts: { shoppingSessions: number; activeHolds: number }): void;\n}\n\nexport interface SubscribeTicket {\n ticket?: string;\n /** Exactly what to hand `new WebSocket(url, protocols)`, per protocol doc §3. */\n protocols?: string[];\n}\n\nexport interface BuyerRealtimeOptions {\n /** The subscribe URL. Must never carry a credential — asserted below. */\n url: string;\n sink: RealtimeSink;\n /** Mint a one-use ticket for THIS connection attempt. Returns null for the\n * anonymous public case (no ticket needed). Throwing stops the client. */\n mintTicket?: () => Promise<SubscribeTicket | null>;\n /** Typed access states. 4401 arrives here as `revoked`. */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /** Test seam. Defaults to the global WebSocket. */\n socketFactory?: (url: string, protocols: string[]) => WebSocket;\n /** Test seam for the keepalive/backoff timers. */\n now?: () => number;\n}\n\nexport const SEATLAYER_V1 = 'seatlayer.v1';\n/**\n * Join separator for the section-visibility dedupe keys. A NUL can never occur\n * in a section id, so two different arrays can never collide on one key. It is\n * written as an escape deliberately: a literal NUL byte in the source made the\n * whole file read as binary to grep, diff, and review tooling.\n */\nconst SEP = '\\u0000';\n\n/** Protocol doc §3: revocation closes the socket with this code. */\nexport const CLOSE_ACCESS_REVOKED = 4401;\n\nconst MAX_BACKOFF_MS = 15_000;\nconst PING_INTERVAL_MS = 25_000;\nconst PONG_GRACE_MS = 10_000;\n/** Only armed when we offered a resume; the server always answers a resume. */\nconst RESUME_ANSWER_GRACE_MS = 5_000;\n\n/**\n * Turn a snapshot frame into a projection. Handles both wire forms: the v1\n * compact frame states its `default` and lists only the exceptions; the legacy\n * verbose frame lists every non-free unit, which is the same thing with an\n * implicit default of `free`.\n */\nexport function projectionFromSnapshot(frame: {\n default?: unknown;\n seats?: unknown;\n}): Projection {\n const fallback = typeof frame.default === 'string' ? frame.default : 'free';\n const exceptions: Record<string, WireStatus> = {};\n if (frame.seats && typeof frame.seats === 'object') {\n for (const [label, status] of Object.entries(frame.seats as Record<string, unknown>)) {\n if (typeof status === 'string' && status !== fallback) exceptions[label] = status;\n }\n }\n return { default: fallback, exceptions };\n}\n\n/**\n * The changes needed to move a renderer from `prev` to `next`.\n *\n * Returns null when the two projections have different defaults: the default\n * describes every unit the frame does NOT name, and the client does not hold\n * that universe, so the move cannot be expressed as a bounded diff. The caller\n * resyncs over HTTP instead — correct, and rare (it means a channel pause or an\n * allocation change moved the whole scope).\n */\nexport function diffProjections(prev: Projection | null, next: Projection): StatusChange[] | null {\n if (!prev || prev.default !== next.default) return null;\n const changes: StatusChange[] = [];\n for (const [label, status] of Object.entries(next.exceptions)) {\n if (prev.exceptions[label] !== status) changes.push({ label, status });\n }\n for (const label of Object.keys(prev.exceptions)) {\n if (!(label in next.exceptions)) changes.push({ label, status: next.default });\n }\n return changes;\n}\n\n/** Fold a delta batch into a projection (an exception equal to the default\n * stops being an exception, so the model cannot grow without bound). */\nexport function applyChanges(projection: Projection, changes: StatusChange[]): void {\n for (const change of changes) {\n if (change.status === projection.default) delete projection.exceptions[change.label];\n else projection.exceptions[change.label] = change.status;\n }\n}\n\n/** Belt and braces for the \"no bearer in a URL\" rule — cheap, and it turns a\n * future refactor that reintroduces one into a thrown error, not a silent leak. */\nexport function assertCredentialFreeUrl(url: string): void {\n if (/(?:^|[?&#])(?:token|access_token|bearer|authorization|ticket|tkt|bse)=/i.test(url)) {\n throw new Error('seatlayer: refusing to open a socket with a credential in the URL');\n }\n if (/\\bbse_[A-Za-z0-9._-]+/.test(url)) {\n throw new Error('seatlayer: refusing to open a socket with a credential in the URL');\n }\n}\n\nexport class BuyerRealtimeClient {\n private readonly opts: BuyerRealtimeOptions;\n private ws: WebSocket | null = null;\n private stopped = true;\n private attempt = 0;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Our model of this scope's projection. Null until the first snapshot. */\n private projection: Projection | null = null;\n /** Last `snapshotVersion` seen on any frame that carried one — the resume point. */\n private version: number | null = null;\n /** True once the 101 echoed `seatlayer.v1`. */\n private v1 = false;\n /** Set when we offered v1 and the handshake came back without it — a proxy\n * most likely stripped the header, so the next attempt selects the v1 frame\n * format with the `?pv=1` marker instead (protocol doc §1). The marker\n * selects a format and can never carry a credential or widen a scope. */\n private useQueryMarker = false;\n private hidden: string | null = null;\n private closedSections: string | null = null;\n\n constructor(options: BuyerRealtimeOptions) {\n this.opts = options;\n assertCredentialFreeUrl(options.url);\n }\n\n /** Negotiated protocol, for tests and diagnostics. */\n get protocol(): 'v1' | 'legacy' | null {\n return this.ws ? (this.v1 ? 'v1' : 'legacy') : null;\n }\n\n get snapshotVersion(): number | null {\n return this.version;\n }\n\n start(): void {\n if (!this.stopped) return;\n this.stopped = false;\n void this.connect();\n }\n\n /** Stop for good (destroy, or a revocation). Safe to call twice. */\n stop(): void {\n this.stopped = true;\n this.clearTimers();\n const ws = this.ws;\n this.ws = null;\n if (ws) {\n ws.onopen = null;\n ws.onmessage = null;\n ws.onclose = null;\n ws.onerror = null;\n try {\n ws.close();\n } catch {\n /* already closing */\n }\n }\n }\n\n /** Restart after the host re-authorized a revoked buyer (`refreshAccess()`). */\n restart(): void {\n this.stop();\n this.projection = null;\n this.version = null;\n this.attempt = 0;\n this.start();\n }\n\n // ---- connection -----------------------------------------------------------\n\n private async connect(): Promise<void> {\n if (this.stopped) return;\n\n let protocols: string[] = [SEATLAYER_V1];\n if (this.opts.mintTicket) {\n let minted: SubscribeTicket | null;\n try {\n // One mint per connection attempt, including every reconnect. Tickets\n // are TTL ≤ 30s and single-redemption, so reusing one cannot work.\n minted = await this.opts.mintTicket();\n } catch (err) {\n // The mint is an ordinary scoped HTTP call: the transport has already\n // classified and reported any access failure. A transport-level failure\n // is transient, so back off rather than give up.\n this.reportIfAccessError(err);\n this.scheduleReconnect();\n return;\n }\n if (this.stopped) return;\n if (minted?.protocols?.length) {\n protocols = [...minted.protocols];\n if (!protocols.includes(SEATLAYER_V1)) protocols.unshift(SEATLAYER_V1);\n } else if (minted?.ticket) {\n protocols = [SEATLAYER_V1, `tkt.${minted.ticket}`];\n }\n }\n\n // Resume from the last version we actually saw. Both outcomes — a `resumed`\n // delta or a full snapshot — are handled in onmessage.\n const offeredResume = this.version !== null;\n if (offeredResume) protocols.push(`sv.${this.version}`);\n\n const url = this.useQueryMarker\n ? `${this.opts.url}${this.opts.url.includes('?') ? '&' : '?'}pv=1`\n : this.opts.url;\n assertCredentialFreeUrl(url);\n\n let ws: WebSocket;\n try {\n const make = this.opts.socketFactory ?? ((u: string, p: string[]) => new WebSocket(u, p));\n ws = make(url, protocols);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.attempt = 0;\n this.v1 = ws.protocol === SEATLAYER_V1;\n // We asked for v1 and the server did not echo it. Either it is a\n // pre-M5 server (legacy frames are correct and byte-compatible) or a\n // proxy ate the header — the next attempt tries the query marker.\n if (!this.v1) this.useQueryMarker = true;\n this.startKeepalive(ws);\n if (offeredResume) {\n // The server always answers a resume with a delta or a snapshot. If\n // neither lands, fall back to authoritative HTTP rather than sit on a\n // possibly stale map. This timer is NOT a liveness check — ordinary\n // silence on a live socket never triggers it.\n this.resumeTimer = setTimeout(() => {\n this.resumeTimer = null;\n void this.opts.sink.resync();\n }, RESUME_ANSWER_GRACE_MS);\n } else {\n // Parity with the controller's own socket: pull authoritative state on\n // every fresh connection.\n void this.opts.sink.resync();\n }\n };\n\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(typeof event.data === 'string' ? event.data : '');\n } catch {\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n this.handleFrame(parsed as Record<string, unknown>);\n };\n\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.ws = null;\n this.clearTimers();\n if (event?.code === CLOSE_ACCESS_REVOKED) {\n // Retrying with the same credential is guaranteed to fail, so this is\n // a typed terminal state, not a reconnect loop (protocol doc §3).\n this.stopped = true;\n this.opts.onAccessUnavailable?.({\n reason: 'revoked',\n code: 'access_revoked',\n retryable: false,\n });\n return;\n }\n this.scheduleReconnect();\n };\n\n ws.onerror = () => {\n try {\n ws.close();\n } catch {\n /* onclose drives the reconnect */\n }\n };\n }\n\n private handleFrame(frame: Record<string, unknown>): void {\n const type = typeof frame.type === 'string' ? frame.type : '';\n\n // A frame carrying `protocol: 1` proves v1 even when the 101 echo was\n // stripped in transit (the `?pv=1` path).\n if (frame.protocol === 1) this.v1 = true;\n\n if (typeof frame.snapshotVersion === 'number') this.version = frame.snapshotVersion;\n\n if (type === 'pong') {\n this.clearPongTimer();\n return;\n }\n\n // Section availability rides on `hidden`/`closed`, either on its own frame\n // or alongside a snapshot. Identical for every scope.\n if (Array.isArray(frame.hidden) || Array.isArray(frame.closed)) {\n const hidden = Array.isArray(frame.hidden) ? (frame.hidden as string[]) : [];\n const closed = Array.isArray(frame.closed) ? (frame.closed as string[]) : [];\n const hKey = hidden.join(SEP);\n const cKey = closed.join(SEP);\n if (hKey !== this.hidden || cKey !== this.closedSections) {\n this.hidden = hKey;\n this.closedSections = cKey;\n this.opts.sink.onSections?.(hidden, closed);\n }\n }\n if (type === 'hidden') return; // carries no inventory\n\n if (type === 'presence') {\n this.opts.sink.onPresence?.({\n shoppingSessions: Number(frame.shoppingSessions) || 0,\n activeHolds: Number(frame.activeHolds) || 0,\n });\n return;\n }\n\n if (type === 'allocation') {\n // Always followed by a fresh snapshot, which is authoritative. Nothing to\n // do here — and deliberately NO dedupe on allocationVersion: a pause or\n // unpause changes the projection without moving that number.\n return;\n }\n\n if (type === 'snapshot' || (!type && frame.seats)) {\n this.answered();\n const next = projectionFromSnapshot(frame);\n const changes = diffProjections(this.projection, next);\n this.projection = next;\n if (changes === null) void this.opts.sink.resync();\n else if (changes.length) this.opts.sink.applyStatuses(changes);\n return;\n }\n\n if (type === 'delta' && Array.isArray(frame.changes)) {\n this.answered();\n const changes = (frame.changes as Array<Record<string, unknown>>)\n .filter((c) => typeof c?.label === 'string' && typeof c?.status === 'string')\n .map((c) => ({ label: c.label as string, status: c.status as string }));\n if (!changes.length) return;\n if (this.projection) applyChanges(this.projection, changes);\n this.opts.sink.applyStatuses(changes);\n }\n }\n\n /** The server answered our resume; cancel the fallback resync. */\n private answered(): void {\n if (!this.resumeTimer) return;\n clearTimeout(this.resumeTimer);\n this.resumeTimer = null;\n }\n\n private reportIfAccessError(err: unknown): void {\n const reason = (err as { reason?: string } | null)?.reason;\n if ((err as { name?: string } | null)?.name !== 'BuyerAccessUnavailableError') return;\n this.stopped = true;\n this.opts.onAccessUnavailable?.({\n reason: (reason ?? 'invalid') as BuyerAccessUnavailableEvent['reason'],\n code: (err as { code?: string }).code,\n status: (err as { status?: number }).status,\n retryable: reason === 'paused',\n });\n }\n\n // ---- keepalive & backoff --------------------------------------------------\n\n /**\n * Liveness is ping/pong, and only ping/pong. A socket that receives nothing\n * for minutes is the normal, correct state for a narrowly-scoped buyer on a\n * busy event (protocol doc §5), so quiet time never triggers a reconnect.\n */\n private startKeepalive(ws: WebSocket): void {\n this.pingTimer = setInterval(() => {\n if (this.ws !== ws) return;\n try {\n ws.send(JSON.stringify({ type: 'ping' }));\n } catch {\n return;\n }\n this.clearPongTimer();\n this.pongTimer = setTimeout(() => {\n this.pongTimer = null;\n try {\n ws.close();\n } catch {\n /* onclose drives the reconnect */\n }\n }, PONG_GRACE_MS);\n }, PING_INTERVAL_MS);\n }\n\n /**\n * FULL jitter, not plain exponential backoff.\n *\n * A deterministic `2**attempt` schedule makes every browser that lost the same\n * socket — a worker redeploy, a DO eviction, a flaky edge PoP — come back in\n * the same millisecond, and an on-sale crowd reconnecting in lockstep is the\n * thing that turns one blip into a self-sustaining thundering herd. Full\n * jitter (`random() * ceiling`) spreads the same crowd across the whole\n * window; the ceiling still doubles, so a persistent outage still backs off.\n *\n * `Math.random` is correct here: this is client code choosing a delay, not a\n * Workflow step that has to replay deterministically.\n */\n private scheduleReconnect(): void {\n if (this.stopped || this.reconnectTimer) return;\n const attempt = Math.min(this.attempt++, 5);\n const ceiling = Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);\n const delay = Math.random() * ceiling;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n void this.connect();\n }, delay);\n }\n\n private clearPongTimer(): void {\n if (!this.pongTimer) return;\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n\n private clearTimers(): void {\n if (this.pingTimer) clearInterval(this.pingTimer);\n this.pingTimer = null;\n this.clearPongTimer();\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n if (this.resumeTimer) clearTimeout(this.resumeTimer);\n this.resumeTimer = null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Controller sink\n// ---------------------------------------------------------------------------\n\n/**\n * The slice of PickerController this module drives. Structural on purpose — it\n * keeps this file free of an `@seatlayer/core` import, and every member here is\n * public controller API, so nothing in the engine mirror has to change.\n */\nexport interface PickerControllerLike {\n idForLabel(label: string): string | undefined;\n tableSelection(seatIdOrLabel: string): { physicalSeatIds: string[] } | null;\n setStatus(ids: string[], status: 'free' | 'held' | 'booked' | 'not_for_sale'): void;\n getStatus(id: string): string | undefined;\n flashSeat(id: string, color?: string): void;\n currentHold(): { labels: string[] } | null;\n getSelection(): Array<{ id: string; label: string }>;\n deselect(ids: string[]): void;\n refresh(): Promise<void>;\n}\n\n/** Wire status → renderer status. `blocked` is the one neutral unavailable\n * value an out-of-scope unit reads as; the buyer must not be able to tell it\n * apart from ordinary off-sale inventory (protocol doc §5). */\nfunction rendererStatus(wire: string): 'free' | 'held' | 'booked' | 'not_for_sale' {\n if (wire === 'blocked') return 'not_for_sale';\n if (wire === 'held' || wire === 'booked' || wire === 'free' || wire === 'not_for_sale') return wire;\n return 'free';\n}\n\nexport interface ControllerSinkOptions {\n /** Pulse seats other buyers take, as the controller's own socket does. */\n flashOnLiveChange?: boolean;\n /** Selected-but-unheld units that stopped being selectable. */\n onSelectedObjectUnavailable?: (labels: string[], reason: 'ineligible' | 'taken') => void;\n /** Section availability changed and the chart itself needs rebuilding. */\n onSections?: (hidden: string[], closed: string[]) => void;\n onStatusChange?: () => void;\n}\n\nexport function createControllerSink(\n controller: PickerControllerLike,\n options: ControllerSinkOptions = {},\n): RealtimeSink {\n const idsForLabel = (label: string): string[] => {\n const table = controller.tableSelection(label);\n if (table) return table.physicalSeatIds;\n const id = controller.idForLabel(label);\n return id ? [id] : [];\n };\n\n return {\n applyStatuses(changes) {\n const held = controller.currentHold()?.labels ?? [];\n // Bucket the whole batch and paint one call per status: a 256-label\n // delta must animate as ONE canvas pass, never one per seat.\n const buckets: Record<string, string[]> = {\n free: [], held: [], booked: [], not_for_sale: [],\n };\n const flashes: Array<{ id: string; color: string }> = [];\n const lost: string[] = [];\n const selected = new Map(controller.getSelection().map((s) => [s.label, s.id]));\n\n for (const change of changes) {\n const ids = idsForLabel(change.label);\n if (!ids.length) continue;\n const next = rendererStatus(change.status);\n buckets[next].push(...ids);\n if (\n options.flashOnLiveChange &&\n next !== 'free' &&\n !held.includes(change.label) &&\n ids.some((id) => controller.getStatus(id) === 'free')\n ) {\n const color = next === 'held' ? '#f4b740' : '#f43f5e';\n for (const id of ids) flashes.push({ id, color });\n }\n if (next !== 'free' && !held.includes(change.label) && selected.has(change.label)) {\n lost.push(change.label);\n }\n }\n\n for (const status of ['free', 'held', 'booked', 'not_for_sale'] as const) {\n if (buckets[status].length) controller.setStatus(buckets[status], status);\n }\n for (const flash of flashes) controller.flashSeat(flash.id, flash.color);\n\n if (lost.length) {\n // One deselect call, so the map cross-fades in a single pass rather\n // than blinking seat by seat (motion system §3, buyer picker).\n const ids = lost.flatMap((label) => idsForLabel(label));\n if (ids.length) controller.deselect(ids);\n const ineligible = changes.some(\n (c) => c.status === 'blocked' && lost.includes(c.label),\n );\n options.onSelectedObjectUnavailable?.(lost, ineligible ? 'ineligible' : 'taken');\n }\n options.onStatusChange?.();\n },\n\n async resync() {\n await controller.refresh();\n },\n\n /**\n * Section availability moved. Statuses are re-pulled so the map repaints.\n *\n * Known limit: rebuilding the chart when a section is newly HIDDEN (its\n * seats are stripped, not greyed) lives inside PickerController's own\n * socket handler and has no public entry point, so an access-scoped picker\n * repaints statuses but does not restructure the chart until its next\n * mount. Closing/opening a section — the common mid-sale move — is a\n * status-level change and is handled here in full.\n */\n onSections(hidden, closed) {\n void controller.refresh();\n options.onSections?.(hidden, closed);\n },\n };\n}\n","/**\n * Minimal client for the public embed surface of workers/api (the `/pub/*`\n * routes). Deliberately self-contained — it does NOT reuse src/lib/api.ts,\n * which bakes in a build-time API base and dashboard session credentials. The\n * SDK runs cross-origin on a third-party ticketing page, so:\n * - apiBase is per-instance (constructor option), not a build constant;\n * - credentials are omitted (no cookie to send, avoids CORS-credential setup);\n * - no custom headers on mutating calls (keeps the CORS preflight trivial).\n */\nimport type { ChartDoc, PickerSeat as SelectedSeat } from '@seatlayer/core';\nimport type {\n BuyerAccessContext,\n SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, SEATLAYER_V1, type RealtimeSink } from './buyerRealtime';\n\nexport interface HoldConflict {\n label: string;\n status: string;\n}\n\nexport interface HoldLineItem {\n label: string; objectId: string; objectType: 'seat' | 'booth' | 'ga' | 'table'; categoryKey: string;\n tierId: string | null;\n /** Price in major currency units (for example 45 means $45.00). */\n unitPrice: number;\n currency: string;\n quantity?: number;\n}\n\nexport class ApiError extends Error {\n status: number;\n code?: string;\n /** Present when a hold 409s because seats were just taken/held. */\n conflicts?: HoldConflict[];\n /** Present when best-available 409s ('not_enough_together' | 'sold_out'). */\n reason?: string;\n /**\n * Seconds the server asked the caller to wait, off a 429's `Retry-After`.\n *\n * Present ONLY on a rate-limit error, and it is the server's number — never a\n * guess. A widget that catches this can say \"try again in N seconds\" instead\n * of rendering the blank map a swallowed 429 used to produce.\n */\n retryAfterS?: number;\n\n constructor(\n status: number,\n message: string,\n code?: string,\n conflicts?: HoldConflict[],\n reason?: string,\n retryAfterS?: number,\n ) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.conflicts = conflicts;\n this.reason = reason;\n this.retryAfterS = retryAfterS;\n }\n}\n\n/**\n * Longest advertised delay we will sit out inside a request.\n *\n * A rate limit the buyer can wait through invisibly is worth absorbing; one\n * that is 30 seconds long is not — sleeping that long inside `chart()` looks\n * like a hung widget, and the retry would very likely 429 again anyway. Past\n * the cap the error is thrown WITH `retryAfterS`, so the host decides.\n */\nconst MAX_RATE_LIMIT_WAIT_S = 10;\n/** What to assume when a 429 names no delay at all. */\nconst DEFAULT_RATE_LIMIT_WAIT_S = 1;\n\n/**\n * `Retry-After` in seconds. RFC 9110 allows either a delta-seconds integer or\n * an HTTP-date; the API sends the integer, and the date form is handled so a\n * proxy that rewrites it cannot turn a well-formed 429 into an untyped one.\n * Returns undefined when neither the header nor the body says anything.\n */\nexport function parseRetryAfter(header: string | null, bodyValue?: unknown): number | undefined {\n const raw = (header ?? '').trim();\n if (raw) {\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);\n const at = Date.parse(raw);\n if (Number.isFinite(at)) return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n }\n if (typeof bodyValue === 'number' && Number.isFinite(bodyValue) && bodyValue >= 0) {\n return Math.ceil(bodyValue);\n }\n return undefined;\n}\n\nexport interface PubChartResult {\n event: { key: string; name: string; inventoryModelVersion?: 1 | 2 };\n doc: ChartDoc;\n}\n\nexport interface PubObjectsResult {\n /** Every non-free seat's status, keyed by seat label. */\n seats: Record<string, string>;\n /** Section/zone ids hidden from buyers this event (seats stripped from the map). */\n hidden?: string[];\n /** Section/zone ids in the `closed` state (Phase 2): rendered grey + not purchasable. */\n closed?: string[];\n updatedAt: number;\n}\n\nexport interface HoldResult {\n holdId: string;\n expiresAt: number;\n /** The held seats with the buyer's chosen ticket tier per seat (present on hold). */\n seats?: SelectedSeat[];\n items?: HoldLineItem[];\n}\n\n/** Browser-safe active-hold projection returned by the resume endpoint. */\nexport interface ResumedHoldResult extends HoldResult {\n items: HoldLineItem[];\n}\n\n/** Best-available response — the server-picked seats plus the hold they landed in. */\nexport interface BestAvailableResult {\n holdId: string;\n expiresAt: number;\n labels: string[];\n seats?: SelectedSeat[];\n items?: HoldResult['items'];\n zoneId?: string;\n}\n\n/** A gateway the organizer can be connected to. */\nexport type PaymentProviderName = 'stripe' | 'razorpay';\n\n/**\n * Why `payment-options` came back with an empty list.\n *\n * The three are NOT interchangeable and two of them give opposite advice:\n * `not_configured` means the organizer takes payment somewhere else,\n * `payments_off_for_event` means they deliberately do not sell THIS event\n * online, and `unavailable_for_event` means they switched it on and it is\n * broken. Collapsing them makes the widget blame a working integration for a\n * decision that was made on purpose.\n */\nexport type PaymentOptionsReason =\n | 'not_configured'\n | 'payments_off_for_event'\n | 'unavailable_for_event';\n\n/**\n * What this event can take money through. Since the per-event gateway column\n * landed, `providers` holds AT MOST ONE entry — the gateway the organizer\n * assigned — so no browser can choose which one charges.\n *\n * `reason` is optional on the wire: a widget pinned against an older worker\n * still parses, and its absence means what that worker meant by an empty list.\n */\nexport interface PaymentOptionsResult {\n providers: PaymentProviderName[];\n currency: string | null;\n reason?: PaymentOptionsReason | null;\n}\n\n/** A started payment. Exactly one of the two handoffs comes back. */\nexport interface CheckoutSessionResult {\n orderId: string;\n totalMinor: number;\n currency: string;\n expiresAt: number;\n /** Hosted gateway page — navigate to it. */\n redirectUrl?: string;\n /** In-page modal gateway — open it without leaving the page. */\n clientPayload?: Record<string, unknown>;\n}\n\n/** An order's state while its gateway webhook is in flight. */\nexport interface OrderStatusResult {\n orderId: string;\n status: string;\n totalMinor: number;\n currency: string;\n amountFormatted: string;\n seatCount: number;\n}\n\n/** Codes a 409 uses to say \"the unit you picked is no longer yours to pick\". */\nconst OBJECT_UNAVAILABLE_CODES: Record<string, SelectedObjectUnavailableEvent['reason']> = {\n seat_conflict: 'taken',\n conflict: 'taken',\n channel_assignment_conflict: 'ineligible',\n allocation_exhausted: 'exhausted',\n};\n\nexport interface PubApiOptions {\n /**\n * Buyer access session. When present, EVERY scoped operation on this client\n * carries `Authorization: Bearer bse_…` — chart, objects, hold, replace-hold,\n * best-available, resume, release, extend, resnapshot and the realtime\n * subscribe ticket. The binding is immutable for the client's lifetime: there\n * is no method that turns it off, so no operation can silently downgrade to\n * anonymous Public sale (guide §6, §7).\n */\n access?: BuyerAccessContext;\n /** A 409 named specific inventory the buyer can no longer have. */\n onObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n}\n\n/** Public-surface client bound to one apiBase (e.g. https://api.seatlayer.io). */\nexport class PubApi {\n private readonly viewerId = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `viewer_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n\n private readonly access?: BuyerAccessContext;\n private readonly onObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n\n constructor(private readonly base: string, options: PubApiOptions = {}) {\n this.access = options.access;\n this.onObjectUnavailable = options.onObjectUnavailable;\n }\n\n /** True when this client is bound to a buyer access session. */\n get accessScoped(): boolean {\n return !!this.access?.configured;\n }\n\n private async request<T>(\n path: string,\n init: { method?: 'GET' | 'POST'; body?: unknown; labels?: string[] } = {},\n retried: { auth?: boolean; rateLimit?: boolean } = {},\n ): Promise<T> {\n const method = init.method ?? 'GET';\n const headers: Record<string, string> = {};\n let body: string | undefined;\n if (init.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(init.body);\n }\n // Throws BuyerAccessUnavailableError rather than returning undefined when a\n // configured session cannot produce a bearer — the request must not go out\n // anonymous, because anonymous means Public sale.\n const authorization = await this.access?.authorization(retried.auth ? 'unauthorized' : 'initial');\n if (authorization) headers.Authorization = authorization;\n\n const res = await fetch(`${this.base}${path}`, { method, headers, body, credentials: 'omit' });\n\n const isJson = (res.headers.get('content-type') ?? '').includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : null;\n\n if (!res.ok) {\n const err = data as\n | {\n error?: string; code?: string; conflicts?: HoldConflict[]; reason?: string;\n retryAfterSeconds?: number;\n }\n | null;\n // The public API names its machine code in `error` (`conflict`, `event_closed`,\n // …); older/other routes may send `code`. Carry whichever into ApiError.code so\n // the code is populated (it was previously always undefined — nothing reads it\n // yet) and the bridge can pass it through. The specific 409 discriminator still\n // rides in `reason` (`sold_out` | `not_enough_together`) and wins downstream.\n const code = err?.code ?? err?.error;\n\n if (this.access?.configured && (res.status === 401 || res.status === 403 || res.status === 422)) {\n const refreshed = await this.access.handleFailure(res.status, code);\n // Exactly one retry, and only for an expiry the provider just renewed.\n // A refresh returns the same or a narrower scope; it never widens, and\n // a second failure is reported rather than looped.\n if (refreshed && !retried.auth) return this.request<T>(path, init, { ...retried, auth: true });\n }\n if (res.status === 409) {\n const reason = code ? OBJECT_UNAVAILABLE_CODES[code] : undefined;\n const labels = err?.conflicts?.map((c) => c.label) ?? init.labels ?? [];\n if (reason) this.onObjectUnavailable?.({ labels, reason, code });\n }\n\n let retryAfterS: number | undefined;\n if (res.status === 429) {\n retryAfterS = parseRetryAfter(res.headers.get('Retry-After'), err?.retryAfterSeconds)\n ?? DEFAULT_RATE_LIMIT_WAIT_S;\n // One automatic retry, and only for a READ.\n //\n // A rate-limited `chart()`/`objects()` is what turns an on-sale spike\n // into a blank widget, and re-reading is free of consequence — the same\n // GET twice is the same GET. A hold, a best-available, a checkout or an\n // extend is NOT: replaying one can take a second seat, start a second\n // payment, or burn an extend allowance, so a 429 on those is reported to\n // the caller with the server's delay attached and never replayed here.\n if (\n method === 'GET'\n && !retried.rateLimit\n && retryAfterS <= MAX_RATE_LIMIT_WAIT_S\n ) {\n await new Promise((resolve) => setTimeout(resolve, retryAfterS! * 1000));\n return this.request<T>(path, init, { ...retried, rateLimit: true });\n }\n }\n\n throw new ApiError(\n res.status,\n err?.error ?? `request_failed_${res.status}`,\n code,\n err?.conflicts,\n err?.reason,\n retryAfterS,\n );\n }\n return data as T;\n }\n\n chart(key: string): Promise<PubChartResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/chart`);\n }\n\n objects(key: string): Promise<PubObjectsResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/objects`);\n }\n\n hold(key: string, selections: Array<{ label: string; tierId?: string | null; quantity?: number }>, ttlMs?: number, replaceHoldId?: string): Promise<HoldResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/hold`, {\n method: 'POST',\n body: { selections, ...(ttlMs ? { ttlMs } : {}), ...(replaceHoldId ? { replaceHoldId } : {}) },\n labels: selections.map((s) => s.label),\n });\n }\n\n // `zoneId` scopes the pick to one zone and `ttlMs` carries the host's checkout\n // window — both are part of the route contract, and dropping either here made\n // the SDK quietly pick venue-wide and hold for the server default instead.\n bestAvailable(key: string, qty: number, categoryKey?: string, zoneId?: string, ttlMs?: number): Promise<BestAvailableResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/best-available`, {\n method: 'POST',\n body: { qty, ...(categoryKey ? { categoryKey } : {}), ...(zoneId ? { zoneId } : {}), ...(ttlMs ? { ttlMs } : {}) },\n });\n }\n\n resume(key: string, holdId: string): Promise<ResumedHoldResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/hold/resume`, {\n method: 'POST',\n body: { holdId },\n });\n }\n\n release(key: string, labels: string[], holdId: string): Promise<{ ok: true; released?: string[] }> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/release`, {\n method: 'POST',\n body: { labels, holdId },\n });\n }\n\n /** P4 \"need more time?\": push an active hold's expiry out. Throws ApiError 409\n * (reason: expired | extend_limit | not_found | not_active) if it can't. */\n extend(key: string, holdId: string, ttlMs?: number): Promise<{ holdId: string; expiresAt: number; extends: number }> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/extend`, {\n method: 'POST',\n body: { holdId, ...(ttlMs ? { ttlMs } : {}) },\n });\n }\n\n /**\n * Which gateways this event can actually take money through — the question\n * `checkout: 'hosted'` has to answer BEFORE it shows a buyer a Pay button, so\n * the answer is never discovered by failing a payment.\n *\n * Anonymous, and it discloses no account, key, mode or currency for a gateway\n * that did not match.\n */\n paymentOptions(key: string): Promise<PaymentOptionsResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/payment-options`);\n }\n\n /**\n * Turn a live hold into an order and start a payment.\n *\n * The amount is NOT sent: the server recomputes it from the hold's own items,\n * which is the only reason a browser cannot alter what it pays. Nor is the\n * PROVIDER — the event row decides which gateway charges, and a `provider` in\n * the body is checked rather than obeyed (409 `provider_mismatch`). Omitting\n * it is the shape that cannot disagree.\n */\n startCheckout(\n key: string,\n input: { holdId: string; buyerEmail: string; buyerName?: string; returnUrl?: string },\n ): Promise<CheckoutSessionResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/checkout`, {\n method: 'POST',\n body: input,\n });\n }\n\n /**\n * Poll an order while its gateway webhook lands. The order id is an\n * unguessable token the buyer already holds, so it acts as the capability —\n * which is also why a buyer returning from a gateway page can be told what\n * happened with nothing but the id in the return URL.\n */\n orderStatus(orderId: string): Promise<OrderStatusResult> {\n return this.request(`/pub/orders/${encodeURIComponent(orderId)}/status`);\n }\n\n /**\n * Mint a one-use subscribe ticket for the next socket attempt (protocol doc\n * §3). The bearer travels here, over ordinary HTTPS where CORS and Origin\n * already apply; the socket then carries only the short-lived ticket, in its\n * subprotocol list. TTL ≤ 30s, single redemption — mint one per attempt.\n */\n subscribeTicket(key: string): Promise<{ ticket?: string; protocols?: string[] } | null> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/subscribe-tickets`, {\n method: 'POST',\n body: {},\n });\n }\n\n /**\n * The subscribe URL. Never carries a credential — not the bearer, not the\n * ticket. Query parameters are diagnostics only.\n */\n subscribeUrl(key: string): string {\n const wsBase = this.base.replace(/^http/, 'ws');\n const params = new URLSearchParams({ surface: 'picker', viewerId: this.viewerId });\n return `${wsBase}/pub/events/${encodeURIComponent(key)}/subscribe?${params}`;\n }\n\n /**\n * What PickerController opens its own socket with.\n *\n * Empty for an access-scoped client: a private scope authenticates with a\n * subprotocol ticket, which a URL-only constructor cannot carry, so the SDK's\n * BuyerRealtimeClient owns that socket instead and the controller skips its\n * own (an empty URL is its documented \"no live feed\" contract). A tokenless\n * public client returns exactly the URL it always has, so nothing about the\n * public picker's realtime path changes.\n */\n socketUrl(key: string): string {\n return this.accessScoped ? '' : this.subscribeUrl(key);\n }\n\n /**\n * The subprotocol list a PLAIN `new WebSocket(url, protocols)` must offer for\n * this transport — `PickerTransport.socketProtocols`, which PickerController\n * calls optionally and which nothing implemented until now.\n *\n * Offering `seatlayer.v1` is the whole point: without it the DO answers an\n * anonymous socket with the LEGACY verbose frame — every unit of a 10k-seat\n * event, on connect and on every reconnect — instead of the compact\n * `{default, exceptions}` form. Empty for an access-scoped client, which\n * authenticates with a one-use ticket a URL-only constructor cannot carry and\n * whose socket BuyerRealtimeClient owns instead (see `socketUrl`).\n *\n * `createRealtime` below is the preferred path and supersedes this for any\n * host that can use it; this stays the correct answer for a host that builds\n * the socket itself from the transport contract.\n */\n socketProtocols(key: string): string[] {\n void key; // same answer for every event; the parameter is the interface's\n return this.accessScoped ? [] : [SEATLAYER_V1];\n }\n\n /**\n * Hand PickerController the v1 realtime client instead of letting it open a\n * bare socket — `PickerTransport.createRealtime`.\n *\n * This is what puts an ANONYMOUS buyer (the on-sale case) on the same wire as\n * a private-channel one: compact snapshots, `sv.<n>` resume so a reconnect\n * inside the ring costs a delta rather than a full re-snapshot, ping/pong\n * liveness, and one jittered backoff implementation shared by both. The\n * anonymous case simply passes no `mintTicket` — the `/pub/events/:key/\n * subscribe` upgrade requires no ticket, and the DO resolves a ticketless\n * socket to the public scope.\n *\n * Null when access-scoped: that socket is owned by the widget's own\n * BuyerRealtimeClient (with the ticket exchange), and `socketUrl()` already\n * returns '' so the controller opens nothing.\n */\n createRealtime(key: string, sink: RealtimeSink): BuyerRealtimeClient | null {\n if (this.accessScoped) return null;\n return new BuyerRealtimeClient({ url: this.subscribeUrl(key), sink });\n }\n}\n","/**\n * Buyer access context — the browser half of the Sales Channels contract\n * (`docs/sales-channels-integration-guide-2026-08-01.md` §6, §9, §10).\n *\n * A promoter's own backend mints a short-lived, opaque buyer-access session\n * (`bse_…`) that grants exactly one event's private channel scope. That bearer\n * reaches the browser, and only the browser — this module is where it lives,\n * and the rules it enforces are the ones the guide states outright:\n *\n * - the token is held in memory on a private field. It is never written to\n * localStorage/sessionStorage/cookies, never appended to a URL, and never\n * placed in a log, an Error message, telemetry, or JSON. `toJSON()` and\n * `toString()` are overridden so an accidental `JSON.stringify(context)` or\n * template interpolation cannot leak it;\n * - refresh goes through the host's `buyerAccessTokenProvider`, which is\n * called with a `reason` so the host can distinguish a first acquisition\n * from an expiry from a 401;\n * - **a configured context never falls back to anonymous Public sale.** When\n * no bearer can be obtained the operation fails with a typed access error\n * instead of going out unauthenticated. Sending the request without the\n * bearer would silently widen the buyer's scope to Public — the exact\n * failure the feature exists to prevent (guide §7).\n *\n * Deliberately free of any `@seatlayer/core` import: it deals in tokens, HTTP\n * status codes and callbacks only, so it vendors into the app's widget copy\n * with no engine coupling.\n */\n\n/** Why the SDK is asking the host for a token. Passed to the provider. */\nexport type BuyerAccessRefreshReason =\n /** First acquisition, before the chart is fetched. */\n | 'initial'\n /** Proactive: the held token is inside the renewal skew. */\n | 'expiring'\n /** Reactive: the held token's own expiry has passed. */\n | 'expired'\n /** Reactive: the server answered 401 `buyer_access_expired`. */\n | 'unauthorized'\n /** A realtime reconnect needs a live bearer to mint a subscribe ticket. */\n | 'reconnect'\n /** The host called `refreshAccess()`. */\n | 'manual';\n\n/** What a `buyerAccessTokenProvider` resolves to — the response body of the\n * host's own mint endpoint, unchanged. */\nexport interface BuyerAccessToken {\n /** The opaque `bse_…` buyer-access session bearer. */\n token: string;\n /** Epoch ms. Optional — absent means \"trust the server\", and the SDK then\n * refreshes only reactively on a 401. */\n expiresAt?: number;\n}\n\nexport type BuyerAccessTokenProvider = (\n context: { reason: BuyerAccessRefreshReason },\n) => BuyerAccessToken | Promise<BuyerAccessToken>;\n\n/**\n * Why private inventory is not available. Never collapsed into a generic\n * network failure (guide §10) and never carrying channel identity — the buyer\n * is told the state, not which allocation they missed.\n */\nexport type BuyerAccessUnavailableReason =\n /** The session was revoked (HTTP 401 after refresh, or WS close 4401). */\n | 'revoked'\n /** The channel is paused — a legitimate, temporary organizer state. */\n | 'paused'\n /** 401 `buyer_access_invalid`: do not retry this bearer. */\n | 'invalid'\n /** 403 `buyer_access_origin_mismatch`. */\n | 'origin_mismatch'\n /** 403 `buyer_access_event_mismatch`. */\n | 'event_mismatch'\n /** 403 `buyer_access_mode_mismatch` (test bearer on a live event or v.v.). */\n | 'mode_mismatch'\n /** 403 `channel_access_denied`. */\n | 'channel_denied'\n /** 422 `invalid_channel_scope` — an integration configuration error. */\n | 'invalid_scope'\n /** The host's token provider threw or returned nothing usable. */\n | 'provider_failed'\n /** A one-shot `buyerAccessToken` lapsed and no provider was configured. */\n | 'no_token';\n\n/** The access session expired. Carries whether the refresh recovered it. */\nexport interface BuyerAccessExpiredEvent {\n reason: BuyerAccessRefreshReason;\n /** The server's machine code when the expiry was observed over HTTP. */\n code?: string;\n /** True when the provider handed back a fresh token and work continues. */\n refreshed: boolean;\n}\n\n/** Private inventory is unavailable, and refreshing will not fix it. */\nexport interface BuyerAccessUnavailableEvent {\n reason: BuyerAccessUnavailableReason;\n /** The server's machine code, when there was one. */\n code?: string;\n /** The HTTP status, when the state came from an HTTP response. */\n status?: number;\n /** True only for states a later retry could clear (`paused`). */\n retryable: boolean;\n}\n\n/** One or more selected-but-unheld units stopped being selectable. */\nexport interface SelectedObjectUnavailableEvent {\n /** Inventory labels (never channel identity). */\n labels: string[];\n reason:\n /** An allocation change moved it out of this buyer's scope (guide §9). */\n | 'ineligible'\n /** Someone else held or booked it. */\n | 'taken'\n /** 409 `allocation_exhausted` — this private allocation has none left. */\n | 'exhausted';\n code?: string;\n}\n\nexport interface BuyerAccessContextOptions {\n provider?: BuyerAccessTokenProvider;\n /** One-shot escape hatch for hosts that already own the token lifecycle. */\n token?: string | BuyerAccessToken;\n /** Renew this long before the stated expiry. Default 30s. */\n skewMs?: number;\n onExpired?: (event: BuyerAccessExpiredEvent) => void;\n onUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n}\n\n/**\n * Thrown instead of letting a scoped request go out unauthenticated. Carries no\n * bearer and no channel identity, so it is safe to log or hand to an error\n * reporter verbatim.\n */\nexport class BuyerAccessUnavailableError extends Error {\n readonly reason: BuyerAccessUnavailableReason;\n readonly code?: string;\n readonly status?: number;\n\n constructor(event: BuyerAccessUnavailableEvent) {\n super(`buyer_access_unavailable:${event.reason}`);\n this.name = 'BuyerAccessUnavailableError';\n this.reason = event.reason;\n this.code = event.code;\n this.status = event.status;\n }\n}\n\n/** Server error codes that mean \"this session lapsed; run the refresh flow\". */\nconst EXPIRED_CODES = new Set(['buyer_access_expired']);\n\n/**\n * Reasons that describe ONE request, not the session behind it. They report to\n * the host but never latch the context terminal and never discard the bearer.\n *\n * `channel_denied` is here on the guide's own reading: §10 answers a 403\n * `channel_access_denied` with \"return buyer to permitted inventory\" — the\n * buyer asked for a seat outside their allocation, which is a mis-click, not a\n * dead session. Latching it meant one wrong seat permanently killed a live\n * buyer's access, including their ability to RELEASE the hold they already\n * legitimately owned. Found against a live worker in the M9 pass.\n */\nconst RECOVERABLE = new Set<BuyerAccessUnavailableReason>([\n 'paused',\n 'provider_failed',\n 'channel_denied',\n]);\n\n/**\n * Guide §10 error table → an unavailable reason. Anything not in the table is\n * not an access failure and must stay an ordinary error, so this returns null.\n */\nexport function classifyAccessFailure(\n status: number,\n code: string | undefined,\n): BuyerAccessUnavailableReason | null {\n switch (code) {\n case 'buyer_access_invalid':\n return 'invalid';\n case 'buyer_access_revoked':\n return 'revoked';\n case 'buyer_access_origin_mismatch':\n return 'origin_mismatch';\n case 'buyer_access_event_mismatch':\n return 'event_mismatch';\n case 'buyer_access_mode_mismatch':\n return 'mode_mismatch';\n case 'channel_access_denied':\n return 'channel_denied';\n case 'channel_paused':\n return 'paused';\n case 'invalid_channel_scope':\n return 'invalid_scope';\n default:\n break;\n }\n // An unnamed 401 on a scoped request is still an access failure; treat it as\n // the non-retryable kind rather than falling through to Public sale.\n if (status === 401) return 'invalid';\n return null;\n}\n\n/** True when this HTTP failure means \"refresh the session and try again\". */\nexport function isAccessExpiry(status: number, code: string | undefined): boolean {\n return status === 401 && !!code && EXPIRED_CODES.has(code);\n}\n\nconst DEFAULT_SKEW_MS = 30_000;\n\nexport class BuyerAccessContext {\n /** Private field: not enumerable, not spreadable, not serializable. */\n #token: string | null = null;\n #expiresAt = 0;\n #provider?: BuyerAccessTokenProvider;\n #skewMs: number;\n #inflight: Promise<string | null> | null = null;\n #terminal: BuyerAccessUnavailableEvent | null = null;\n /** The most recent failure, terminal or not — so one cause reports once. */\n #lastFailure: BuyerAccessUnavailableEvent | null = null;\n #onExpired?: (event: BuyerAccessExpiredEvent) => void;\n #onUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /** Decided once, at construction. See the `configured` getter. */\n #configured = false;\n\n constructor(options: BuyerAccessContextOptions) {\n this.#provider = options.provider;\n this.#skewMs = options.skewMs ?? DEFAULT_SKEW_MS;\n this.#onExpired = options.onExpired;\n this.#onUnavailable = options.onUnavailable;\n if (options.token) {\n const seed = typeof options.token === 'string' ? { token: options.token } : options.token;\n this.#accept(seed);\n }\n this.#configured = !!this.#provider || !!this.#token;\n }\n\n /**\n * True when this picker is access-scoped at all. A false here is the\n * tokenless public picker, which must behave exactly as it always has.\n *\n * Answered from what the HOST asked for, never from live token state. It used\n * to be `!!#provider || !!#token`, which quietly inverted this file's central\n * rule for a one-shot `buyerAccessToken` host: `#fail()` clears `#token`, so\n * the first refusal turned a configured context into an \"unconfigured\" one,\n * `authorization()` then returned null instead of throwing, and the very next\n * call went out with no bearer — the anonymous Public sale fallback this\n * module exists to prevent. A provider host never saw it, because `#provider`\n * held `configured` true. Found against a live worker in the M9 pass.\n */\n get configured(): boolean {\n return this.#configured;\n }\n\n /** Set once a state arrives that refreshing cannot clear. */\n get unavailable(): BuyerAccessUnavailableEvent | null {\n return this.#terminal;\n }\n\n /** True while a usable bearer is held (ignores skew). */\n get hasToken(): boolean {\n return !!this.#token && (this.#expiresAt === 0 || this.#expiresAt > Date.now());\n }\n\n /** Epoch ms the current token expires, or 0 when the host didn't say. */\n get expiresAt(): number {\n return this.#expiresAt;\n }\n\n /**\n * The `Authorization` header value for a scoped operation.\n *\n * Returns null only when this context is not configured at all (the ordinary\n * anonymous public picker). A configured context either returns a bearer or\n * throws `BuyerAccessUnavailableError` — it never returns null, because a\n * null here would send the request as anonymous Public sale.\n */\n async authorization(reason: BuyerAccessRefreshReason = 'initial'): Promise<string | null> {\n if (!this.configured) return null;\n if (this.#terminal) throw new BuyerAccessUnavailableError(this.#terminal);\n\n const now = Date.now();\n const stale = !this.#token || (this.#expiresAt > 0 && this.#expiresAt - this.#skewMs <= now);\n if (stale) {\n const expired = !!this.#token && this.#expiresAt > 0 && this.#expiresAt <= now;\n const why: BuyerAccessRefreshReason = this.#token ? (expired ? 'expired' : 'expiring') : reason;\n const token = await this.#renew(why);\n if (!token) {\n // #renew already classified and reported the failure; reuse that event\n // rather than raising a second one for the same cause.\n throw new BuyerAccessUnavailableError(\n this.#terminal ?? this.#lastFailure ?? this.#fail('provider_failed'),\n );\n }\n return `Bearer ${token}`;\n }\n return `Bearer ${this.#token}`;\n }\n\n /**\n * Handle a 401/403 from a scoped call. Returns true when the caller should\n * retry the same request once with the refreshed bearer.\n */\n async handleFailure(status: number, code: string | undefined): Promise<boolean> {\n if (!this.configured) return false;\n\n if (isAccessExpiry(status, code)) {\n this.#token = null;\n this.#expiresAt = 0;\n const token = await this.#renew('unauthorized', code);\n this.#onExpired?.({ reason: 'unauthorized', code, refreshed: !!token });\n return !!token;\n }\n\n const reason = classifyAccessFailure(status, code);\n if (reason) {\n this.#fail(reason, code, status);\n return false;\n }\n return false;\n }\n\n /** Host-driven re-acquisition (after the buyer signs in again, say). */\n async refresh(reason: BuyerAccessRefreshReason = 'manual'): Promise<boolean> {\n this.#terminal = null;\n this.#lastFailure = null;\n this.#token = null;\n this.#expiresAt = 0;\n return !!(await this.#renew(reason));\n }\n\n /** Drop the bearer. Called on destroy so nothing outlives the widget. */\n clear(): void {\n this.#token = null;\n this.#expiresAt = 0;\n this.#inflight = null;\n }\n\n /** Redaction: the bearer must not survive a stringify or an interpolation. */\n toJSON(): { configured: boolean; hasToken: boolean } {\n return { configured: this.configured, hasToken: this.hasToken };\n }\n\n toString(): string {\n return '[BuyerAccessContext redacted]';\n }\n\n // ---- internals ------------------------------------------------------------\n\n #accept(next: BuyerAccessToken | null | undefined): string | null {\n if (!next || typeof next.token !== 'string' || !next.token) return null;\n this.#token = next.token;\n this.#expiresAt = typeof next.expiresAt === 'number' ? next.expiresAt : 0;\n return this.#token;\n }\n\n /**\n * One provider call at a time. Several operations racing an expiry (chart +\n * objects + a socket ticket) must not mint several sessions — the guide's\n * rotate-on-retry rule would revoke the ones they didn't observe.\n */\n #renew(reason: BuyerAccessRefreshReason, code?: string): Promise<string | null> {\n if (this.#inflight) return this.#inflight;\n const provider = this.#provider;\n if (!provider) {\n // A one-shot token with no provider cannot be renewed. That is a legal\n // host choice, so it is a typed state, not a crash.\n this.#fail('no_token', code);\n return Promise.resolve(null);\n }\n const run = (async (): Promise<string | null> => {\n try {\n const next = await provider({ reason });\n const token = this.#accept(next);\n if (!token) {\n this.#fail('provider_failed', code);\n return null;\n }\n return token;\n } catch {\n // The provider's own error text may contain host detail; it is not\n // rethrown and not logged. The host already saw its own failure.\n this.#fail('provider_failed', code);\n return null;\n } finally {\n this.#inflight = null;\n }\n })();\n this.#inflight = run;\n return run;\n }\n\n #fail(\n reason: BuyerAccessUnavailableReason,\n code?: string,\n status?: number,\n ): BuyerAccessUnavailableEvent {\n const event: BuyerAccessUnavailableEvent = {\n reason,\n code,\n status,\n // Unchanged: `retryable` means \"the SAME request may succeed later\".\n // `provider_failed` is recoverable but not retryable — the host must fix\n // its mint endpoint first — so the two sets are deliberately different.\n retryable: reason === 'paused' || reason === 'channel_denied',\n };\n this.#lastFailure = event;\n // A recoverable reason says nothing about the SESSION, so it must not latch\n // the context terminal and must not throw the bearer away.\n if (!RECOVERABLE.has(reason)) {\n this.#terminal = event;\n this.#token = null;\n this.#expiresAt = 0;\n }\n this.#onUnavailable?.(event);\n return event;\n }\n}\n\n/** Build a context from widget options, or null for the tokenless public path. */\nexport function createBuyerAccessContext(\n options: {\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n buyerAccessToken?: string | BuyerAccessToken;\n },\n hooks: Pick<BuyerAccessContextOptions, 'onExpired' | 'onUnavailable'> = {},\n): BuyerAccessContext | null {\n if (!options.buyerAccessTokenProvider && !options.buyerAccessToken) return null;\n return new BuyerAccessContext({\n provider: options.buyerAccessTokenProvider,\n token: options.buyerAccessToken,\n ...hooks,\n });\n}\n","/** Dependency-free canonical SeatLayer mark for distributed SDK attribution.\n *\n * Keep the geometry in sync with `SeatLayerMark` and\n * `scripts/generate-brand-assets.py`. The fixed dark-surface palette makes the\n * fragment safe inside the self-contained midnight attribution tile.\n */\nexport const SEATLAYER_ATTRIBUTION_MARK_SVG =\n '<svg viewBox=\"0 0 64 56\" width=\"12\" height=\"11\" fill=\"none\" aria-hidden=\"true\" focusable=\"false\" style=\"display:block\">' +\n '<path d=\"M4 13 Q16 6 29 7 L28.5 17 Q17 16.5 7 22 Z\" fill=\"#f4b740\"/>' +\n '<path d=\"M4 13 Q16 6 29 7 L28.5 17 Q17 16.5 7 22 Z\" fill=\"#f4b740\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '<path d=\"M8 28 Q18 22 28.6 23 L28.2 32 Q18 28.5 10 36 Z\" fill=\"#fcf7ee\"/>' +\n '<path d=\"M8 28 Q18 22 28.6 23 L28.2 32 Q18 28.5 10 36 Z\" fill=\"#fcf7ee\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '<path d=\"M11 41 Q19 35 28.2 36 L27.8 45 Q19.5 42 13.5 49 Z\" fill=\"#fcf7ee\"/>' +\n '<path d=\"M11 41 Q19 35 28.2 36 L27.8 45 Q19.5 42 13.5 49 Z\" fill=\"#fcf7ee\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '</svg>';\n","/**\n * A secure, framework-neutral host for the SeatLayer chart Designer.\n *\n * The Designer remains an iframe so a platform never gives its SeatLayer secret\n * key to a browser. This class owns the iframe lifecycle and accepts messages\n * only from that iframe's exact origin.\n */\nexport type EmbeddedDesignerEventType =\n | 'seatlayer.designer.ready'\n | 'seatlayer.designer.saved'\n | 'seatlayer.designer.published'\n | 'seatlayer.designer.close'\n | 'seatlayer.designer.error';\n\nexport interface EmbeddedDesignerMessage {\n type: EmbeddedDesignerEventType;\n chartId?: string;\n workspaceId?: string;\n expiresAt?: number;\n code?: string;\n message?: string;\n meta?: unknown;\n /**\n * Set by the Designer on an error it raised while the editor was already\n * running (a failed autosave, thumbnail upload, reload…). Such an error is\n * about ONE operation, not about the session, so the SDK reports it to the\n * host and leaves the live editor mounted instead of replacing it with the\n * dead-end card. Absent on older Designer builds — see\n * {@link EmbeddedDesigner} for the phase-based fallback.\n */\n fatal?: boolean;\n /** The operation that failed, when `fatal` is `false` (e.g. `'save'`). */\n action?: string;\n}\n\nexport interface EmbeddedDesignerOptions {\n /** The short-lived URL returned by your backend's Designer-session call. */\n designerUrl: string;\n /** CSS selector or element where the iframe is mounted. */\n container: string | HTMLElement;\n /** Verify the message belongs to the chart your backend opened. */\n expectedChartId?: string;\n /** Verify the message belongs to the workspace your backend opened. */\n expectedWorkspaceId?: string;\n title?: string;\n className?: string;\n style?: Partial<CSSStyleDeclaration>;\n allow?: string;\n referrerPolicy?: ReferrerPolicy;\n /**\n * Show the built-in branded loading skeleton and error/expiry card inside the\n * container while the Designer boots. Defaults to `true`. Set `false` when the\n * host renders its own loading and error chrome.\n */\n showLoadingState?: boolean;\n /**\n * If the Designer never posts `ready` within this many milliseconds, the host\n * transitions to the error card with a timeout message. Defaults to `20000`.\n * Only used when `showLoadingState` is enabled.\n */\n loadingTimeoutMs?: number;\n /**\n * How to size the iframe's height. The Designer is a full application (its\n * shell is `position:fixed; height:100dvh`), not flowing content, so it should\n * fill its box rather than be measured.\n *\n * - `'fill'` (default): container-aware. On mount the SDK probes whether the\n * host gave the container a DEFINITE (bounded) height:\n * - **Bounded container** (a fixed-height block, `height`/`max-height`,\n * `flex:1; min-h:0`, a resolved `%`, etc.) → the iframe fills 100% of\n * that block and tracks its size live via a `ResizeObserver`.\n * - **Content-sized container** (the block collapses to whatever the iframe\n * measures — typical full-page usage) → the iframe grows so its bottom\n * edge reaches the bottom of the viewport (`window.innerHeight -\n * iframe.top`), recomputed (rAF-throttled) on `resize` /\n * `orientationchange` / `scroll`.\n * Either way the result is clamped to `minHeight`. The verdict is cached but\n * re-probed on `resize`/`orientationchange` so a responsive host layout can\n * flip between the two. The legacy `seatlayer.designer.resize` message is\n * ignored in `'fill'` mode: it is circular, because the fixed-position shell\n * just echoes the iframe height.\n * - a number: a fixed pixel height. In this mode the legacy resize message is\n * still honoured (unless `autoResize` is `false`) so older hosts keep growing.\n *\n * All SDK-managed heights are written with `!important` priority so a host\n * theme's `iframe { height: … !important }` cannot override them.\n */\n height?: 'fill' | number;\n /** Minimum height (px) that `'fill'` mode clamps to. Defaults to `480`. */\n minHeight?: number;\n /**\n * Auto-grow the iframe to the height the Designer reports over the resize\n * protocol (`seatlayer.designer.resize`). Only applies when `height` is a fixed\n * number; ignored in `'fill'` mode. Defaults to `true`. Set `false` when the\n * host sizes a fixed-height iframe itself.\n */\n autoResize?: boolean;\n /**\n * Called when the user presses \"Try again\" on the error card. Use it to mint a\n * fresh Designer session and call `setDesignerUrl()` with the new URL, which\n * recreates the iframe and returns to the loading state. When omitted, \"Try\n * again\" reloads the current `designerUrl` in place.\n *\n * When supplied, it also powers automatic session renewal — see\n * {@link EmbeddedDesignerOptions.autoRenewSession}.\n */\n onRequestRelaunch?: () => void;\n /**\n * Keep long editing sessions alive without the user ever hitting the expiry\n * wall. Designer sessions are short-lived security tokens; when the host wires\n * `onRequestRelaunch` the SDK, with this enabled, will:\n *\n * - **Renew proactively.** From each `ready` message's `expiresAt` it schedules\n * a silent relaunch shortly before the session lapses (~3 min ahead; for a\n * TTL under 15 min it renews after 80% of the remaining life, and never\n * sooner than 30s after `ready`). The host mints a fresh session and swaps\n * `designerUrl`, so the editor keeps working with no error card.\n * - **Recover on expiry.** If an expiry error still slips through (a slept\n * laptop woke past the renewal window, say) it makes ONE automatic relaunch\n * attempt before showing the \"Try again\" card, and only falls back to the\n * card if that relaunch also fails.\n *\n * Defaults to `true` whenever `onRequestRelaunch` is provided; a no-op without\n * it. Set `false` to keep the fully manual \"Try again\" behavior.\n */\n autoRenewSession?: boolean;\n onReady?: (message: EmbeddedDesignerMessage) => void;\n onSaved?: (message: EmbeddedDesignerMessage) => void;\n onPublished?: (message: EmbeddedDesignerMessage) => void;\n onClose?: (message: EmbeddedDesignerMessage) => void;\n onError?: (message: EmbeddedDesignerMessage) => void;\n}\n\nconst TYPES = new Set<EmbeddedDesignerEventType>([\n 'seatlayer.designer.ready',\n 'seatlayer.designer.saved',\n 'seatlayer.designer.published',\n 'seatlayer.designer.close',\n 'seatlayer.designer.error',\n]);\n\nconst DEFAULT_LOADING_TIMEOUT_MS = 20000;\nconst DEFAULT_MIN_FILL_HEIGHT = 480;\n/**\n * Proactive session-renewal timing (see {@link EmbeddedDesigner.scheduleRenewal}).\n * We aim to relaunch a comfortable lead ahead of `expiresAt`; short-lived sessions\n * instead renew after a fraction of their life so the lead never overshoots the TTL.\n */\nconst RENEW_LEAD_MS = 3 * 60 * 1000; // standard lead: renew ~3 min before expiry\nconst RENEW_SHORT_TTL_MS = 15 * 60 * 1000; // below this TTL, use the fraction clamp\nconst RENEW_SHORT_TTL_FRACTION = 0.8; // short TTL: renew after 80% of remaining life\nconst RENEW_MIN_DELAY_MS = 30 * 1000; // never renew sooner than 30s after `ready`\n/**\n * Container-fill detection tunables. The probe drives the iframe to two extreme\n * heights within one synchronous task (no paint between reads, so no flash) and\n * watches whether the container tracks it.\n */\nconst FILL_PROBE_HEIGHT_PX = 100000; // \"huge\" iframe used to see if the box grows with it\nconst FILL_PROBE_TRACK_EPSILON_PX = 4; // container grew with the iframe ⇒ content-sized\nconst FILL_MIN_DEFINITE_HEIGHT_PX = 50; // a bounded box must keep at least this much height\n\n/** Internal reason the error card is being shown, used to pick human copy. */\ntype ErrorCause = 'expired' | 'mismatch' | 'timeout' | 'load';\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container !== 'string') return container;\n const element = document.querySelector<HTMLElement>(container);\n if (!element) throw new Error(`EmbeddedDesigner container not found: ${container}`);\n return element;\n}\n\n/** Map an error message's `code` onto one of the human-copy causes. */\nfunction causeFromCode(code: string | undefined): ErrorCause {\n const value = (code ?? '').toLowerCase();\n if (value.includes('expire') || value.includes('revoke') || value === '401') return 'expired';\n if (value.includes('mismatch')) return 'mismatch';\n if (value.includes('timeout')) return 'timeout';\n return 'load';\n}\n\nconst ERROR_COPY: Record<ErrorCause, { title: string; body: string }> = {\n expired: {\n title: 'This design session expired',\n body: 'For your security, editing sessions are short-lived. Start a fresh one to keep designing.',\n },\n mismatch: {\n title: \"This editor doesn't match this chart\",\n body: 'The session that loaded belongs to a different chart or workspace. Reopen the designer to continue.',\n },\n timeout: {\n title: 'The designer is taking too long',\n body: 'It did not finish loading in time. This is usually a slow connection — try again.',\n },\n load: {\n title: \"We couldn't load the designer\",\n body: 'Something went wrong while opening the editor. Please try again.',\n },\n};\n\n/** Mount, replace, and destroy a scoped Designer iframe safely. */\nexport class EmbeddedDesigner {\n private options: EmbeddedDesignerOptions;\n private frame: HTMLIFrameElement | null = null;\n private designerOrigin = '';\n private overlay: HTMLDivElement | null = null;\n private timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n /** Proactive session-renewal timer; armed from each `ready`, cleared on re-mount. */\n private renewTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * One automatic recovery relaunch is allowed per expiry. Reset ONLY when a fresh\n * `ready` arrives — deliberately not on re-mount — so a session that keeps failing\n * to load can't loop the host through endless silent relaunches.\n */\n private autoRecoverUsed = false;\n private phase: 'loading' | 'ready' | 'error' = 'loading';\n private restoreContainerPosition: string | null = null;\n // Host-side fullscreen pin: saved state we restore on `off`/Escape/destroy.\n private pinned = false;\n private frameStyleBeforeFs: string | null = null;\n private docOverflowBeforeFs: string | null = null;\n private bodyOverflowBeforeFs: string | null = null;\n private fsKeyHandler: ((event: KeyboardEvent) => void) | null = null;\n /** Latest height (px string) the Designer reported; re-applied after unpin. */\n private lastAutoHeight = '';\n // Fill sizing: pending rAF handles + whether window listeners are attached.\n private fillRaf: number | null = null;\n private reprobeRaf: number | null = null;\n private fillListening = false;\n /** Resolved container element (fill measurement + ResizeObserver target). */\n private containerEl: HTMLElement | null = null;\n /** Cached fill verdict: 'container' = bounded block, 'viewport' = full page. */\n private fillMode: 'viewport' | 'container' | null = null;\n /** Live block-size tracking in container-fill mode; disconnected on destroy. */\n private resizeObs: ResizeObserver | null = null;\n\n constructor(options: EmbeddedDesignerOptions) {\n this.options = options;\n }\n\n mount(): HTMLIFrameElement {\n this.destroy();\n const url = new URL(this.options.designerUrl, window.location.href);\n if (url.protocol !== 'https:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {\n throw new Error('EmbeddedDesigner requires an HTTPS designerUrl outside local development.');\n }\n this.designerOrigin = url.origin;\n\n const frame = document.createElement('iframe');\n frame.title = this.options.title ?? 'Venue chart Designer';\n frame.allow = this.options.allow ?? 'fullscreen; clipboard-write';\n frame.referrerPolicy = this.options.referrerPolicy ?? 'origin';\n frame.src = url.toString();\n // Width/height are written with `!important` priority so a host theme's\n // `iframe { height: … !important }` cannot beat the SDK's inline sizing.\n frame.style.setProperty('width', '100%', 'important');\n // `'fill'` (default) is (re)computed once the frame is in the DOM (see\n // startFill); a numeric height is a fixed pixel box.\n frame.style.setProperty(\n 'height',\n typeof this.options.height === 'number' ? `${this.options.height}px` : '100%',\n 'important',\n );\n frame.style.border = '0';\n Object.assign(frame.style, this.options.style);\n if (this.options.className) frame.className = this.options.className;\n\n const container = resolveContainer(this.options.container);\n this.containerEl = container;\n window.addEventListener('message', this.handleMessage);\n container.append(frame);\n this.frame = frame;\n\n // Fill mode owns the height from the viewport now the frame is measurable.\n if (this.fillEnabled()) this.startFill();\n\n this.phase = 'loading';\n if (this.loadingStateEnabled()) {\n this.ensureContainerPositioned(container);\n this.renderOverlay(container, 'loading');\n const timeout = this.options.loadingTimeoutMs ?? DEFAULT_LOADING_TIMEOUT_MS;\n if (timeout > 0 && Number.isFinite(timeout)) {\n this.timeoutTimer = setTimeout(() => {\n if (this.phase === 'loading') this.showError('timeout');\n }, timeout);\n }\n }\n return frame;\n }\n\n /** Replace the iframe instead of assigning a new fragment to an existing one. */\n setDesignerUrl(designerUrl: string): HTMLIFrameElement {\n this.options = { ...this.options, designerUrl };\n // mount() tears everything down and re-enters the loading state.\n return this.mount();\n }\n\n getIframe(): HTMLIFrameElement | null {\n return this.frame;\n }\n\n destroy(): void {\n window.removeEventListener('message', this.handleMessage);\n this.stopFill();\n this.unpinFullscreen();\n this.clearTimeoutTimer();\n this.clearRenewTimer();\n this.removeOverlay();\n this.restoreContainerStyle();\n this.frame?.remove();\n this.frame = null;\n this.containerEl = null;\n this.fillMode = null;\n this.designerOrigin = '';\n this.phase = 'loading';\n this.lastAutoHeight = '';\n }\n\n private loadingStateEnabled(): boolean {\n return this.options.showLoadingState !== false;\n }\n\n private autoResizeEnabled(): boolean {\n return this.options.autoResize !== false;\n }\n\n /** Fill mode is the default; a numeric `height` opts into a fixed pixel box. */\n private fillEnabled(): boolean {\n return typeof this.options.height !== 'number';\n }\n\n /** Write an SDK-managed height with `!important` so a host theme can't win. */\n private setFrameHeight(value: string): void {\n this.frame?.style.setProperty('height', value, 'important');\n }\n\n /**\n * Decide whether the host gave the container a DEFINITE (bounded) height — a\n * fixed block the embed should fill 100% of — versus a content-sized container\n * that collapses to whatever the iframe measures (full-page usage).\n *\n * We drive the iframe to two extreme heights within a single synchronous task\n * and watch whether the container follows: a bounded box barely moves, a\n * content-sized one grows with the iframe. Because we restore the height before\n * yielding, the browser only lays out — it never paints the extremes, so there\n * is no visible flash. Works for px, resolved `%`, and flex (`flex:1;min-h:0`)\n * heights, and leaves a mere `min-height` floor classified as content-sized so\n * full-page hosts keep the old viewport-fill behavior.\n */\n private detectFillMode(): 'viewport' | 'container' {\n const container = this.containerEl;\n const frame = this.frame;\n if (this.pinned || !container || !frame) return this.fillMode ?? 'viewport';\n const measure = (): number => container.getBoundingClientRect().height;\n const savedValue = frame.style.getPropertyValue('height');\n const savedPriority = frame.style.getPropertyPriority('height');\n\n frame.style.setProperty('height', '0px', 'important');\n const collapsed = measure();\n frame.style.setProperty('height', `${FILL_PROBE_HEIGHT_PX}px`, 'important');\n const expanded = measure();\n\n if (savedValue) frame.style.setProperty('height', savedValue, savedPriority);\n else frame.style.removeProperty('height');\n\n const tracksIframe = expanded - collapsed > FILL_PROBE_TRACK_EPSILON_PX;\n const bounded = !tracksIframe && collapsed >= FILL_MIN_DEFINITE_HEIGHT_PX;\n return bounded ? 'container' : 'viewport';\n }\n\n /**\n * Size the iframe for the current fill verdict, clamped to `minHeight`. In\n * container mode it fills 100% of the bounded block; in viewport mode its\n * bottom edge meets the bottom of the viewport (`window.innerHeight - top`).\n * No-op while pinned fullscreen (the pin fills the viewport itself).\n */\n private applyFill(): void {\n if (!this.frame || this.pinned) return;\n const min = this.options.minHeight ?? DEFAULT_MIN_FILL_HEIGHT;\n if (this.fillMode === 'container' && this.containerEl) {\n const target = Math.max(min, Math.round(this.containerEl.getBoundingClientRect().height));\n this.setFrameHeight(`${target}px`);\n return;\n }\n const top = this.frame.getBoundingClientRect().top;\n const target = Math.max(min, Math.round(window.innerHeight - top));\n this.setFrameHeight(`${target}px`);\n }\n\n /** rAF-throttled fill recompute, so a burst of scroll/RO ticks coalesces. */\n private scheduleFill = (): void => {\n if (this.fillRaf !== null) return;\n this.fillRaf = requestAnimationFrame(() => {\n this.fillRaf = null;\n this.applyFill();\n });\n };\n\n /**\n * rAF-throttled re-probe: a host layout change (responsive breakpoint, a block\n * gaining/losing a definite height) can flip the verdict, so `resize` /\n * `orientationchange` re-detect and swap the container observer accordingly.\n */\n private scheduleReprobe = (): void => {\n if (this.reprobeRaf !== null) return;\n this.reprobeRaf = requestAnimationFrame(() => {\n this.reprobeRaf = null;\n if (this.pinned) return;\n this.fillMode = this.detectFillMode();\n this.syncContainerObserver();\n this.applyFill();\n });\n };\n\n /** Attach/detach the container ResizeObserver to match the current verdict. */\n private syncContainerObserver(): void {\n const want =\n this.fillMode === 'container' && !!this.containerEl && typeof ResizeObserver !== 'undefined';\n if (want && !this.resizeObs) {\n this.resizeObs = new ResizeObserver(() => this.scheduleFill());\n this.resizeObs.observe(this.containerEl!);\n } else if (!want && this.resizeObs) {\n this.resizeObs.disconnect();\n this.resizeObs = null;\n }\n }\n\n private startFill(): void {\n this.fillMode = this.detectFillMode();\n this.syncContainerObserver();\n this.applyFill();\n if (this.fillListening) return;\n this.fillListening = true;\n // Layout-changing events re-probe (the verdict can flip); scroll only shifts\n // the viewport-fill top offset, so it just re-applies.\n window.addEventListener('resize', this.scheduleReprobe);\n window.addEventListener('orientationchange', this.scheduleReprobe);\n window.addEventListener('scroll', this.scheduleFill, { passive: true });\n }\n\n private stopFill(): void {\n if (this.fillRaf !== null) {\n cancelAnimationFrame(this.fillRaf);\n this.fillRaf = null;\n }\n if (this.reprobeRaf !== null) {\n cancelAnimationFrame(this.reprobeRaf);\n this.reprobeRaf = null;\n }\n if (this.resizeObs) {\n this.resizeObs.disconnect();\n this.resizeObs = null;\n }\n if (!this.fillListening) return;\n this.fillListening = false;\n window.removeEventListener('resize', this.scheduleReprobe);\n window.removeEventListener('orientationchange', this.scheduleReprobe);\n window.removeEventListener('scroll', this.scheduleFill);\n }\n\n /**\n * Pin the iframe over the host page as a viewport-filling overlay. We save the\n * iframe's inline style and the document scroll state so `unpinFullscreen`\n * restores everything exactly. Escape (host-side) also exits.\n */\n private pinFullscreen(): void {\n if (this.pinned || !this.frame) return;\n this.pinned = true;\n this.frameStyleBeforeFs = this.frame.getAttribute('style');\n // Every pin property is `!important` so a host theme's `iframe { … }` rules\n // (height/width/inset) can't unpin us. `inset` is written as its four longhands\n // for reliability across engines. Restored wholesale via the saved style attr.\n const pin: Record<string, string> = {\n position: 'fixed',\n top: '0',\n right: '0',\n bottom: '0',\n left: '0',\n width: '100vw',\n height: '100vh',\n margin: '0',\n border: '0',\n 'z-index': '2147483000',\n background: '#101625',\n };\n for (const [property, value] of Object.entries(pin)) {\n this.frame.style.setProperty(property, value, 'important');\n }\n\n const docEl = document.documentElement;\n this.docOverflowBeforeFs = docEl.style.overflow;\n docEl.style.overflow = 'hidden';\n if (document.body) {\n this.bodyOverflowBeforeFs = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n this.fsKeyHandler = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') this.unpinFullscreen();\n };\n window.addEventListener('keydown', this.fsKeyHandler);\n }\n\n /** Undo `pinFullscreen`: restore the iframe style + scroll lock. Idempotent. */\n private unpinFullscreen(): void {\n if (!this.pinned) return;\n this.pinned = false;\n if (this.frame) {\n if (this.frameStyleBeforeFs === null) this.frame.removeAttribute('style');\n else this.frame.setAttribute('style', this.frameStyleBeforeFs);\n // Restore the right height for the mode: recompute the fill, or re-apply\n // the last height the Designer reported (numeric mode). Both use\n // `!important` so a host theme can't win after we unpin.\n if (this.fillEnabled()) this.applyFill();\n else if (this.autoResizeEnabled() && this.lastAutoHeight) this.setFrameHeight(this.lastAutoHeight);\n }\n this.frameStyleBeforeFs = null;\n\n if (this.docOverflowBeforeFs !== null) {\n document.documentElement.style.overflow = this.docOverflowBeforeFs;\n this.docOverflowBeforeFs = null;\n }\n if (this.bodyOverflowBeforeFs !== null && document.body) {\n document.body.style.overflow = this.bodyOverflowBeforeFs;\n this.bodyOverflowBeforeFs = null;\n }\n if (this.fsKeyHandler) {\n window.removeEventListener('keydown', this.fsKeyHandler);\n this.fsKeyHandler = null;\n }\n }\n\n private clearTimeoutTimer(): void {\n if (this.timeoutTimer !== null) {\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = null;\n }\n }\n\n /**\n * Auto-renewal (proactive + one expiry recovery) is on when the host wired a\n * relaunch hook and did not opt out. Without the hook there is nothing to call,\n * so it is a no-op.\n */\n private autoRenewEnabled(): boolean {\n return !!this.options.onRequestRelaunch && this.options.autoRenewSession !== false;\n }\n\n private clearRenewTimer(): void {\n if (this.renewTimer !== null) {\n clearTimeout(this.renewTimer);\n this.renewTimer = null;\n }\n }\n\n /**\n * Arm the proactive renewal timer from a `ready` message's `expiresAt` (epoch\n * ms). We relaunch a comfortable lead before expiry so the host can mint a fresh\n * session and swap `designerUrl` without the user ever seeing the expiry card:\n *\n * - normal TTL (≥ 15 min): renew {@link RENEW_LEAD_MS} (~3 min) before expiry;\n * - short TTL (< 15 min): renew after {@link RENEW_SHORT_TTL_FRACTION} (80%) of\n * the remaining life, so the lead can't overshoot the whole session;\n * - either way, never sooner than {@link RENEW_MIN_DELAY_MS} (30s) after `ready`\n * so a burst of `ready` messages can't spin the host.\n *\n * Re-armed on every `ready`; cleared on destroy / setDesignerUrl (via re-mount).\n * A no-op when auto-renewal is off or `expiresAt` is missing/already past — the\n * expiry-error path recovers a session that has already lapsed.\n */\n private scheduleRenewal(expiresAt: number | undefined): void {\n this.clearRenewTimer();\n if (!this.autoRenewEnabled()) return;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return;\n const remaining = expiresAt - Date.now();\n if (remaining <= 0) return;\n const lead =\n remaining < RENEW_SHORT_TTL_MS\n ? remaining * RENEW_SHORT_TTL_FRACTION\n : remaining - RENEW_LEAD_MS;\n const delay = Math.max(RENEW_MIN_DELAY_MS, lead);\n this.renewTimer = setTimeout(() => {\n this.renewTimer = null;\n // Silent renewal: the host mints a fresh session and swaps designerUrl,\n // which re-mounts the iframe and re-arms us from the next `ready`.\n if (this.autoRenewEnabled()) this.options.onRequestRelaunch!();\n }, delay);\n }\n\n private ensureContainerPositioned(container: HTMLElement): void {\n // The overlay is absolutely positioned; the container must establish a\n // positioning context. Only touch a `static` container, and remember to\n // restore it on destroy.\n const position = getComputedStyle(container).position;\n if (position === 'static') {\n this.restoreContainerPosition = container.style.position;\n container.style.position = 'relative';\n }\n }\n\n private restoreContainerStyle(): void {\n if (this.restoreContainerPosition === null) return;\n try {\n resolveContainer(this.options.container).style.position = this.restoreContainerPosition;\n } catch {\n /* container already gone — nothing to restore */\n }\n this.restoreContainerPosition = null;\n }\n\n private removeOverlay(): void {\n this.overlay?.remove();\n this.overlay = null;\n }\n\n private showError(cause: ErrorCause): void {\n this.phase = 'error';\n this.clearTimeoutTimer();\n if (!this.loadingStateEnabled()) return;\n let container: HTMLElement;\n try {\n container = resolveContainer(this.options.container);\n } catch {\n return;\n }\n this.renderOverlay(container, 'error', cause);\n }\n\n private handleTryAgain(): void {\n if (this.options.onRequestRelaunch) {\n // Host mints a fresh session and calls setDesignerUrl(), which re-mounts\n // the iframe and returns to the loading state.\n this.options.onRequestRelaunch();\n return;\n }\n // No relaunch hook: reload the same session URL in place.\n this.mount();\n }\n\n /**\n * Build (or rebuild) the overlay for the given phase. A single overlay element\n * is reused so we never stack stale skeletons or cards.\n */\n private renderOverlay(container: HTMLElement, phase: 'loading' | 'error', cause?: ErrorCause): void {\n this.removeOverlay();\n const overlay = document.createElement('div');\n overlay.setAttribute('data-seatlayer-designer-overlay', phase);\n overlay.setAttribute('role', phase === 'error' ? 'alert' : 'status');\n overlay.setAttribute('aria-live', 'polite');\n Object.assign(overlay.style, {\n position: 'absolute',\n inset: '0',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#101625',\n color: '#e6ebf5',\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif',\n zIndex: '2',\n overflow: 'hidden',\n } satisfies Partial<CSSStyleDeclaration>);\n\n if (phase === 'loading') this.buildSkeleton(overlay);\n else this.buildErrorCard(overlay, cause ?? 'load');\n\n container.append(overlay);\n this.overlay = overlay;\n }\n\n private buildSkeleton(overlay: HTMLDivElement): void {\n // Scoped keyframes; the shimmer only runs when the user allows motion.\n // `@sl-css` opts it into build-time minification (cdn/minifyCssLiterals.ts).\n const style = document.createElement('style');\n style.textContent = /* @sl-css */ `\n@media (prefers-reduced-motion: no-preference) {\n @keyframes seatlayer-designer-shimmer {\n 0% { background-position: -320px 0; }\n 100% { background-position: 320px 0; }\n }\n [data-seatlayer-designer-overlay=\"loading\"] .sl-shimmer {\n animation: seatlayer-designer-shimmer 1.25s ease-in-out infinite;\n background-size: 640px 100%;\n }\n}`;\n overlay.append(style);\n\n const shimmer =\n 'linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.10) 37%, rgba(255,255,255,0.04) 63%)';\n\n const scaffold = document.createElement('div');\n Object.assign(scaffold.style, {\n position: 'absolute',\n inset: '0',\n display: 'flex',\n flexDirection: 'column',\n padding: '16px',\n gap: '14px',\n opacity: '0.9',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const bar = (styles: Partial<CSSStyleDeclaration>): HTMLDivElement => {\n const node = document.createElement('div');\n node.className = 'sl-shimmer';\n Object.assign(node.style, {\n background: shimmer,\n borderRadius: '8px',\n } satisfies Partial<CSSStyleDeclaration>);\n Object.assign(node.style, styles);\n return node;\n };\n\n // Top toolbar row.\n scaffold.append(bar({ height: '40px', width: '100%', flex: '0 0 auto' }));\n\n // Body: side panel + canvas.\n const body = document.createElement('div');\n Object.assign(body.style, {\n display: 'flex',\n gap: '14px',\n flex: '1 1 auto',\n minHeight: '0',\n } satisfies Partial<CSSStyleDeclaration>);\n body.append(bar({ width: '220px', height: '100%', flex: '0 0 auto' }));\n body.append(bar({ flex: '1 1 auto', height: '100%' }));\n scaffold.append(body);\n\n overlay.append(scaffold);\n\n // Centered caption above the scaffold.\n const caption = document.createElement('div');\n Object.assign(caption.style, {\n position: 'relative',\n zIndex: '1',\n display: 'flex',\n alignItems: 'center',\n gap: '10px',\n padding: '10px 16px',\n borderRadius: '999px',\n background: 'rgba(16, 22, 37, 0.72)',\n fontSize: '13px',\n fontWeight: '500',\n letterSpacing: '0.01em',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const dot = document.createElement('span');\n dot.className = 'sl-shimmer';\n Object.assign(dot.style, {\n width: '9px',\n height: '9px',\n borderRadius: '50%',\n background: shimmer,\n flex: '0 0 auto',\n } satisfies Partial<CSSStyleDeclaration>);\n caption.append(dot);\n caption.append(document.createTextNode('Loading designer…'));\n overlay.append(caption);\n }\n\n private buildErrorCard(overlay: HTMLDivElement, cause: ErrorCause): void {\n const copy = ERROR_COPY[cause];\n const card = document.createElement('div');\n Object.assign(card.style, {\n maxWidth: '420px',\n margin: '0 24px',\n padding: '28px',\n textAlign: 'center',\n background: 'rgba(255, 255, 255, 0.03)',\n border: '1px solid rgba(255, 255, 255, 0.08)',\n borderRadius: '16px',\n boxShadow: '0 12px 40px rgba(0, 0, 0, 0.35)',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const heading = document.createElement('h2');\n heading.textContent = copy.title;\n Object.assign(heading.style, {\n margin: '0 0 8px',\n fontSize: '17px',\n fontWeight: '600',\n color: '#f4f7ff',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const body = document.createElement('p');\n body.textContent = copy.body;\n Object.assign(body.style, {\n margin: '0 0 20px',\n fontSize: '13.5px',\n lineHeight: '1.5',\n color: '#aab4c8',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = 'Try again';\n Object.assign(button.style, {\n appearance: 'none',\n cursor: 'pointer',\n border: '0',\n borderRadius: '10px',\n padding: '10px 22px',\n fontSize: '14px',\n fontWeight: '600',\n color: '#101625',\n background: '#7aa2ff',\n } satisfies Partial<CSSStyleDeclaration>);\n button.addEventListener('click', () => this.handleTryAgain());\n\n card.append(heading, body, button);\n overlay.append(card);\n }\n\n private handleMessage = (event: MessageEvent<unknown>) => {\n if (!this.frame || event.origin !== this.designerOrigin || event.source !== this.frame.contentWindow) return;\n if (!event.data || typeof event.data !== 'object') return;\n const data = event.data as Record<string, unknown>;\n\n // Layout protocol — origin-locked like everything else, but handled here\n // rather than dispatched to the host callbacks.\n if (data.type === 'seatlayer.designer.resize') {\n // Fill mode owns the height from the viewport; the reported scrollHeight is\n // circular (the fixed-position shell echoes the iframe height), so ignore\n // it. Only a fixed numeric height honours the legacy auto-grow.\n if (!this.fillEnabled() && this.autoResizeEnabled()\n && typeof data.px === 'number' && Number.isFinite(data.px) && data.px > 0) {\n this.lastAutoHeight = `${Math.round(data.px)}px`;\n // While pinned fullscreen the iframe fills the viewport; apply the\n // reported height only when not pinned (it's re-applied on unpin).\n // `!important` so a host theme's `iframe { height … }` can't win.\n if (!this.pinned) this.setFrameHeight(this.lastAutoHeight);\n }\n return;\n }\n if (data.type === 'seatlayer.designer.fullscreen') {\n if (data.on === true) this.pinFullscreen();\n else if (data.on === false) this.unpinFullscreen();\n return;\n }\n\n if (typeof data.type !== 'string' || !TYPES.has(data.type as EmbeddedDesignerEventType)) return;\n\n const message: EmbeddedDesignerMessage = {\n type: data.type as EmbeddedDesignerEventType,\n chartId: typeof data.chartId === 'string' ? data.chartId : undefined,\n workspaceId: typeof data.workspaceId === 'string' ? data.workspaceId : undefined,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : undefined,\n code: typeof data.code === 'string' ? data.code : undefined,\n message: typeof data.message === 'string' ? data.message : undefined,\n meta: data.meta,\n };\n if (\n (this.options.expectedChartId && message.chartId && message.chartId !== this.options.expectedChartId) ||\n (this.options.expectedWorkspaceId && message.workspaceId && message.workspaceId !== this.options.expectedWorkspaceId)\n ) {\n // A message from our exact iframe carrying the wrong identity is a real\n // session mismatch, not spoofing. Surface it (loading state on) rather than\n // dispatching it to the host callbacks.\n this.showError('mismatch');\n return;\n }\n\n switch (message.type) {\n case 'seatlayer.designer.ready':\n this.phase = 'ready';\n this.clearTimeoutTimer();\n this.removeOverlay();\n // A fresh live session: clear the recovery guard and (re)arm proactive\n // renewal from this session's expiry.\n this.autoRecoverUsed = false;\n this.scheduleRenewal(message.expiresAt);\n this.options.onReady?.(message);\n break;\n case 'seatlayer.designer.saved': this.options.onSaved?.(message); break;\n case 'seatlayer.designer.published': this.options.onPublished?.(message); break;\n case 'seatlayer.designer.close': this.options.onClose?.(message); break;\n case 'seatlayer.designer.error': {\n const cause = causeFromCode(message.code);\n // Expiry is recoverable. If the host wired a relaunch hook, make ONE\n // silent auto-relaunch before ever showing the dead-end card — the user\n // never sees an overlay. Guarded (reset only on a fresh `ready`) so a\n // session that keeps failing to load falls through to the card instead of\n // looping the host.\n if (cause === 'expired' && this.autoRenewEnabled() && !this.autoRecoverUsed) {\n this.autoRecoverUsed = true;\n this.clearRenewTimer();\n this.options.onRequestRelaunch!();\n return;\n }\n // Only a dead session justifies tearing the editor down. An operation\n // that failed inside a running editor (autosave hitting a transient 5xx,\n // a thumbnail upload) leaves the session and the user's work intact, so\n // it is reported to the host and surfaced by the Designer's own in-editor\n // banner — replacing the canvas with \"We couldn't load the designer\"\n // would be both wrong and destructive. `fatal` is authoritative when the\n // Designer sends it; otherwise we fall back to the phase, which is the\n // same signal (we already had a `ready`).\n const fatal = typeof message.fatal === 'boolean'\n ? message.fatal\n : (cause !== 'load' || this.phase !== 'ready');\n if (fatal) this.showError(cause);\n this.options.onError?.(message);\n break;\n }\n }\n };\n}\n","/**\n * SeatPicker — the full buyer experience as a widget.\n *\n * Where `SeatingChart` is canvas-only, SeatPicker owns the complete chrome\n * from the canonical UX contract: branded header,\n * live price panel, selection tray with GA steppers, hold countdown, snipe\n * toasts and expiry recovery — all on top of the shared PickerController, so\n * every host gets the whole experience with one mount.\n *\n * Render contexts (owner requirement): the SAME widget adapts to a full-screen\n * takeover, an inline <div> in a content page, or a popup — breakpoints key\n * off the CONTAINER via ResizeObserver, never the viewport. `SeatPicker.open()`\n * mounts a document-level modal (scrim, ESC, focus restore) in one call.\n *\n * Theming (owner requirement): org account customization flows automatically —\n * the chart payload's ChartTheme (accent, accentInk, logoUrl, brand name,\n * fontFamily, …) seeds the look; the host `theme` option overrides any subset;\n * and every value lands as a `--sl-*` CSS custom property on the widget root\n * so plain host CSS can restyle too.\n */\nimport {\n PickerController,\n ACCESSIBILITY_TYPES,\n expandChart,\n // generateSeatPanorama is deliberately NOT here — see loadPanorama().\n generateSeatThumb,\n loadLocale,\n setStringOverrides,\n t,\n tCount,\n type AccessibilityType,\n type ChartTheme,\n type ExpandedSeat,\n type LodRung,\n type PanoramaResult,\n type PickerSeat,\n type PickerTransport,\n type RendererViewMode,\n type SeatCommercialAttributes,\n type SeatHoverDetails,\n type SectionSummary,\n type TableSelectionDetails,\n} from '@seatlayer/core';\nimport type { Venue3DHandle, SeatView as View3DSeatView } from '@seatlayer/core/view3d';\nimport {\n PubApi,\n type HoldLineItem,\n type HoldResult,\n type OrderStatusResult,\n type PaymentOptionsReason,\n type PaymentOptionsResult,\n} from './api';\n// mountCheckout is deliberately NOT imported here — see loadHostedCheckout().\nimport type { CheckoutHandle, CheckoutState } from './hostedCheckout';\nimport {\n createBuyerAccessContext,\n type BuyerAccessContext,\n type BuyerAccessExpiredEvent,\n type BuyerAccessToken,\n type BuyerAccessTokenProvider,\n type BuyerAccessUnavailableEvent,\n type BuyerAccessUnavailableReason,\n type SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, createControllerSink } from './buyerRealtime';\nimport { SEATLAYER_ATTRIBUTION_MARK_SVG } from './seatLayerBrand';\n\nconst DEFAULT_API_BASE = 'https://api.seatlayer.io';\nconst DEFAULT_MAX_SELECTION = 10;\n/** Show the \"Need more time?\" prompt when the hold has this long (ms) left. */\nconst EXTEND_PROMPT_MS = 60_000;\n/** Default seat ceiling for offering 3D — see the `max3DSeats` option. */\nconst MAX_3D_SEATS_DEFAULT = 15_000;\n/** Most section pills the 3D navigation rail will offer before it stays quiet. */\nconst MAX_3D_SECTION_PILLS = 12;\n\n/** Minimal shape of a section object read off the ChartDoc for the minimap. */\ninterface SectionLike {\n type: string;\n id: string;\n outline?: { x: number; y: number }[];\n color?: string;\n zone?: string;\n}\n\n/** Even-odd point-in-polygon test in world units (minimap click → section). */\nfunction pointInPolygon(x: number, y: number, poly: { x: number; y: number }[]): boolean {\n let inside = false;\n for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n const xi = poly[i].x, yi = poly[i].y, xj = poly[j].x, yj = poly[j].y;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n return inside;\n}\n\n/** One price band in the F4 filter — a set of category keys within a price range. */\ninterface PriceBand {\n id: string;\n label: string;\n keys: string[];\n min: number;\n max: number;\n}\n\n/**\n * Stable checkout-handoff contract (P4). Passed as the THIRD argument to\n * `onCheckout(hold, seats, handoff)` — additive, so the legacy `(hold, seats)`\n * shape used by DesiPass web-v2 (SDK 0.7.3+) is untouched. This is the object to\n * build your order against: it is self-contained (holdId, expiry, currency, and\n * per-line tier + price) and never changes shape across minor releases.\n */\nexport interface CheckoutLineItem {\n /** Seat label (or GA synthetic-unit label) — the stable booking identity. */\n label: string;\n /**\n * Buyer-facing name (the designer's `displayLabel` override), when set.\n * Show this in YOUR order summary; `label` stays the booking identity you\n * pass to the book call. Absent = no override, fall back to `label`.\n */\n displayLabel?: string;\n /**\n * Buyer-facing type word override (seats.io \"Displayed type\", e.g. \"Table\",\n * \"Bench\", \"Box\"), when the designer set one. Absent = the default word.\n */\n displayType?: string;\n /** Chart object id (row/booth/GA area) the unit belongs to. */\n objectId: string;\n objectType: 'seat' | 'booth' | 'ga' | 'table';\n categoryKey: string;\n /** Chosen ticket tier id (Adult/Child/…), or null when the category has no tiers. */\n tierId: string | null;\n /** Unit price in MAJOR currency units (e.g. 45 = 45.00). Server-authoritative. */\n unitPrice: number;\n /** ISO-4217, resolved server-side (per-event override → org → USD). */\n currency: string;\n quantity: number;\n}\n\nexport interface CheckoutHandoff {\n /** Server hold id — pass this to YOUR book call. */\n holdId: string;\n /** Epoch ms the hold expires (after any extensions). */\n expiresAt: number;\n /** ISO-4217 currency for the whole order. */\n currency: string;\n /** Priced line items (tier + unit price + currency), server-authoritative. */\n lineItems: CheckoutLineItem[];\n /** Convenience total in major units (Σ unitPrice × quantity). */\n total: number;\n}\n\n/** Host-authoritative pricing — see {@link SeatPickerOptions.pricing}. */\nexport interface SeatPickerPricing {\n /** Unit prices by category key: a flat number, or `{ base, tiers: { tierId: price } }`. */\n prices?: Record<string, number | { base?: number; tiers?: Record<string, number> }>;\n /** Custom money renderer (e.g. `(n) => n + '€'`). Defaults to Intl currency formatting. */\n formatter?: (amount: number, currency: string) => string;\n}\n\n/** Host theme overrides — any subset; unset keys fall back to the org's chart theme, then defaults. */\nexport interface SeatPickerTheme {\n /** Brand accent (CTA, active chips, hold pill). */\n accent?: string;\n /** Ink on the accent (button labels). */\n accentInk?: string;\n /** Widget background. */\n background?: string;\n /** Panel/card surface color. */\n surface?: string;\n /** Primary text color. */\n text?: string;\n /** Secondary text color. */\n muted?: string;\n /** Hairline/border color. */\n line?: string;\n /** Font stack for all widget chrome. */\n fontFamily?: string;\n /** Corner radius base (px). */\n radius?: number;\n /** Header logo URL (falls back to the org logo from the chart theme, then a monogram). */\n logoUrl?: string;\n /** Brand/event fallback name for the monogram. */\n brandName?: string;\n}\n\nexport interface SeatPickerOptions {\n /** CSS selector or element to mount into. Omit when using SeatPicker.open(). */\n container?: string | HTMLElement;\n /** Event key, e.g. `ev_xxx`. */\n event: string;\n /** API origin. Defaults to https://api.seatlayer.io. */\n apiBase?: string;\n /**\n * Custom data transport. Defaults to the CORS-trivial PubApi against\n * `apiBase`. Inject to run the widget against another backend adapter (the\n * SeatLayer dashboard's own transport) or a fully local mock (demos).\n */\n transport?: PickerTransport;\n /** Reserved for future authenticated rendering. NOT the channel-access\n * credential — a buyer access session is a different thing with different\n * authority, and uses the two options below. */\n publicKey?: string;\n /**\n * Buyer access session provider — the recommended way to show private channel\n * inventory (Sales Channels guide §6).\n *\n * Called with a `reason` whenever the widget needs a bearer: first\n * acquisition, a near/actual expiry, a 401 `buyer_access_expired`, a realtime\n * reconnect, or `refreshAccess()`. It should POST to YOUR backend, which\n * mints the session with your secret key and returns `{ token, expiresAt }`.\n *\n * The token lives in memory for the widget's lifetime and nowhere else: never\n * in storage, never in a URL, never in a log or an error message. Refresh\n * returns the same or a narrower scope; the widget never widens to Public\n * sale on its own, and a failed refresh stops the scoped operation rather\n * than retrying it anonymously. Any held seats stay held — a hold is\n * relinquished by its own opaque capability, not by channel access, so\n * losing access never strands inventory (guide §9).\n *\n * Ignored when a custom `transport` is supplied: that host owns its own\n * credentials.\n */\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n /**\n * One-shot escape hatch for hosts that already own the session lifecycle.\n * Cannot be renewed — when it lapses the widget reports `onAccessExpired`\n * and then `onAccessUnavailable`. Prefer `buyerAccessTokenProvider`.\n */\n buyerAccessToken?: string | BuyerAccessToken;\n /** Max seats selectable at once (default 10). */\n maxSelection?: number;\n /** BCP 47 language for the widget UI. Built-in: en, es, de, fr. */\n locale?: string;\n /** Per-key string overrides layered over the active locale. */\n messages?: Record<string, string>;\n /** ISO 4217 currency fallback (the org/event currency on the chart wins). */\n currency?: string;\n /** Colorblind-safe rendering (Okabe-Ito palette, hollow booked seats). */\n colorblindSafe?: boolean;\n /** Initial map projection. Buyers now toggle **Map (flat 2D) + 3D** only; the\n * legacy `perspective` (2.5D) value is still ACCEPTED for source compatibility\n * but is deprecated — it is coerced to `flat` with a one-time console warning.\n * The 3D venue view is entered from the Map/3D control, not this option. */\n initialView?: RendererViewMode;\n /**\n * Offer the interactive 3D venue view (Map | 3D toggle + a \"See it in 3D\"\n * action on the seat-confirm card). Default true. The 3D button is shown only\n * when this is not false AND the browser exposes WebGL2; there are ZERO GL\n * bytes on the wire until the buyer actually opens 3D (the OGL chunk is\n * dynamically imported on first use). Set false for embed hosts that must\n * stay strictly 2D. */\n enable3D?: boolean;\n /**\n * Seat-count ceiling above which 3D is not offered. Default: the measured-good\n * ceiling of 15,000 seats (14,142 renders at 58 fps), halved to 7,500 on a\n * device that reports itself as small/low-core.\n *\n * The 3D scene holds EVERY seat resident — there is no streaming rung yet — so\n * a 53,000-seat chart builds its scene in ~780 ms on a desktop and much worse\n * on a phone. Offering 3D there is offering a stall. A host that knows its\n * audience can raise this; the ceiling goes away when seat streaming lands. */\n max3DSeats?: number;\n /**\n * Optional analytics sink for the widget's own journey events. Currently emits\n * the 3D venue-view journey (`3d_opened`, `3d_orbit_engaged`, `3d_seat_picked`,\n * `3d_cinematic_played`/`_skipped`/`_cancelled`, `3d_panorama_opened`/`_closed`)\n * with `{ surface: 'buyer' }` merged into the props. A throwing sink never\n * breaks the widget. Route it to your product analytics (e.g. PostHog). */\n onAnalytics?: (event: string, props: Record<string, unknown>) => void;\n /**\n * Hide the \"Powered by SeatLayer\" attribution badge in the side panel foot.\n * The chart theme's own `hideBadge` flag (paid orgs) also hides it — the badge\n * is shown only when BOTH this option and the theme flag are unset/false.\n */\n hideBadge?: boolean;\n /** Host theme overrides — see SeatPickerTheme. */\n theme?: SeatPickerTheme;\n /**\n * Host-authoritative pricing. When your shop charges different prices than\n * the chart's stored category prices, pass them here so the buyer sees the\n * price they will actually pay — on the map tooltip, confirm popover, price\n * panel, tray, totals, and in the checkout handoff's line items. Keyed by\n * category key; per-tier overrides nest under `tiers`. Unlisted categories\n * fall back to the chart price.\n */\n pricing?: SeatPickerPricing;\n /** Hold TTL in ms passed to hold(); server clamps to its own limits. */\n holdTtlMs?: number;\n /**\n * An opaque hold id supplied by the host to restore after navigation. It is\n * verified against the event and active server state before anything renders\n * as owned by this buyer.\n */\n initialHoldId?: string;\n /**\n * Automatically remember the active hold id in sessionStorage and restore it\n * when this event's picker mounts again. Default true. Set false when the host\n * owns hold persistence and supplies initialHoldId itself.\n */\n restoreHold?: boolean;\n /**\n * Confirm mode: tapping a seat shows a confirmation card with section, row,\n * seat, category, price and Select/Cancel before it enters the tray. Default\n * true for the full buyer picker; set false only when the host supplies its\n * own equivalent confirmation UI.\n */\n confirmSelection?: boolean;\n /**\n * Offer a \"View from seat\" 360° preview (confirm popover + tray chips). The\n * panorama is generated from the chart geometry, or the organizer's uploaded\n * photo when a seat carries one. Default true; set false to hide the affordance.\n */\n seatView?: boolean;\n /**\n * WHERE the buyer goes once their seats are held. Default `'handoff'`.\n *\n * 'handoff' (default, and every integration that has ever existed) the\n * widget fires {@link onCheckout} with a holdId and priced line\n * items, and YOUR server takes the money. Nothing about this path\n * changes, and no payment code is even downloaded.\n * 'hosted' the widget takes the money through the gateway the ORGANIZER\n * connected, on their account — the \"sell tickets with no\n * backend\" path. Requires the org to be on hosted checkout and\n * the event to have a gateway assigned; when it does not, this\n * falls back to `'handoff'` for that buyer rather than dead-ending\n * them, and reports why through {@link onCheckoutUnavailable}.\n *\n * Named for the destination rather than as a boolean flag because there is a\n * real third answer coming and `hostedCheckout: true` would have no room for\n * it; spelling the default out also makes a host's intent legible in their own\n * source instead of hiding it in an absent option.\n *\n * TWO THINGS ARE WORTH KNOWING BEFORE YOU SWITCH THIS ON:\n *\n * 1. It needs the widget's own transport. A host-supplied `transport` owns its\n * credentials and its backend, so hosted checkout stays off there (with one\n * console warning) rather than reaching past it to api.seatlayer.io.\n * 2. WHERE A HOSTED GATEWAY RETURNS THE BUYER is settled by {@link returnUrl}\n * and by the organizer. Without one — or from an origin the organizer has\n * not declared — the buyer comes back to SeatLayer's own buyer page and is\n * confirmed THERE, not in this widget. Declare the embedding site under\n * Embed domains in the dashboard and pass `returnUrl`, and the buyer\n * returns to your page instead. In-page gateways never navigate away at\n * all, so they are unaffected either way.\n */\n checkout?: 'handoff' | 'hosted';\n /**\n * Where a redirecting gateway should send the buyer back to, for\n * `checkout: 'hosted'`.\n *\n * The server keeps this URL verbatim — path and query included — and only\n * stamps `?order=…&status=success|cancelled` onto it, so point it at\n * whichever of YOUR pages should confirm the purchase (often just\n * `window.location.href`). Mount a picker on that page and it resumes in\n * place from those parameters.\n *\n * It is validated, not trusted: the organizer declares their embed origins\n * in the dashboard, and an undeclared origin is ignored rather than\n * refused — the sale still completes, the buyer just finishes on\n * SeatLayer's page. Supplying a URL therefore cannot authorize it, which is\n * what stops a copied snippet from redirecting a paid buyer anywhere it\n * likes.\n */\n returnUrl?: string;\n /**\n * Buyer pressed the CTA and the hold succeeded — hand off to YOUR checkout.\n * `hold` and `seats` are the legacy args (unchanged since 0.6). `handoff` (P4)\n * is the stable, self-contained {@link CheckoutHandoff} to build your order\n * against — holdId, expiry, currency and priced line items. Prefer it.\n *\n * Under `checkout: 'hosted'` this fires ONLY when hosted checkout cannot run\n * for this event, so a host can keep one code path for both. It never fires\n * alongside a payment the widget is taking itself.\n */\n onCheckout?: (hold: HoldResult, seats: PickerSeat[], handoff: CheckoutHandoff) => void;\n /**\n * `checkout: 'hosted'` was asked for and this event cannot take money.\n * The seats ARE held — the buyer is mid-journey — so this is a routing\n * decision, not an error, and it is never collapsed into {@link onError}.\n *\n * `reason` carries the server's three-way answer verbatim, because two of the\n * three give opposite advice: `payments_off_for_event` means the organizer\n * deliberately does not sell this event online (nothing is wrong), while\n * `unavailable_for_event` means they switched it on and it is broken. Anything\n * unreadable — a failed lookup, an older worker — reads as `not_configured`,\n * which asserts the least about them.\n *\n * `onCheckout` fires immediately after this with the same hold. Supply either\n * (or both) and you own the next screen; supply NEITHER and the widget shows\n * the buyer an honest card of its own rather than swallowing the press.\n */\n onCheckoutUnavailable?: (event: {\n reason: PaymentOptionsReason;\n handoff: CheckoutHandoff;\n }) => void;\n /**\n * `checkout: 'hosted'` only — the gateway's webhook landed and the order is\n * PAID. The one signal a host with no backend actually needs, and the only\n * place a receipt can come from on a page that has no server of its own.\n *\n * Distinct from {@link onBooked}, which reports the same sale seen from the\n * seat map over the realtime channel and cannot fire at all for a buyer whose\n * widget was torn down by a redirect to the gateway.\n */\n onOrderConfirmed?: (order: OrderStatusResult) => void;\n /**\n * The held seats were BOOKED (P4) — your server completed payment and the\n * booking landed over the realtime channel while the widget was still open.\n * The widget shows a success state; use this to advance your own UI (receipt,\n * redirect). Fires once per hold.\n */\n onBooked?: (handoff: CheckoutHandoff) => void;\n /** Selection changed (tap or best-available). */\n onSelectionChange?: (seats: PickerSeat[]) => void;\n /**\n * Active hold changed because it was created, restored, extended, partially\n * released, or fully released. Hosts should persist this state for route\n * navigation and clear their checkout cart when `hold` becomes null.\n */\n onHoldChange?: (hold: HoldResult | null, seats: PickerSeat[], handoff: CheckoutHandoff | null) => void;\n /** The open hold expired server-side (widget already reset itself). */\n onHoldExpired?: () => void;\n /** A prior active hold was verified and restored into the tray. */\n onHoldRestored?: (hold: HoldResult, seats: PickerSeat[], handoff: CheckoutHandoff) => void;\n /** Modal only: the buyer closed the picker (ESC / scrim / ✕). */\n onClose?: () => void;\n /**\n * The buyer access session lapsed. `refreshed` says whether the provider\n * already recovered it — false means private inventory is now unavailable and\n * `onAccessUnavailable` follows. Never collapsed into `onError`: an expiry is\n * a recoverable, buyer-explainable state, not a network failure (guide §10).\n */\n onAccessExpired?: (event: BuyerAccessExpiredEvent) => void;\n /**\n * Private inventory is unavailable and refreshing will not fix it — revoked,\n * paused, wrong origin/event/mode, or the provider failed. Carries a reason,\n * never a channel name, id, colour or count. The widget shows its own\n * explanatory panel; return nothing to keep it, or handle the state yourself.\n */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /**\n * Selected-but-unheld units stopped being selectable — someone else took\n * them, or an allocation change moved them out of this buyer's scope. The\n * widget has already dropped them from the tray.\n */\n onSelectedObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n onError?: (err: unknown) => void;\n}\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container === 'string') {\n const el = document.querySelector(container);\n if (!el) throw new Error(`seatmap: container \"${container}\" not found`);\n return el as HTMLElement;\n }\n if (!(container instanceof HTMLElement)) {\n throw new Error('seatmap: container must be a CSS selector or an HTMLElement');\n }\n return container;\n}\n\nfunction escapeOption(value: unknown): string {\n return String(value ?? '').replace(/[&<>\"']/g, (character) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''',\n })[character]!);\n}\n\n// ---- 3D venue view: lazy loader + capability probe -------------------------\n\n/** The full module type for the lazy OGL venue-view chunk (`@seatlayer/core/view3d`). */\ntype Venue3DModule = typeof import('@seatlayer/core/view3d');\n\n/**\n * Injected `true` only in the CDN/IIFE build (see cdn/vite.config.ts `define`).\n * Undefined in the npm/tsup build and the vendored app copy, so the runtime-URL\n * branch below is never taken there and esbuild dead-code-eliminates it in the\n * CDN build once the constant folds to `true`.\n */\ndeclare const __SEATLAYER_CDN__: boolean | undefined;\n\n/**\n * This bundle's own URL, used only in the CDN build to locate its sibling lazy\n * chunks (`./seatlayer-view3d.mjs`, `./seatlayer-panorama.mjs`).\n * `import.meta.url` resolves to the module URL in\n * the ESM CDN output (`…/seatlayer.mjs`), and Rollup auto-shims it to a\n * `document.currentScript.src` expression in the IIFE output (`…/seatlayer.js`),\n * so both CDN formats find the chunk next to them. Guarded so no environment\n * that lacks `import.meta` throws at module init.\n */\nconst SEATLAYER_MODULE_URL: string | undefined = (() => {\n // IIFE/classic-script (CDN seatlayer.js): the tag sets document.currentScript\n // synchronously while this module's top level runs. Resolve from it first —\n // the IIFE build folds `import.meta` to `{}`, so import.meta.url is unusable\n // there anyway.\n if (typeof document !== 'undefined'\n && document.currentScript instanceof HTMLScriptElement\n && document.currentScript.src) {\n return document.currentScript.src;\n }\n // ESM (CDN seatlayer.mjs / bundlers): import.meta.url is the module URL.\n try {\n const u = import.meta.url;\n if (typeof u === 'string' && u) return u;\n } catch {\n /* no import.meta in this environment */\n }\n return undefined;\n})();\n\nlet _webgl2Cache: boolean | null = null;\n/** Whether the browser exposes WebGL2 (cached). Gates the 3D affordances. */\nfunction hasWebGL2(): boolean {\n if (_webgl2Cache !== null) return _webgl2Cache;\n try {\n if (typeof document === 'undefined') return (_webgl2Cache = false);\n const canvas = document.createElement('canvas');\n _webgl2Cache = !!canvas.getContext('webgl2');\n } catch {\n _webgl2Cache = false;\n }\n return _webgl2Cache;\n}\n\n/** Absolute URL of a sibling lazy chunk in this bundle's pinned CDN directory. */\nfunction cdnChunkUrl(fileName: string): string {\n const base = SEATLAYER_MODULE_URL ?? (typeof location !== 'undefined' ? location.href : undefined);\n if (!base) throw new Error(`seatlayer: cannot resolve the ${fileName} chunk URL`);\n return new URL(`./${fileName}`, base).href;\n}\n\n/**\n * Dynamically load the view3d module. Two build targets, one source:\n * - CDN/IIFE (cannot code-split): load the sibling ESM asset by absolute URL\n * derived from this script's own src.\n * - npm/ESM and the vendored app copy (rewritten to `../../view3d`): a bare\n * dynamic import the consumer's bundler chunk-splits automatically.\n * Either way, ZERO GL bytes are fetched until this actually runs.\n */\nasync function loadVenue3d(): Promise<Venue3DModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-view3d.mjs')) as Promise<Venue3DModule>;\n }\n return import('@seatlayer/core/view3d');\n}\n\n/** Just the generator, so the type does not drag the rest of the engine in. */\ntype PanoramaModule = Pick<typeof import('@seatlayer/core'), 'generateSeatPanorama'>;\n\n/**\n * Dynamically load the view-from-seat panorama generator, on exactly the same\n * pattern as {@link loadVenue3d}. It is ~25 KB of drawing code that runs only\n * when a buyer asks to see the view from a seat, so it stays out of the bytes\n * every buyer downloads to look at a seat map.\n *\n * Its own chunk rather than a fold into the 3D one: the 2D \"View from here\"\n * button does not enter 3D, so folding would make that tap pull the whole OGL\n * scene — 74 KB gzipped, unrunnable without WebGL2 — to draw a 2D canvas.\n *\n * On npm and in the vendored app copy this is a dynamic import of a module the\n * widget ALREADY imports statically, so every bundler resolves it out of the\n * chunk that is loaded anyway: same bytes, same behaviour, no extra request.\n */\nasync function loadPanorama(): Promise<PanoramaModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-panorama.mjs')) as Promise<PanoramaModule>;\n }\n return import('@seatlayer/core');\n}\n\n/** Just the mount function, so the type does not drag the module's DOM in. */\ntype HostedCheckoutModule = Pick<typeof import('./hostedCheckout'), 'mountCheckout'>;\n\n/**\n * Dynamically load the hosted-checkout card, on the same pattern as\n * {@link loadVenue3d} and {@link loadPanorama}, and for a stronger reason than\n * either: this is payment UI, and the overwhelming majority of buyers who load\n * a seat map never reach it. Most integrations never enable it at all —\n * `checkout` defaults to `'handoff'`, where these bytes are unreachable code.\n *\n * So there are ZERO payment bytes on the wire until a buyer presses the CTA in\n * a picker whose host opted into `checkout: 'hosted'`. Unlike the panorama\n * chunk, `./hostedCheckout` is NOT imported statically anywhere, so on npm this\n * is a genuine code split rather than a free reference into a module that was\n * loading anyway — which is exactly what we want here.\n */\nasync function loadHostedCheckout(): Promise<HostedCheckoutModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-checkout.mjs')) as Promise<HostedCheckoutModule>;\n }\n return import('./hostedCheckout');\n}\n\n/**\n * Read the wire's reason, failing to the least-accusing one.\n *\n * Anything unrecognised — a failed read, an older worker that sent nothing, a\n * newer one naming a reason this build has never heard of — becomes\n * `not_configured`, which asserts the least about the organizer. A story\n * invented from a missing field is worse than the coarse truth.\n */\nexport function paymentsOffReason(reason: string | null | undefined): PaymentOptionsReason {\n return reason === 'unavailable_for_event' || reason === 'payments_off_for_event'\n ? reason\n : 'not_configured';\n}\n\n/**\n * Widget stylesheet — injected once per document. Every color/font/radius is a\n * --sl-* token.\n *\n * The `@sl-css` marker opts this literal into build-time CSS minification (see\n * cdn/minifyCssLiterals.ts). Keep writing it long-hand and commented: the CDN\n * build strips the comments and the indentation, the source keeps them.\n */\nconst STYLE_ID = 'seatlayer-picker-style';\nconst CSS = /* @sl-css */ `\n.sl-picker{position:relative;display:flex;flex-direction:column;width:100%;height:100%;min-height:420px;overflow:hidden;\n background:var(--sl-bg);color:var(--sl-text);font-family:var(--sl-font);border-radius:var(--sl-radius);\n --sl-r-sm:calc(var(--sl-radius) * .55);\n /* Motion tokens, defined ON the widget root so an embed is self-contained and\n never inherits (or fights) the host page's own timing. Values mirror\n docs/motion-system-2026-08-01.md §2. */\n --slm-mo-instant:80ms;--slm-mo-quick:140ms;--slm-mo-base:200ms;--slm-mo-slow:320ms;\n --slm-mo-out:cubic-bezier(0.2,0.8,0.2,1);--slm-mo-exit:cubic-bezier(0.4,0,1,1)}\n.sl-picker *{box-sizing:border-box;margin:0;padding:0}\n.sl-picker button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}\n\n/* header */\n.sl-head{display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--sl-line);flex:none}\n.sl-logo{width:34px;height:34px;border-radius:9px;flex:none;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink);font-weight:800;font-size:15px;overflow:hidden}\n.sl-logo img{width:100%;height:100%;object-fit:cover;display:block}\n.sl-head-info{min-width:0;flex:1}\n.sl-head-name{font-weight:700;font-size:15px;line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-head-meta{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--sl-muted);margin-top:3px;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600}\n.sl-hold-pill{display:none;align-items:center;gap:6px;padding:6px 12px;border-radius:999px;flex:none;\n background:var(--sl-accent);color:var(--sl-accent-ink);font-weight:700;font-size:12px;font-variant-numeric:tabular-nums;\n transform-origin:right center}\n.sl-hold-pill.on{display:inline-flex;animation:slPillIn .34s cubic-bezier(.2,.8,.2,1) both}\n.sl-hold-dot{width:7px;height:7px;border-radius:50%;background:currentColor;opacity:.78;box-shadow:0 0 0 0 currentColor}\n.sl-hold-pill.is-expiring .sl-hold-dot{animation:slHoldPulse 1.4s ease-out infinite}\n.sl-hold-time{min-width:3.35em;text-align:left}\n.sl-close{width:32px;height:32px;border-radius:999px;flex:none;display:none;align-items:center;justify-content:center;\n border:1px solid var(--sl-line);color:var(--sl-muted);transition:color .15s,border-color .15s}\n.sl-close:hover{color:var(--sl-text);border-color:var(--sl-muted)}\n.sl-close.on{display:inline-flex}\n.sl-close svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round}\n\n/* body */\n.sl-body{display:flex;flex:1;min-height:0}\n.sl-map{position:relative;flex:1;min-width:0}\n.sl-map-host{position:absolute;inset:0}\n.sl-side{width:300px;flex:none;border-left:1px solid var(--sl-line);display:flex;flex-direction:column;min-height:0;overflow:hidden}\n\n/* narrow (container < 640px): map-first — the map claims ~80-85% of the\n container and the side panel becomes a PEEKING bottom sheet (AXS/Ticketmaster\n mobile pattern). data-sheet on the root: \"peek\" (default: grab handle + one\n summary line) / \"open\" (room for rows + checkout, swipe up to open).\n Swipe handling lives on the sheet head ONLY — never the map host, so the\n map's raw-pointer gesture pipeline is untouched. */\n.sl-picker[data-layout=\"narrow\"] .sl-body{flex-direction:column}\n.sl-picker[data-layout=\"narrow\"] .sl-map{min-height:0;flex:1}\n.sl-picker[data-layout=\"narrow\"] .sl-side{width:100%;border-left:0;border-top:1px solid var(--sl-line);\n flex:none;height:min(72%,480px);overflow:hidden;transition:height .3s cubic-bezier(.2,.8,.2,1);overscroll-behavior:contain}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"][data-has-selection=\"false\"] .sl-side{height:min(252px,52%)}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"peek\"] .sl-side{height:86px;overflow:hidden}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"peek\"] .sl-side > :not(.sl-sheet-head){display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-tray{flex:1;min-height:0;overflow-y:auto;overscroll-behavior:contain}\n.sl-picker[data-layout=\"narrow\"] .sl-foot{position:static;background:var(--sl-bg)}\n.sl-picker[data-layout=\"narrow\"] .sl-foot.empty{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-sheet-head{order:0}\n.sl-picker[data-layout=\"narrow\"] .sl-seats-sec{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-tray{order:2}\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec{order:3}\n.sl-picker[data-layout=\"narrow\"] .sl-filters{order:4}\n.sl-picker[data-layout=\"narrow\"] .sl-prices-sec{order:5}\n.sl-picker[data-layout=\"narrow\"] .sl-pricef{order:6}\n.sl-picker[data-layout=\"narrow\"] .sl-prices{order:7}\n.sl-picker[data-layout=\"narrow\"] .sl-foot{order:8}\n.sl-picker[data-layout=\"narrow\"] .sl-tray-hint,\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec,\n.sl-picker[data-layout=\"narrow\"] .sl-filters,\n.sl-picker[data-layout=\"narrow\"] .sl-prices-sec,\n.sl-picker[data-layout=\"narrow\"] .sl-prices{display:none!important}\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filtersec,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filters,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-prices-sec{display:none}\n/* Reclaim the bottom sheet once the cart has anything: the \"Find best seats\"\n panel collapses too. EXCEPT the confirm (\"Replace your current choices?\") and\n in-flight busy states, which legitimately show with a non-empty cart — those\n set data-ba-active=\"true\" (see setAttribute alongside data-has-selection). */\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"]:not([data-ba-active=\"true\"]) .sl-ba{display:none}\n/* touch chrome: pinch-zoom exists — hide +/− on the sheet layout (keep fit) */\n.sl-picker[data-layout=\"narrow\"] .sl-zoom [data-ref=\"zin\"],\n.sl-picker[data-layout=\"narrow\"] .sl-zoom [data-ref=\"zout\"]{display:none}\n\n/* bottom-sheet head: grab handle + one-line summary (narrow only). The WHOLE\n head is the tap/swipe toggle target (min 44px), so it reads as one control. */\n.sl-sheet-head{display:none;flex-direction:column;justify-content:center;padding:6px 12px 8px;min-height:56px;\n cursor:pointer;touch-action:none;user-select:none;-webkit-user-select:none;flex:none}\n.sl-picker[data-layout=\"narrow\"] .sl-sheet-head{display:flex}\n.sl-sheet-grab{width:36px;height:4px;border-radius:999px;background:var(--sl-muted);opacity:.55;margin:2px auto 7px}\n.sl-sheet-bar{display:flex;align-items:center;gap:10px;min-height:26px}\n.sl-sheet-peek{display:flex;align-items:center;gap:7px;flex:1;min-width:0;font-size:13px;font-weight:700;color:var(--sl-text);\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-sheet-peek .sub{color:var(--sl-muted);font-weight:600}\n/* collapsed-peek \"Continue\" affordance: a real accent pill, not plain text */\n.sl-sheet-peek .go{margin-left:auto;flex:none;display:inline-flex;align-items:center;min-height:30px;\n padding:6px 13px;border-radius:999px;background:var(--sl-accent);color:var(--sl-accent-ink);\n font-weight:800;font-size:12.5px}\n/* state chevron: points UP while peeking, rotates to point DOWN when open.\n Base keeps an explicit rotate(0) — transitioning to/from a bare 'none' leaves\n the value stuck in some engines, so both endpoints must be real transforms. */\n.sl-sheet-toggle{width:44px;height:44px;margin:-8px -8px -8px 0;border-radius:999px;flex:none;display:flex;\n align-items:center;justify-content:center;color:var(--sl-muted);transition:color .15s,background .15s}\n.sl-sheet-toggle:hover,.sl-sheet-toggle:focus-visible{color:var(--sl-text);background:color-mix(in srgb,var(--sl-line) 44%,transparent)}\n.sl-sheet-toggle svg{width:21px;height:21px;stroke:currentColor;stroke-width:2.4;fill:none;\n stroke-linecap:round;stroke-linejoin:round}\n.sl-sheet-toggle svg{transform:rotate(0deg);transition:transform .24s cubic-bezier(.2,.8,.2,1)}\n.sl-picker[data-sheet=\"open\"] .sl-sheet-toggle svg{transform:rotate(180deg)}\n\n/* consolidated Filters row inside the sheet (a11y chips + colorblind toggle\n dock here on narrow; they live on the map / zoom column on wide) */\n.sl-filtersec{display:none}\n.sl-filters{display:none;gap:6px;flex-wrap:wrap;align-items:center;padding:2px 16px 10px}\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec.has,\n.sl-picker[data-layout=\"narrow\"] .sl-filters.has{display:none}\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filtersec.has,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filters.has{display:none}\n/* Accessibility and colour-safety controls must remain reachable on phones.\n Keep them out of the 86px peek, then reveal their consolidated row whenever\n the buyer explicitly opens the ticket panel. */\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"] .sl-filtersec.has{display:block!important}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"] .sl-filters.has{display:flex!important}\n.sl-cbbtn{width:32px;height:32px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-cbbtn:hover{border-color:var(--sl-muted)}\n.sl-cbbtn svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* price panel — one compact filter control replaces the wrapping price-chip row. */\n.sl-sec{padding:14px 14px 4px;font-size:9.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--sl-muted);font-weight:700}\n.sl-prices-sec{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:13px}\n.sl-price-select{min-height:32px;max-width:130px;padding:5px 28px 5px 9px;border:1px solid var(--sl-line);border-radius:9px;\n background:var(--sl-surface);color:var(--sl-text);font:inherit;font-size:11px;font-weight:750;letter-spacing:0;text-transform:none}\n.sl-prices{display:flex;flex-direction:column;padding:4px 14px 8px;border-bottom:1px solid var(--sl-line)}\n.sl-prices-sec,.sl-prices,.sl-seats-sec{flex:none}\n.sl-price-row{display:flex;align-items:center;gap:7px;min-height:28px;font-size:12px;\n padding:0 6px;margin:0 -6px;border-radius:8px;cursor:pointer;transition:background .15s}\n.sl-price-row:hover,.sl-price-row:focus-visible{background:color-mix(in srgb,var(--sl-line) 40%,transparent)}\n.sl-price-row.sl-active{background:color-mix(in srgb,var(--sl-accent) 9%,transparent)}\n.sl-price-row.sl-active .sl-price-label{color:var(--sl-accent)}\n.sl-dot{width:9px;height:9px;border-radius:50%;flex:none}\n.sl-price-label{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600}\n.sl-price-left{font-size:11px;color:var(--sl-muted);font-variant-numeric:tabular-nums}\n.sl-price-amt{font-weight:800;font-variant-numeric:tabular-nums}\n/* long category lists: capped by default, scroll once expanded */\n.sl-prices.sl-expanded{max-height:196px;overflow-y:auto;overscroll-behavior:contain;scrollbar-gutter:stable}\n.sl-price-more{display:flex;align-items:center;min-height:26px;padding:0;\n color:var(--sl-muted);font-size:11px;font-weight:750;transition:color .15s}\n.sl-price-more:hover,.sl-price-more:focus-visible{color:var(--sl-text)}\n/* held/sold key — one quiet caption line; the map itself teaches these states */\n.sl-status-key{display:flex;gap:11px;flex-wrap:wrap;padding:5px 0 0;margin-top:4px;border-top:1px solid var(--sl-line);color:var(--sl-muted);font-size:10px}\n.sl-status-item{display:inline-flex;align-items:center;gap:5px}\n.sl-status-icon{width:13px;height:13px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;\n color:#fff;background:#6b7280;line-height:1}\n.sl-status-icon svg{width:8px;height:8px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-status-icon.sold{background:#8b93a0}\n.sl-status-icon.sold svg{width:9px;height:9px;stroke-width:2.4}\n\n/* tray */\n.sl-seats-sec{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:13px}\n.sl-seat-summary{font-size:10px;letter-spacing:0;text-transform:none;white-space:nowrap}\n.sl-tray{flex:1;padding:10px 14px 14px;display:flex;flex-direction:column;gap:7px;min-height:0;overflow-y:auto;\n overscroll-behavior:contain;scrollbar-gutter:stable}\n.sl-tray-hint{font-size:12.5px;color:var(--sl-muted);line-height:1.5}\n.sl-chip{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 34px;align-items:stretch;\n flex:none;min-height:53px;border:1px solid var(--sl-line);border-radius:var(--sl-r-sm);overflow:hidden;\n background:var(--sl-surface);font-size:13px;transform-origin:center;transition:border-color .15s,background .15s}\n.sl-chip:hover{border-color:color-mix(in srgb,var(--sl-accent) 38%,var(--sl-line))}\n.sl-chip.sl-enter{animation:slChipIn .38s cubic-bezier(.2,.8,.2,1) both}\n.sl-chip.sl-leave{pointer-events:none;animation:slChipOut .16s ease-in both}\n.sl-chip.sl-held{border-color:var(--sl-line);background:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-surface));\n box-shadow:inset 3px 0 0 color-mix(in srgb,var(--sl-accent) 72%,transparent)}\n.sl-ticket-state{width:17px;height:17px;border-radius:999px;flex:none;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-ticket-state.held{background:color-mix(in srgb,var(--sl-accent) 18%,var(--sl-surface));color:var(--sl-accent)}\n.sl-ticket-state svg{width:10px;height:10px;stroke:currentColor;stroke-width:2.6;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-chip-main{min-width:0;padding:8px 10px 8px 11px;display:flex;flex-direction:column;justify-content:center;gap:5px}\n.sl-chip-id{display:flex;gap:12px;min-width:0}\n.sl-chip-id .fld{min-width:0}\n.sl-chip-id .fld.sec{flex:1}\n.sl-chip-id .fld.mid{flex:none;text-align:center}\n.sl-chip-eb{display:block;font-size:8px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);margin-bottom:1px}\n.sl-chip-id .val{display:block;font-weight:600;font-size:13px;line-height:1.25;white-space:nowrap}\n.sl-chip-id .fld.sec .val{overflow:hidden;text-overflow:ellipsis}\n.sl-chip-sub{display:flex;align-items:center;gap:6px;min-width:0}\n.sl-chip .cat{color:var(--sl-muted);font-size:10.5px;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-chip .amt{font-weight:700;font-variant-numeric:tabular-nums;flex:none;white-space:nowrap}\n.sl-chip-rail{display:flex;flex-direction:column;border-left:1px solid var(--sl-line)}\n.sl-chip .rm,.sl-chip .view{flex:1;min-height:26px;border-radius:0;display:flex;align-items:center;justify-content:center;\n color:var(--sl-muted);transition:color .15s,background .15s}\n.sl-chip .view{border-top:1px solid var(--sl-line)}\n.sl-chip .rm:hover,.sl-chip .rm:focus-visible{color:#e5484d;background:color-mix(in srgb,#e5484d 9%,transparent)}\n.sl-chip .view:hover,.sl-chip .view:focus-visible{color:var(--sl-text);background:color-mix(in srgb,var(--sl-accent) 10%,transparent)}\n.sl-chip .rm svg{width:11px;height:11px;stroke:currentColor;stroke-width:2.4;fill:none;stroke-linecap:round}\n.sl-chip .view svg{width:13px;height:13px;stroke:currentColor;stroke-width:1.8;fill:none}\n/* live-activity strip — narrates WS availability deltas (social proof + urgency).\n Hidden until a delta actually happens: a static \"seats update in real time\"\n banner is dead vertical space, a \"2 seats just taken\" flash is a signal. */\n.sl-live{display:none;align-items:center;gap:7px;margin:10px 14px 0;padding:7px 9px;flex:none;\n border:1px solid var(--sl-line);border-radius:8px;background:color-mix(in srgb,var(--sl-accent) 4%,var(--sl-surface));\n font-size:11px;color:var(--sl-muted)}\n.sl-live .dot{width:6px;height:6px;border-radius:999px;background:#22a06b;box-shadow:0 0 6px rgba(34,160,107,.75);flex:none}\n.sl-live span:last-child{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-live.on{display:flex;animation:slNoticeIn .38s cubic-bezier(.2,.8,.2,1) both}\n\n/* GA rows */\n.sl-ga{display:flex;align-items:center;gap:10px;padding:9px 11px;border:1px dashed var(--sl-line);border-radius:var(--sl-r-sm)}\n.sl-ga-info{flex:1;min-width:0}\n.sl-ga-name{font-weight:700;font-size:13px}\n.sl-ga-sub{font-size:11px;color:var(--sl-muted);margin-top:2px}\n.sl-ga-qty{display:flex;align-items:center;gap:8px}\n.sl-ga-qty button{width:26px;height:26px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n font-size:15px;font-weight:700;display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-ga-qty button:hover{border-color:var(--sl-muted)}\n.sl-ga-qty span{min-width:16px;text-align:center;font-weight:800;font-variant-numeric:tabular-nums}\n\n/* footer */\n.sl-foot{position:relative;z-index:2;padding:12px 16px 14px;border-top:1px solid var(--sl-line);flex:none;\n background:var(--sl-bg);box-shadow:0 -10px 24px -22px rgba(0,0,0,.72)}\n.sl-hold-note{display:none;align-items:center;gap:7px;margin-bottom:8px;padding:7px 8px;border-radius:var(--sl-r-sm);\n border:1px solid var(--sl-line);background:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-surface));\n box-shadow:inset 3px 0 0 color-mix(in srgb,var(--sl-accent) 72%,transparent);\n font-size:11.5px;line-height:1.35;color:var(--sl-muted)}\n.sl-hold-note.on{display:flex;animation:slNoticeIn .38s cubic-bezier(.2,.8,.2,1) both}\n.sl-hold-note svg{width:16px;height:16px;flex:none;stroke:var(--sl-accent);stroke-width:2.4;fill:none;\n stroke-linecap:round;stroke-linejoin:round}\n.sl-hold-note b{display:block;color:var(--sl-text);font-size:11.5px;white-space:nowrap}\n.sl-hold-copy{display:block;white-space:nowrap;font-size:10.5px}\n.sl-hold-note>span{flex:1;min-width:0}\n.sl-hold-change{flex:none;min-height:30px;padding:5px 8px;border-radius:8px;border:1px solid var(--sl-line);\n color:var(--sl-text);font-size:10.5px;font-weight:750;white-space:nowrap}\n.sl-hold-change:hover,.sl-hold-change:focus-visible{border-color:var(--sl-accent);color:var(--sl-accent)}\n.sl-hold-change:disabled{opacity:.58;cursor:wait}\n.sl-total{display:flex;justify-content:space-between;align-items:center;font-size:13px;margin-bottom:10px}\n.sl-total b{font-size:17px;font-variant-numeric:tabular-nums}\n.sl-value-pop{animation:slValuePop .32s cubic-bezier(.2,.8,.2,1)}\n/* Primary checkout CTA. Scoped under .sl-picker so it OUTWEIGHS the\n '.sl-picker button' reset (0,1,1) — an unscoped '.sl-cta' (0,1,0) loses to it\n and the button renders as plain text with no accent fill. */\n.sl-picker .sl-cta{display:flex;align-items:center;justify-content:center;width:100%;min-height:44px;\n padding:12px 16px;border-radius:var(--sl-r-sm);font-weight:800;font-size:14px;line-height:1.1;\n background:var(--sl-accent);color:var(--sl-accent-ink);\n transition:filter .15s,background .22s,color .22s,transform .12s,box-shadow .22s;gap:8px}\n.sl-picker .sl-cta:hover{filter:brightness(1.08)}\n.sl-picker .sl-cta:active{transform:translateY(1px);filter:brightness(.94)}\n.sl-picker .sl-cta.sl-ready{animation:slCtaReady .42s cubic-bezier(.2,.8,.2,1)}\n.sl-cta-spin,.sl-ba-spin{width:14px;height:14px;border-radius:50%;border:2px solid currentColor;border-right-color:transparent;\n animation:slspin .7s linear infinite;flex:none}\n/* Disabled (\"Select seats\"): quieter, but still a full-width button shape. */\n.sl-picker .sl-cta:disabled{background:var(--sl-surface);color:var(--sl-muted);opacity:1;\n cursor:not-allowed;filter:none;transform:none}\n\n/* Chrome anchor regions (Feature 6) — every persistent map overlay is APPENDED\n INTO one of these positioned flex containers and flows/stacks within it, so no\n two pieces of chrome free-float on top of each other. Regions never overlap:\n the top strip splits into left/center/right; rails + corners own their edge. */\n.sl-anchor{position:absolute;z-index:5;display:flex;gap:8px;pointer-events:none}\n.sl-anchor > *{pointer-events:auto}\n.sl-anchor[data-region=\"top-left\"]{top:12px;left:12px;flex-wrap:wrap;max-width:38%}\n.sl-anchor[data-region=\"top-center\"]{top:12px;left:50%;transform:translateX(-50%);flex-direction:column;\n align-items:center;max-width:44%}\n.sl-anchor[data-region=\"top-right\"]{top:12px;right:12px;justify-content:flex-end;flex-wrap:wrap;max-width:38%}\n.sl-anchor[data-region=\"left-rail\"]{top:50%;left:12px;transform:translateY(-50%);flex-direction:column;max-width:42%;gap:6px}\n.sl-anchor[data-region=\"bottom-left\"]{left:12px;bottom:12px;flex-direction:column;align-items:flex-start}\n.sl-anchor[data-region=\"bottom-center\"]{left:50%;bottom:14px;transform:translateX(-50%);z-index:9;\n flex-direction:column;align-items:center;gap:8px;max-width:92%}\n.sl-anchor[data-region=\"bottom-right\"]{right:12px;bottom:12px;flex-direction:column;align-items:flex-end;gap:6px}\n/* narrow: tighten the top strip so left/center can't crowd each other */\n.sl-picker[data-layout=\"narrow\"] .sl-anchor[data-region=\"top-left\"]{max-width:30%}\n.sl-picker[data-layout=\"narrow\"] .sl-anchor[data-region=\"top-center\"]{max-width:44%}\n\n/* TEST MODE badge — a small pill in the top-right region (shrinks on narrow) */\n.sl-testbadge{padding:5px 11px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.1em;\n text-transform:uppercase;white-space:nowrap;background:var(--sl-accent);color:var(--sl-accent-ink);\n box-shadow:0 2px 8px rgba(0,0,0,.25)}\n.sl-picker[data-layout=\"narrow\"] .sl-testbadge{padding:3px 8px;font-size:8.5px;letter-spacing:.06em}\n\n/* zoom column (flows within the bottom-right region) */\n.sl-zoom{display:flex;flex-direction:column;gap:6px}\n/* CSS-fallback full screen (iOS Safari has no element fullscreen API) */\n.sl-picker.sl-fs{position:fixed;inset:0;z-index:2147483000;width:auto;height:auto;max-height:none;border-radius:0}\n.sl-zoom button{width:36px;height:36px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);font-size:17px;font-weight:700;display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-zoom button:hover{border-color:var(--sl-muted)}\n.sl-zoom svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* toast + boot states (toast flows in the bottom-center region) */\n.sl-toast{transform:translateY(6px) scale(.98);max-width:100%;\n background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-text);border-radius:999px;padding:9px 16px;\n font-size:12.5px;font-weight:600;opacity:0;pointer-events:none;transition:opacity .22s,transform .22s;white-space:nowrap;\n overflow:hidden;text-overflow:ellipsis}\n.sl-toast.on{opacity:1;transform:translateY(0) scale(1)}\n.sl-toast.has-action{pointer-events:auto;display:flex;align-items:center;gap:12px;padding-right:8px}\n.sl-toast-action{min-height:30px;padding:5px 10px;border-radius:999px;background:var(--sl-accent);color:var(--sl-accent-ink);\n font:inherit;font-weight:800}\n.sl-toast[data-tone=\"error\"]{border-color:#ef4444}\n.sl-toast[data-tone=\"warning\"]{border-color:var(--sl-accent)}\n.sl-toast[data-tone=\"success\"]{border-color:#22c55e}\n.sl-toast.on[data-tone=\"error\"]{animation:slToastNudge .32s ease-out}\n.sl-boot{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;align-items:center;justify-content:center;\n gap:10px;background:var(--sl-bg);font-size:13px;font-weight:600;color:var(--sl-muted)}\n.sl-boot-spin{width:24px;height:24px;border-radius:50%;border:3px solid var(--sl-line);border-top-color:var(--sl-accent);\n animation:slspin .8s linear infinite}\n@keyframes slspin{to{transform:rotate(360deg)}}\n.sl-boot-title{font-weight:800;font-size:15px;color:var(--sl-text)}\n.sl-boot-retry{margin-top:4px;padding:9px 20px;border-radius:var(--sl-r-sm);background:var(--sl-accent);\n color:var(--sl-accent-ink);font-weight:700;font-size:13px}\n\n/* \"Need more time?\" extend prompt (flows in the bottom-center region, above the toast) */\n.sl-extend{transform:translateY(6px);\n display:none;align-items:center;gap:12px;max-width:100%;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);border-radius:14px;padding:10px 12px 10px 16px;box-shadow:0 18px 50px -18px rgba(0,0,0,.6);\n opacity:0;transition:opacity .2s,transform .2s}\n.sl-extend.on{display:flex;opacity:1;transform:translateY(0)}\n.sl-extend-txt{font-size:12.5px;font-weight:600;line-height:1.35}\n.sl-extend-txt b{font-variant-numeric:tabular-nums}\n.sl-extend-btn{flex:none;padding:8px 14px;border-radius:999px;font-weight:800;font-size:12.5px;\n background:var(--sl-accent);color:var(--sl-accent-ink);transition:filter .15s,opacity .15s}\n.sl-extend-btn:hover{filter:brightness(1.08)}\n.sl-extend-btn:disabled{opacity:.5;cursor:not-allowed}\n\n/* booked confirmation overlay (covers the widget once the held seats are sold) */\n.sl-booked{position:absolute;inset:0;z-index:11;display:flex;flex-direction:column;align-items:center;\n justify-content:center;gap:12px;text-align:center;padding:28px;background:var(--sl-bg);opacity:0;visibility:hidden;\n pointer-events:none;transition:opacity .34s ease,visibility 0s linear .34s}\n.sl-booked.on{opacity:1;visibility:visible;pointer-events:auto;transition:opacity .34s ease,visibility 0s}\n.sl-booked-badge{width:60px;height:60px;border-radius:999px;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink);transform:scale(.72)}\n.sl-booked.on .sl-booked-badge{animation:slSuccessPop .58s cubic-bezier(.2,1.25,.3,1) .08s both}\n.sl-booked-badge svg{width:30px;height:30px;stroke:currentColor;stroke-width:2.6;fill:none;stroke-linecap:round;stroke-linejoin:round;\n stroke-dasharray:30;stroke-dashoffset:30}\n.sl-booked.on .sl-booked-badge svg{animation:slCheckDraw .42s ease-out .32s forwards}\n.sl-booked-title{font-weight:800;font-size:19px;color:var(--sl-text)}\n.sl-booked-sub{font-size:13px;color:var(--sl-muted);line-height:1.5;max-width:320px}\n.sl-booked-seats{font-weight:700;color:var(--sl-text)}\n.sl-booked.on .sl-booked-title,.sl-booked.on .sl-booked-sub{animation:slCopyRise .42s ease-out both}\n.sl-booked.on .sl-booked-title{animation-delay:.22s}\n.sl-booked.on .sl-booked-sub{animation-delay:.3s}\n\n/* sold-out overlay — every SEATED category's live availability is 0. Centered\n over the map; a stub (disabled) \"Join waitlist\" button, exactly like the page.\n Suppressed when GA areas exist (GA capacity isn't seat-counted). Clears live\n the moment WS frees a seat up. */\n.sl-soldout{position:absolute;inset:0;z-index:10;display:none;flex-direction:column;align-items:center;\n justify-content:center;text-align:center;gap:8px;padding:24px;\n background:color-mix(in srgb,var(--sl-bg) 82%,transparent);backdrop-filter:blur(4px)}\n.sl-soldout.on{display:flex}\n.sl-soldout-eyebrow{font-size:10px;letter-spacing:.2em;text-transform:uppercase;color:var(--sl-accent);font-weight:800}\n.sl-soldout-title{font-size:32px;font-weight:800;color:var(--sl-text);line-height:1.05}\n.sl-soldout-copy{max-width:360px;font-size:13px;color:var(--sl-muted);line-height:1.5}\n.sl-picker .sl-soldout-btn{margin-top:10px;min-height:40px;padding:10px 18px;border-radius:var(--sl-r-sm);\n background:var(--sl-surface);color:var(--sl-muted);border:1px solid var(--sl-line);font-weight:800;font-size:13px;\n cursor:not-allowed;opacity:.85}\n\n/* sales-closed pill (header) — persistent read-only state when the event's sales\n window is closed at load or closes live mid-session. Neutral (not accent) so it\n reads as \"unavailable\", distinct from the accent hold pill next to it. */\n.sl-closed-pill{display:none;align-items:center;gap:6px;padding:6px 12px;border-radius:999px;flex:none;\n background:color-mix(in srgb,var(--sl-text) 12%,var(--sl-surface));color:var(--sl-text);\n font-weight:700;font-size:12px;white-space:nowrap}\n.sl-closed-pill.on{display:inline-flex}\n.sl-closed-pill svg{width:13px;height:13px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* \"Powered by SeatLayer\" attribution badge (side-panel foot) — the canonical\n Layered Rows mark + wordmark. Hidden when the host opts out or the org's paid\n theme sets hideBadge. */\n.sl-powered{display:flex;align-items:center;justify-content:center;gap:6px;margin-top:10px;\n font-size:11px;letter-spacing:.03em;color:var(--sl-muted)}\n.sl-powered-mark{width:16px;height:16px;border-radius:4px;flex:none;display:flex;align-items:center;justify-content:center;\n background:#0c1220;color:#fcf7ee}\n.sl-powered-mark svg{width:12px;height:11px}\n\n/* a11y filter chips (flow within the top-left region) */\n.sl-chips{display:flex;gap:6px;flex-wrap:wrap}\n.sl-chip-f{display:inline-flex;align-items:center;gap:6px;padding:7px 12px;border-radius:999px;font-size:12px;font-weight:700;\n background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted);transition:color .15s,border-color .15s}\n.sl-chip-f:hover{color:var(--sl-text)}\n.sl-chip-f.on{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n\n/* confirm card: a candidate is not in the tray until Select. Map gestures and\n floating chrome pause while the card owns focus, keeping the camera stable. */\n.sl-picker[data-confirming=\"true\"] .sl-map-host>:not(.sl-confirm){pointer-events:none}\n.sl-picker[data-confirming=\"true\"] .sl-anchor{pointer-events:none;opacity:.28;transition:opacity .16s}\n.sl-picker[data-confirming=\"true\"] .sl-side{pointer-events:none;opacity:.58;transition:opacity .16s}\n.sl-confirm{position:absolute;z-index:10;width:276px;max-width:calc(100% - 24px);overflow:hidden;pointer-events:auto;\n background:var(--sl-surface);border:1px solid color-mix(in srgb,var(--sl-line) 70%,var(--sl-text));\n border-radius:15px;box-shadow:0 24px 64px -18px rgba(0,0,0,.72);transform:translate(-50%,calc(-100% - 16px));\n animation:slConfirmIn .24s cubic-bezier(.2,.8,.2,1) both}\n.sl-confirm[data-placement=\"below\"]{transform:translate(-50%,16px);animation:slConfirmBelowIn .24s cubic-bezier(.2,.8,.2,1) both}\n.sl-confirm-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(52px,auto) minmax(52px,auto);border-bottom:1px solid var(--sl-line)}\n.sl-confirm-field{min-width:0;padding:12px 11px 10px;border-right:1px solid var(--sl-line)}\n.sl-confirm-field:last-child{border-right:0;text-align:center}\n.sl-confirm-field:nth-child(2){text-align:center}\n.sl-confirm-key{display:block;font-size:8.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-confirm-value{display:block;margin-top:4px;color:var(--sl-text);font-size:17px;line-height:1.1;font-weight:850;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n/* Long venue section names must read in full: smaller type + up to two lines\n beats an ellipsis at identity-confirmation time. Row/seat stay big — they're\n short and they're what the buyer double-checks against the map. */\n.sl-confirm-field:first-child .sl-confirm-value{font-size:13.5px;line-height:1.25;white-space:normal;\n display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}\n.sl-confirm-cat{display:flex;align-items:center;gap:8px;padding:10px 12px;background:color-mix(in srgb,var(--sl-cat) 76%,var(--sl-surface))}\n.sl-confirm-cat .sl-dot{border:2px solid rgba(255,255,255,.78);width:11px;height:11px}\n.sl-confirm-cat-name{font-size:13.5px;font-weight:800;color:#fff;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-confirm-price{font-size:17px;font-weight:850;color:#fff;font-variant-numeric:tabular-nums}\n.sl-confirm-body{padding:11px 12px 12px}\n.sl-confirm-row{display:flex;gap:8px;margin-top:10px}\n.sl-confirm-row button{flex:1;min-height:44px;padding:9px 12px;border-radius:9px;font-weight:800;font-size:13px}\n.sl-confirm-add{background:var(--sl-accent)!important;color:var(--sl-accent-ink)!important;display:flex;align-items:center;justify-content:center;gap:7px}\n.sl-confirm-add svg{width:16px;height:16px;stroke:currentColor;stroke-width:2.8;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-confirm-cancel{background:color-mix(in srgb,var(--sl-line) 44%,transparent)!important;border:1px solid var(--sl-line)!important;color:var(--sl-muted)!important}\n.sl-confirm-cancel:hover{color:var(--sl-text)}\n.sl-picker[data-layout=\"narrow\"] .sl-confirm{left:50%!important;top:auto!important;bottom:14px;width:min(342px,calc(100% - 24px));\n transform:translateX(-50%);animation:slConfirmMobileIn .24s cubic-bezier(.2,.8,.2,1) both}\n\n/* Atomic whole/variable-table chooser. Lives inside the widget so the same\n accessible dialog works in inline, modal, desktop and 390px mobile hosts. */\n.sl-table-scrim{position:absolute;inset:0;z-index:45;display:flex;align-items:center;justify-content:center;padding:18px;\n background:color-mix(in srgb,var(--sl-bg) 66%,transparent);backdrop-filter:blur(3px)}\n.sl-table-dialog{width:min(408px,100%);max-height:calc(100% - 24px);overflow:auto;border:1px solid var(--sl-line);\n border-radius:calc(var(--sl-radius) * 1.15);background:var(--sl-surface);box-shadow:0 28px 70px rgba(0,0,0,.42)}\n.sl-table-head{padding:18px 18px 14px;border-bottom:1px solid var(--sl-line)}\n.sl-table-eyebrow{font-size:10px;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-table-title{margin-top:5px;font-size:22px;line-height:1.15;font-weight:850}\n.sl-table-copy{margin-top:7px;color:var(--sl-muted);font-size:13px;line-height:1.45}\n.sl-table-body{padding:16px 18px 18px}\n.sl-table-summary{display:grid;grid-template-columns:1fr auto;gap:8px 16px;padding:12px;border:1px solid var(--sl-line);\n border-radius:var(--sl-r-sm);background:color-mix(in srgb,var(--sl-line) 22%,transparent);font-size:13px}\n.sl-table-summary b{font-size:15px}.sl-table-summary .muted{color:var(--sl-muted)}\n.sl-table-qtylabel{display:block;margin:16px 0 8px;font-size:12px;font-weight:800}\n.sl-table-stepper{display:grid;grid-template-columns:48px 1fr 48px;align-items:center;border:1px solid var(--sl-line);\n border-radius:12px;overflow:hidden;background:var(--sl-bg)}\n.sl-table-stepper button{height:48px;font-size:24px;font-weight:700;background:color-mix(in srgb,var(--sl-line) 34%,transparent)!important}\n.sl-table-stepper button:disabled{opacity:.38;cursor:not-allowed}\n.sl-table-stepper output{text-align:center;font-size:19px;font-weight:850;font-variant-numeric:tabular-nums}\n.sl-table-range{margin-top:7px;color:var(--sl-muted);font-size:11px;text-align:center}\n.sl-table-actions{display:flex;gap:9px;margin-top:17px}.sl-table-actions button{flex:1;min-height:46px;border-radius:10px;font-weight:800}\n.sl-table-cancel{border:1px solid var(--sl-line)!important;color:var(--sl-muted)!important}\n.sl-table-confirm{background:var(--sl-accent)!important;color:var(--sl-accent-ink)!important}\n.sl-table-confirm:disabled{opacity:.62;cursor:wait}\n.sl-table-edit{margin-left:4px;padding:2px 7px!important;border:1px solid var(--sl-line)!important;border-radius:999px!important;\n color:var(--sl-muted)!important;font-size:10px!important;font-weight:800!important}\n.sl-picker[data-layout=\"narrow\"] .sl-table-scrim{align-items:flex-end;padding:0;background:rgba(5,7,12,.58)}\n.sl-picker[data-layout=\"narrow\"] .sl-table-dialog{width:100%;max-height:min(78%,620px);border-radius:18px 18px 0 0;border-width:1px 0 0}\n.sl-picker[data-layout=\"narrow\"] .sl-table-head{padding-top:22px}.sl-picker[data-layout=\"narrow\"] .sl-table-body{padding-bottom:max(20px,env(safe-area-inset-bottom))}\n\n/* hover preview — a COMPACT echo of the confirm card (deliberately smaller: it's\n a passing preview on hover, not the click/select action surface). Reuses the\n Section·Row·Seat identity grid so hover, confirm and the cart chip all share\n one visual language, just at three sizes. */\n.sl-tip{position:absolute;z-index:7;pointer-events:none;display:none;width:190px;overflow:hidden;\n background:var(--sl-surface);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:11px;\n box-shadow:0 12px 30px -14px rgba(0,0,0,.6)}\n.sl-tip-grid{display:grid;grid-template-columns:1.3fr .85fr .85fr;border-bottom:1px solid var(--sl-line)}\n.sl-tip-grid.one{grid-template-columns:1fr}\n.sl-tip-field{min-width:0;padding:6px 9px;border-right:1px solid var(--sl-line)}\n.sl-tip-field:last-child{border-right:0;text-align:center}\n.sl-tip-grid:not(.one) .sl-tip-field:nth-child(2){text-align:center}\n.sl-tip-key{display:block;font-size:7.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-tip-val{display:block;margin-top:2px;color:var(--sl-text);font-size:13px;line-height:1.1;font-weight:750;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-tip-cat{display:flex;align-items:center;gap:7px;padding:6px 10px;font-size:11px;\n background:color-mix(in srgb,var(--sl-cat) 12%,var(--sl-surface))}\n.sl-tip-dot{width:8px;height:8px;border-radius:50%;flex:none}\n.sl-tip-name{color:var(--sl-muted);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-tip-amt{margin-left:auto;font-weight:800;color:var(--sl-text);font-variant-numeric:tabular-nums;font-size:12px}\n.sl-tip-status{padding:5px 10px 7px;font-size:8.5px;letter-spacing:.09em;text-transform:uppercase;font-weight:700;color:var(--sl-muted)}\n\n/* Best available is a first-class shortcut, not an anonymous utility row. */\n.sl-ba{position:relative;flex:none;overflow:hidden;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:7px;\n padding:13px;border:1px solid color-mix(in srgb,var(--sl-accent) 34%,var(--sl-line));border-radius:13px;\n background:linear-gradient(135deg,color-mix(in srgb,var(--sl-accent) 5%,var(--sl-surface)),color-mix(in srgb,var(--sl-accent) 11%,var(--sl-surface)))}\n.sl-ba::after{content:'✦';position:absolute;right:10px;top:3px;color:color-mix(in srgb,var(--sl-accent) 20%,transparent);font-size:42px;line-height:1}\n.sl-ba-title,.sl-ba-copy,.sl-ba select,.sl-ba-qty,.sl-ba-go{position:relative;z-index:1}\n.sl-ba-title{grid-column:1/-1;display:flex;align-items:center;gap:7px;font-size:13px;font-weight:850}\n.sl-ba-title .spark{color:var(--sl-accent);font-size:16px}\n.sl-ba-copy{grid-column:1/-1;margin:-4px 0 2px 23px;color:var(--sl-muted);font-size:10.5px;line-height:1.35}\n.sl-ba-copy .narrow{display:none}\n/* \"★ Best seats\" premium quick-pick — gold accent echoing the ★ Premium pill on\n the confirm popover; deliberately distinct from the accent-toned qty/go. */\n.sl-ba-premium{position:relative;z-index:1;grid-column:1/-1;justify-self:start;display:inline-flex;align-items:center;gap:6px;\n padding:6px 12px;border-radius:999px;font-size:11px;font-weight:800;letter-spacing:.02em;cursor:pointer;\n color:#c9a24b;background:color-mix(in srgb,#e8c15a 10%,var(--sl-surface));\n border:1px solid color-mix(in srgb,#e8c15a 34%,var(--sl-line));transition:filter .15s,background .15s,color .15s}\n.sl-ba-premium .star{font-size:12px;line-height:1;color:#e8c15a}\n.sl-ba-premium:hover{filter:brightness(1.05)}\n.sl-ba-premium.on{color:#1c1608;background:linear-gradient(135deg,#f0cf6b,#e0b23f);border-color:transparent;\n box-shadow:0 6px 16px color-mix(in srgb,#e8c15a 26%,transparent)}\n.sl-ba-premium.on .star{color:#5a4410}\n.sl-ba select{background:var(--sl-surface);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:8px;\n font:inherit;font-size:11px;padding:7px 8px;min-width:0;width:100%;max-width:none}\n.sl-ba-qty{display:flex;align-items:center;gap:7px;padding:3px;border:1px solid var(--sl-line);border-radius:9px;background:var(--sl-surface)}\n.sl-ba-qty button{width:25px;height:25px;border-radius:7px;background:color-mix(in srgb,var(--sl-line) 35%,transparent);border:0;\n font-size:14px;font-weight:800;display:flex;align-items:center;justify-content:center}\n.sl-ba-qty span{min-width:14px;text-align:center;font-weight:800}\n.sl-picker .sl-ba-go{grid-column:1/-1;width:100%;min-height:37px;padding:7px 12px;border-radius:9px;background:var(--sl-accent);\n color:var(--sl-accent-ink);font-weight:800;font-size:12px;transition:filter .15s,opacity .15s;display:flex;align-items:center;justify-content:center;gap:6px;\n box-shadow:0 8px 18px color-mix(in srgb,var(--sl-accent) 18%,transparent)}\n.sl-picker .sl-ba-go:hover{filter:brightness(1.06)}\n.sl-picker .sl-ba-go:disabled{opacity:.62;cursor:wait}\n.sl-ba-replace{grid-column:1/-1;padding:3px 0 1px}\n.sl-ba-replace b{display:block;font-size:12.5px}\n.sl-ba-replace span{display:block;margin-top:3px;color:var(--sl-muted);font-size:10.5px;line-height:1.35}\n.sl-ba-actions{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;gap:7px}\n.sl-ba-actions button{min-height:36px;border-radius:9px;border:1px solid var(--sl-line);font-size:11.5px;font-weight:800}\n.sl-ba-actions .replace{border-color:var(--sl-accent);background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-picker[data-layout=\"narrow\"] .sl-ba{padding:11px}\n.sl-picker[data-layout=\"narrow\"] .sl-ba-copy .wide{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-ba-copy .narrow{display:inline}\n.sl-picker[data-layout=\"narrow\"] .sl-ba select{min-height:44px}\n\n/* screen-reader live region */\n.sl-sr{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n\n/* per-seat ticket-tier select + view-from-seat button in tray chips */\n.sl-chip .tier{background:var(--sl-bg);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:6px;\n font:inherit;font-size:10px;padding:2px 4px;min-width:0;max-width:100%;cursor:pointer}\n\n/* arena: LOD rung pills (flow within the top-center region) */\n.sl-rungs{display:none;background:var(--sl-surface);border:1px solid var(--sl-line);border-radius:999px;padding:3px}\n.sl-rungs.on{display:inline-flex;gap:2px}\n.sl-rungs button{padding:6px 13px;border-radius:999px;font-size:10.5px;font-weight:800;letter-spacing:.07em;\n color:var(--sl-muted);white-space:nowrap;transition:color .15s}\n.sl-rungs button:hover{color:var(--sl-text)}\n.sl-rungs button.on{background:var(--sl-accent);color:var(--sl-accent-ink)}\n/* narrow: shrink the rung pills so the centered row can't reach the corner regions */\n.sl-picker[data-layout=\"narrow\"] .sl-rungs button{padding:5px 9px;font-size:9px;letter-spacing:.03em}\n\n/* Projection is deliberately a separate control from zoom/LOD. Perspective\n changes geometry; the two choices stay explicit and keyboard-native. */\n.sl-projection{display:inline-flex;align-items:center;gap:2px;padding:3px;border-radius:999px;\n background:var(--sl-surface);border:1px solid var(--sl-line);box-shadow:0 8px 24px -16px rgba(0,0,0,.65)}\n.sl-projection button{min-width:42px;min-height:30px;padding:5px 10px;border-radius:999px;color:var(--sl-muted);\n font-size:10px;font-weight:800;letter-spacing:.04em;white-space:nowrap}\n.sl-projection button:hover,.sl-projection button:focus-visible{color:var(--sl-text)}\n.sl-projection button.on{background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-picker[data-layout=\"narrow\"] .sl-projection button{min-width:38px;min-height:32px;padding:5px 8px;font-size:9.5px}\n\n/* 3D venue overlay — mounts over the (paused) Konva stage inside the map host.\n Carries its own gradient so it paints instantly before the scene builds, and\n cross-fades on enter/exit via a compositor-only opacity transition. Sits below\n the anchored chrome (z-index:5) and the confirm card (z-index:10) so the\n Map|3D toggle and the seat confirm both stay usable over it. */\n.sl-view3d{position:absolute;inset:0;z-index:4;opacity:0;touch-action:none;\n transition:opacity .3s ease;background:radial-gradient(120% 120% at 50% 0%,#191f28 0%,#0d1014 70%)}\n.sl-view3d canvas{display:block;width:100%;height:100%}\n[data-view3d=on] .sl-chips,[data-view3d=on] .sl-rungs{display:none}\n.sl-view3d-back{position:absolute;top:12px;left:12px;z-index:2;display:inline-flex;align-items:center;gap:6px;\n padding:7px 13px 7px 9px;border-radius:999px;font-size:11px;font-weight:800;letter-spacing:.03em;\n color:#e6edf3;background:rgba(10,14,20,.62);border:1px solid rgba(255,255,255,.22);backdrop-filter:blur(6px)}\n.sl-view3d-back:hover,.sl-view3d-back:focus-visible{background:rgba(16,22,30,.82);border-color:rgba(255,255,255,.4)}\n.sl-view3d-back svg{width:15px;height:15px;stroke:currentColor;stroke-width:2.4;fill:none;stroke-linecap:round;stroke-linejoin:round}\n/* Venue navigation inside 3D: levels (isolate a floor) and areas (fly to a zone).\n Bottom-LEFT, clear of the module's own chips (Overview bottom-right, 360\n bottom-centre) and of the bottom-sheeted confirm card. Horizontally scrollable\n so a venue with many zones never pushes the rail off a phone screen. */\n.sl-view3d-nav{position:absolute;left:12px;bottom:16px;z-index:3;display:flex;flex-direction:column;gap:6px;\n max-width:calc(100% - 24px);pointer-events:none}\n.sl-view3d-nav > div{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;pointer-events:auto;\n padding:1px;-webkit-overflow-scrolling:touch}\n.sl-view3d-nav > div::-webkit-scrollbar{display:none}\n.sl-view3d-nav button{flex:0 0 auto;min-height:32px;padding:7px 12px;border-radius:999px;white-space:nowrap;\n font-size:11.5px;font-weight:700;color:#c9d4ea;background:rgba(12,18,32,.72);\n border:1px solid rgba(150,165,205,.35);backdrop-filter:blur(6px);cursor:pointer}\n.sl-view3d-nav button:hover,.sl-view3d-nav button:focus-visible{color:#eef1f8;border-color:rgba(190,205,240,.6)}\n.sl-view3d-nav button[aria-pressed=\"true\"]{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n/* While immersed, the 2D-only chrome is meaningless — hide it, keep Map|3D. */\n.sl-picker[data-view3d=\"on\"] .sl-rungs,\n.sl-picker[data-view3d=\"on\"] .sl-floors,\n.sl-picker[data-view3d=\"on\"] .sl-zoom,\n.sl-picker[data-view3d=\"on\"] .sl-seccard,\n.sl-picker[data-view3d=\"on\"] .sl-minimap{display:none!important}\n/* The confirm card bottom-sheets over 3D (no 2D screen anchor to track). */\n.sl-picker[data-view3d=\"on\"] .sl-confirm{left:50%!important;top:auto!important;bottom:16px;\n transform:translateX(-50%);width:min(342px,calc(100% - 24px))}\n.sl-picker[data-view3d=\"on\"] .sl-confirm[data-placement]{transform:translateX(-50%)}\n\n/* Plain \"View from here\" action shown when no real photo exists (the synthetic\n thumb is suppressed at card size — full-screen is where it earns its keep). */\n.sl-confirm-viewbtn{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n display:flex;align-items:center;justify-content:center;gap:7px;font-size:12px;font-weight:800;\n color:var(--sl-text);background:transparent;transition:border-color .15s,background .15s}\n.sl-confirm-viewbtn:hover,.sl-confirm-viewbtn:focus-visible{border-color:var(--sl-accent);background:color-mix(in srgb,var(--sl-accent) 10%,transparent)}\n/* confirm-card \"See it in 3D\" / \"View from this seat\" action — the purchase-\n moment bridge into the cinematic. Styled like the view-from-seat button. */\n.sl-confirm-3d{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n display:flex;align-items:center;justify-content:center;gap:7px;font-size:12px;font-weight:800;\n color:var(--sl-text);background:color-mix(in srgb,var(--sl-accent) 12%,transparent);transition:border-color .15s,background .15s}\n.sl-confirm-3d:hover,.sl-confirm-3d:focus-visible{border-color:var(--sl-accent);background:color-mix(in srgb,var(--sl-accent) 20%,transparent)}\n.sl-confirm-3d svg{width:15px;height:15px;stroke:currentColor;stroke-width:1.9;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* multi-floor switcher (flows within the left-rail region) */\n.sl-floors{display:none;flex-direction:column;gap:6px;max-width:100%}\n.sl-floors.on{display:flex}\n.sl-floors button{padding:7px 13px;border-radius:999px;font-size:12px;font-weight:700;background:var(--sl-surface);\n border:1px solid var(--sl-line);color:var(--sl-muted);white-space:nowrap;max-width:100%;overflow:hidden;\n text-overflow:ellipsis;transition:color .15s,border-color .15s}\n.sl-floors button:hover{color:var(--sl-text)}\n.sl-floors button.on{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n\n/* tapped-section summary card — docks INSIDE the top-center anchor region on\n wide (flows below the rung pills, never over them, never floating over the\n seats at the tap point). Auto-collapses to a slim pill once seat-picking\n begins (first seat select, or a pan/zoom after the focus glide); tapping the\n pill re-expands; ✕ closes in both states. On narrow it renders as a compact\n strip inside the bottom sheet's peek head — never over the canvas. */\n.sl-seccard{width:250px;max-width:100%;background:var(--sl-surface);border:1px solid var(--sl-line);border-radius:12px;\n padding:12px 14px;box-shadow:0 18px 50px -18px rgba(0,0,0,.6);display:none}\n.sl-seccard.on{display:block}\n/* collapsed pill (wide) */\n.sl-seccard.mini{width:auto;padding:5px 7px 5px 12px;border-radius:999px;cursor:pointer}\n.sl-seccard.mini.on{display:inline-flex;align-items:center;gap:7px}\n.sl-seccard.mini .sl-seccard-name{font-size:12px;flex:none;max-width:120px}\n.sl-seccard.mini .sl-seccard-left{font-size:11px}\n/* narrow: compact strip inside the sheet head (peek area) */\n.sl-seccard.strip{width:100%;padding:7px 0 0;border:0;border-radius:0;box-shadow:none;background:none;cursor:default}\n.sl-seccard.strip.on{display:flex;align-items:center;gap:7px;font-size:12.5px}\n.sl-seccard.strip .sl-seccard-name{font-size:12.5px}\n.sl-seccard.strip .sl-seccard-price{margin-left:auto}\n.sl-seccard-head{display:flex;align-items:center;gap:8px}\n.sl-seccard-dot{width:10px;height:10px;border-radius:50%;flex:none}\n.sl-seccard-name{font-weight:800;font-size:14px;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-seccard-price{font-weight:800;font-size:12.5px;font-variant-numeric:tabular-nums}\n.sl-seccard-x{width:22px;height:22px;border-radius:999px;flex:none;display:flex;align-items:center;justify-content:center;\n color:var(--sl-muted);font-size:12px}\n.sl-seccard-x:hover{color:var(--sl-text)}\n.sl-seccard-zone{font-size:11.5px;color:var(--sl-muted);margin-top:6px}\n.sl-seccard-left{color:var(--sl-text);font-weight:700}\n.sl-seccard-mix{display:flex;flex-wrap:wrap;gap:6px 10px;margin-top:8px}\n.sl-seccard-mix-item{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;color:var(--sl-muted)}\n.sl-seccard-mix-dot{width:8px;height:8px;border-radius:50%;flex:none}\n.sl-seccard-mix-price{font-weight:700;color:var(--sl-text)}\n.sl-seccard-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:10px}\n.sl-seccard-overview{font-size:12px;font-weight:800;color:var(--sl-accent)}\n.sl-seccard-hint{font-size:10.5px;color:var(--sl-muted)}\n\n/* view-from-seat button on the confirm popover */\n/* Eager sightline preview inside the confirm card */\n.sl-confirm-thumbwrap{position:relative;display:block;width:100%;height:74px;margin:0 0 8px;padding:0!important;\n border-radius:9px;overflow:hidden;border:1px solid var(--sl-line);cursor:pointer}\n.sl-confirm-thumb{display:block;width:100%;height:100%;object-fit:cover}\n.sl-confirm-thumb-badge{position:absolute;right:7px;top:7px;display:inline-flex;align-items:center;gap:5px;\n font-size:10px;font-weight:700;color:#fff;background:rgba(10,14,22,0.72);border-radius:12px;padding:4px 9px;backdrop-filter:blur(3px)}\n.sl-confirm-sight{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--sl-muted);margin-bottom:2px}\n.sl-confirm-sight span{color:#22a06b;font-weight:800}\n.sl-confirm-view{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n color:var(--sl-text);font-weight:700;font-size:12px;display:flex;align-items:center;justify-content:center;gap:7px}\n.sl-confirm-view:hover{border-color:var(--sl-muted)}\n.sl-confirm-view svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* commercial seat flags — limited-view caution + premium tag. Amber tone,\n deliberately distinct from the red taken/held state; shown on the confirm\n card, echoed as a small ◐ marker on cart chips and the hover tip. */\n.sl-cx{display:flex;flex-direction:column;gap:6px;margin-bottom:10px}\n.sl-cx-warn{display:flex;align-items:flex-start;gap:7px;padding:8px 10px;border-radius:9px;\n background:color-mix(in srgb,#f4b740 13%,var(--sl-surface));border:1px solid color-mix(in srgb,#f4b740 40%,var(--sl-line));\n animation:slNoticeIn .28s ease both}\n.sl-cx-glyph{flex:none;font-size:14px;line-height:1.2;color:#f4b740}\n.sl-cx-txt{min-width:0;display:flex;flex-direction:column;gap:2px}\n.sl-cx-txt b{font-size:12px;font-weight:800;color:var(--sl-text)}\n.sl-cx-note{font-size:11px;line-height:1.4;color:var(--sl-muted)}\n.sl-cx-premium{display:inline-flex;align-items:center;gap:6px;align-self:flex-start;padding:4px 10px;border-radius:999px;\n font-size:11px;font-weight:800;letter-spacing:.02em;color:#c9a24b;\n background:color-mix(in srgb,#e8c15a 13%,var(--sl-surface));border:1px solid color-mix(in srgb,#e8c15a 38%,var(--sl-line))}\n.sl-cx-star{font-size:12px;line-height:1;color:#e8c15a}\n.sl-cx-mark{flex:none;font-size:12px;line-height:1;color:#f4b740;cursor:help}\n.sl-tip-cx{display:flex;align-items:center;gap:6px;padding:5px 10px 7px;font-size:10.5px;font-weight:700;color:#e8b24a}\n.sl-tip-cx .g{font-size:12px}\n\n/* 360° seat-view modal (fills the widget; drag-to-look-around equirectangular) */\n.sl-view{position:absolute;inset:0;z-index:12;display:flex;flex-direction:column;background:var(--sl-bg)}\n.sl-view-head{display:flex;align-items:center;gap:8px;padding:12px 16px;border-bottom:1px solid var(--sl-line);flex:none}\n.sl-view-title{font-weight:800;font-size:15px}\n.sl-view-cap{font-size:11px;color:var(--sl-muted)}\n.sl-view-x{margin-left:auto;width:32px;height:32px;border-radius:999px;border:1px solid var(--sl-line);color:var(--sl-muted);\n flex:none;display:flex;align-items:center;justify-content:center;transition:color .15s,border-color .15s}\n.sl-view-x:hover{color:var(--sl-text);border-color:var(--sl-muted)}\n.sl-view-x svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round}\n.sl-view-pano{position:relative;flex:1;min-height:0;overflow:hidden;cursor:grab;background-color:#05070c;\n background-repeat:repeat-x;touch-action:none;user-select:none}\n.sl-view-pano.drag{cursor:grabbing}\n.sl-view-badge{position:absolute;top:12px;left:12px;padding:5px 11px;border-radius:999px;font-size:10px;font-weight:800;\n letter-spacing:.08em;background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted)}\n.sl-view-hint{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);padding:6px 14px;border-radius:999px;\n font-size:11.5px;font-weight:600;background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted);\n white-space:nowrap;pointer-events:none;max-width:90%;overflow:hidden;text-overflow:ellipsis}\n\n/* F3 minimap — venue overview + live viewport rect (flows in the bottom-left region) */\n.sl-minimap{border:1px solid var(--sl-line);border-radius:9px;\n overflow:hidden;background:var(--sl-surface);box-shadow:0 12px 34px -14px rgba(0,0,0,.55);line-height:0;cursor:pointer}\n.sl-minimap canvas{display:block}\n.sl-picker[data-layout=\"narrow\"] .sl-minimap{display:none}\n\n/* F4 legend reflection: rows + counts for out-of-band categories read muted */\n.sl-price-row.sl-dim{opacity:.4}\n.sl-seccard-mix-item.sl-dim{opacity:.4}\n\n/* Buyer-journey motion: every animation explains a state transition (selected,\n held, checkout handoff, conflict or booked). No decorative infinite motion\n except the expiring-hold pulse and active progress spinners. */\n@keyframes slPillIn{from{opacity:0;transform:translateX(7px) scale(.9)}to{opacity:1;transform:translateX(0) scale(1)}}\n@keyframes slHoldPulse{0%{box-shadow:0 0 0 0 currentColor;opacity:.9}75%,100%{box-shadow:0 0 0 7px transparent;opacity:.55}}\n@keyframes slChipIn{from{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}\n@keyframes slChipOut{to{opacity:0;transform:translateX(10px) scale(.98)}}\n@keyframes slNoticeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}\n@keyframes slValuePop{0%{opacity:.6;transform:translateY(3px)}55%{transform:translateY(-1px) scale(1.05)}100%{opacity:1;transform:none}}\n@keyframes slCtaReady{0%{transform:scale(.98);box-shadow:0 0 0 0 transparent}55%{transform:scale(1.01);box-shadow:0 0 0 5px color-mix(in srgb,var(--sl-accent) 18%,transparent)}100%{transform:none;box-shadow:none}}\n@keyframes slToastNudge{0%,100%{margin-left:0}30%{margin-left:-4px}60%{margin-left:3px}}\n@keyframes slSuccessPop{0%{opacity:0;transform:scale(.72)}65%{opacity:1;transform:scale(1.08)}100%{opacity:1;transform:scale(1)}}\n@keyframes slCheckDraw{to{stroke-dashoffset:0}}\n@keyframes slCopyRise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\n@keyframes slConfirmIn{from{opacity:0;transform:translate(-50%,calc(-100% - 8px)) scale(.96)}to{opacity:1;transform:translate(-50%,calc(-100% - 14px)) scale(1)}}\n@keyframes slConfirmBelowIn{from{opacity:0;transform:translate(-50%,8px) scale(.96)}to{opacity:1;transform:translate(-50%,16px) scale(1)}}\n@keyframes slConfirmMobileIn{from{opacity:0;transform:translate(-50%,10px) scale(.97)}to{opacity:1;transform:translate(-50%,0) scale(1)}}\n\n/* Access state (channels): the panel fades AND rises at --slm-mo-base. It never\n covers the map — inventory is cross-faded to neutral by the canvas in one\n batched pass, so nothing blinks away underneath it. */\n.sl-access{position:absolute;left:50%;bottom:18px;z-index:9;transform:translateX(-50%);\n max-width:min(420px,calc(100% - 24px));display:flex;gap:12px;align-items:flex-start;\n padding:12px 14px;border-radius:var(--sl-r-sm);background:var(--sl-panel,#151b2c);color:var(--sl-text);\n border:1px solid var(--sl-line);box-shadow:0 18px 44px -18px rgba(0,0,0,.6);\n animation:slAccessIn var(--slm-mo-base) var(--slm-mo-out) both}\n.sl-access-title{font-weight:700;font-size:13px}\n.sl-access-body{font-size:12px;line-height:1.5;opacity:.82;margin-top:2px}\n.sl-access-act{margin-top:8px;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:700;\n background:var(--sl-accent);color:var(--sl-accent-ink)}\n@keyframes slAccessIn{from{opacity:0;transform:translate(-50%,10px)}to{opacity:1;transform:translate(-50%,0)}}\n\n@media(prefers-reduced-motion:reduce){\n .sl-picker *,.sl-modal-scrim *{animation-duration:.001ms!important;animation-iteration-count:1!important;\n transition-duration:.001ms!important;scroll-behavior:auto!important}\n .sl-access{animation:none;opacity:1;transform:translate(-50%,0)}\n}\n.sl-ba [data-ba-zone]{grid-column:1/-1;width:100%}\n\n/* modal host */\n.sl-modal-scrim{position:fixed;inset:0;z-index:2147483000;background:rgba(5,7,12,.66);display:flex;align-items:center;justify-content:center;padding:18px}\n.sl-modal-frame{width:min(1200px,100%);height:min(820px,100%);border-radius:16px;overflow:hidden;box-shadow:0 40px 120px -30px rgba(0,0,0,.8)}\n@media(max-width:640px){.sl-modal-scrim{padding:0}.sl-modal-frame{width:100%;height:100%;border-radius:0}}\n`;\n\nfunction ensureStyle(): void {\n if (document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = CSS;\n document.head.appendChild(el);\n}\n\n/** Merge order: defaults ← org chart theme ← host overrides. */\nfunction resolveTokens(chart: ChartTheme | undefined, host: SeatPickerTheme | undefined): Record<string, string> {\n const accent = host?.accent ?? chart?.accent ?? '#f4b740';\n const accentInk = host?.accentInk ?? chart?.accentInk ?? '#1a1200';\n return {\n '--sl-accent': accent,\n '--sl-accent-ink': accentInk,\n '--sl-bg': host?.background ?? chart?.background ?? '#0f1522',\n '--sl-surface': host?.surface ?? '#1a2234',\n '--sl-text': host?.text ?? chart?.textColor ?? '#eef1f8',\n '--sl-muted': host?.muted ?? '#8b93a7',\n '--sl-line': host?.line ?? 'rgba(139,147,167,.22)',\n '--sl-font': host?.fontFamily ?? chart?.fontFamily ?? \"-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif\",\n '--sl-radius': `${host?.radius ?? 14}px`,\n };\n}\n\n/**\n * Colorblind-safe preference is a SHARED buyer preference across every SeatLayer\n * surface (the bespoke public page persists it too), so the widget reads/writes\n * the SAME localStorage key. All access is guarded — private-mode/SSR safe.\n */\nconst CB_STORAGE_KEY = 'seatmap.a11y.cb';\nfunction readStoredColorblind(): boolean | null {\n try {\n if (typeof window === 'undefined') return null;\n const raw = window.localStorage.getItem(CB_STORAGE_KEY);\n return raw == null ? null : raw === '1';\n } catch {\n return null;\n }\n}\nfunction writeStoredColorblind(on: boolean): void {\n try {\n window.localStorage.setItem(CB_STORAGE_KEY, on ? '1' : '0');\n } catch {\n /* private mode / storage disabled — preference is best-effort */\n }\n}\n\nexport class SeatPicker {\n private readonly opts: SeatPickerOptions;\n private readonly api: PickerTransport;\n /** Our own public client, or null when the host injected a transport. */\n private readonly pubApi: PubApi | null;\n /** Null for the ordinary public picker — the tokenless path is untouched. */\n private readonly access: BuyerAccessContext | null;\n private realtime: BuyerRealtimeClient | null = null;\n private accessEl: HTMLDivElement | null = null;\n private readonly apiBase: string;\n private readonly controller: PickerController;\n private readonly maxTickets: number;\n\n private root: HTMLDivElement | null = null;\n private mapHost: HTMLDivElement | null = null;\n private rendered = false;\n private destroyed = false;\n\n // chrome refs\n private els: Record<string, HTMLElement> = {};\n /** Feature 6 anchor regions — positioned flex containers over the map. */\n private regions: Record<string, HTMLElement> = {};\n private ro: ResizeObserver | null = null;\n private holdTimer: ReturnType<typeof setInterval> | null = null;\n private toastTimer: ReturnType<typeof setTimeout> | null = null;\n /** Short-lived UI motion timers; all are cancelled on destroy. */\n private motionTimers = new Set<ReturnType<typeof setTimeout>>();\n\n // state\n private currency = 'USD';\n private hold: HoldResult | null = null;\n /** Latest server expiry for the open hold (moves on extend). */\n private holdExpiresAt = 0;\n /** True once we handed off to checkout — arms booked-confirmation detection. */\n private handedOff = false;\n /** Guards single onBooked + single success overlay per hold. */\n private bookedShown = false;\n /**\n * `'hosted'` only when the host asked for it AND the widget owns its own\n * transport. Resolved once in the constructor so every later read is a field\n * comparison rather than a re-derivation that could drift.\n */\n private readonly checkoutMode: 'handoff' | 'hosted';\n /**\n * In-flight or settled `payment-options` for this event, started at render in\n * hosted mode. One request, kicked off while the buyer is still choosing, so\n * pressing Pay does not wait on a lookup whose answer never changes mid-session.\n */\n private paymentOptions: Promise<PaymentOptionsResult> | null = null;\n /** The mounted payment card, while one is up. */\n private checkoutPanel: CheckoutHandle | null = null;\n private extendEl: HTMLDivElement | null = null;\n private bookedEl: HTMLDivElement | null = null;\n private gaQty = new Map<string, number>();\n private tipEl: HTMLDivElement | null = null;\n private tipPos = { x: 0, y: 0 };\n private confirmEl: HTMLDivElement | null = null;\n private confirmSeat: ExpandedSeat | null = null;\n private tableDialogEl: HTMLDivElement | null = null;\n private tableDialog: TableSelectionDetails | null = null;\n private tableDialogHeld = false;\n private tableDialogReturnFocus: HTMLElement | null = null;\n private srEl: HTMLDivElement | null = null;\n private baQty = 2;\n private baCat = '';\n /** Optional navigation-zone scope for buyer best-available. */\n private baZone = '';\n /** \"★ Best seats\" premium quick-pick toggle — biases best-available to premium seats. */\n private baPremium = false;\n private bestAvailableConfirm = false;\n private releasingHold = false;\n /** Event sales window is closed (read-only load state / live close). */\n private salesClosed = false;\n /** Every seated category's live availability is 0 (sold-out overlay is up). */\n private soldOut = false;\n private soldoutEl: HTMLDivElement | null = null;\n /** Resolved colorblind-safe state — stored preference wins over the option. */\n private cbSafe = false;\n\n // arena / multi-floor / seat-view chrome\n private rungsEl: HTMLDivElement | null = null;\n private projectionEl: HTMLDivElement | null = null;\n // --- 3D venue view (Map | 3D) ---\n private buyerView: 'map' | 'venue3d' = 'map';\n private view3dEl: HTMLDivElement | null = null;\n private view3dHandle: Venue3DHandle | null = null;\n /** Monotonic token so a stale async mount (buyer left before OGL finished\n * loading) never installs its handle over a newer state. */\n private view3dGen = 0;\n /** Seat whose 2D confirm card launched \"See it in 3D\"; re-shown on return. */\n private view3dReturnSeat: ExpandedSeat | null = null;\n private floorsEl: HTMLDivElement | null = null;\n private secCardEl: HTMLDivElement | null = null;\n private viewEl: HTMLDivElement | null = null;\n private viewCleanup: (() => void) | null = null;\n private allSeatsCache: ExpandedSeat[] | null = null;\n\n // F3 minimap\n private miniCanvas: HTMLCanvasElement | null = null;\n private miniBase: HTMLCanvasElement | null = null;\n private miniTf: { scale: number; offX: number; offY: number; dpr: number } | null = null;\n\n // F4 price-band filter — active band's category keys (null = all prices)\n private priceBandKeys: Set<string> | null = null;\n private focusedCatKey: string | null = null;\n /** \"Hide limited-view seats\" — mirrored into 3D by `seatState3dFor`. */\n private limitedViewFilter = false;\n private pricesExpanded = false;\n /** Last surfaced section summary (re-rendered when the price band changes). */\n private lastSection: SectionSummary | null = null;\n /** Section card collapsed to its slim pill (seat-picking has begun). */\n private secCardCollapsed = false;\n /** When the card was (re)shown — the focus glide's own view change must not collapse it. */\n private secCardShownAt = 0;\n /** Previous tray ticket count — first 0→n transition auto-expands the mobile sheet. */\n private lastTrayCount = 0;\n /** Previous computed total — drives a single explanatory value bump. */\n private lastTrayTotal = 0;\n /** Stable item keys prevent tray chips re-animating on unrelated realtime syncs. */\n private lastTrayKeys = new Set<string>();\n private bestAvailableBusy = false;\n private releasingLabels = new Set<string>();\n /** Selected labels awaiting the hold response; their own realtime echo can arrive first. */\n private holdingLabels = new Set<string>();\n private ctaPhase: 'idle' | 'holding' | 'checkout' = 'idle';\n // narrow-layout chrome that docks into the sheet's Filters row on mobile\n private a11yChipsEl: HTMLDivElement | null = null;\n private fsFallback = false;\n private fsChangeHandler: (() => void) | null = null;\n private fsEscHandler: ((e: KeyboardEvent) => void) | null = null;\n /** True once we've asked the host page to pin us fullscreen (framed, no native). */\n private framedFs = false;\n /** Last height (px) posted to a host frame; dedupes redundant reports. */\n private lastPostedHeight = 0;\n\n /** True when the chart carries a real performance anchor — a stage-kind shape.\n * Every chart has a `focalPoint` (a bare look-at coordinate), so its presence\n * alone never justifies a \"to stage\" claim; only an actual stage does. */\n private chartHasStage(): boolean {\n const doc = this.controller.doc;\n if (!doc) return false;\n const objectSets = doc.floors?.length ? doc.floors.map((f) => f.objects ?? []) : [doc.objects ?? []];\n for (const objects of objectSets) {\n for (const obj of objects) {\n if (obj.type === 'shape' && (obj.role === 'stage' || obj.stageKind)) return true;\n }\n }\n return false;\n }\n\n /**\n * Eager sightline preview for the confirm card: the organizer's real view\n * photo, or — only when the chart has an actual stage to look at — a generated\n * forward view plus an \"≈ Nm to stage · clear sightline\" line. On a stageless\n * chart both the distance/sightline claim and the generic stage silhouette are\n * invented promises, so we suppress them; a real attached photo always shows.\n * (OV-52)\n */\n private confirmThumbHtml(seat: ExpandedSeat): string {\n const doc = this.controller.doc;\n if (!doc) return '';\n const realPhoto = seat.viewUrl ?? '';\n const hasStage = this.chartHasStage();\n // No organizer photo AND no stage to measure against → nothing honest to show.\n if (!realPhoto && !hasStage) return '';\n let distance: number | null = null;\n if (!realPhoto) {\n try {\n // Rendered only for its distance figure — the synthetic image itself is\n // deliberately NOT shown at card size, where it reads as a cheap fake\n // photo (owner call 2026-07-24). Full-screen is where generated views\n // earn their keep; the card keeps a plain \"View from here\" button.\n const thumb = generateSeatThumb(seat, seat.focalPoint ?? doc.focalPoint);\n distance = thumb.distanceM ?? null;\n } catch {\n return '';\n }\n }\n // The distance/sightline line is only truthful when a stage anchors it.\n const sightHtml = hasStage\n ? `<div class=\"sl-confirm-sight\"><span aria-hidden=\"true\">✓</span>${distance != null\n ? t('picker.sightline', { m: distance })\n : this.tf('picker.sightlineClear', 'Clear sightline')}</div>`\n : '';\n const viewBtn = realPhoto\n ? `<button type=\"button\" class=\"sl-confirm-view sl-confirm-thumbwrap\" aria-label=\"${t('picker.viewFromSeat', { label: seat.label })}\">` +\n `<img class=\"sl-confirm-thumb\" src=\"${realPhoto}\" alt=\"\" />` +\n `<span class=\"sl-confirm-thumb-badge\">🔭 ${this.tf('picker.viewFromHere', 'View from here')}</span>` +\n `</button>`\n : `<button type=\"button\" class=\"sl-confirm-view sl-confirm-viewbtn\" aria-label=\"${t('picker.viewFromSeat', { label: seat.label })}\">` +\n `<span aria-hidden=\"true\">🔭</span><span>${this.tf('picker.viewFromHere', 'View from here')}</span>` +\n `</button>`;\n return viewBtn + sightHtml;\n }\n\n /** \"See it in 3D\" (2D) / \"View from this seat\" (already in 3D) action for the\n * confirm card. Only when 3D is available — the purchase-moment bridge into\n * the cinematic that reaches buyers who never press the Map | 3D toggle. */\n private see3dConfirmHtml(): string {\n if (!this.canOffer3d()) return '';\n const label = this.buyerView === 'venue3d'\n ? this.tf('picker.viewFromThisSeat', 'View from this seat')\n : this.tf('picker.seeItIn3d', 'See it in 3D');\n return (\n `<button type=\"button\" class=\"sl-confirm-3d\" aria-label=\"${label}\">`\n + '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2l9 5v10l-9 5-9-5V7z\"/><path d=\"M12 12l9-5M12 12v10M12 12L3 7\"/></svg>'\n + `<span>${label}</span></button>`\n );\n }\n\n /** Minimal HTML/attribute escaper for buyer-authored commercial text (notes). */\n private escCx(value: unknown): string {\n return String(value ?? '').replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!));\n }\n\n /** Localized \"Restricted view\" / \"Obstructed view\" label for a seat's flags,\n * or '' when neither is set. Restricted takes precedence when both are on. */\n private limitedViewLabel(c: SeatCommercialAttributes | undefined): string {\n if (c?.restrictedView) return this.tf('picker.restrictedView', 'Restricted view');\n if (c?.obstructedView) return this.tf('picker.obstructedView', 'Obstructed view');\n return '';\n }\n\n /**\n * Commercial flags block for the confirm/detail surface: a subtle ★ Premium\n * tag plus an amber ◐ limited-view caution (with the organizer's note when\n * present). '' when the seat carries no surfaced commercial flag.\n */\n private commercialConfirmHtml(c: SeatCommercialAttributes | undefined): string {\n if (!c) return '';\n const rows: string[] = [];\n if (c.premium) {\n rows.push(\n `<div class=\"sl-cx-premium\"><span class=\"sl-cx-star\" aria-hidden=\"true\">★</span>${this.tf('picker.premiumSeat', 'Premium seat')}</div>`,\n );\n }\n const limited = this.limitedViewLabel(c);\n if (limited) {\n rows.push(\n `<div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">◐</span>` +\n `<span class=\"sl-cx-txt\"><b>${limited}</b>${c.note ? `<span class=\"sl-cx-note\">${this.escCx(c.note)}</span>` : ''}</span></div>`,\n );\n } else if (c.note) {\n // A note with no view flag (e.g. seller info) still deserves a calm line.\n rows.push(\n `<div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">ℹ</span>` +\n `<span class=\"sl-cx-txt\"><span class=\"sl-cx-note\">${this.escCx(c.note)}</span></span></div>`,\n );\n }\n return rows.length ? `<div class=\"sl-cx\">${rows.join('')}</div>` : '';\n }\n\n /** Small ◐ limited-view marker for a cart chip; title/aria uses the seat's\n * note when present, else the generic view label. '' for a clear-view seat. */\n private commercialChipMarker(c: SeatCommercialAttributes | undefined): string {\n const limited = this.limitedViewLabel(c);\n if (!limited) return '';\n const title = this.escCx(c?.note ? c.note : limited);\n return `<span class=\"sl-cx-mark\" role=\"img\" aria-label=\"${title}\" title=\"${title}\">◐</span>`;\n }\n\n private wheelchairProvisionLabel(type: 'seat-present' | 'no-seat' | undefined): string {\n if (type === 'no-seat') return 'Empty wheelchair space';\n if (type === 'seat-present') return 'Accessible physical seat';\n return '';\n }\n\n private wheelchairConfirmHtml(type: 'seat-present' | 'no-seat' | undefined): string {\n const label = this.wheelchairProvisionLabel(type);\n return label\n ? `<div class=\"sl-cx\"><div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">♿</span><span class=\"sl-cx-txt\"><b>${label}</b></span></div></div>`\n : '';\n }\n\n private wheelchairChipMarker(type: 'seat-present' | 'no-seat' | undefined): string {\n const label = this.wheelchairProvisionLabel(type);\n return label\n ? `<span class=\"sl-cx-mark\" role=\"img\" aria-label=\"${label}\" title=\"${label}\">♿</span>`\n : '';\n }\n\n /** True when the picker is rendered inside an iframe (snippet embed at /e/:key). */\n private isFramed(): boolean {\n return typeof window !== 'undefined' && window.parent !== window;\n }\n\n /**\n * Post a widget→host message when framed. targetOrigin is '*' because the\n * payload carries nothing sensitive (a height number / a fullscreen flag);\n * hosts verify `event.origin` on their side (see `attachPickerFrame`).\n */\n private postToHost(message: { type: string; [key: string]: unknown }): void {\n if (!this.isFramed()) return;\n try {\n window.parent.postMessage(message, '*');\n } catch {\n /* a hostile/cross-origin parent may reject postMessage — nothing to do */\n }\n }\n\n /**\n * Height (px) to advertise to a host frame.\n *\n * The picker fills whatever box it's given: `.sl-picker` is `height:100%;\n * overflow:hidden`, and the /e/:key shell mounts it `position:fixed; inset:0`.\n * So it has no intrinsic *document* height to read — `scrollHeight` just\n * collapses to the current viewport, which for a framed embed would echo the\n * host's own iframe height straight back (a circular value). We therefore\n * report a width-driven *desired* height: a pleasant landscape box on desktop,\n * taller on narrow widths where the bottom sheet needs room, clamped to the\n * widget's `min-height` of 420. Width is host-controlled and never moves in\n * response to the height we report, so this cannot feedback-loop.\n */\n private measureFramedHeight(): number {\n const root = this.root;\n if (!root) return 0;\n const width = root.clientWidth || (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;\n if (width <= 0) return 0;\n const ratio = width < 640 ? 1.2 : 0.62;\n return Math.max(420, Math.round(width * ratio));\n }\n\n /** Post `seatlayer:height` to the host when framed and the value changed. */\n private reportFramedHeight(): void {\n if (!this.isFramed()) return;\n const px = this.measureFramedHeight();\n if (px <= 0 || px === this.lastPostedHeight) return;\n this.lastPostedHeight = px;\n this.postToHost({ type: 'seatlayer:height', px });\n }\n\n /** Full screen via the native API, falling back to a fixed-position overlay (iOS Safari). */\n private toggleFullscreen(): void {\n const root = this.root;\n if (!root) return;\n const active = !!document.fullscreenElement || this.fsFallback || this.framedFs;\n if (!active) {\n if (root.requestFullscreen) {\n root.requestFullscreen().catch(() => this.enterFsFallback());\n } else {\n this.enterFsFallback();\n }\n } else if (document.fullscreenElement) {\n void document.exitFullscreen().catch(() => {});\n } else if (this.framedFs) {\n this.setFramedFs(false);\n } else {\n this.setFsFallback(false);\n }\n }\n\n /**\n * Native element-fullscreen was unavailable or rejected. When framed, a CSS\n * `.sl-fs` overlay can't escape the iframe, so we ask the host page to pin us\n * (`seatlayer:fullscreen`). Otherwise (iOS Safari, same document) fall back to\n * the `.sl-fs` overlay as before.\n */\n private enterFsFallback(): void {\n if (this.isFramed()) this.setFramedFs(true);\n else this.setFsFallback(true);\n }\n\n /** Toggle host-driven (framed) fullscreen: post the flag + own the Esc key. */\n private setFramedFs(on: boolean): void {\n if (this.framedFs === on) return;\n this.framedFs = on;\n this.els.zfs?.setAttribute('aria-pressed', String(on || !!document.fullscreenElement));\n this.postToHost({ type: 'seatlayer:fullscreen', on });\n if (on && !this.fsEscHandler) {\n this.fsEscHandler = (e: KeyboardEvent): void => {\n if (e.key === 'Escape' && !document.fullscreenElement) this.setFramedFs(false);\n };\n window.addEventListener('keydown', this.fsEscHandler);\n } else if (!on && this.fsEscHandler) {\n window.removeEventListener('keydown', this.fsEscHandler);\n this.fsEscHandler = null;\n }\n requestAnimationFrame(() => this.controller.zoomToFit());\n }\n\n private setFsFallback(on: boolean): void {\n if (this.fsFallback === on) return;\n this.fsFallback = on;\n this.root?.classList.toggle('sl-fs', on);\n this.els.zfs?.setAttribute('aria-pressed', String(on || !!document.fullscreenElement));\n if (on && !this.fsEscHandler) {\n this.fsEscHandler = (e: KeyboardEvent): void => {\n if (e.key === 'Escape' && !document.fullscreenElement) this.setFsFallback(false);\n };\n window.addEventListener('keydown', this.fsEscHandler);\n } else if (!on && this.fsEscHandler) {\n window.removeEventListener('keydown', this.fsEscHandler);\n this.fsEscHandler = null;\n }\n requestAnimationFrame(() => this.controller.zoomToFit());\n }\n private cbEl: HTMLButtonElement | null = null;\n\n // modal plumbing (set by open())\n private modalScrim: HTMLElement | null = null;\n private prevFocus: Element | null = null;\n private escHandler: ((e: KeyboardEvent) => void) | null = null;\n\n /** Set by open(): closes the modal (scroll restore + destroy + onClose). */\n private closeModal: (() => void) | null = null;\n\n /**\n * Close the picker. In modal mode (SeatPicker.open()) this dismisses the\n * modal exactly like ESC/scrim/✕ — restores page scroll and fires onClose.\n * For inline mounts it simply destroys the widget.\n */\n close(): void {\n if (this.closeModal) this.closeModal();\n else this.destroy();\n }\n\n /** Mount the full picker as a document-level modal. Resolves after render. */\n static async open(options: Omit<SeatPickerOptions, 'container'>): Promise<SeatPicker> {\n ensureStyle();\n const scrim = document.createElement('div');\n scrim.className = 'sl-modal-scrim';\n const frame = document.createElement('div');\n frame.className = 'sl-modal-frame';\n scrim.appendChild(frame);\n document.body.appendChild(scrim);\n const prevOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n const picker = new SeatPicker({ ...options, container: frame });\n picker.modalScrim = scrim;\n picker.prevFocus = document.activeElement;\n let closing = false;\n const close = (): void => {\n if (closing) return;\n closing = true;\n document.body.style.overflow = prevOverflow;\n // Visually dismiss immediately, but let an abandoned auto-hold finish its\n // release request before tearing down the transport. This keeps closing a\n // modal from stranding inventory until the normal hold expiry.\n scrim.style.opacity = '0';\n scrim.style.pointerEvents = 'none';\n const finish = (): void => {\n picker.destroy();\n options.onClose?.();\n };\n if (picker.hold && !picker.handedOff) void picker.release().finally(finish);\n else finish();\n };\n picker.closeModal = close;\n scrim.addEventListener('mousedown', (e) => {\n if (e.target === scrim) close();\n });\n picker.escHandler = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (picker.tableDialog) {\n e.preventDefault();\n picker.cancelTableDialog();\n } else if (picker.confirmSeat) {\n e.preventDefault();\n picker.cancelConfirm();\n } else if (picker.bestAvailableConfirm) {\n e.preventDefault();\n picker.bestAvailableConfirm = false;\n picker.syncTray();\n } else {\n close();\n }\n };\n document.addEventListener('keydown', picker.escHandler);\n await picker.render();\n picker.els.close?.classList.add('on');\n picker.els.close?.addEventListener('click', close);\n return picker;\n }\n\n constructor(options: SeatPickerOptions) {\n if (!options || typeof options !== 'object') throw new Error('seatmap: options object is required');\n if (!options.event || typeof options.event !== 'string') throw new Error('seatmap: `event` key is required');\n if (!options.container) throw new Error('seatmap: `container` is required (or use SeatPicker.open())');\n this.opts = { ...options, confirmSelection: options.confirmSelection ?? true };\n this.apiBase = (options.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '');\n // A host-supplied transport owns its own credentials, so the access context\n // is only built for our own PubApi.\n this.access = options.transport\n ? null\n : createBuyerAccessContext(options, {\n onExpired: (event) => {\n this.opts.onAccessExpired?.(event);\n if (!event.refreshed) this.showAccessPanel({ reason: 'no_token', retryable: false });\n },\n onUnavailable: (event) => {\n this.opts.onAccessUnavailable?.(event);\n this.showAccessPanel(event);\n },\n });\n this.pubApi = options.transport\n ? null\n : new PubApi(this.apiBase, {\n access: this.access ?? undefined,\n onObjectUnavailable: (event) => this.opts.onSelectedObjectUnavailable?.(event),\n });\n this.api = options.transport ?? this.pubApi!;\n // Hosted checkout talks to OUR /pub routes with OUR client. A host that\n // injected a transport owns its backend and its credentials, and quietly\n // reaching past it to api.seatlayer.io would be the widget deciding where a\n // buyer's money goes. Refuse out loud, once, and stay on the default.\n if (options.checkout === 'hosted' && !this.pubApi) {\n console.warn(\n 'seatlayer: checkout: \"hosted\" needs the widget\\'s own transport — a custom `transport` '\n + 'owns its backend, so the picker is staying on onCheckout for this mount.',\n );\n }\n this.checkoutMode = options.checkout === 'hosted' && this.pubApi ? 'hosted' : 'handoff';\n this.maxTickets = Math.max(1, Math.floor(options.maxSelection ?? DEFAULT_MAX_SELECTION));\n // Colorblind preference: the stored (cross-surface) value wins over the\n // option; the option is only the initial default when nothing is stored.\n this.cbSafe = readStoredColorblind() ?? !!options.colorblindSafe;\n this.controller = new PickerController({\n transport: this.api,\n eventKey: options.event,\n maxSelection: this.maxTickets,\n currency: options.currency,\n flashOnLiveChange: true,\n colorblindSafe: this.cbSafe,\n onSelectionChange: () => {\n this.syncTray();\n // Seat-picking has begun — collapse the section card out of the way.\n if (this.committedSelection().length) this.collapseSectionCard();\n // Keep the 3D overlay's selection highlight in lockstep (both directions).\n this.syncSelectionTo3d();\n },\n onStatusChange: () => {\n this.syncPrices();\n this.evictTakenSelections();\n this.detectBooked();\n // Live open/close of a section repaints the minimap's static overview.\n this.refreshMinimap();\n // Mirror every live availability delta into the 3D view while it's open.\n this.pushAvailabilityTo3d();\n },\n onHoldExpired: () => {\n this.hold = null;\n this.forgetHold();\n this.handedOff = false;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.stopHoldTimer();\n this.gaQty.clear();\n this.toast(t('picker.holdExpired', undefined) || 'Your hold expired — seats released. Pick again.', 'warning');\n this.syncTray();\n this.emitHoldChange();\n this.opts.onHoldExpired?.();\n },\n confirmSelection: this.opts.confirmSelection,\n onSelect: (seat) => {\n // Sales-closed is a read-only state — refuse the pick (the controller\n // doesn't gate tapping; server would 409 the eventual hold anyway).\n if (this.salesClosed) {\n this.controller.deselect([seat.id]);\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n return;\n }\n // Grouped tables own a dedicated whole/guest-count dialog. The raw\n // chair callback is retained for compatibility, but must not open the\n // ordinary one-seat confirm card in this full buyer widget.\n if (this.controller.tableSelection(seat.id)) return;\n this.flashPickedSeat(seat.id);\n if (this.opts.confirmSelection) this.showConfirm(seat);\n },\n onTableSelectionRequest: (table) => {\n if (this.salesClosed) {\n this.controller.deselect(table.physicalSeatIds);\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n return;\n }\n this.showTableDialog(table, false);\n },\n onDeselect: (seat) => {\n if (this.confirmSeat?.id === seat.id) this.dismissConfirm();\n if (this.tableDialog?.physicalSeatIds.includes(seat.id)) this.dismissTableDialog();\n },\n onSelectionLimit: () => {\n this.toast(`You can select up to ${this.maxTickets} tickets for this order.`, 'warning');\n },\n onViewChange: () => {\n this.reanchorConfirm();\n this.syncRung();\n this.syncProjection();\n this.drawMinimapRect();\n this.sectionCardOnView();\n },\n // Tapped-section glide-in → surface (or clear) the section-summary card.\n onSectionFocus: (summary) => this.showSectionCard(summary),\n onFocusSeat: (seat) => this.announceSeat(seat),\n onSeatHover: (d) => this.updateTooltip(d),\n onHint: (m) => {\n if (m) this.toast(m);\n },\n // Server declared the event closed mid-session (409 event_closed) — keep\n // the toast (raised by handleCta), and add the persistent read-only state.\n onSalesClosed: () => this.setSalesClosed(true),\n onError: (err) => this.opts.onError?.(err),\n });\n }\n\n async render(): Promise<this> {\n if (this.rendered) return this;\n this.rendered = true;\n ensureStyle();\n await loadLocale(this.opts.locale);\n if (this.opts.messages) setStringOverrides(this.opts.messages);\n\n // Hosted checkout asks the server what this event can charge through while\n // the buyer is still looking at the map. The answer cannot change mid-\n // session, and asking now means pressing Pay is not gated on a round trip.\n // A rejection is caught at the point of use, not here — a widget must not\n // die because a payment lookup failed.\n if (this.checkoutMode === 'hosted') this.paymentOptions = this.pubApi!.paymentOptions(this.opts.event);\n\n const mount = resolveContainer(this.opts.container!);\n const root = document.createElement('div');\n root.className = 'sl-picker';\n root.tabIndex = -1;\n this.root = root;\n mount.appendChild(root);\n root.addEventListener('keydown', (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (this.tableDialog) {\n e.preventDefault();\n e.stopPropagation();\n this.cancelTableDialog();\n } else if (this.confirmSeat) {\n e.preventDefault();\n e.stopPropagation();\n this.cancelConfirm();\n } else if (this.bestAvailableConfirm) {\n e.preventDefault();\n e.stopPropagation();\n this.bestAvailableConfirm = false;\n this.syncTray();\n }\n });\n\n // skeleton first — tokens get re-applied once the chart theme arrives\n Object.entries(resolveTokens(undefined, this.opts.theme)).forEach(([k, v]) => root.style.setProperty(k, v));\n root.innerHTML = `\n <div class=\"sl-head\">\n <div class=\"sl-logo\" data-ref=\"logo\"></div>\n <div class=\"sl-head-info\">\n <div class=\"sl-head-name\" data-ref=\"name\"></div>\n <div class=\"sl-head-meta\" data-ref=\"meta\"></div>\n </div>\n <span class=\"sl-hold-pill\" data-ref=\"hold\"></span>\n <span class=\"sl-closed-pill\" data-ref=\"closedPill\" role=\"status\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"5\" y=\"11\" width=\"14\" height=\"9\" rx=\"2\"/><path d=\"M8 11V7a4 4 0 0 1 8 0v4\"/></svg>\n <span data-ref=\"closedPillText\"></span>\n </span>\n <button type=\"button\" class=\"sl-close\" data-ref=\"close\" aria-label=\"Close\">\n <svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg>\n </button>\n </div>\n <div class=\"sl-body\">\n <div class=\"sl-map\">\n <div class=\"sl-map-host\" data-ref=\"map\"></div>\n <div class=\"sl-zoom\" data-ref=\"zoom\">\n <button type=\"button\" aria-label=\"Zoom in\" data-ref=\"zin\">+</button>\n <button type=\"button\" aria-label=\"Zoom out\" data-ref=\"zout\">−</button>\n <button type=\"button\" aria-label=\"Fit to screen\" data-ref=\"zfit\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3\"/></svg>\n </button>\n <button type=\"button\" aria-label=\"Full screen\" aria-pressed=\"false\" data-ref=\"zfs\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7\"/></svg>\n </button>\n </div>\n <div class=\"sl-boot\" data-ref=\"boot\"><span class=\"sl-boot-spin\"></span>Loading seat map…</div>\n <div class=\"sl-toast\" data-ref=\"toast\" role=\"status\" aria-live=\"polite\"></div>\n </div>\n <div class=\"sl-side\" data-ref=\"side\">\n <div class=\"sl-sheet-head\" data-ref=\"sheetHead\">\n <div class=\"sl-sheet-grab\"></div>\n <div class=\"sl-sheet-bar\">\n <div class=\"sl-sheet-peek\" data-ref=\"peek\"></div>\n <button type=\"button\" class=\"sl-sheet-toggle\" data-ref=\"sheetToggle\" aria-label=\"Open ticket panel\" aria-expanded=\"false\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M6 15l6-6 6 6\"/></svg>\n </button>\n </div>\n </div>\n <div class=\"sl-sec sl-filtersec\" data-ref=\"filtersSec\">Filters</div>\n <div class=\"sl-filters\" data-ref=\"filters\"></div>\n <div class=\"sl-sec sl-prices-sec\" data-ref=\"pricesSec\"><span>Ticket prices</span></div>\n <div class=\"sl-prices\" data-ref=\"prices\"></div>\n <div class=\"sl-live\" data-ref=\"live\" role=\"status\" aria-live=\"polite\"><span class=\"dot\" aria-hidden=\"true\"></span><span data-ref=\"liveText\">Live availability — seats update in real time</span></div>\n <div class=\"sl-sec sl-seats-sec\"><span>Your seats</span><span class=\"sl-seat-summary\" data-ref=\"seatSummary\"></span></div>\n <div class=\"sl-tray\" data-ref=\"tray\"></div>\n <div class=\"sl-foot\" data-ref=\"foot\">\n <div class=\"sl-hold-note\" data-ref=\"holdNote\" role=\"status\" aria-live=\"polite\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M20 6L9 17l-5-5\"/></svg>\n <span><b data-ref=\"holdTitle\">Seats secured</b><span class=\"sl-hold-copy\" data-ref=\"holdCopy\">Checkout timer is running.</span></span>\n <button type=\"button\" class=\"sl-hold-change\" data-ref=\"holdChange\" aria-label=\"Release held tickets and choose different seats\">Change</button>\n </div>\n <div class=\"sl-total\"><span data-ref=\"count\"></span><b data-ref=\"total\"></b></div>\n <button type=\"button\" class=\"sl-cta\" data-ref=\"cta\" disabled></button>\n </div>\n </div>\n </div>`;\n root.querySelectorAll<HTMLElement>('[data-ref]').forEach((el) => {\n this.els[el.dataset.ref!] = el;\n });\n this.mapHost = this.els.map as HTMLDivElement;\n\n // container-adaptive layout (breakpoint keys off the CONTAINER, not the viewport)\n const applyLayout = (): void => {\n const w = root.clientWidth;\n if (w <= 0) return;\n // Report our desired height to a host frame on every size change (deduped),\n // not just when the layout breakpoint flips below.\n this.reportFramedHeight();\n const next = w < 640 ? 'narrow' : 'wide';\n if (root.dataset.layout === next) return;\n root.dataset.layout = next;\n // Entering the mobile sheet layout: start in the peek state (map-first).\n if (next === 'narrow' && !root.dataset.sheet) root.dataset.sheet = 'peek';\n this.dockLayoutChrome();\n };\n this.ro = new ResizeObserver(applyLayout);\n this.ro.observe(root);\n // Some environments defer the ResizeObserver's initial callback (backgrounded\n // tabs throttle delivery). Seed the layout synchronously + next frame so a\n // container that mounts already-wide gets data-layout=\"wide\" immediately,\n // instead of waiting on a resize that may never arrive.\n applyLayout();\n requestAnimationFrame(applyLayout);\n\n // zoom + tooltip wiring\n this.els.zin.addEventListener('click', () => this.controller.zoomIn());\n this.els.zout.addEventListener('click', () => this.controller.zoomOut());\n this.els.zfit.addEventListener('click', () => this.controller.zoomToFit());\n // Full screen: native API with a CSS-fallback overlay for iOS Safari\n // (which has no element fullscreen). Esc exits both paths; the renderer's\n // ResizeObserver re-fits, plus an explicit zoomToFit for a crisp frame.\n this.els.zfs.addEventListener('click', () => this.toggleFullscreen());\n this.fsChangeHandler = (): void => {\n if (!document.fullscreenElement) this.setFsFallback(false);\n this.els.zfs?.setAttribute('aria-pressed', String(!!document.fullscreenElement || this.fsFallback || this.framedFs));\n requestAnimationFrame(() => this.controller.zoomToFit());\n };\n document.addEventListener('fullscreenchange', this.fsChangeHandler);\n\n // Mobile bottom sheet: swipe/tap on the sheet HEAD only (never the map host,\n // so the map's raw-pointer gesture pipeline is untouched). Swipe up → open\n // (≤50%); swipe down → peek; a plain tap toggles. The section-card strip's\n // ✕ lives inside the head — taps on the card must not toggle the sheet.\n const head = this.els.sheetHead;\n if (head) {\n const toggle = this.els.sheetToggle as HTMLButtonElement | undefined;\n const setSheet = (open: boolean): void => {\n root.dataset.sheet = open ? 'open' : 'peek';\n toggle?.setAttribute('aria-expanded', String(open));\n toggle?.setAttribute('aria-label', open ? 'Collapse ticket panel' : 'Open ticket panel');\n };\n setSheet(root.dataset.sheet === 'open');\n toggle?.addEventListener('click', (e) => {\n e.stopPropagation();\n setSheet(root.dataset.sheet !== 'open');\n });\n let startY = 0;\n let swiped = false;\n let tracking = false;\n head.addEventListener('pointerdown', (e: PointerEvent) => {\n tracking = true;\n swiped = false;\n startY = e.clientY;\n head.setPointerCapture?.(e.pointerId);\n });\n head.addEventListener('pointermove', (e: PointerEvent) => {\n if (!tracking || swiped) return;\n const dy = e.clientY - startY;\n if (dy < -18) {\n setSheet(true);\n swiped = true;\n } else if (dy > 18) {\n setSheet(false);\n swiped = true;\n }\n });\n head.addEventListener('pointerup', (e: PointerEvent) => {\n if (tracking && !swiped && Math.abs(e.clientY - startY) < 6) {\n if (!(e.target as HTMLElement).closest('.sl-seccard,.sl-sheet-toggle')) setSheet(root.dataset.sheet !== 'open');\n }\n tracking = false;\n head.releasePointerCapture?.(e.pointerId);\n });\n }\n this.tipEl = document.createElement('div');\n this.tipEl.setAttribute('role', 'tooltip');\n this.tipEl.className = 'sl-tip';\n this.els.map.appendChild(this.tipEl);\n this.els.map.addEventListener('mousemove', (e: MouseEvent) => {\n const r = this.els.map.getBoundingClientRect();\n this.tipPos = { x: e.clientX - r.left, y: e.clientY - r.top };\n if (this.tipEl && this.tipEl.style.display !== 'none') this.placeTooltip();\n });\n\n this.els.cta.addEventListener('click', () => void this.handleCta());\n this.els.holdChange?.addEventListener('click', () => void this.handleChangeSeats());\n\n const canvasHost = document.createElement('div');\n canvasHost.style.cssText = 'position:absolute;inset:0';\n this.mapHost.appendChild(canvasHost);\n const info = await this.controller.render(canvasHost);\n if (this.destroyed) return this;\n if (!info) {\n this.els.boot.innerHTML =\n '<div class=\"sl-boot-title\">The seat map didn’t load</div>' +\n '<div>Check your connection and try again.</div>' +\n '<button type=\"button\" class=\"sl-boot-retry\">Try again</button>';\n this.els.boot.querySelector('button')!.addEventListener('click', () => {\n // full remount: cheapest reliable recovery\n const container = this.opts.container!;\n const opts = this.opts;\n this.destroy();\n void new SeatPicker({ ...opts, container }).render();\n });\n return this;\n }\n this.els.boot.remove();\n this.startRealtime();\n // Read-only load state: the chart() payload carries salesClosed.\n this.salesClosed = !!info.salesClosed;\n this.controller.setViewMode(this.normalizeInitialView(this.opts.initialView));\n\n // Feature 6: anchor regions for all persistent map chrome, then move the\n // pre-built zoom column + toast into their regions (both were in the skeleton).\n this.buildRegions();\n this.regions['bottom-right'].appendChild(this.els.zoom);\n this.regions['bottom-center'].appendChild(this.els.toast);\n\n if (info.mode === 'test') {\n // TEST MODE reads as a small badge in the top-right region (was a corner\n // ribbon that collided with the top-right control cluster on narrow widths).\n const badge = document.createElement('div');\n badge.className = 'sl-testbadge';\n badge.textContent = t('picker.testMode');\n badge.setAttribute('aria-label', t('picker.testMode'));\n this.regions['top-right'].appendChild(badge);\n }\n\n // theme: defaults ← org chart theme ← host overrides\n const chartTheme = this.controller.doc?.theme;\n Object.entries(resolveTokens(chartTheme, this.opts.theme)).forEach(([k, v]) => root.style.setProperty(k, v));\n this.currency = info.currency ?? this.opts.currency ?? 'USD';\n\n // header\n const logoUrl = this.opts.theme?.logoUrl ?? chartTheme?.logoUrl;\n if (logoUrl) this.els.logo.innerHTML = `<img src=\"${logoUrl}\" alt=\"\">`;\n else this.els.logo.textContent = (this.opts.theme?.brandName ?? chartTheme?.brandName ?? info.eventName ?? '?').slice(0, 1).toUpperCase();\n this.els.name.textContent = info.eventName ?? '';\n const when = info.startsAt\n ? new Date(info.startsAt).toLocaleString(this.opts.locale, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })\n : '';\n this.els.meta.textContent = [info.venue, when].filter(Boolean).join(' · ');\n\n // \"Powered by SeatLayer\" attribution badge — hidden when the host opts out\n // OR the org's paid chart theme sets hideBadge (either being true hides it).\n this.buildBadge(chartTheme);\n\n // Accessibility filter chips — only for types actually present in the chart.\n // Same sweep also detects whether ANY seat carries a limited-view (restricted\n // or obstructed) commercial flag, which gates the \"Hide limited-view seats\"\n // toggle that shares this chip row.\n const present = new Set<AccessibilityType>();\n let hasLimitedView = false;\n if (this.controller.doc) {\n for (const seat of expandChart(this.controller.doc)) {\n for (const type of seat.accessibility ?? []) present.add(type);\n if (seat.accessible && !seat.accessibility?.length) present.add('wheelchair');\n if (seat.commercial?.restrictedView || seat.commercial?.obstructedView) hasLimitedView = true;\n }\n }\n // Jump to the seats rung when a dimming filter turns on — the dimming only\n // renders at seat detail; applying it zoomed out would silently dim seats\n // the buyer can't see. Shared by the a11y chips and the limited-view toggle.\n const focusSeatsForFilter = (): void => {\n if (this.rungsEl && this.controller.getRung() !== 'seats') {\n this.controller.setRung('seats');\n this.collapseSectionCard();\n this.syncRung();\n }\n };\n if (present.size || hasLimitedView) {\n const chips = document.createElement('div');\n chips.className = 'sl-chips';\n this.regions['top-left'].appendChild(chips);\n this.a11yChipsEl = chips;\n\n if (present.size) {\n const mk = (key: AccessibilityType | 'all', label: string): string =>\n `<button type=\"button\" class=\"sl-chip-f${key === 'all' ? ' on' : ''}\" data-a11y=\"1\" data-f=\"${key}\">${label}</button>`;\n chips.insertAdjacentHTML('beforeend',\n mk('all', 'All seats') +\n ACCESSIBILITY_TYPES\n .filter(({ key }) => present.has(key))\n .map(({ key, short, icon }) => mk(key, `${icon} ${short}`))\n .join(''));\n // Multi-select OR semantics (parity with the buyer page): each type chip\n // toggles independently; the active filter is the union; \"All seats\"\n // clears. A buyer needing wheelchair AND companion seats combines both.\n const active = new Set<AccessibilityType>();\n const syncChips = (): void => {\n chips.querySelectorAll<HTMLButtonElement>('button[data-a11y]').forEach((b) => {\n const f = b.dataset.f as AccessibilityType | 'all';\n const on = f === 'all' ? active.size === 0 : active.has(f);\n b.classList.toggle('on', on);\n b.setAttribute('aria-pressed', String(on));\n });\n const filter = active.size ? [...active] : null;\n this.controller.setAccessibilityFilter(filter);\n if (filter) focusSeatsForFilter();\n };\n chips.querySelectorAll<HTMLButtonElement>('button[data-a11y]').forEach((btn) => {\n btn.addEventListener('click', () => {\n const f = btn.dataset.f as AccessibilityType | 'all';\n if (f === 'all') active.clear();\n else if (active.has(f)) active.delete(f);\n else active.add(f);\n syncChips();\n });\n });\n }\n\n // \"Hide limited-view seats\" toggle — one independent on/off chip that dims\n // free seats flagged restricted/obstructed view (same chip pattern, sits\n // beside the a11y chips). Isolated from the a11y OR-union above.\n if (hasLimitedView) {\n const limited = document.createElement('button');\n limited.type = 'button';\n limited.className = 'sl-chip-f';\n limited.setAttribute('aria-pressed', 'false');\n limited.innerHTML = `◐ ${this.tf('picker.hideLimitedView', 'Hide limited-view seats')}`;\n chips.appendChild(limited);\n limited.addEventListener('click', () => {\n const limitedOn = !this.limitedViewFilter;\n this.limitedViewFilter = limitedOn;\n limited.classList.toggle('on', limitedOn);\n limited.setAttribute('aria-pressed', String(limitedOn));\n this.controller.setCommercialLimitedFilter(limitedOn);\n // Keep 3D in step — the filter must survive the switch between views.\n this.pushAvailabilityTo3d();\n if (limitedOn) focusSeatsForFilter();\n });\n }\n }\n\n // Colorblind-safe toggle rides in the zoom column (wide) or the sheet's\n // Filters row (narrow) — dockLayoutChrome moves it between the two.\n const cb = document.createElement('button');\n cb.type = 'button';\n cb.className = 'sl-cbbtn';\n this.cbEl = cb;\n cb.setAttribute('aria-label', 'Toggle colorblind-friendly colors');\n // Rehydrated from the shared preference (constructor read stored → this.cbSafe).\n cb.setAttribute('aria-pressed', String(this.cbSafe));\n cb.innerHTML = '<svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg>';\n this.els.zfit.parentElement!.appendChild(cb);\n // Route through the single source of truth so host chrome (e.g. the Designer\n // preview chip) and this in-widget button always agree.\n cb.addEventListener('click', () => { this.setColorblindSafe(!this.cbSafe); });\n\n // Screen-reader announcements for keyboard seat focus.\n this.srEl = document.createElement('div');\n this.srEl.className = 'sl-sr';\n this.srEl.setAttribute('aria-live', 'polite');\n root.appendChild(this.srEl);\n\n // Big-venue chrome: LOD rung pills, multi-floor switcher, section card.\n // Appended AFTER controller.render() — render() wipes the map host's children.\n this.buildArenaChrome();\n\n // F3 minimap (venue overview + viewport rect) and F4 price-band filter.\n // Same post-render append (the map host was wiped by controller.render()).\n this.buildMinimap();\n this.buildPriceFilter();\n\n // \"Need more time?\" prompt (over the map) + booked-confirmation overlay (over\n // the whole widget). Both appended post-render for the same wipe reason.\n this.buildExtendPrompt();\n this.buildBookedOverlay();\n this.buildSoldoutOverlay();\n\n // Dock layout-dependent chrome (a11y chips + colorblind toggle) for the\n // CURRENT layout — the initial applyLayout ran before these were built.\n this.dockLayoutChrome();\n\n await this.restoreRememberedHold();\n if (this.destroyed) return this;\n\n // Reflect the read-only load state (pill + disabled CTA/controls) with no\n // toast — a fresh mount into a closed event is not a live \"just closed\" event.\n if (this.salesClosed) this.applySalesClosed();\n this.syncPrices();\n this.syncTray();\n // Last, so a buyer coming back from a gateway sees a finished map behind the\n // confirmation rather than a skeleton.\n this.resumeHostedOrder();\n return this;\n }\n\n /**\n * A hosted gateway returned this buyer to a page that runs the widget, with\n * `?order=…&status=…` in the URL. Pick the order up and finish the story.\n *\n * Only `success` resumes. `cancelled` means the buyer backed out at the\n * gateway and their seats are still held — the map they are looking at IS the\n * right screen, and opening a card to say \"you cancelled\" would be noise.\n *\n * The two parameters are then stripped with `replaceState`, because they are a\n * one-shot instruction: leaving them in place would re-open the confirmation\n * on every later navigation, and would carry an order id into browser history\n * and any Referer this page later sends. `status` is only ever removed\n * alongside an `order` we actually consumed, so a host page that uses a\n * `status` parameter of its own keeps it.\n */\n private resumeHostedOrder(): void {\n if (this.checkoutMode !== 'hosted' || typeof location === 'undefined') return;\n const params = new URLSearchParams(location.search);\n const orderId = params.get('order');\n if (!orderId) return;\n const status = params.get('status');\n params.delete('order');\n params.delete('status');\n try {\n const query = params.toString();\n history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);\n } catch {\n // A sandboxed frame can refuse replaceState. Losing the tidy-up is not a\n // reason to lose the confirmation.\n }\n if (status !== 'success') return;\n void this.openCheckoutPanel({ kind: 'resume', orderId });\n }\n\n /**\n * Move layout-dependent chrome between its wide dock (map regions / zoom\n * column) and its narrow dock (the sheet's consolidated Filters row), and\n * re-render the section card in the form the layout wants (docked card/pill\n * on wide, sheet strip on narrow). Runs on every layout flip + once post-render.\n */\n private dockLayoutChrome(): void {\n const narrow = this.root?.dataset.layout === 'narrow';\n const filters = this.els.filters;\n if (filters) {\n if (narrow) {\n if (this.a11yChipsEl) filters.appendChild(this.a11yChipsEl);\n if (this.cbEl) filters.appendChild(this.cbEl);\n } else {\n if (this.a11yChipsEl) this.regions['top-left']?.appendChild(this.a11yChipsEl);\n if (this.cbEl) this.els.zoom?.appendChild(this.cbEl);\n }\n const has = narrow && filters.children.length > 0;\n filters.classList.toggle('has', has);\n this.els.filtersSec?.classList.toggle('has', has);\n }\n if (this.lastSection) this.renderSectionCard(this.lastSection);\n }\n\n /** The \"Need more time?\" prompt shown in the hold's final EXTEND_PROMPT_MS. */\n private buildExtendPrompt(): void {\n const el = document.createElement('div');\n el.className = 'sl-extend';\n el.setAttribute('role', 'status');\n el.innerHTML =\n `<span class=\"sl-extend-txt\" data-ref=\"extendTxt\"></span>` +\n `<button type=\"button\" class=\"sl-extend-btn\" data-ref=\"extendBtn\"></button>`;\n (this.regions['bottom-center'] ?? this.els.map).appendChild(el);\n this.extendEl = el;\n this.els.extendTxt = el.querySelector('[data-ref=\"extendTxt\"]') as HTMLElement;\n this.els.extendBtn = el.querySelector('[data-ref=\"extendBtn\"]') as HTMLElement;\n this.els.extendBtn.textContent = 'Add time';\n this.els.extendBtn.addEventListener('click', () => void this.handleExtend());\n }\n\n /** Success overlay + onBooked fire when the held seats settle to booked. */\n private buildBookedOverlay(): void {\n const el = document.createElement('div');\n el.className = 'sl-booked';\n el.setAttribute('role', 'status');\n el.setAttribute('aria-live', 'polite');\n el.innerHTML =\n `<div class=\"sl-booked-badge\"><svg viewBox=\"0 0 24 24\"><path d=\"M20 6L9 17l-5-5\"/></svg></div>` +\n `<div class=\"sl-booked-title\">You're all set</div>` +\n `<div class=\"sl-booked-sub\" data-ref=\"bookedSub\"></div>`;\n this.root!.appendChild(el);\n this.bookedEl = el;\n this.els.bookedSub = el.querySelector('[data-ref=\"bookedSub\"]') as HTMLElement;\n }\n\n /**\n * Localized string with a literal fallback. `t()` returns the key itself for\n * unknown keys, so this collapses that to `fallback` — while still honoring a\n * host `messages` override (which makes `t()` return the override, not the key).\n */\n private tf(key: string, fallback: string): string {\n const v = t(key);\n return v === key ? fallback : v;\n }\n\n /** Sold-out overlay — centered over the map, disabled waitlist stub (Gap 2). */\n private buildSoldoutOverlay(): void {\n if (!this.els.map) return;\n const el = document.createElement('div');\n el.className = 'sl-soldout';\n el.setAttribute('role', 'status');\n const name = (this.controller.doc?.theme?.brandName ?? this.opts.theme?.brandName ?? this.els.name?.textContent ?? this.tf('picker.soldOutEyebrow', 'This event')).toUpperCase();\n el.innerHTML =\n `<div class=\"sl-soldout-eyebrow\">${name}</div>` +\n `<div class=\"sl-soldout-title\">${this.tf('picker.soldOutTitle', 'Sold out')}</div>` +\n `<p class=\"sl-soldout-copy\">${this.tf('picker.soldOutCopy', \"Every seat is gone. Join the waitlist and we’ll email you if seats are released.\")}</p>` +\n `<button type=\"button\" class=\"sl-soldout-btn\" disabled>${this.tf('picker.waitlist', 'Join waitlist')}</button>`;\n this.els.map.appendChild(el);\n this.soldoutEl = el;\n }\n\n /**\n * Recompute the sold-out state on every price/availability sync. Sold-out ⇔\n * every SEATED category's live free count is 0. Suppressed when the chart has\n * GA areas (GA capacity isn't per-seat, so seated counts would read 0 and\n * falsely block standing room) — mirrors the public page. Clears live when WS\n * frees a seat up.\n */\n private syncSoldout(categories: Array<{ key: string }>, left: Record<string, number>): void {\n const hasGA = this.controller.getGAAreas().length > 0;\n const soldOut = this.isSoldOut(categories, left, hasGA);\n if (soldOut === this.soldOut) return;\n this.soldOut = soldOut;\n this.soldoutEl?.classList.toggle('on', soldOut);\n }\n\n /**\n * Pure sold-out predicate: every SEATED category's free count is 0, there is at\n * least one seated category, and there are no GA areas (GA capacity isn't\n * per-seat, so seated counts read 0 and would falsely block standing room).\n * `left` is seeded implicitly — a missing key means a fully-booked tier (0 free).\n */\n private isSoldOut(categories: Array<{ key: string }>, left: Record<string, number>, hasGA: boolean): boolean {\n return !hasGA && categories.length > 0 && categories.every((c) => (left[c.key] ?? 0) === 0);\n }\n\n /**\n * Sales-closed read-only state (Gap 3): persistent header pill, disabled CTA\n * with a closed label, and frozen best-available / GA controls. `setSalesClosed`\n * is the reactive entry (live 409 event_closed); `applySalesClosed` is the\n * idempotent DOM apply used at load and on transition.\n */\n private setSalesClosed(closed: boolean): void {\n if (this.salesClosed === closed) return;\n this.salesClosed = closed;\n this.applySalesClosed();\n }\n\n private applySalesClosed(): void {\n if (this.salesClosed && this.tableDialog && !this.tableDialogHeld) this.cancelTableDialog();\n const pill = this.els.closedPill;\n if (pill) {\n pill.classList.toggle('on', this.salesClosed);\n const text = this.els.closedPillText ?? pill;\n text.textContent = this.tf('picker.salesClosedPill', 'Sales are closed');\n }\n this.root?.setAttribute('data-sales-closed', String(this.salesClosed));\n this.syncCta();\n this.syncTray();\n }\n\n /** The badge is hidden when the host opts out OR the org's theme sets hideBadge. */\n private badgeHidden(chartTheme?: ChartTheme): boolean {\n return !!(this.opts.hideBadge || chartTheme?.hideBadge);\n }\n\n /** Attribution badge in the side-panel foot (Gap 7). Hidden per host/theme. */\n private buildBadge(chartTheme: ChartTheme | undefined): void {\n if (this.badgeHidden(chartTheme)) return;\n const foot = this.els.foot;\n if (!foot) return;\n const el = document.createElement('div');\n el.className = 'sl-powered';\n el.innerHTML =\n `<span class=\"sl-powered-mark\" aria-hidden=\"true\">` +\n SEATLAYER_ATTRIBUTION_MARK_SVG +\n `</span><span>${this.tf('picker.poweredBy', 'Powered by SeatLayer')}</span>`;\n foot.appendChild(el);\n }\n\n // ---- Feature 6: chrome anchor regions -------------------------------------\n\n /**\n * Create the positioned flex containers that own every persistent map overlay.\n * Appended once after controller.render(); each chrome piece is then appended\n * INTO its region and flows within it, so nothing free-floats over anything\n * else. Regions carve the map into non-overlapping zones (top strip split into\n * left/center/right, left rail, and the three used corners).\n */\n private buildRegions(): void {\n if (!this.els.map) return;\n const REGIONS = ['top-left', 'top-center', 'top-right', 'left-rail', 'bottom-left', 'bottom-center', 'bottom-right'];\n for (const region of REGIONS) {\n const el = document.createElement('div');\n el.className = 'sl-anchor';\n el.dataset.region = region;\n this.els.map.appendChild(el);\n this.regions[region] = el;\n }\n }\n\n // ---- F3 minimap -----------------------------------------------------------\n\n /** Read a resolved --sl-* token value (canvas needs a real color, not var()). */\n private cssVar(name: string): string {\n return this.root ? getComputedStyle(this.root).getPropertyValue(name).trim() : '';\n }\n\n /** Motion is progressive enhancement; all state remains legible when reduced. */\n private reducedMotion(): boolean {\n return typeof window !== 'undefined' &&\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n }\n\n private scheduleMotion(fn: () => void, delay: number): void {\n const timer = setTimeout(() => {\n this.motionTimers.delete(timer);\n if (!this.destroyed) fn();\n }, delay);\n this.motionTimers.add(timer);\n }\n\n /** Restart one finite CSS animation without leaving a permanent state class. */\n private animateOnce(el: HTMLElement | undefined, className: string, duration = 600): void {\n if (!el || this.reducedMotion()) return;\n el.classList.remove(className);\n void el.offsetWidth;\n el.classList.add(className);\n this.scheduleMotion(() => el.classList.remove(className), duration);\n }\n\n /** Selection feedback belongs on the selected seat, not across the whole map. */\n private flashPickedSeat(id: string): void {\n if (this.reducedMotion()) return;\n this.controller.flashSeat(id, this.cssVar('--sl-accent') || '#f4b740');\n }\n\n /** A completed hold gets one short map ripple per concrete seat. */\n private flashHeldSeats(hold: HoldResult): void {\n if (this.reducedMotion()) return;\n const labels = (hold.items ?? []).filter((item) => item.objectType !== 'ga').map((item) => item.label);\n labels.slice(0, 10).forEach((label, index) => {\n const seat = this.controller.seatByLabel(label);\n if (!seat) return;\n this.scheduleMotion(\n () => this.controller.flashSeat(seat.id, this.cssVar('--sl-accent') || '#f4b740'),\n index * 55,\n );\n });\n }\n\n /** Update only the action affordance; selection callbacks must not refire. */\n private committedSelection(): PickerSeat[] {\n const candidateId = this.confirmSeat?.id;\n const pendingTableId = this.tableDialog && !this.tableDialogHeld ? this.tableDialog.id : null;\n return this.controller.getSelection().filter((seat) => seat.id !== candidateId && seat.id !== pendingTableId);\n }\n\n private pendingSelectionCount(): number {\n const heldItems = this.hold?.items ?? [];\n const heldLabels = new Set(heldItems.map((item) => item.label));\n const pendingSeats = this.committedSelection()\n .filter((seat) => !heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n return pendingSeats + this.pendingGACount();\n }\n\n private heldGACounts(): Map<string, number> {\n const heldGA = new Map<string, number>();\n for (const item of (this.hold?.items ?? []).filter((candidate) => candidate.objectType === 'ga')) {\n heldGA.set(item.objectId, (heldGA.get(item.objectId) ?? 0) + (item.quantity ?? 1));\n }\n return heldGA;\n }\n\n private pendingGACount(): number {\n const heldGA = this.heldGACounts();\n return [...this.gaQty.entries()].reduce(\n (sum, [areaId, qty]) => sum + Math.max(0, qty - (heldGA.get(areaId) ?? 0)),\n 0,\n );\n }\n\n private heldTicketCount(): number {\n return (this.hold?.items ?? []).reduce((sum, item) => sum + (item.quantity ?? 1), 0);\n }\n\n private totalTicketCount(): number {\n const heldLabels = new Set((this.hold?.items ?? []).map((item) => item.label));\n const freshSeats = this.committedSelection()\n .filter((seat) => !heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n return this.heldTicketCount() + freshSeats + this.pendingGACount();\n }\n\n /** Held tickets and standing quantities consume the same order-wide cap. */\n private updateSelectionCapacity(): void {\n const heldLabels = new Set((this.hold?.items ?? []).map((item) => item.label));\n const selectedHeld = this.committedSelection()\n .filter((seat) => heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n const remaining = Math.max(0, this.maxTickets - this.heldTicketCount() - this.pendingGACount());\n this.controller.setMaxSelection(selectedHeld + remaining);\n }\n\n private canAddTicket(): boolean {\n if (this.totalTicketCount() < this.maxTickets) return true;\n this.toast(`You can select up to ${this.maxTickets} tickets for this order.`, 'warning');\n return false;\n }\n\n private pendingGATotal(gaAreas: ReturnType<PickerController['getGAAreas']>): number {\n const heldGA = new Map<string, number>();\n for (const item of (this.hold?.items ?? []).filter((candidate) => candidate.objectType === 'ga')) {\n heldGA.set(item.objectId, (heldGA.get(item.objectId) ?? 0) + (item.quantity ?? 1));\n }\n return gaAreas.reduce(\n (sum, area) => sum + this.paidPrice(area.categoryKey, null, area.price) * Math.max(0, (this.gaQty.get(area.id) ?? 0) - (heldGA.get(area.id) ?? 0)),\n 0,\n );\n }\n\n private syncCta(count = this.lastTrayCount, pending = this.pendingSelectionCount()): void {\n const cta = this.els.cta as HTMLButtonElement | undefined;\n if (!cta) return;\n if (this.salesClosed) {\n cta.disabled = true;\n cta.textContent = this.tf('picker.salesClosedCta', 'Sales closed');\n return;\n }\n if (this.confirmSeat || (this.tableDialog && !this.tableDialogHeld)) {\n cta.disabled = true;\n cta.textContent = this.tableDialog ? 'Confirm your table' : 'Confirm or cancel this seat';\n return;\n }\n if (this.ctaPhase === 'holding') {\n cta.disabled = true;\n cta.innerHTML = '<span class=\"sl-cta-spin\" aria-hidden=\"true\"></span>Securing seats…';\n return;\n }\n if (this.ctaPhase === 'checkout') {\n cta.disabled = true;\n cta.innerHTML = '<span class=\"sl-cta-spin\" aria-hidden=\"true\"></span>Opening checkout…';\n return;\n }\n cta.disabled = count === 0;\n cta.textContent = this.hold\n ? pending\n ? `Secure ${pending} more & checkout`\n : 'Continue to checkout'\n : count\n ? 'Hold seats & checkout'\n : 'Select seats';\n }\n\n private setCtaPhase(phase: 'idle' | 'holding' | 'checkout'): void {\n this.ctaPhase = phase;\n this.syncCta();\n if (phase === 'checkout') {\n this.scheduleMotion(() => {\n if (this.ctaPhase !== 'checkout') return;\n this.ctaPhase = 'idle';\n this.syncCta();\n }, 1100);\n }\n }\n\n /** Session-scoped capability key: isolated by API origin and event. */\n private holdStorageKey(): string {\n return `@seatlayer/hold/v1/${encodeURIComponent(this.apiBase)}/${encodeURIComponent(this.opts.event)}`;\n }\n\n private rememberedHoldId(): string | null {\n if (this.opts.initialHoldId) return this.opts.initialHoldId;\n if (this.opts.restoreHold === false || typeof window === 'undefined') return null;\n try {\n return window.sessionStorage.getItem(this.holdStorageKey());\n } catch {\n return null;\n }\n }\n\n private rememberHold(hold: HoldResult): void {\n if (this.opts.restoreHold === false || typeof window === 'undefined') return;\n try {\n // Persist only the opaque capability. Labels, prices and expiry are\n // always reloaded from the authoritative server projection.\n window.sessionStorage.setItem(this.holdStorageKey(), hold.holdId);\n } catch {\n // Storage can be unavailable in privacy/sandboxed embeds; the live picker\n // remains fully functional for the current mount.\n }\n }\n\n private forgetHold(): void {\n if (typeof window === 'undefined') return;\n try {\n window.sessionStorage.removeItem(this.holdStorageKey());\n } catch {\n // Best-effort cleanup only.\n }\n }\n\n private async resumeHoldFromServer(holdId: string, automatic: boolean): Promise<HoldResult | null> {\n try {\n const h = await this.controller.resumeHold(holdId);\n if (!h) return null;\n const restored: HoldResult = {\n holdId: h.holdId,\n expiresAt: h.expiresAt,\n seats: h.seats,\n items: h.items,\n };\n this.hold = restored;\n // A resumed capability came from an earlier checkout handoff. Keep it\n // alive if this picker mount is refreshed or torn down before the buyer\n // explicitly removes/releases it.\n this.handedOff = true;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.startHoldTimer(restored.expiresAt);\n this.rememberHold(restored);\n this.syncTray();\n this.emitHoldChange();\n this.opts.onHoldRestored?.(restored, restored.seats ?? [], this.buildHandoff(restored));\n if (automatic) this.toast('Your held tickets have been restored.', 'success');\n return restored;\n } catch (error) {\n const status = (error as { status?: number })?.status;\n if (status === 404 || status === 409) {\n // A stale/foreign/settled capability is expected recovery state, not a\n // picker failure. Drop it and let the buyer choose again.\n this.forgetHold();\n } else {\n this.opts.onError?.(error);\n }\n return null;\n }\n }\n\n private async restoreRememberedHold(): Promise<void> {\n const holdId = this.rememberedHoldId();\n if (holdId) await this.resumeHoldFromServer(holdId, true);\n }\n\n /** Section-bearing objects on the active floor (single-floor → doc.objects). */\n private activeFloorObjects(): SectionLike[] {\n const doc = this.controller.doc;\n if (!doc) return [];\n const floors = doc.floors;\n if (floors?.length) {\n const id = this.controller.getActiveFloorId();\n return ((floors.find((f) => f.id === id) ?? floors[0]).objects as unknown as SectionLike[]) ?? [];\n }\n return (doc.objects as unknown as SectionLike[]) ?? [];\n }\n\n /**\n * Build the overview minimap: a static venue thumbnail (section outlines, or\n * seat dots when the chart has no sections) with the live viewport rectangle\n * drawn on top. The rect tracks pan/zoom via the constructor's onViewChange.\n */\n private buildMinimap(): void {\n const vp = this.controller.getViewport();\n if (!vp || !this.els.map) return;\n const b = vp.bounds;\n if (!(b.width > 0 && b.height > 0)) return;\n\n const MAXW = 158;\n const MAXH = 118;\n const PAD = 6;\n const aspect = b.width / Math.max(1, b.height);\n let w = MAXW;\n let h = Math.round(MAXW / aspect);\n if (h > MAXH) {\n h = MAXH;\n w = Math.round(MAXH * aspect);\n }\n w = Math.max(64, w);\n h = Math.max(48, h);\n const dpr = Math.min(2, window.devicePixelRatio || 1);\n\n const wrap = document.createElement('div');\n wrap.className = 'sl-minimap';\n wrap.setAttribute('aria-hidden', 'true'); // decorative; the map itself is the keyboard surface\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(w * dpr);\n canvas.height = Math.round(h * dpr);\n canvas.style.width = `${w}px`;\n canvas.style.height = `${h}px`;\n wrap.appendChild(canvas);\n (this.regions['bottom-left'] ?? this.els.map).appendChild(wrap);\n this.miniCanvas = canvas;\n\n // world → minimap (device px), contain + centre — matches thumb.ts.\n const scale = Math.min((w - PAD * 2) / Math.max(1, b.width), (h - PAD * 2) / Math.max(1, b.height)) * dpr;\n const offX = (w * dpr - b.width * scale) / 2 - b.x * scale;\n const offY = (h * dpr - b.height * scale) / 2 - b.y * scale;\n this.miniTf = { scale, offX, offY, dpr };\n\n const base = document.createElement('canvas');\n base.width = canvas.width;\n base.height = canvas.height;\n this.miniBase = base;\n\n // Click a section on the minimap → glide the camera into it (existing API).\n wrap.addEventListener('click', (e) => this.minimapJump(e));\n\n this.drawMinimapStatic();\n this.drawMinimapRect();\n }\n\n /** Repaint the static overview + rect (floor switch, live open/close). */\n private refreshMinimap(): void {\n if (!this.miniBase) return;\n this.drawMinimapStatic();\n this.drawMinimapRect();\n }\n\n /** Paint the venue overview into the offscreen base canvas. */\n private drawMinimapStatic(): void {\n const base = this.miniBase;\n const tf = this.miniTf;\n const doc = this.controller.doc;\n if (!base || !tf || !doc) return;\n const ctx = base.getContext('2d');\n if (!ctx) return;\n ctx.clearRect(0, 0, base.width, base.height);\n const fx = (x: number): number => x * tf.scale + tf.offX;\n const fy = (y: number): number => y * tf.scale + tf.offY;\n const line = this.cssVar('--sl-line') || 'rgba(139,147,167,.5)';\n const muted = this.cssVar('--sl-muted') || '#8b93a7';\n const accent = this.cssVar('--sl-accent') || '#6e7bff';\n const zoneColor = new Map((doc.zones ?? []).map((z) => [z.id, z.color] as const));\n\n let drewSection = false;\n for (const o of this.activeFloorObjects()) {\n if (o.type !== 'section' || !o.outline || o.outline.length < 3) continue;\n drewSection = true;\n const closed = this.controller.isSectionClosed(o.id);\n const fill = closed ? muted : o.color ?? (o.zone && zoneColor.get(o.zone)) ?? accent;\n ctx.beginPath();\n o.outline.forEach((p, i) => (i === 0 ? ctx.moveTo(fx(p.x), fy(p.y)) : ctx.lineTo(fx(p.x), fy(p.y))));\n ctx.closePath();\n ctx.globalAlpha = closed ? 0.26 : 0.42;\n ctx.fillStyle = fill;\n ctx.fill();\n ctx.globalAlpha = 0.85;\n ctx.lineWidth = Math.max(1, tf.dpr);\n ctx.strokeStyle = line;\n ctx.stroke();\n }\n ctx.globalAlpha = 1;\n\n // Section-less charts: fall back to faint category-colored seat dots.\n if (!drewSection) {\n const r = Math.max(1, tf.dpr);\n for (const seat of expandChart(doc)) {\n const cat = doc.categories.find((c) => c.key === seat.categoryKey);\n ctx.fillStyle = cat?.color ?? accent;\n ctx.beginPath();\n ctx.arc(fx(seat.x), fy(seat.y), r, 0, Math.PI * 2);\n ctx.fill();\n }\n }\n }\n\n /** Blit the base overview, then stroke the current viewport rectangle on top. */\n private drawMinimapRect(): void {\n const canvas = this.miniCanvas;\n const base = this.miniBase;\n const tf = this.miniTf;\n if (!canvas || !base || !tf) return;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(base, 0, 0);\n const vp = this.controller.getViewport();\n if (!vp) return;\n const v = vp.visible;\n const x = v.x * tf.scale + tf.offX;\n const y = v.y * tf.scale + tf.offY;\n const w = v.width * tf.scale;\n const h = v.height * tf.scale;\n const accent = this.cssVar('--sl-accent') || '#f4b740';\n ctx.save();\n ctx.globalAlpha = 0.14;\n ctx.fillStyle = accent;\n ctx.fillRect(x, y, w, h);\n ctx.globalAlpha = 1;\n ctx.lineWidth = Math.max(1.5, tf.dpr * 1.5);\n ctx.strokeStyle = accent;\n ctx.strokeRect(x, y, w, h);\n ctx.restore();\n }\n\n /** Minimap click → focus the section under the point (or overview on a miss). */\n private minimapJump(e: MouseEvent): void {\n const canvas = this.miniCanvas;\n const tf = this.miniTf;\n if (!canvas || !tf) return;\n const r = canvas.getBoundingClientRect();\n const px = (e.clientX - r.left) * (canvas.width / r.width);\n const py = (e.clientY - r.top) * (canvas.height / r.height);\n const wx = (px - tf.offX) / tf.scale;\n const wy = (py - tf.offY) / tf.scale;\n for (const o of this.activeFloorObjects()) {\n if (o.type !== 'section' || !o.outline || o.outline.length < 3) continue;\n if (this.controller.isSectionClosed(o.id)) continue;\n if (pointInPolygon(wx, wy, o.outline)) {\n this.controller.focusSection(o.id);\n return;\n }\n }\n this.controller.overview();\n }\n\n // ---- F4 price-band filter -------------------------------------------------\n\n /** Effective display price of a category: host pricing override → first tier → base. */\n private catPrice(c: { key?: string; price?: number; tiers?: { id?: string; price: number }[] }): number | undefined {\n const chart = c.tiers?.length ? c.tiers[0].price : c.price;\n if (chart === undefined || !c.key) return chart;\n return this.paidPrice(c.key, c.tiers?.[0]?.id ?? null, chart);\n }\n\n /** Derive price bands: one chip per distinct price (≤5), else quantile ranges. */\n private priceBands(): PriceBand[] {\n const doc = this.controller.doc;\n if (!doc) return [];\n const priced = doc.categories\n .map((c) => ({ key: c.key, price: this.catPrice(c) }))\n .filter((x): x is { key: string; price: number } => x.price != null);\n if (!priced.length) return [];\n const distinct = [...new Set(priced.map((p) => p.price))].sort((a, b) => a - b);\n if (distinct.length <= 5) {\n return distinct.map((price) => ({\n id: `p${price}`,\n label: this.money(price),\n keys: priced.filter((p) => p.price === price).map((p) => p.key),\n min: price,\n max: price,\n }));\n }\n // Many distinct prices → ~4 contiguous quantile bands (ranges).\n const chunk = Math.ceil(distinct.length / 4);\n const bands: PriceBand[] = [];\n for (let i = 0; i < distinct.length; i += chunk) {\n const slice = distinct.slice(i, i + chunk);\n const lo = slice[0];\n const hi = slice[slice.length - 1];\n bands.push({\n id: `b${i}`,\n label: lo === hi ? this.money(lo) : `${this.money(lo)}–${this.money(hi)}`,\n keys: priced.filter((p) => p.price >= lo && p.price <= hi).map((p) => p.key),\n min: lo,\n max: hi,\n });\n }\n return bands;\n }\n\n /** Build the compact price selector in the panel header. Choosing a band both\n * filters availability and smoothly frames the matching seats on the map. */\n private buildPriceFilter(): void {\n if (!this.els.prices || !this.els.pricesSec) return;\n const bands = this.priceBands();\n if (bands.length < 2) return;\n const select = document.createElement('select');\n select.className = 'sl-price-select';\n select.setAttribute('aria-label', 'Filter and focus seats by price');\n select.innerHTML = `<option value=\"all\">All prices</option>` + bands\n .map((band) => `<option value=\"${band.id}\">${band.label}</option>`)\n .join('');\n this.els.pricesSec.appendChild(select);\n select.addEventListener('change', () => {\n const band = bands.find((candidate) => candidate.id === select.value);\n const keys = band?.keys ?? null;\n this.focusedCatKey = null; // band filter supersedes any pinned row focus\n this.priceBandKeys = keys ? new Set(keys) : null;\n this.controller.setCategoryFilter(keys);\n this.controller.focusCategoryFilter(keys);\n // The band has to survive a switch into 3D, which paints from its own\n // state snapshot rather than from Konva opacity.\n this.pushAvailabilityTo3d();\n // A band whose seats live on another deck switches floors — mirror it.\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n // Reflect the band in the legend rows + any open section card.\n this.syncPrices();\n if (this.lastSection) this.showSectionCard(this.lastSection);\n });\n }\n\n // ---- arena / multi-floor chrome -------------------------------------------\n\n /** Build projection, rung and floor controls for arena-scale charts. */\n private buildArenaChrome(): void {\n const doc = this.controller.doc;\n if (!doc || !this.els.map) return;\n const hasSections = doc.objects.some((o) => o.type === 'section')\n || (doc.floors ?? []).some((f) => f.objects.some((o) => o.type === 'section'));\n\n // Buyer view toggle: **Map | 3D** (2.5D/perspective is retired from the buyer\n // surface). The 3D button is offered only when 3D is enabled AND the browser\n // exposes WebGL2 — otherwise the picker stays a plain flat map with no toggle\n // at all. Available for ANY chart with a real 3D relief source, not just\n // sectioned venues.\n if (this.canOffer3d()) {\n const projection = document.createElement('div');\n projection.className = 'sl-projection';\n projection.setAttribute('role', 'group');\n projection.setAttribute('aria-label', 'Venue view');\n projection.innerHTML =\n '<button type=\"button\" data-view=\"map\" aria-pressed=\"true\" title=\"Flat 2D map\">Map</button>' +\n '<button type=\"button\" data-view=\"venue3d\" aria-pressed=\"false\" title=\"Interactive 3D venue view\">3D</button>';\n projection.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {\n button.addEventListener('click', () => {\n this.setBuyerView(button.dataset.view as 'map' | 'venue3d');\n });\n });\n this.regions['top-right'].appendChild(projection);\n this.projectionEl = projection;\n this.syncProjection();\n }\n\n // LOD rung pills — jump straight between zones / sections / seats.\n if (hasSections) {\n const RUNGS: LodRung[] = ['zones', 'sections', 'seats'];\n const pills = document.createElement('div');\n pills.className = 'sl-rungs on';\n pills.setAttribute('role', 'group');\n pills.setAttribute('aria-label', t('picker.zoomLevel'));\n const LABEL: Record<LodRung, string> = {\n zones: t('picker.rungLabel.zones'),\n sections: t('picker.rungLabel.sections'),\n seats: t('picker.rungLabel.seats'),\n };\n const TIP: Record<LodRung, string> = {\n zones: t('picker.rungTip.zones'),\n sections: t('picker.rungTip.sections'),\n seats: t('picker.rungTip.seats'),\n };\n pills.innerHTML = RUNGS.map(\n (r) => `<button type=\"button\" data-rung=\"${r}\" title=\"${TIP[r]}\" aria-pressed=\"false\">${LABEL[r]}</button>`,\n ).join('');\n pills.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.addEventListener('click', () => {\n const rung = btn.dataset.rung as LodRung;\n this.controller.setRung(rung);\n if (rung === 'seats') this.collapseSectionCard();\n });\n });\n this.regions['top-center'].appendChild(pills);\n this.rungsEl = pills;\n this.syncRung();\n }\n\n // Multi-floor switcher — only when the chart truly has >1 floor.\n if (this.controller.isMultiFloor()) {\n const floors = this.controller.getFloors();\n const rail = document.createElement('div');\n rail.className = 'sl-floors on';\n rail.setAttribute('role', 'group');\n rail.setAttribute('aria-label', t('picker.floor'));\n rail.innerHTML = floors\n .map((f) => `<button type=\"button\" data-floor=\"${f.id}\">${f.name}</button>`)\n .join('');\n rail.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.addEventListener('click', () => {\n this.controller.setFloor(btn.dataset.floor!);\n this.showSectionCard(null);\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n });\n });\n this.regions['left-rail'].appendChild(rail);\n this.floorsEl = rail;\n this.syncFloors();\n }\n }\n\n /** Reflect the engine's current LOD rung onto the pill group. */\n private syncRung(): void {\n if (!this.rungsEl) return;\n const active = this.controller.getRung();\n this.rungsEl.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n const on = btn.dataset.rung === active;\n btn.classList.toggle('on', on);\n btn.setAttribute('aria-pressed', String(on));\n });\n }\n\n private syncProjection(): void {\n if (!this.projectionEl) return;\n this.projectionEl.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {\n const on = button.dataset.view === this.buyerView;\n button.classList.toggle('on', on);\n button.setAttribute('aria-pressed', String(on));\n });\n }\n\n /** Can this picker offer the 3D venue view? Requires the option (default on),\n * WebGL2, a chart to render, and a chart small enough to render WELL. */\n private canOffer3d(): boolean {\n if (this.opts.enable3D === false || !this.controller.doc || !hasWebGL2()) return false;\n return this.allSeats().length <= this.max3dSeats();\n }\n\n /**\n * The seat ceiling for offering 3D. See `max3DSeats` — an explicit host value\n * always wins; otherwise a small/low-core device gets half the desktop budget,\n * because it is the device that turns \"slow\" into \"stalled\".\n */\n private max3dSeats(): number {\n const authored = this.opts.max3DSeats;\n if (typeof authored === 'number' && authored > 0) return authored;\n const nav = globalThis.navigator as (Navigator & { deviceMemory?: number }) | undefined;\n const small = (nav?.hardwareConcurrency ?? 8) <= 4\n || (nav?.deviceMemory ?? 8) <= 4\n || (globalThis.matchMedia?.('(pointer: coarse)').matches ?? false);\n return small ? MAX_3D_SEATS_DEFAULT / 2 : MAX_3D_SEATS_DEFAULT;\n }\n\n /** Reflect the active floor onto the switcher rail. */\n private syncFloors(): void {\n if (!this.floorsEl) return;\n const active = this.controller.getActiveFloorId();\n this.floorsEl.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.classList.toggle('on', btn.dataset.floor === active);\n });\n }\n\n /** Show (or clear, on null) the tapped-section summary card. */\n private showSectionCard(summary: SectionSummary | null): void {\n this.lastSection = summary;\n this.secCardEl?.remove();\n this.secCardEl = null;\n if (!summary) return;\n // At seat level the summary is context, not a blocking decision surface.\n // Keep it as the compact pill from the first seat-level paint.\n this.secCardCollapsed = this.controller.getRung() === 'seats';\n this.secCardShownAt = Date.now();\n this.renderSectionCard(summary);\n }\n\n /**\n * Render the section card in the form the layout + state want: expanded card\n * or slim pill in the top-center anchor region (wide), or a compact strip in\n * the sheet head (narrow). Never floats over the seats at the tap point.\n */\n private renderSectionCard(summary: SectionSummary): void {\n if (!this.els.map) return;\n this.secCardEl?.remove();\n // min/max over the section's categories at the price the buyer will PAY\n // (host pricing override aware) — not the chart's stored range.\n const paid = summary.categories.length\n ? summary.categories.map((c) => this.paidPrice(c.key, null, c.price))\n : [summary.priceMin, summary.priceMax];\n const paidMin = Math.min(...paid);\n const paidMax = Math.max(...paid);\n const priceLabel =\n paidMin === paidMax\n ? this.money(paidMin)\n : `${this.money(paidMin)}–${this.money(paidMax)}`;\n const leftLabel = tCount('picker.seatsLeftInSection', summary.seatsLeft);\n const xBtn = `<button type=\"button\" class=\"sl-seccard-x\" aria-label=\"${t('picker.closeSectionSummary')}\">✕</button>`;\n const card = document.createElement('div');\n const narrow = this.root?.dataset.layout === 'narrow';\n\n if (narrow) {\n // Compact strip inside the bottom sheet's peek head — never over the map.\n card.className = 'sl-seccard strip on';\n card.setAttribute('role', 'status');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n card.innerHTML =\n `<span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span>` +\n (summary.categories.length ? `<span class=\"sl-seccard-price\">${priceLabel}</span>` : '') +\n xBtn;\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n (this.els.sheetHead ?? this.els.side ?? this.els.map).appendChild(card);\n } else if (this.secCardCollapsed) {\n // Slim pill — seat-picking has begun. Tap to re-expand; ✕ still closes.\n card.className = 'sl-seccard mini on';\n card.setAttribute('role', 'button');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n card.innerHTML =\n `<span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span>` +\n xBtn;\n card.addEventListener('click', (e) => {\n if ((e.target as HTMLElement).closest('.sl-seccard-x')) return;\n this.secCardCollapsed = false;\n this.secCardShownAt = Date.now();\n this.renderSectionCard(summary);\n });\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n (this.regions['top-center'] ?? this.els.map).appendChild(card);\n } else {\n card.className = 'sl-seccard on';\n card.setAttribute('role', 'dialog');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n const mix = summary.categories\n .map((c) => {\n const dim = this.priceBandKeys != null && !this.priceBandKeys.has(c.key);\n return (\n `<span class=\"sl-seccard-mix-item${dim ? ' sl-dim' : ''}\"><span class=\"sl-seccard-mix-dot\" style=\"background:${c.color}\"></span>` +\n `${c.label} <span class=\"sl-seccard-mix-price\">${this.money(this.paidPrice(c.key, null, c.price))}</span></span>`\n );\n })\n .join('');\n card.innerHTML =\n `<div class=\"sl-seccard-head\"><span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n (summary.categories.length ? `<span class=\"sl-seccard-price\">${priceLabel}</span>` : '') +\n xBtn + `</div>` +\n `<div class=\"sl-seccard-zone\">${summary.zoneLabel ? `${summary.zoneLabel} · ` : ''}` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span></div>` +\n (summary.entrance\n ? `<div class=\"sl-seccard-entrance\">${t('picker.entrance')} ${String(summary.entrance).replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!))}</div>`\n : '') +\n (mix ? `<div class=\"sl-seccard-mix\">${mix}</div>` : '') +\n `<div class=\"sl-seccard-foot\">` +\n `<button type=\"button\" class=\"sl-seccard-overview\">← ${t('picker.overview')}</button>` +\n `<span class=\"sl-seccard-hint\">${t('picker.tapSeatHint')}</span></div>`;\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n card.querySelector('.sl-seccard-overview')!.addEventListener('click', () => this.controller.overview());\n (this.regions['top-center'] ?? this.els.map).appendChild(card);\n }\n this.secCardEl = card;\n }\n\n /** Collapse the expanded card to its slim pill (seat-picking started). */\n private collapseSectionCard(): void {\n if (!this.secCardEl || this.secCardCollapsed || !this.lastSection) return;\n if (this.root?.dataset.layout === 'narrow') return; // strip is already compact\n this.secCardCollapsed = true;\n this.renderSectionCard(this.lastSection);\n }\n\n /**\n * onViewChange hook for the card. The focus glide's own settle (within the\n * grace window) enforces the ~25% coverage rule with the FINAL viewport; any\n * later pan/zoom means seat-picking has begun → collapse to the pill.\n */\n private sectionCardOnView(): void {\n if (!this.secCardEl || this.secCardCollapsed || !this.lastSection) return;\n if (this.root?.dataset.layout === 'narrow') return;\n if (this.controller.getRung() === 'seats') {\n this.collapseSectionCard();\n return;\n }\n if (Date.now() - this.secCardShownAt < 1400) {\n if (this.sectionCardCoverage() > 0.25) this.collapseSectionCard();\n return;\n }\n this.collapseSectionCard();\n }\n\n /** Fraction of the focused section's on-screen bbox covered by the card. */\n private sectionCardCoverage(): number {\n const card = this.secCardEl;\n const sec = this.lastSection;\n if (!card || !sec || !this.els.map) return 0;\n const outline = this.activeFloorObjects().find((o) => o.type === 'section' && o.id === sec.id)?.outline;\n if (!outline || outline.length < 3) return 0;\n const pts = outline.map((p) => this.controller.worldToScreen(p));\n const xs = pts.map((p) => p.x);\n const ys = pts.map((p) => p.y);\n const bx = Math.min(...xs);\n const by = Math.min(...ys);\n const bw = Math.max(...xs) - bx;\n const bh = Math.max(...ys) - by;\n if (bw <= 0 || bh <= 0) return 0;\n const mapR = this.els.map.getBoundingClientRect();\n const cr = card.getBoundingClientRect();\n const cx = cr.left - mapR.left;\n const cy = cr.top - mapR.top;\n const ox = Math.max(0, Math.min(cx + cr.width, bx + bw) - Math.max(cx, bx));\n const oy = Math.max(0, Math.min(cy + cr.height, by + bh) - Math.max(cy, by));\n return (ox * oy) / (bw * bh);\n }\n\n /** aria-live readout when keyboard focus lands on a seat. */\n private announceSeat(seat: ExpandedSeat | null): void {\n if (!this.srEl) return;\n if (!seat) {\n this.srEl.textContent = '';\n return;\n }\n const cat = this.controller.doc?.categories.find((c) => c.key === seat.categoryKey);\n const status = this.controller.getStatus(seat.id) ?? 'free';\n const statusText = status === 'free' ? 'available' : status === 'held' ? 'on hold' : 'taken';\n const price = cat ? this.catPrice(cat) : undefined;\n const table = this.controller.tableSelection(seat.id);\n const details = table ?? this.controller.seatDetails(seat.id);\n const typeWord = this.rowTypeWord(details);\n const buyerName = details?.rowLabel ?? details?.displayLabel ?? seat.displayLabel ?? seat.label;\n const identity = table\n ? `${typeWord} ${buyerName}, ${table.bookingMode === 'variable' ? `${table.minOccupancy} to ${table.maxOccupancy} guests` : `${table.capacity} guests`}`\n : details?.objectType === 'booth'\n ? `${typeWord} ${buyerName}`\n : details?.objectType === 'table'\n ? `${typeWord} ${buyerName}, seat ${details.seatNumber ?? seat.label}`\n : `Seat ${details?.displayLabel ?? seat.displayLabel ?? seat.label}`;\n this.srEl.textContent = `${identity}, ${cat?.label ?? seat.categoryKey}${\n price != null ? `, ${this.money(price)}` : ''\n }, ${statusText}`;\n }\n\n // ---- atomic table confirmation / guest quantity ---------------------------\n\n private showTableDialog(\n table: TableSelectionDetails,\n held: boolean,\n returnFocus?: HTMLElement | null,\n ): void {\n this.dismissTableDialog(false);\n this.tableDialog = { ...table };\n this.tableDialogHeld = held;\n this.tableDialogReturnFocus = returnFocus ?? (document.activeElement as HTMLElement | null);\n const esc = (value: unknown): string => String(value ?? '').replace(/[&<>\"']/g, (ch) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''',\n })[ch]!);\n const cat = this.controller.doc?.categories.find((candidate) => candidate.key === table.categoryKey);\n const variable = table.bookingMode === 'variable';\n const typeWord = this.rowTypeWord(table);\n const el = document.createElement('div');\n el.className = 'sl-table-scrim';\n el.innerHTML =\n `<section class=\"sl-table-dialog\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"sl-table-title\" aria-describedby=\"sl-table-copy\">` +\n `<div class=\"sl-table-head\"><div class=\"sl-table-eyebrow\">${esc(variable ? `Flexible party · ${typeWord}` : `Whole ${typeWord}`)}</div>` +\n `<h2 class=\"sl-table-title\" id=\"sl-table-title\">${esc(table.displayLabel ?? table.label)}</h2>` +\n `<p class=\"sl-table-copy\" id=\"sl-table-copy\">${variable\n ? `Choose how many guests will sit together. This table is held exclusively for your party.`\n : `All ${table.capacity} places are booked together as one exclusive table.`}</p></div>` +\n `<div class=\"sl-table-body\">` +\n `<div class=\"sl-table-summary\"><span>${esc(cat?.label ?? table.categoryKey)}</span><b data-table-unit>${this.money(this.paidPrice(table.categoryKey, table.tierId ?? null, table.price))} per guest</b>` +\n `<span class=\"muted\">Table capacity</span><span>${table.capacity} guests</span>` +\n `<span class=\"muted\">Total</span><b data-table-total></b></div>` +\n (variable\n ? `<label class=\"sl-table-qtylabel\" id=\"sl-table-qty-label\">Number of guests</label>` +\n `<div class=\"sl-table-stepper\" role=\"group\" aria-labelledby=\"sl-table-qty-label\">` +\n `<button type=\"button\" data-table-step=\"-1\" aria-label=\"Fewer guests\">−</button>` +\n `<output aria-live=\"polite\" data-table-qty>${table.quantity}</output>` +\n `<button type=\"button\" data-table-step=\"1\" aria-label=\"More guests\">+</button></div>` +\n `<div class=\"sl-table-range\">Choose ${table.minOccupancy}–${table.maxOccupancy} guests</div>`\n : `<input type=\"hidden\" data-table-qty value=\"${table.capacity}\">`) +\n `<div class=\"sl-table-actions\"><button type=\"button\" class=\"sl-table-cancel\">Cancel</button>` +\n `<button type=\"button\" class=\"sl-table-confirm\">${held ? 'Update table' : variable ? 'Select table' : 'Select whole table'}</button></div>` +\n `</div></section>`;\n this.root!.appendChild(el);\n this.tableDialogEl = el;\n this.renderTableDialogState();\n\n el.querySelectorAll<HTMLButtonElement>('[data-table-step]').forEach((button) => {\n button.addEventListener('click', () => {\n if (!this.tableDialog) return;\n const next = Math.max(\n this.tableDialog.minOccupancy,\n Math.min(this.tableDialog.maxOccupancy, this.tableDialog.quantity + Number(button.dataset.tableStep)),\n );\n this.tableDialog = { ...this.tableDialog, quantity: next };\n this.renderTableDialogState();\n });\n });\n el.querySelector<HTMLButtonElement>('.sl-table-cancel')!.addEventListener('click', () => this.cancelTableDialog());\n el.querySelector<HTMLButtonElement>('.sl-table-confirm')!.addEventListener('click', () => void this.confirmTableDialog());\n el.addEventListener('mousedown', (event) => {\n if (event.target === el) this.cancelTableDialog();\n });\n el.addEventListener('keydown', (event) => {\n if (event.key !== 'Tab') return;\n const focusable = [...el.querySelectorAll<HTMLElement>('button:not(:disabled),[tabindex]:not([tabindex=\"-1\"])')];\n if (!focusable.length) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n });\n requestAnimationFrame(() => (\n el.querySelector<HTMLButtonElement>(variable ? '[data-table-step=\"-1\"]' : '.sl-table-confirm')?.focus()\n ));\n }\n\n private renderTableDialogState(): void {\n const table = this.tableDialog;\n const el = this.tableDialogEl;\n if (!table || !el) return;\n const output = el.querySelector<HTMLOutputElement>('output[data-table-qty]');\n if (output) output.value = String(table.quantity);\n const hidden = el.querySelector<HTMLInputElement>('input[data-table-qty]');\n if (hidden) hidden.value = String(table.quantity);\n el.querySelectorAll<HTMLButtonElement>('[data-table-step]').forEach((button) => {\n const delta = Number(button.dataset.tableStep);\n button.disabled = delta < 0\n ? table.quantity <= table.minOccupancy\n : table.quantity >= table.maxOccupancy;\n });\n const unit = this.paidPrice(table.categoryKey, table.tierId ?? null, table.price);\n const total = el.querySelector<HTMLElement>('[data-table-total]');\n if (total) total.textContent = this.money(unit * table.quantity);\n }\n\n private async confirmTableDialog(): Promise<void> {\n const table = this.tableDialog;\n const held = this.tableDialogHeld;\n if (!table) return;\n const button = this.tableDialogEl?.querySelector<HTMLButtonElement>('.sl-table-confirm');\n if (button) {\n button.disabled = true;\n button.textContent = held ? 'Updating…' : 'Selecting…';\n }\n if (held) {\n try {\n const updated = await this.controller.replaceTableQuantity(table.label, table.quantity, this.opts.holdTtlMs);\n if (!updated) {\n this.toast('That guest count could not be secured. Your current table hold is unchanged.', 'warning');\n this.renderTableDialogState();\n if (button) {\n button.disabled = false;\n button.textContent = 'Update table';\n }\n return;\n }\n this.hold = {\n holdId: updated.holdId,\n expiresAt: updated.expiresAt,\n seats: updated.seats,\n items: updated.items,\n };\n this.startHoldTimer(updated.expiresAt);\n this.dismissTableDialog();\n this.syncTray();\n this.emitHoldChange();\n this.toast(`${table.label} updated for ${table.quantity} guests.`, 'success');\n } catch (error) {\n this.opts.onError?.(error);\n this.toast('That guest count is no longer available. Your current hold is unchanged.', 'error');\n if (button) {\n button.disabled = false;\n button.textContent = 'Update table';\n }\n }\n return;\n }\n\n if (!this.controller.setTableQuantity(table.label, table.quantity)) {\n if (button) {\n button.disabled = false;\n button.textContent = table.bookingMode === 'variable' ? 'Select table' : 'Select whole table';\n }\n return;\n }\n this.dismissTableDialog();\n this.collapseSectionCard();\n this.syncTray();\n }\n\n private cancelTableDialog(): void {\n const table = this.tableDialog;\n const held = this.tableDialogHeld;\n this.dismissTableDialog();\n if (table && !held) this.controller.deselect(table.physicalSeatIds);\n }\n\n private dismissTableDialog(restoreFocus = true): void {\n const focus = this.tableDialogReturnFocus;\n this.tableDialogEl?.remove();\n this.tableDialogEl = null;\n this.tableDialog = null;\n this.tableDialogHeld = false;\n this.tableDialogReturnFocus = null;\n if (restoreFocus) requestAnimationFrame(() => (focus?.isConnected ? focus : this.root)?.focus());\n }\n\n // ---- seat candidate confirmation ------------------------------------------\n\n private showConfirm(seat: ExpandedSeat): void {\n const previousId = this.confirmSeat?.id;\n this.confirmEl?.remove();\n this.confirmEl = null;\n this.confirmSeat = seat;\n this.root?.setAttribute('data-confirming', 'true');\n this.controller.setSelectionFocus(seat.id);\n if (previousId && previousId !== seat.id) this.controller.deselect([previousId]);\n if (this.tipEl) this.tipEl.style.display = 'none';\n const details = this.controller.seatDetails(seat.id);\n const cat = this.controller.doc?.categories.find((c) => c.key === seat.categoryKey);\n const chartPrice = details?.price ?? (cat?.tiers?.length ? cat.tiers[0].price : cat?.price);\n const price = chartPrice != null\n ? this.paidPrice(seat.categoryKey, details?.tierId ?? cat?.tiers?.[0]?.id ?? null, chartPrice)\n : undefined;\n const safe = (value: unknown): string => String(value ?? '—').replace(/[&<>\"]/g, (char) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"',\n })[char]!);\n const identityFields = [\n details?.sectionLabel\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">Section</span><span class=\"sl-confirm-value\">${safe(details.sectionLabel)}</span></div>`\n : '',\n details?.rowLabel || details?.objectType === 'booth'\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">${safe(this.rowTypeWord(details))}</span><span class=\"sl-confirm-value\">${safe(this.rowShort(details) ?? details?.displayLabel ?? seat.displayLabel ?? seat.label)}</span></div>`\n : '',\n details?.objectType !== 'booth'\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">Seat</span><span class=\"sl-confirm-value\">${safe(details?.seatNumber ?? details?.displayLabel ?? seat.displayLabel ?? seat.label)}</span></div>`\n : '',\n ].filter(Boolean).join('');\n const el = document.createElement('div');\n el.className = 'sl-confirm';\n el.setAttribute('role', 'dialog');\n el.setAttribute('aria-modal', 'true');\n el.setAttribute('aria-label', `Confirm seat ${seat.label}`);\n el.style.setProperty('--sl-cat', cat?.color ?? '#6e7bff');\n el.innerHTML =\n `<div class=\"sl-confirm-grid\">` +\n identityFields +\n `</div>` +\n `<div class=\"sl-confirm-cat\"><span class=\"sl-dot\" style=\"background:${cat?.color ?? '#6e7bff'}\"></span>` +\n `<span class=\"sl-confirm-cat-name\">${safe(details?.categoryLabel ?? cat?.label ?? seat.categoryKey)}</span>` +\n (price != null ? `<span class=\"sl-confirm-price\">${this.money(price)}</span>` : '') + `</div>` +\n `<div class=\"sl-confirm-body\">` +\n this.wheelchairConfirmHtml(details?.wheelchairSpaceType) +\n this.commercialConfirmHtml(seat.commercial) +\n (this.seatViewEnabled() ? this.confirmThumbHtml(seat) : '') +\n this.see3dConfirmHtml() +\n `<div class=\"sl-confirm-row\">` +\n `<button type=\"button\" class=\"sl-confirm-cancel\">Cancel</button>` +\n `<button type=\"button\" class=\"sl-confirm-add\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M5 12.5l4 4L19 7\"/></svg>Select</button></div></div>`;\n this.els.map.appendChild(el);\n this.confirmEl = el;\n this.reanchorConfirm();\n el.querySelector('.sl-confirm-view')?.addEventListener('click', () => void this.openSeatView(seat));\n el.querySelector('.sl-confirm-3d')?.addEventListener('click', () => {\n if (this.buyerView === 'venue3d') {\n // Already immersed — just fly the cinematic to this seat.\n void this.view3dHandle?.flyToSeat(seat.id);\n } else {\n // Enter 3D flying straight to the seat; re-show this card on return.\n this.view3dReturnSeat = seat;\n this.dismissConfirm();\n void this.enter3d(seat.id);\n }\n });\n el.querySelector('.sl-confirm-add')!.addEventListener('click', () => this.commitConfirm());\n el.querySelector('.sl-confirm-cancel')!.addEventListener('click', () => this.cancelConfirm());\n requestAnimationFrame(() => el.querySelector<HTMLButtonElement>('.sl-confirm-add')?.focus());\n }\n\n private reanchorConfirm(): void {\n if (!this.confirmEl || !this.confirmSeat) return;\n // In 3D the seat has no stable 2D screen anchor, so CSS bottom-sheets the\n // card (same treatment as the narrow layout). Nothing to position here.\n if (this.root?.dataset.view3d === 'on') return;\n const p = this.controller.worldToScreen({ x: this.confirmSeat.x, y: this.confirmSeat.y });\n if (this.root?.dataset.layout === 'narrow') return;\n const mapWidth = this.els.map.clientWidth;\n const mapHeight = this.els.map.clientHeight;\n const cardWidth = this.confirmEl.offsetWidth || 276;\n const cardHeight = this.confirmEl.offsetHeight || 230;\n const half = cardWidth / 2 + 12;\n const x = Math.max(half, Math.min(mapWidth - half, p.x));\n const belowFits = p.y + cardHeight + 24 <= mapHeight;\n const placeBelow = p.y < cardHeight + 24 && belowFits;\n this.confirmEl.dataset.placement = placeBelow ? 'below' : 'above';\n this.confirmEl.style.left = `${x}px`;\n this.confirmEl.style.top = `${Math.max(8, Math.min(mapHeight - 8, p.y))}px`;\n }\n\n private dismissConfirm(): void {\n this.confirmEl?.remove();\n this.confirmEl = null;\n this.confirmSeat = null;\n this.root?.removeAttribute('data-confirming');\n this.controller.setSelectionFocus(null);\n }\n\n private commitConfirm(): void {\n if (!this.confirmSeat) return;\n this.dismissConfirm();\n this.collapseSectionCard();\n this.syncTray();\n }\n\n private cancelConfirm(): void {\n const seat = this.confirmSeat;\n if (!seat) return;\n this.controller.deselect([seat.id]);\n if (this.confirmSeat) this.dismissConfirm();\n this.root?.focus({ preventScroll: true });\n }\n\n private closeConfirm(): void {\n this.dismissConfirm();\n }\n\n // ---- 360° view-from-seat modal --------------------------------------------\n\n private seatViewEnabled(): boolean {\n return this.opts.seatView !== false;\n }\n\n /** Every bookable seat (cached) — neighbor heads for the generated panorama. */\n private allSeats(): ExpandedSeat[] {\n if (!this.allSeatsCache) {\n const doc = this.controller.doc;\n this.allSeatsCache = doc ? expandChart(doc) : [];\n }\n return this.allSeatsCache;\n }\n\n /**\n * Open the drag-to-look-around 360° preview for a seat. Uses the organizer's\n * uploaded photo (seat.viewUrl) when present, else a panorama generated from\n * the chart geometry — the stage placed at this seat's true bearing + size.\n * Zero extra dependencies: an equirectangular image panned with `repeat-x`.\n *\n * Async only because the generator is a lazy chunk (see `loadPanorama`); an\n * organizer photo needs no generator and never waits on it. The two callers\n * are click handlers, so nothing observes the promise.\n */\n private async openSeatView(seat: ExpandedSeat): Promise<void> {\n if (!this.root || !this.seatViewEnabled()) return;\n\n const doc = this.controller.doc;\n const activeId = this.controller.getActiveFloorId();\n const focal = seat.focalPoint\n ?? doc?.floors?.find((f) => f.id === activeId)?.focalPoint\n ?? doc?.focalPoint\n ?? { x: 0, y: 0 };\n let panoUrl: string;\n let caption: string;\n let real = false;\n if (seat.viewUrl) {\n panoUrl = seat.viewUrl;\n caption = t('picker.panorama360');\n real = true;\n } else {\n let pano: PanoramaResult;\n try {\n const { generateSeatPanorama } = await loadPanorama();\n pano = generateSeatPanorama(seat, focal, this.allSeats());\n } catch (err) {\n // The chunk failed to fetch, or the draw threw. Report it and leave the\n // buyer on the map rather than opening an empty viewer.\n this.opts.onError?.(err);\n return;\n }\n // Torn down (or another view opened) while the chunk loaded.\n if (!this.root || !this.seatViewEnabled()) return;\n panoUrl = pano.url;\n caption = t('picker.illustrationCaption', { m: pano.distanceM });\n }\n\n // Retire any open view HERE, not before the await: two quick taps would\n // otherwise each close nothing and then leave the first viewer orphaned in\n // the DOM. It also means the current view stays up while the chunk loads.\n this.closeSeatView();\n\n const el = document.createElement('div');\n el.className = 'sl-view';\n el.setAttribute('role', 'dialog');\n el.setAttribute('aria-label', t('picker.viewFromSeat', { label: seat.label }));\n el.innerHTML =\n `<div class=\"sl-view-head\">` +\n `<span class=\"sl-view-title\">${t('picker.viewFromSeat', { label: seat.label })}</span>` +\n `<span class=\"sl-view-cap\">${caption}</span>` +\n `<button type=\"button\" class=\"sl-view-x\" aria-label=\"Close\">` +\n `<svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button></div>` +\n `<div class=\"sl-view-pano\">` +\n `<span class=\"sl-view-badge\">${real ? t('picker.real360') : t('picker.preview')}</span>` +\n `<span class=\"sl-view-hint\">Drag to look around · scroll to zoom</span>` +\n `</div>`;\n this.root.appendChild(el);\n this.viewEl = el;\n\n const pano = el.querySelector<HTMLDivElement>('.sl-view-pano')!;\n pano.style.backgroundImage = `url(\"${panoUrl}\")`;\n\n // Equirectangular pan: repeat-x gives seamless 360° horizontal wrap. The\n // source is a full 180° sphere; showing it raw wastes ~⅔ of the frame on\n // dead sky + black floor. So we WINDOW a ~70° vertical slice (horizon-centred)\n // to fill the viewport height, and clamp the vertical drag to ±35° so the\n // buyer looks around a real seat's field of view, never past the image edge.\n // `zoom` narrows the FOV further (scroll to zoom in); it never widens past 70°.\n const VFOV_DEG = 70;\n const MAX_PITCH_DEG = 35;\n let zoom = 1;\n // The generator draws the STAGE at the image's horizontal centre (yaw 0 =\n // stage). Open with that centre in the middle of the viewport — a view\n // that opens facing away from the stage is disorienting (seat 11G-21\n // owner report). Same default is right for uploaded 360s until Case-1\n // calibration exists. bgW = 2·bgH (2:1 equirect), zoom 1 at open.\n const vh0 = pano.clientHeight || 1;\n const vw0 = pano.clientWidth || 1;\n let posX = -(vh0 * (180 / VFOV_DEG) * 2 / 2 - vw0 / 2);\n let posY = 0;\n const apply = (): void => {\n const h = pano.clientHeight || 1;\n const bgH = h * (180 / VFOV_DEG) * zoom;\n const overV = Math.max(0, bgH - h);\n // Clamp pitch to ±35° of image travel (bgH px map the full 180°), and never\n // past the image edge (overV/2).\n const pitchLimit = Math.min(overV / 2, (MAX_PITCH_DEG / 180) * bgH);\n posY = Math.min(pitchLimit, Math.max(-pitchLimit, posY));\n pano.style.backgroundSize = `auto ${bgH}px`;\n // Horizon-centred: -overV/2 places the image's vertical centre at the\n // viewport centre; `posY` (drag, clamped ±35°) tilts up/down from there.\n pano.style.backgroundPosition = `${posX}px ${posY - overV / 2}px`;\n };\n apply();\n\n let dragging = false;\n let lastX = 0;\n let lastY = 0;\n const onDown = (e: PointerEvent): void => {\n dragging = true;\n lastX = e.clientX;\n lastY = e.clientY;\n pano.classList.add('drag');\n pano.setPointerCapture?.(e.pointerId);\n };\n const onMove = (e: PointerEvent): void => {\n if (!dragging) return;\n posX += e.clientX - lastX;\n posY += e.clientY - lastY;\n lastX = e.clientX;\n lastY = e.clientY;\n apply();\n };\n const onUp = (e: PointerEvent): void => {\n dragging = false;\n pano.classList.remove('drag');\n pano.releasePointerCapture?.(e.pointerId);\n };\n const onWheel = (e: WheelEvent): void => {\n e.preventDefault();\n zoom = Math.min(2.4, Math.max(1, zoom + (e.deltaY < 0 ? 0.12 : -0.12)));\n apply();\n };\n pano.addEventListener('pointerdown', onDown);\n pano.addEventListener('pointermove', onMove);\n pano.addEventListener('pointerup', onUp);\n pano.addEventListener('pointercancel', onUp);\n pano.addEventListener('wheel', onWheel, { passive: false });\n\n const closeBtn = el.querySelector<HTMLButtonElement>('.sl-view-x')!;\n closeBtn.addEventListener('click', () => this.closeSeatView());\n const onKey = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') {\n e.stopPropagation();\n this.closeSeatView();\n }\n };\n el.addEventListener('keydown', onKey);\n closeBtn.focus();\n\n this.viewCleanup = () => {\n pano.removeEventListener('pointerdown', onDown);\n pano.removeEventListener('pointermove', onMove);\n pano.removeEventListener('pointerup', onUp);\n pano.removeEventListener('pointercancel', onUp);\n pano.removeEventListener('wheel', onWheel);\n el.removeEventListener('keydown', onKey);\n };\n }\n\n private closeSeatView(): void {\n this.viewCleanup?.();\n this.viewCleanup = null;\n this.viewEl?.remove();\n this.viewEl = null;\n }\n\n // ---- chrome sync ----------------------------------------------------------\n\n private money(n: number): string {\n const formatter = this.opts.pricing?.formatter;\n if (formatter) return formatter(n, this.currency);\n try {\n return new Intl.NumberFormat(this.opts.locale, { style: 'currency', currency: this.currency }).format(n);\n } catch {\n return `${n} ${this.currency}`;\n }\n }\n\n /**\n * The price the buyer will actually pay for a category (+tier): the host's\n * `pricing` override when present, else the chart's stored price. Every\n * price the widget DISPLAYS or hands off must flow through here — a map\n * that shows one price while checkout charges another destroys trust.\n */\n private paidPrice(categoryKey: string | undefined, tierId: string | null | undefined, fallback: number): number {\n const entry = categoryKey ? this.opts.pricing?.prices?.[categoryKey] : undefined;\n if (entry === undefined) return fallback;\n if (typeof entry === 'number') return entry;\n if (tierId && entry.tiers?.[tierId] !== undefined) return entry.tiers[tierId];\n return entry.base ?? fallback;\n }\n\n private syncPrices(): void {\n const doc = this.controller.doc;\n if (!doc || !this.els.prices) return;\n const left = this.controller.categoryAvailability();\n this.narrateAvailability(doc.categories, left);\n this.syncSoldout(doc.categories, left);\n // Big events ship 10–20 ticket types; an uncapped list shoves \"Your seats\"\n // and the CTA below the fold. Cap the closed list and expand on demand\n // (never hide a single row behind a toggle — that costs more than it saves).\n const PRICE_LIMIT = 5;\n const overflow = doc.categories.length - PRICE_LIMIT;\n const collapsed = overflow > 1 && !this.pricesExpanded;\n const shown = collapsed ? doc.categories.slice(0, PRICE_LIMIT) : doc.categories;\n this.els.prices.classList.toggle('sl-expanded', overflow > 1 && this.pricesExpanded);\n this.els.prices.innerHTML = shown\n .map((c) => {\n const price = this.catPrice(c);\n const active = this.focusedCatKey === c.key;\n const dim = this.priceBandKeys != null && !this.priceBandKeys.has(c.key);\n return (\n `<div class=\"sl-price-row${dim ? ' sl-dim' : ''}${active ? ' sl-active' : ''}\" data-cat=\"${c.key}\"` +\n ` role=\"button\" tabindex=\"0\" aria-pressed=\"${active}\"` +\n ` title=\"${active ? 'Show all seats' : `Show ${c.label} seats on the map`}\">` +\n `<span class=\"sl-dot\" style=\"background:${c.color}\"></span>` +\n `<span class=\"sl-price-label\">${c.label}</span>` +\n `<span class=\"sl-price-left\">${left[c.key] ?? 0} left</span>` +\n (price != null ? `<span class=\"sl-price-amt\">${this.money(price)}</span>` : '') +\n `</div>`\n );\n })\n .join('') +\n (overflow > 1\n ? `<button type=\"button\" class=\"sl-price-more\" aria-expanded=\"${!collapsed}\">` +\n (collapsed ? `Show all ${doc.categories.length} ticket types` : 'Show fewer') +\n `</button>`\n : '') +\n `<div class=\"sl-status-key\" aria-label=\"Seat status legend\">` +\n `<span class=\"sl-status-item\"><i class=\"sl-status-icon\" aria-hidden=\"true\">` +\n `<svg viewBox=\"0 0 24 24\"><rect x=\"5\" y=\"10\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/></svg>` +\n `</i>Temporarily held</span>` +\n `<span class=\"sl-status-item\"><i class=\"sl-status-icon sold\" aria-hidden=\"true\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M7 17L17 7\"/></svg>` +\n `</i>Sold</span>` +\n `</div>`;\n // Legend-hover highlight: dim other categories on the map while hovering a row.\n // Click (or Enter/Space) pins that focus — filter + frame the category on\n // the map; a second click clears it.\n this.els.prices.querySelectorAll<HTMLElement>('.sl-price-row').forEach((row) => {\n row.addEventListener('mouseenter', () => this.controller.getRenderer()?.setCategoryHighlight?.(row.dataset.cat ?? null));\n row.addEventListener('mouseleave', () => this.controller.getRenderer()?.setCategoryHighlight?.(null));\n const toggle = () => this.focusCategory(row.dataset.cat ?? '');\n row.addEventListener('click', toggle);\n row.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n toggle();\n }\n });\n });\n this.els.prices.querySelector<HTMLButtonElement>('.sl-price-more')?.addEventListener('click', () => {\n this.pricesExpanded = !this.pricesExpanded;\n this.syncPrices();\n });\n }\n\n /** Tap a price row → filter + frame that category on the map; tap again to\n * clear. Shares `priceBandKeys` with the band selector so the row-dim state\n * has one source of truth (and each control resets the other). */\n private focusCategory(key: string): void {\n if (!key) return;\n const next = this.focusedCatKey === key ? null : key;\n this.focusedCatKey = next;\n this.priceBandKeys = next ? new Set([next]) : null;\n const select = this.els.pricesSec?.querySelector<HTMLSelectElement>('.sl-price-select');\n if (select) select.value = 'all';\n this.controller.setCategoryFilter(next ? [next] : null);\n this.controller.focusCategoryFilter(next ? [next] : null);\n this.pushAvailabilityTo3d();\n // Focusing a category on another deck switches floors — mirror that onto\n // the floor pills / rung pills / minimap, same as a manual deck switch.\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n this.syncPrices();\n if (this.lastSection) this.showSectionCard(this.lastSection);\n }\n\n /**\n * Live-activity strip: turn WS availability deltas into one quiet line of\n * social proof (\"2 seats just taken in VIP · 118 left\"). Diffs per-category\n * counts on every status change — no per-seat payload needed. Skips the very\n * first computation (initial load is not \"activity\").\n */\n private narrateAvailability(\n categories: Array<{ key: string; label: string }>,\n left: Record<string, number>,\n ): void {\n const textEl = this.els.liveText;\n const prev = this.lastCatAvail;\n this.lastCatAvail = { ...left };\n // A floor switch re-baselines availability (counts are per-rendered-floor,\n // and the post-switch status snapshot lands asynchronously a beat later).\n // Narrating across that window produces a phantom \"N seats just taken\", so\n // stay quiet until the new floor settles — only genuine WS deltas after\n // that are news.\n const floorId = this.controller.getActiveFloorId();\n if (floorId !== this.lastAvailFloorId) {\n this.lastAvailFloorId = floorId;\n this.availQuietUntil = performance.now() + 2000;\n }\n if (!textEl || !prev || performance.now() < this.availQuietUntil) return;\n for (const cat of categories) {\n const before = prev[cat.key];\n const now = left[cat.key] ?? 0;\n if (before === undefined || now >= before) continue;\n const taken = before - now;\n textEl.textContent = `${taken} seat${taken === 1 ? '' : 's'} just taken in ${cat.label} · ${now} left`;\n // Surface the strip only while it carries news, then give the space back.\n this.els.live?.classList.remove('on');\n // Reflow between remove/add restarts the entrance animation on repeats.\n void (this.els.live as HTMLElement | undefined)?.offsetWidth;\n this.els.live?.classList.add('on');\n if (this.liveTimer) clearTimeout(this.liveTimer);\n this.liveTimer = setTimeout(() => this.els.live?.classList.remove('on'), 8000);\n return;\n }\n }\n private lastCatAvail: Record<string, number> | null = null;\n private lastAvailFloorId = '';\n private availQuietUntil = 0;\n private liveTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** A live delta took one of OUR selected (not yet held) seats — evict + tell the buyer. */\n private evictTakenSelections(): void {\n // Our own hold's WS echo paints our seats 'held' — never treat those as sniped.\n const ownLabels = new Set<string>([\n ...(this.controller.currentHold()?.labels ?? []),\n ...this.holdingLabels,\n ]);\n const gone = this.controller\n .getSelection()\n .filter((s) => !ownLabels.has(s.label) && (this.controller.getStatus(s.id) ?? 'free') !== 'free');\n if (!gone.length) return;\n this.controller.deselect(gone.map((s) => s.id));\n this.toast(`Seat ${gone[0].label} was just taken by another buyer.`, 'error');\n }\n\n private syncTray(): void {\n if (!this.els.tray) return;\n this.updateSelectionCapacity();\n const seats = this.committedSelection();\n const gaAreas = this.controller.getGAAreas();\n const heldItems = this.hold?.items ?? [];\n const parts: string[] = [];\n const nextTrayKeys = new Set<string>();\n\n if (!seats.length && !heldItems.length && !gaAreas.length) {\n parts.push(`<div class=\"sl-tray-hint\">Tap a seat on the map, or let us pick the best available for you.</div>`);\n } else if (!seats.length && !heldItems.length) {\n parts.push(`<div class=\"sl-tray-hint\">Tap a seat on the map — or grab standing tickets below.</div>`);\n }\n\n // Best available is the fastest path for buyers who haven't picked yet —\n // but the moment a seat lands in the tray, the ticket cards own this space.\n // (Busy/confirm states stay visible so an in-flight search isn't cut off.)\n const noPicks = !seats.length && !heldItems.length && !this.pendingGACount();\n if (!this.hold && (noPicks || this.bestAvailableBusy || this.bestAvailableConfirm)) {\n const cats = this.controller.doc?.categories ?? [];\n const zones = this.controller.getBestAvailableZones();\n if (this.baZone && !zones.some((zone) => zone.id === this.baZone)) this.baZone = '';\n parts.push(this.bestAvailableConfirm\n ? `<div class=\"sl-ba\" role=\"alert\">` +\n `<div class=\"sl-ba-title\"><span class=\"spark\" aria-hidden=\"true\">✦</span>Replace your current choices?</div>` +\n `<div class=\"sl-ba-replace\"><b>We’ll find ${this.baQty} seats together.</b>` +\n `<span>Your manually selected tickets will be removed only after a new group is secured.</span></div>` +\n `<div class=\"sl-ba-actions\"><button type=\"button\" data-ba-cancel>Keep mine</button>` +\n `<button type=\"button\" class=\"replace\" data-ba-replace>Find new seats</button></div></div>`\n : `<div class=\"sl-ba\">` +\n `<div class=\"sl-ba-title\"><span class=\"spark\" aria-hidden=\"true\">✦</span>Find the best seats together</div>` +\n `<div class=\"sl-ba-copy\"><span class=\"wide\">We’ll choose the closest available group for you.</span>` +\n `<span class=\"narrow\">Closest available group, chosen instantly.</span></div>` +\n // Premium quick-pick — present only when the chart actually has premium\n // seats (same present-only philosophy as the a11y filter chips).\n (this.controller.hasPremiumSeats()\n ? `<button type=\"button\" class=\"sl-ba-premium${this.baPremium ? ' on' : ''}\" data-ba-premium aria-pressed=\"${this.baPremium ? 'true' : 'false'}\">` +\n `<span class=\"star\" aria-hidden=\"true\">★</span>${this.tf('picker.bestSeatsPremium', 'Best seats')}</button>`\n : '') +\n (cats.length > 1\n ? `<select aria-label=\"Preferred ticket type\" data-ba-cat>` +\n `<option value=\"\">Any ticket type</option>` +\n cats.map((c) => `<option value=\"${c.key}\"${this.baCat === c.key ? ' selected' : ''}>${c.label}</option>`).join('') +\n `</select>`\n : `<span aria-hidden=\"true\"></span>`) +\n (zones.length\n ? `<select aria-label=\"Preferred venue zone\" data-ba-zone>` +\n `<option value=\"\">Any venue zone</option>` +\n zones.map((zone) => `<option value=\"${escapeOption(zone.id)}\"${this.baZone === zone.id ? ' selected' : ''}>${escapeOption(zone.label)}</option>`).join('') +\n `</select>`\n : '') +\n `<div class=\"sl-ba-qty\">` +\n `<button type=\"button\" data-ba=\"-1\" aria-label=\"Fewer seats\">−</button><span>${this.baQty}</span>` +\n `<button type=\"button\" data-ba=\"1\" aria-label=\"More seats\">+</button></div>` +\n `<button type=\"button\" class=\"sl-ba-go\"${this.bestAvailableBusy ? ' disabled' : ''}>` +\n (this.bestAvailableBusy\n ? `<span class=\"sl-ba-spin\" aria-hidden=\"true\"></span>Finding the best seats…`\n : `Find ${this.baQty} best ${this.baQty === 1 ? 'seat' : 'seats'}`) +\n `</button></div>`);\n }\n\n // Held line items (best-available, completed, or restored). Tier is\n // server-committed, but each item can be released without discarding the\n // rest of the hold.\n // Ticket-card identity grid: SECTION | ROW | SEAT, echoing the confirm\n // popover so the buyer meets the same identity pattern at confirm and in\n // the cart. Falls back to the raw label when spatial context is missing\n // (GA lines, legacy labels).\n const idGrid = (\n seatId: string | null,\n label: string,\n objectType?: HoldLineItem['objectType'] | PickerSeat['objectType'],\n quantity = 1,\n objectId?: string,\n identity?: Partial<PickerSeat>,\n ): string => {\n const esc = (value: unknown): string => String(value ?? '—').replace(/[&<>\"]/g, (char) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"',\n })[char]!);\n const d = seatId ? this.controller.seatDetails(seatId) : null;\n const area = objectType === 'ga' ? gaAreas.find((candidate) => candidate.id === objectId) : undefined;\n const effectiveType = objectType === 'ga' ? 'ga' : d?.objectType ?? objectType;\n const typeWord = identity?.displayType?.trim()\n || d?.displayType?.trim()\n || area?.displayType?.trim()\n || (effectiveType === 'table' ? 'Table' : effectiveType === 'booth' ? 'Booth' : effectiveType === 'ga' ? 'General admission' : 'Row');\n const buyerName = identity?.rowLabel\n ?? identity?.displayLabel\n ?? d?.rowLabel\n ?? d?.displayLabel\n ?? area?.displayLabel\n ?? area?.label\n ?? label;\n if (effectiveType === 'table' && identity?.bookingMode) {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span>` +\n `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Guests</span><span class=\"val\">${quantity}</span></span></div>`;\n }\n if (effectiveType === 'ga') {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span>` +\n (quantity > 1 ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Tickets</span><span class=\"val\">${quantity}</span></span>` : '') + `</div>`;\n }\n if (effectiveType === 'booth') {\n return `<div class=\"sl-chip-id\">` +\n (d?.sectionLabel ? `<span class=\"fld sec\"><span class=\"sl-chip-eb\">Section</span><span class=\"val\">${esc(d.sectionLabel)}</span></span>` : '') +\n `<span class=\"fld mid\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span></div>`;\n }\n if (!d?.sectionLabel && !d?.rowLabel && !d?.seatNumber) {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">Seat</span><span class=\"val\">${esc(buyerName)}</span></span></div>`;\n }\n return (\n `<div class=\"sl-chip-id\">` +\n (d.sectionLabel ? `<span class=\"fld sec\"><span class=\"sl-chip-eb\">Section</span><span class=\"val\">${esc(d.sectionLabel)}</span></span>` : '') +\n (d.rowLabel ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(this.rowShort(d))}</span></span>` : '') +\n (d.seatNumber ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Seat</span><span class=\"val\">${esc(d.seatNumber)}</span></span>` : '') +\n `</div>`\n );\n };\n // Right icon rail per the canonical mock: remove on top, seat view below.\n const iconRail = (rmAria: string, viewLabel: string | null): string =>\n `<div class=\"sl-chip-rail\">` +\n `<button type=\"button\" class=\"rm\" aria-label=\"${rmAria}\">` +\n `<svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button>` +\n (viewLabel\n ? `<button type=\"button\" class=\"view\" data-view-label=\"${viewLabel}\" aria-label=\"${t('picker.viewFromSeat', { label: viewLabel })}\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg></button>`\n : '') +\n `</div>`;\n\n for (const item of heldItems) {\n const itemKey = `held:${item.label}`;\n nextTrayKeys.add(itemKey);\n const cat = this.controller.doc?.categories.find((c) => c.key === item.categoryKey);\n const tierName = item.tierId ? cat?.tiers?.find((ti) => ti.id === item.tierId)?.name : undefined;\n const heldSeat = item.objectType !== 'ga' ? this.controller.seatByLabel(item.label) : null;\n const table = item.objectType === 'table' ? this.controller.tableSelection(item.label) : null;\n const canView = this.seatViewEnabled() && !!heldSeat && item.objectType !== 'table';\n parts.push(\n `<div class=\"sl-chip sl-held${this.lastTrayKeys.has(itemKey) ? '' : ' sl-enter'}\" data-key=\"${itemKey}\" data-held=\"${encodeURIComponent(item.label)}\"${heldSeat ? ` data-locate=\"${heldSeat.id}\"` : ''}>` +\n `<div class=\"sl-chip-main\">` +\n idGrid(heldSeat?.id ?? null, item.label, item.objectType, item.quantity ?? 1, item.objectId, table ?? undefined) +\n `<div class=\"sl-chip-sub\">` +\n `<span class=\"sl-ticket-state held\" aria-label=\"Held for you\" title=\"Held for you\">` +\n `<svg viewBox=\"0 0 24 24\"><rect x=\"5\" y=\"10\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/></svg></span>` +\n `<span class=\"cat\">${cat?.label ?? item.categoryKey}${tierName ? ` · ${tierName}` : ''}</span>` +\n (table?.bookingMode === 'variable'\n ? `<button type=\"button\" class=\"sl-table-edit\" data-table-edit=\"${encodeURIComponent(item.label)}\">${item.quantity ?? 1} guests · Edit</button>`\n : '') +\n this.wheelchairChipMarker(heldSeat?.wheelchairSpaceType) +\n this.commercialChipMarker(heldSeat?.commercial) +\n `<span class=\"amt\">${this.money(this.paidPrice(item.categoryKey, item.tierId, item.unitPrice) * (item.quantity ?? 1))}</span>` +\n `</div></div>` +\n iconRail(`Remove held ticket ${item.label}`, canView ? item.label : null) +\n `</div>`,\n );\n }\n\n const heldLabels = new Set(heldItems.map((item) => item.label));\n const canView = this.seatViewEnabled();\n for (const s of seats.filter((seat) => !heldLabels.has(seat.label))) {\n const itemKey = `seat:${s.id}`;\n nextTrayKeys.add(itemKey);\n const cat = this.controller.doc?.categories.find((c) => c.key === s.categoryKey);\n const tierSelect =\n s.tiers && s.tiers.length\n ? `<select class=\"tier\" data-tier=\"${s.id}\" aria-label=\"${t('picker.ticketTierFor', { label: s.label })}\">` +\n s.tiers\n .map((ti) => `<option value=\"${ti.id}\"${ti.id === s.tierId ? ' selected' : ''}>${ti.name} · ${this.money(this.paidPrice(s.categoryKey, ti.id, ti.price))}</option>`)\n .join('') +\n `</select>`\n : '';\n parts.push(\n `<div class=\"sl-chip${this.lastTrayKeys.has(itemKey) ? '' : ' sl-enter'}\" data-key=\"${itemKey}\" data-seat=\"${s.id}\" data-locate=\"${s.id}\">` +\n `<div class=\"sl-chip-main\">` +\n idGrid(s.id, s.label, s.objectType, s.quantity ?? 1, s.objectId, s) +\n `<div class=\"sl-chip-sub\">` +\n `<span class=\"sl-ticket-state\" aria-label=\"Selected\" title=\"Selected\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M5 12l4 4L19 6\"/></svg></span>` +\n `<span class=\"cat\">${cat?.label ?? s.categoryKey}</span>` +\n (s.objectType === 'table' && s.bookingMode === 'variable'\n ? `<button type=\"button\" class=\"sl-table-edit\" data-table-edit=\"${encodeURIComponent(s.label)}\">${s.quantity ?? 1} guests · Edit</button>`\n : '') +\n `${this.wheelchairChipMarker(s.wheelchairSpaceType)}${this.commercialChipMarker(s.commercial)}${tierSelect}` +\n `<span class=\"amt\">${this.money(this.paidPrice(s.categoryKey, s.tierId ?? null, s.price) * (s.quantity ?? 1))}</span>` +\n `</div></div>` +\n iconRail(`Remove ${s.label}`, canView && s.objectType !== 'table' ? s.label : null) +\n `</div>`,\n );\n }\n\n for (const area of gaAreas) {\n const qty = this.gaQty.get(area.id) ?? 0;\n parts.push(\n `<div class=\"sl-ga\" data-ga=\"${area.id}\"><div class=\"sl-ga-info\">` +\n `<div class=\"sl-ga-name\">${area.displayLabel ?? area.label}</div>` +\n `<div class=\"sl-ga-sub\">${area.displayType ?? 'General admission'} · ${this.money(this.paidPrice(area.categoryKey, null, area.price))} · ${area.available} left</div></div>` +\n `<div class=\"sl-ga-qty\">` +\n `<button type=\"button\" data-d=\"-1\" aria-label=\"Fewer\">−</button><span>${qty}</span>` +\n `<button type=\"button\" data-d=\"1\" aria-label=\"More\">+</button></div></div>`,\n );\n }\n\n this.els.tray.innerHTML = parts.join('');\n this.lastTrayKeys = nextTrayKeys;\n this.els.tray.querySelectorAll<HTMLButtonElement>('[data-ba]').forEach((btn) => {\n btn.addEventListener('click', () => {\n this.baQty = Math.max(1, Math.min(this.maxTickets, this.baQty + Number(btn.dataset.ba)));\n this.syncTray();\n });\n });\n this.els.tray.querySelector<HTMLSelectElement>('[data-ba-cat]')?.addEventListener('change', (e) => {\n this.baCat = (e.target as HTMLSelectElement).value;\n });\n this.els.tray.querySelector<HTMLSelectElement>('[data-ba-zone]')?.addEventListener('change', (e) => {\n this.baZone = (e.target as HTMLSelectElement).value;\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-premium]')?.addEventListener('click', () => {\n this.baPremium = !this.baPremium;\n this.syncTray();\n });\n this.els.tray.querySelector<HTMLButtonElement>('.sl-ba-go')?.addEventListener('click', () => {\n if (this.pendingSelectionCount() > 0) {\n this.bestAvailableConfirm = true;\n this.syncTray();\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-replace]')?.focus();\n return;\n }\n void this.bestAvailable(this.baQty, this.baCat || undefined, { preferPremium: this.baPremium, zoneId: this.baZone || undefined });\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-cancel]')?.addEventListener('click', () => {\n this.bestAvailableConfirm = false;\n this.syncTray();\n this.els.tray.querySelector<HTMLButtonElement>('.sl-ba-go')?.focus();\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-replace]')?.addEventListener('click', () => {\n this.bestAvailableConfirm = false;\n void this.bestAvailable(this.baQty, this.baCat || undefined, { preferPremium: this.baPremium, zoneId: this.baZone || undefined });\n });\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip .rm').forEach((btn) => {\n btn.addEventListener('click', () => {\n const chip = btn.closest('.sl-chip') as HTMLElement;\n if (chip.dataset.held) {\n void this.removeHeldLabel(decodeURIComponent(chip.dataset.held), chip);\n return;\n }\n const id = chip.dataset.seat!;\n const label = this.controller.getSelection().find((sel) => sel.id === id)?.label ?? 'Seat';\n const remove = (): void => {\n this.controller.deselect([id]);\n this.toast(`${label} removed.`, 'neutral', {\n label: 'Undo',\n onClick: () => {\n const restored = this.controller.select([id]);\n this.toast(\n restored.length ? `${label} restored.` : `${label} is no longer available.`,\n restored.length ? 'success' : 'warning',\n );\n },\n });\n };\n if (this.reducedMotion()) {\n remove();\n return;\n }\n chip.classList.add('sl-leave');\n this.scheduleMotion(remove, 150);\n });\n });\n this.els.tray.querySelectorAll<HTMLButtonElement>('[data-table-edit]').forEach((button) => {\n button.addEventListener('click', (event) => {\n event.stopPropagation();\n const label = decodeURIComponent(button.dataset.tableEdit ?? '');\n const details = this.controller.tableSelection(label);\n if (!details) return;\n const heldItem = heldItems.find((item) => item.label === label && item.objectType === 'table');\n this.showTableDialog(\n { ...details, quantity: heldItem?.quantity ?? details.quantity },\n !!heldItem,\n button,\n );\n });\n });\n // Per-seat ticket-tier pick (Adult/Child/…) — updates price via onSelectionChange.\n this.els.tray.querySelectorAll<HTMLSelectElement>('.sl-chip .tier').forEach((sel) => {\n sel.addEventListener('change', () => this.controller.setSeatTier(sel.dataset.tier!, sel.value || null));\n });\n // View-from-seat button (data-view-label = seat label) on fresh + held chips.\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip .view[data-view-label]').forEach((btn) => {\n btn.addEventListener('click', () => {\n const seat = this.controller.seatByLabel(btn.dataset.viewLabel!);\n if (seat) void this.openSeatView(seat);\n });\n });\n // Card ↔ map linkage: hovering (or keyboard-focusing) a ticket card pulses\n // its seat on the map so the buyer can locate what they picked.\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip[data-locate]').forEach((chip) => {\n const locate = (): void => this.controller.flashSeat(chip.dataset.locate!, this.cssVar('--sl-accent') || '#f4b740');\n chip.addEventListener('mouseenter', locate);\n chip.addEventListener('focusin', locate);\n });\n this.els.tray.querySelectorAll<HTMLElement>('.sl-ga button').forEach((btn) => {\n btn.addEventListener('click', () => {\n const areaEl = btn.closest('.sl-ga') as HTMLElement;\n const id = areaEl.dataset.ga!;\n const area = gaAreas.find((a) => a.id === id);\n const delta = Number(btn.dataset.d);\n if (delta > 0 && !this.canAddTicket()) return;\n const next = Math.max(0, Math.min(area?.available ?? 0, (this.gaQty.get(id) ?? 0) + delta));\n this.gaQty.set(id, next);\n this.syncTray();\n });\n });\n\n // Sales closed: freeze the best-available + GA controls (read-only state).\n if (this.salesClosed) {\n this.els.tray\n .querySelectorAll<HTMLButtonElement | HTMLSelectElement>('.sl-ba-go,[data-ba],[data-ba-cat],[data-ba-zone],[data-ba-replace],.sl-ga button')\n .forEach((el) => {\n el.disabled = true;\n });\n }\n\n // totals + CTA (held lines + fresh selections + GA)\n const gaTotal = this.pendingGATotal(gaAreas);\n const gaCount = this.pendingGACount();\n const heldTotal = heldItems.reduce((sum, item) => sum + this.paidPrice(item.categoryKey, item.tierId, item.unitPrice) * (item.quantity ?? 1), 0);\n const heldCount = heldItems.reduce((sum, item) => sum + (item.quantity ?? 1), 0);\n const freshSeats = seats.filter((seat) => !heldLabels.has(seat.label));\n const total = freshSeats.reduce(\n (sum, s) => sum + this.paidPrice(s.categoryKey, s.tierId ?? null, s.price) * (s.quantity ?? 1),\n 0,\n ) + gaTotal + heldTotal;\n const count = freshSeats.reduce((sum, seat) => sum + (seat.quantity ?? 1), 0) + gaCount + heldCount;\n const pendingCount = this.pendingSelectionCount();\n const previousCount = this.lastTrayCount;\n const previousTotal = this.lastTrayTotal;\n this.els.count.textContent = count\n ? `${count} ${count === 1 ? 'ticket' : 'tickets'}`\n : 'No seats selected';\n this.els.total.textContent = count ? this.money(total) : '';\n this.root?.setAttribute('data-has-selection', String(count > 0));\n // The best-available panel's confirm (\"Replace your current choices?\") and\n // in-flight busy states must survive the narrow-layout collapse that hides\n // .sl-ba once the cart is non-empty. Mark them so the CSS keeps them shown.\n this.root?.setAttribute(\n 'data-ba-active',\n String(this.bestAvailableConfirm || this.bestAvailableBusy),\n );\n this.els.foot?.classList.toggle('empty', count === 0);\n if (this.els.seatSummary) {\n this.els.seatSummary.textContent = count ? `${count} selected` : '';\n }\n this.syncCta(count, pendingCount);\n if (this.hold) {\n const securedCount = heldCount || this.hold.seats?.length || 0;\n if (this.els.holdTitle) {\n this.els.holdTitle.textContent = `${securedCount} secured`;\n }\n if (this.els.holdCopy) {\n this.els.holdCopy.textContent = pendingCount\n ? `${pendingCount} more selected`\n : 'Checkout timer running';\n }\n const change = this.els.holdChange as HTMLButtonElement | undefined;\n if (change) {\n change.disabled = this.releasingHold;\n change.textContent = this.releasingHold ? 'Releasing…' : 'Change';\n }\n }\n if (count !== previousCount) this.animateOnce(this.els.count, 'sl-value-pop', 380);\n if (total !== previousTotal) this.animateOnce(this.els.total, 'sl-value-pop', 380);\n if (previousCount === 0 && count > 0) this.animateOnce(this.els.cta, 'sl-ready', 520);\n\n // Mobile sheet: one-line peek summary. Selected → \"N tickets · $X · Continue\";\n // empty → \"From $min · Best available\". Tap (sheet head) expands the sheet.\n if (this.els.peek) {\n if (count) {\n // Sheet state is shown by the persistent chevron in the head; the pill is\n // the action affordance (\"Continue\"/\"Review\") — no inline text arrow.\n this.els.peek.innerHTML =\n `<span>${count} ${count === 1 ? 'ticket' : 'tickets'} · ${this.money(total)}</span>` +\n `<span class=\"go\">${this.hold ? (pendingCount ? 'Secure more' : 'Continue') : 'Review'}</span>`;\n } else {\n const prices = (this.controller.doc?.categories ?? [])\n .map((c) => this.catPrice(c))\n .filter((p): p is number => p != null);\n this.els.peek.innerHTML =\n (prices.length ? `<span>From ${this.money(Math.min(...prices))}</span>` : '<span>Pick your seats</span>') +\n `<span class=\"go\">✦ Best seats</span>`;\n }\n }\n // Keep the mobile map stable after selection. The persistent Review pill\n // exposes the updated count/total without covering the seat the buyer just\n // confirmed; opening the sheet remains an explicit tap or swipe.\n this.lastTrayCount = count;\n this.lastTrayTotal = total;\n\n this.opts.onSelectionChange?.(seats);\n }\n\n private async removeHeldLabel(label: string, chip?: HTMLElement): Promise<boolean> {\n if (!label || this.releasingLabels.has(label)) return false;\n this.releasingLabels.add(label);\n chip?.setAttribute('aria-busy', 'true');\n const button = chip?.querySelector<HTMLButtonElement>('.rm');\n if (button) button.disabled = true;\n try {\n const preserveAcrossNavigation = this.handedOff;\n const released = await this.controller.releaseLabels([label]);\n if (!released) {\n this.toast(`Couldn't remove ${label}. Your hold is unchanged.`, 'error');\n return false;\n }\n const remaining = this.controller.currentHold();\n this.hold = remaining\n ? { holdId: remaining.holdId, expiresAt: remaining.expiresAt, seats: remaining.seats, items: remaining.items }\n : null;\n this.handedOff = !!this.hold && preserveAcrossNavigation;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n if (this.hold) {\n this.startHoldTimer(this.hold.expiresAt);\n } else {\n this.stopHoldTimer();\n this.forgetHold();\n }\n this.syncTray();\n this.emitHoldChange();\n this.toast(`${label} removed from your hold.`, 'success');\n return true;\n } finally {\n this.releasingLabels.delete(label);\n chip?.removeAttribute('aria-busy');\n if (button?.isConnected) button.disabled = false;\n }\n }\n\n private async handleChangeSeats(): Promise<void> {\n if (!this.hold || this.releasingHold) return;\n this.releasingHold = true;\n const button = this.els.holdChange as HTMLButtonElement | undefined;\n if (button) {\n button.disabled = true;\n button.textContent = 'Releasing…';\n }\n try {\n await this.release();\n if (!this.hold) this.toast('Held tickets released. Choose your new seats.', 'success');\n } finally {\n this.releasingHold = false;\n if (button?.isConnected) {\n button.disabled = false;\n button.textContent = 'Change';\n }\n }\n }\n\n private async handleCta(): Promise<void> {\n if (this.salesClosed) return;\n if (this.totalTicketCount() > this.maxTickets) {\n this.toast(`Remove tickets until your order has ${this.maxTickets} or fewer.`, 'warning');\n return;\n }\n // Best-available (or a prior CTA press) already holds the seats — hand off.\n // Held seats are NOT in the client selection (the server holds them), so\n // pass the hold's own seat list to the host.\n const committed = this.committedSelection();\n if (this.hold && !committed.some((s) => !(this.hold!.items ?? []).some((i) => i.label === s.label))) {\n const seats = this.hold.seats ?? committed;\n this.handedOff = true;\n this.setCtaPhase('checkout');\n this.checkoutHandoff(this.hold, seats);\n return;\n }\n this.holdingLabels = new Set(committed.map((seat) => seat.label));\n this.setCtaPhase('holding');\n try {\n // seats first (controller.hold covers selected seats); GA quantities ride along\n let hold: HoldResult | null = null;\n const gaEntries = [...this.gaQty.entries()].filter(([, q]) => q > 0);\n // Snapshot before hold — the hold's own WS echo repaints these seats.\n const chosenSeats = this.committedSelection();\n if (chosenSeats.length) {\n const h = await this.controller.hold(undefined, this.opts.holdTtlMs);\n hold = h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n for (const [areaId, qty] of gaEntries) {\n const h = await this.controller.holdGA(areaId, qty, { ttlMs: this.opts.holdTtlMs });\n hold = h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : hold;\n }\n if (!hold) {\n this.toast('One or more seats were just taken. Please pick again.', 'error');\n this.setCtaPhase('idle');\n this.syncTray();\n return;\n }\n this.hold = hold;\n this.handedOff = true;\n this.startHoldTimer(hold.expiresAt);\n this.flashHeldSeats(hold);\n this.setCtaPhase('checkout');\n this.emitHoldChange();\n // The replacement hold can combine an earlier best-available set with\n // newly selected seats. Hand the host the complete held seat set; the\n // server-priced line items remain authoritative for GA and totals.\n this.checkoutHandoff(hold, hold.seats ?? chosenSeats);\n } catch (err) {\n this.opts.onError?.(err);\n const problem = err as { reason?: string; conflicts?: Array<{ label?: string }> };\n const labels = (problem.conflicts ?? []).map((conflict) => conflict.label).filter(Boolean).slice(0, 3);\n // The CTA's controller.hold() path doesn't surface onSalesClosed — apply the\n // persistent read-only state here (the toast below stays). book/bestAvailable\n // paths reach it via the onSalesClosed callback.\n if (problem.reason === 'event_closed') this.setSalesClosed(true);\n const message = problem.reason === 'event_closed'\n ? 'Seat sales have closed for this event.'\n : labels.length\n ? `${labels.join(', ')} ${labels.length === 1 ? 'is' : 'are'} no longer available. Choose another ${labels.length === 1 ? 'seat' : 'group'}.`\n : 'One or more seats were just taken. Please pick again.';\n this.toast(message, 'error');\n this.setCtaPhase('idle');\n } finally {\n this.holdingLabels.clear();\n if (this.ctaPhase === 'holding') this.ctaPhase = 'idle';\n this.syncTray();\n }\n }\n\n private startHoldTimer(expiresAt: number): void {\n this.stopHoldTimer();\n this.holdExpiresAt = expiresAt;\n if (this.hold) this.rememberHold(this.hold);\n const pill = this.els.hold;\n pill.innerHTML =\n '<span class=\"sl-hold-dot\" aria-hidden=\"true\"></span><span>Held</span><span class=\"sl-hold-time\" data-ref=\"holdTime\"></span>';\n const time = pill.querySelector<HTMLElement>('[data-ref=\"holdTime\"]');\n this.els.holdNote?.classList.add('on');\n const tick = (): void => {\n const ms = Math.max(0, this.holdExpiresAt - Date.now());\n const m = Math.floor(ms / 60000);\n const s = String(Math.floor((ms % 60000) / 1000)).padStart(2, '0');\n if (time) time.textContent = `${m}:${s}`;\n pill.classList.add('on');\n pill.classList.toggle('is-expiring', ms > 0 && ms <= EXTEND_PROMPT_MS);\n // Offer an extension in the final stretch (but not once it's booked/expired).\n this.setExtendPrompt(ms > 0 && ms <= EXTEND_PROMPT_MS, ms);\n if (ms <= 0) this.stopHoldTimer();\n };\n tick();\n this.holdTimer = setInterval(tick, 500);\n }\n\n private stopHoldTimer(): void {\n if (this.holdTimer) clearInterval(this.holdTimer);\n this.holdTimer = null;\n this.els.hold?.classList.remove('on', 'is-expiring');\n this.els.holdNote?.classList.remove('on');\n this.setExtendPrompt(false, 0);\n }\n\n /** Show/refresh (or hide) the \"Need more time?\" prompt with the live seconds left. */\n private setExtendPrompt(show: boolean, ms: number): void {\n if (!this.extendEl) return;\n if (show && this.controller.currentHold() && !this.bookedShown) {\n const secs = Math.ceil(ms / 1000);\n this.els.extendTxt.innerHTML = `Your seats are held for <b>0:${String(secs).padStart(2, '0')}</b>. Need more time?`;\n this.extendEl.classList.add('on');\n } else {\n this.extendEl.classList.remove('on');\n }\n }\n\n private async handleExtend(): Promise<void> {\n const btn = this.els.extendBtn as HTMLButtonElement;\n btn.disabled = true;\n const prev = btn.textContent;\n btn.textContent = 'Adding…';\n try {\n const h = await this.controller.extendHold(this.opts.holdTtlMs);\n if (h) {\n // The controller re-armed its own expiry; sync ours + the pill, hide prompt.\n this.hold = { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items };\n this.holdExpiresAt = h.expiresAt;\n this.extendEl?.classList.remove('on');\n this.rememberHold(this.hold);\n this.emitHoldChange();\n this.toast('More time added — your seats are still held.', 'success');\n } else {\n this.toast(\"Couldn't add more time — please head to checkout now.\", 'warning');\n }\n } catch (err) {\n this.opts.onError?.(err);\n this.toast(\"Couldn't add more time — please head to checkout now.\", 'warning');\n } finally {\n btn.disabled = false;\n btn.textContent = prev;\n }\n }\n\n /**\n * Fire the booked-confirmation state once the buyer's held seats settle to\n * booked. The controller clears its own hold the moment every held label reads\n * 'booked' over the realtime channel (clearBookedHoldIfSettled), and this runs\n * on the same onStatusChange — so `currentHold() === null` while we still hold\n * a checkout handoff means \"sold\", not expired (expiry clears via onHoldExpired\n * on a different path, which nulls this.hold first).\n */\n private detectBooked(): void {\n if (this.bookedShown || !this.handedOff || !this.hold) return;\n if (this.controller.currentHold() !== null) return; // hold still open\n this.showBooked();\n }\n\n private showBooked(): void {\n if (this.bookedShown || !this.hold) return;\n this.bookedShown = true;\n const handoff = this.buildHandoff(this.hold);\n this.stopHoldTimer();\n this.forgetHold();\n const n = handoff.lineItems.reduce((sum, i) => sum + i.quantity, 0);\n if (this.els.bookedSub) {\n this.els.bookedSub.innerHTML =\n `<span class=\"sl-booked-seats\">${n} ${n === 1 ? 'ticket' : 'tickets'}</span> confirmed. ` +\n `A confirmation is on its way.`;\n }\n this.bookedEl?.classList.add('on');\n this.opts.onBooked?.(handoff);\n }\n\n /**\n * The seats are held. Send the buyer wherever this picker's `checkout` option\n * says they go.\n *\n * The default branch is the literal call that stood here before hosted\n * checkout existed, unchanged, so nothing about an existing integration moves.\n */\n private checkoutHandoff(hold: HoldResult, seats: PickerSeat[]): void {\n if (this.checkoutMode === 'hosted') {\n void this.startHostedCheckout(hold, seats);\n return;\n }\n this.opts.onCheckout?.(hold, seats, this.buildHandoff(hold));\n }\n\n /**\n * Take the money ourselves, through the organizer's own gateway.\n *\n * Order of operations matters: ASK FIRST, load second. `payment-options` is\n * already in flight from render, and its answer decides whether any payment\n * code is fetched at all — an event that cannot charge never downloads the\n * card that would have charged it.\n *\n * An empty list is not a failure and never dead-ends the buyer. It routes them\n * to whatever the host has: `onCheckoutUnavailable` (with the server's reason,\n * so the host can say the right one of three very different sentences), then\n * `onCheckout` with the ordinary handoff. A host that supplied neither gets\n * the widget's own honest card instead of a press that did nothing.\n */\n private async startHostedCheckout(hold: HoldResult, seats: PickerSeat[]): Promise<void> {\n const handoff = this.buildHandoff(hold);\n let options: PaymentOptionsResult | null = null;\n try {\n options = await (this.paymentOptions ??= this.pubApi!.paymentOptions(this.opts.event));\n } catch (err) {\n // A failed lookup is not evidence about the organizer's setup, so it falls\n // through to the reason that asserts the least about them.\n this.opts.onError?.(err);\n }\n if (this.destroyed) return;\n\n const provider = options?.providers?.[0];\n if (!provider) {\n const reason = paymentsOffReason(options?.reason);\n const handled = !!this.opts.onCheckoutUnavailable || !!this.opts.onCheckout;\n this.opts.onCheckoutUnavailable?.({ reason, handoff });\n this.opts.onCheckout?.(hold, seats, handoff);\n if (!handled) {\n void this.openCheckoutPanel({\n kind: 'unavailable',\n reason,\n seatCount: handoff.lineItems.reduce((sum, item) => sum + item.quantity, 0),\n });\n }\n return;\n }\n\n await this.openCheckoutPanel({\n kind: 'pay',\n provider,\n order: {\n holdId: handoff.holdId,\n expiresAt: handoff.expiresAt,\n currency: handoff.currency,\n total: handoff.total,\n labels: handoff.lineItems.map((item) => item.displayLabel ?? item.label),\n },\n });\n }\n\n /**\n * Fetch the checkout chunk and put its card over the map.\n *\n * Every failure here lands the buyer back on a map with their seats still\n * held, which is a place they can act from — a blocked chunk request must not\n * leave them staring at a CTA that no longer does anything.\n */\n private async openCheckoutPanel(state: CheckoutState): Promise<void> {\n let mountCheckout: HostedCheckoutModule['mountCheckout'];\n try {\n ({ mountCheckout } = await loadHostedCheckout());\n } catch (err) {\n this.opts.onError?.(err);\n this.toast('Checkout could not be opened. Your seats are still held — please try again.', 'error');\n this.setCtaPhase('idle');\n return;\n }\n if (this.destroyed || !this.root) return;\n this.closeCheckoutPanel();\n this.checkoutPanel = mountCheckout({\n root: this.root,\n state,\n // `returnUrl` rides along so a redirecting gateway can come back to the\n // HOST's page. The server validates its origin against the organizer's\n // declared embed domains and silently falls back to our own buyer page\n // when it does not match, so passing one can never redirect a paid buyer\n // somewhere the organizer did not sanction.\n startSession: (input) => this.pubApi!.startCheckout(this.opts.event, {\n ...input,\n ...(this.opts.returnUrl ? { returnUrl: this.opts.returnUrl } : {}),\n }),\n orderStatus: (orderId) => this.pubApi!.orderStatus(orderId),\n onCancel: () => {\n this.checkoutPanel = null;\n // The hold is untouched by cancelling — the buyer goes back to a map\n // that still has their seats, and the CTA still says checkout.\n if (!this.hold) this.setCtaPhase('idle');\n },\n onConfirmed: (order) => {\n this.opts.onOrderConfirmed?.(order);\n // The seats are sold. Re-read the map so they repaint as booked for this\n // buyer immediately rather than whenever the next realtime frame lands.\n void this.controller.refresh();\n },\n onError: (err) => this.opts.onError?.(err),\n });\n }\n\n private closeCheckoutPanel(): void {\n this.checkoutPanel?.destroy();\n this.checkoutPanel = null;\n }\n\n /** Assemble the stable {@link CheckoutHandoff} from a hold's server line items. */\n private buildHandoff(hold: HoldResult): CheckoutHandoff {\n const items = hold.items ?? [];\n // Host `pricing` overrides win in the handoff too — the host gets back the\n // prices it will actually charge, so map display and order total agree.\n const lineItems: CheckoutLineItem[] = items.map((it: HoldLineItem) => {\n const display = this.controller.lineItemDisplay(it);\n return {\n label: it.label,\n ...(display.displayLabel ? { displayLabel: display.displayLabel } : {}),\n ...(display.displayType ? { displayType: display.displayType } : {}),\n objectId: it.objectId,\n objectType: it.objectType,\n categoryKey: it.categoryKey,\n tierId: it.tierId,\n unitPrice: this.paidPrice(it.categoryKey, it.tierId, it.unitPrice),\n currency: it.currency ?? this.currency,\n quantity: it.quantity ?? 1,\n };\n });\n const currency = lineItems[0]?.currency ?? this.currency;\n const total = lineItems.reduce((sum, i) => sum + i.unitPrice * i.quantity, 0);\n return { holdId: hold.holdId, expiresAt: hold.expiresAt, currency, lineItems, total };\n }\n\n private emitHoldChange(): void {\n const hold = this.hold;\n this.opts.onHoldChange?.(\n hold,\n hold?.seats ?? [],\n hold ? this.buildHandoff(hold) : null,\n );\n }\n\n private toast(\n msg: string,\n tone: 'neutral' | 'success' | 'warning' | 'error' = 'neutral',\n action?: { label: string; onClick: () => void },\n ): void {\n const el = this.els.toast;\n if (!el) return;\n el.replaceChildren();\n const copy = document.createElement('span');\n copy.textContent = msg;\n el.appendChild(copy);\n el.classList.toggle('has-action', !!action);\n if (action) {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'sl-toast-action';\n button.textContent = action.label;\n button.addEventListener('click', action.onClick, { once: true });\n el.appendChild(button);\n }\n el.dataset.tone = tone;\n el.classList.add('on');\n if (this.toastTimer) clearTimeout(this.toastTimer);\n this.toastTimer = setTimeout(() => {\n el.classList.remove('on');\n el.classList.remove('has-action');\n el.dataset.tone = 'neutral';\n }, 4200);\n }\n\n private placeTooltip(): void {\n if (!this.tipEl) return;\n const hw = this.els.map.clientWidth;\n const tw = this.tipEl.offsetWidth;\n const th = this.tipEl.offsetHeight;\n let x = this.tipPos.x + 14;\n let y = this.tipPos.y - th - 12;\n if (x + tw > hw - 8) x = this.tipPos.x - tw - 14;\n if (y < 8) y = this.tipPos.y + 18;\n this.tipEl.style.left = `${Math.max(8, x)}px`;\n this.tipEl.style.top = `${Math.max(8, y)}px`;\n }\n\n /**\n * Row label without the redundant section prefix. Charts commonly name row\n * objects \"104-A\" while the Section column already shows \"104\" — so the Row\n * cell repeats the section and, in the compact hover card, truncates to\n * \"10…\". Strip a leading \"<section><sep>\" so Row reads a clean \"A\". Only when\n * the prefix is exact (won't touch \"1040-A\" under section \"104\"); otherwise\n * the label is shown verbatim.\n */\n /** Buyer-facing type word for the row/table key label — the designer's\n * per-object \"Displayed type\" override, or the default \"Row\". */\n private rowTypeWord(details: { displayType?: string; rowType?: string; objectType?: PickerSeat['objectType'] } | null | undefined): string {\n const authored = details?.displayType?.trim() || details?.rowType?.trim();\n if (authored) return authored;\n if (details?.objectType === 'table') return 'Table';\n if (details?.objectType === 'booth') return 'Booth';\n return 'Row';\n }\n\n private rowShort(details: { sectionLabel?: string; rowLabel?: string } | null | undefined): string | undefined {\n const row = details?.rowLabel;\n const sec = details?.sectionLabel;\n if (!row || !sec) return row;\n for (const sep of ['-', ' ', '·', '/', '_']) {\n const prefix = `${sec}${sep}`;\n if (row.startsWith(prefix) && row.length > prefix.length) return row.slice(prefix.length);\n }\n return row;\n }\n\n private updateTooltip(details: SeatHoverDetails | null): void {\n if (!this.tipEl) return;\n if (!details) {\n this.tipEl.style.display = 'none';\n return;\n }\n const esc = (v: unknown): string =>\n String(v ?? '—').replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!));\n const price = this.money(this.paidPrice(details.categoryKey, details.tierId ?? null, details.price));\n // Identity grid — the same Section·Row·Seat card the buyer meets on confirm\n // and in the cart, just smaller. Falls back to a single field for a bare\n // label (GA / legacy seats with no spatial context).\n const isGroupedTable = details.objectType === 'table' && !!details.bookingMode;\n const isBooth = details.objectType === 'booth';\n const hasLoc = details.sectionLabel || details.rowLabel || details.seatNumber;\n const grid = isGroupedTable\n ? `<div class=\"sl-tip-grid\">` +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(details.rowLabel ?? details.displayLabel ?? details.label)}</span></div>` +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Guests</span><span class=\"sl-tip-val\">${details.bookingMode === 'variable' ? `${details.minOccupancy}–${details.maxOccupancy}` : details.capacity}</span></div>` +\n `</div>`\n : isBooth\n ? `<div class=\"sl-tip-grid\">` +\n (details.sectionLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Section</span><span class=\"sl-tip-val\">${esc(details.sectionLabel)}</span></div>` : '') +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(details.rowLabel ?? details.displayLabel ?? details.label)}</span></div>` +\n `</div>`\n : hasLoc\n ? `<div class=\"sl-tip-grid\">` +\n (details.sectionLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Section</span><span class=\"sl-tip-val\">${esc(details.sectionLabel)}</span></div>` : '') +\n (details.rowLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(this.rowShort(details))}</span></div>` : '') +\n (details.seatNumber ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Seat</span><span class=\"sl-tip-val\">${esc(details.seatNumber)}</span></div>` : '') +\n `</div>`\n : `<div class=\"sl-tip-grid one\"><div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Seat</span><span class=\"sl-tip-val\">${esc(details.displayLabel ?? details.label)}</span></div></div>`;\n const statusLine =\n details.status === 'free'\n ? ''\n : `<div class=\"sl-tip-status\">${details.status === 'held' ? t('map.statusHeld') : t('map.statusTaken')}</div>`;\n const limited = this.limitedViewLabel(details.commercial);\n const cxLine = limited\n ? `<div class=\"sl-tip-cx\"><span class=\"g\" aria-hidden=\"true\">◐</span>${esc(limited)}</div>`\n : '';\n const wheelchair = this.wheelchairProvisionLabel(details.wheelchairSpaceType);\n const wheelchairLine = wheelchair\n ? `<div class=\"sl-tip-cx\"><span class=\"g\" aria-hidden=\"true\">♿</span>${esc(wheelchair)}</div>`\n : '';\n this.tipEl.style.setProperty('--sl-cat', details.categoryColor);\n this.tipEl.innerHTML =\n grid +\n `<div class=\"sl-tip-cat\"><span class=\"sl-tip-dot\" style=\"background:${details.categoryColor}\"></span>` +\n `<span class=\"sl-tip-name\">${esc(details.categoryLabel)}</span>` +\n `<span class=\"sl-tip-amt\">${price}</span></div>` +\n wheelchairLine +\n cxLine +\n statusLine;\n this.tipEl.style.display = 'block';\n this.placeTooltip();\n }\n\n // ---- public conveniences ----------------------------------------------------\n\n getSelection(): PickerSeat[] {\n return this.committedSelection();\n }\n\n /** Current colorblind-safe render state, resolved from the stored buyer\n * preference at mount. Host chrome (e.g. the Designer preview) reads this to\n * surface the state rather than rendering colorblind colors silently. */\n isColorblindSafe(): boolean {\n return this.cbSafe;\n }\n\n /** Single source of truth for the colorblind-safe toggle — used by both the\n * in-widget button and host chrome. Updates the renderer, the persisted\n * cross-surface preference, and the in-widget button's pressed state together\n * so the two controls never diverge. */\n setColorblindSafe(on: boolean): void {\n if (on === this.cbSafe) return;\n this.cbSafe = on;\n this.cbEl?.setAttribute('aria-pressed', String(on));\n this.controller.setColorblindSafe(on);\n // Persist under the SAME key the public page uses (cross-surface preference).\n writeStoredColorblind(on);\n }\n\n /** Switch the underlying 2D renderer projection (flat / isometric). The buyer\n * UI no longer exposes `perspective`; it is coerced to `flat`. */\n setViewMode(mode: RendererViewMode): void {\n this.controller.setViewMode(this.normalizeInitialView(mode));\n this.syncProjection();\n this.dismissConfirm();\n }\n\n /** Current buyer canvas projection. */\n getViewMode(): RendererViewMode {\n return this.controller.getViewMode();\n }\n\n /** `perspective` (2.5D) is retired from the buyer surface — accept it for\n * source compatibility but coerce to `flat` with a one-time deprecation warn. */\n private perspectiveWarned = false;\n private normalizeInitialView(mode: RendererViewMode | undefined): RendererViewMode {\n if (mode === 'perspective') {\n if (!this.perspectiveWarned) {\n this.perspectiveWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[seatlayer] initialView:'perspective' (2.5D) is deprecated for the buyer picker and \"\n + \"was coerced to 'flat'. Use the Map | 3D control for the immersive view.\",\n );\n }\n return 'flat';\n }\n return mode ?? 'flat';\n }\n\n // ---- 3D venue view ---------------------------------------------------------\n\n /** Current buyer view: the flat map, or the interactive 3D venue. */\n getBuyerView(): 'map' | 'venue3d' {\n return this.buyerView;\n }\n\n /**\n * Switch between the flat seat **Map** and the interactive **3D venue** view —\n * the same control the buyer's on-widget `Map | 3D` toggle drives.\n *\n * Entering `'venue3d'` with `opts.flyToSeatId` runs the cinematic tour: the\n * camera flies to the seat and holds in the live scene (a chip offers the\n * 360° view-from-seat) —\n * the widget enters 3D and auto-flies the camera to that seat, dissolving into\n * its view-from-seat panorama (the same chain as tapping \"See the view from\n * here\" on a seat's confirm card). When the widget is **already** in the 3D\n * view, the camera simply flies to the requested seat — the GL scene is not\n * torn down or rebuilt, so there is no flash or re-entry.\n *\n * No-op when the view is unchanged and no `flyToSeatId` is given, or when 3D is\n * unavailable for this chart.\n *\n * @param view `'map'` for the flat picker, `'venue3d'` for the 3D venue.\n * @param opts.flyToSeatId When entering (or already in) `'venue3d'`, the seat\n * id to fly the camera to — cinematic → panorama.\n * Ignored when `view` is `'map'`.\n *\n * @example\n * // Public 3D tour entry — enter 3D and fly straight to the buyer's seat:\n * picker.setBuyerView('venue3d', { flyToSeatId: 'A-12' });\n */\n setBuyerView(view: 'map' | 'venue3d', opts?: { flyToSeatId?: string }): void {\n if (view === 'map') {\n this.exit3d();\n return;\n }\n const flyToSeatId = opts?.flyToSeatId;\n if (this.buyerView === 'venue3d') {\n // Already immersed — just fly the cinematic to the requested seat (if any),\n // without a jarring teardown/rebuild of the GL scene.\n if (flyToSeatId) void this.view3dHandle?.flyToSeat(flyToSeatId);\n return;\n }\n // Enter 3D; when a seat is given, the cinematic flies straight to it.\n void this.enter3d(flyToSeatId);\n }\n\n /** SeatStatus → the view3d palette state. Selection is layered separately. */\n private seatState3dFor(seat: ExpandedSeat): 'available' | 'held' | 'sold' | 'dimmed' {\n switch (this.controller.getStatus(seat.id)) {\n case 'held': return 'held';\n case 'booked': return 'sold';\n case 'not_for_sale': return 'dimmed';\n default: break;\n }\n // A filter that dims a seat on the map has to dim it in 3D too. 2D applies\n // these as Konva opacity, which the GL view never saw — so a buyer who\n // filtered to one price band and then switched to 3D got the unfiltered\n // venue back with no indication the filter was still on. The 'dimmed' state\n // already exists for held-back inventory and is exactly this treatment.\n if (this.priceBandKeys != null && !this.priceBandKeys.has(seat.categoryKey)) return 'dimmed';\n if (this.limitedViewFilter && (seat.commercial?.restrictedView || seat.commercial?.obstructedView)) {\n return 'dimmed';\n }\n return 'available';\n }\n\n /** Push the full live availability snapshot into the 3D handle (selection is\n * preserved inside the module). Cheap enough per status delta. */\n private pushAvailabilityTo3d(): void {\n if (!this.view3dHandle) return;\n const updates = this.allSeats().map((s) => ({ seatId: s.id, state: this.seatState3dFor(s) }));\n this.view3dHandle.setAvailability(updates);\n }\n\n /** Mirror the authoritative widget selection into the 3D handle. */\n private syncSelectionTo3d(): void {\n if (!this.view3dHandle) return;\n this.view3dHandle.setSelection(this.controller.getSelection().map((s) => s.id));\n }\n\n /** Build the view-from-seat panorama the cinematic dissolves into — reuses the\n * exact input path as the 2D `openSeatView` (organizer photo, else generated). */\n private async seatViewFor3d(seatId: string): Promise<View3DSeatView | null> {\n const seat = this.allSeats().find((s) => s.id === seatId);\n if (!seat) return null;\n if (seat.viewUrl) return { url: seat.viewUrl };\n const doc = this.controller.doc;\n if (!doc) return null;\n const activeId = this.controller.getActiveFloorId();\n const focal = seat.focalPoint\n ?? doc.floors?.find((f) => f.id === activeId)?.focalPoint\n ?? doc.focalPoint\n ?? { x: 0, y: 0 };\n try {\n // Async only for the lazy generator chunk; by the time a cinematic asks\n // for a view the buyer has already been in 3D for a second or more.\n const { generateSeatPanorama } = await loadPanorama();\n return { url: generateSeatPanorama(seat, focal, this.allSeats()).url };\n } catch {\n return null;\n }\n }\n\n /** Route the module's decoupled analytics into the host callback, tagged buyer. */\n private emit3dAnalytics(event: string, props?: Record<string, unknown>): void {\n try {\n this.opts.onAnalytics?.(event, { ...props, surface: 'buyer' });\n } catch {\n /* a throwing host sink never breaks the widget */\n }\n }\n\n /** A 3D seat tap runs the SAME selection path as a 2D tap: toggle through the\n * controller, then raise the shared confirm card (bottom-sheeted in 3D). */\n private onView3dSeatPick(seatId: string): void {\n if (this.salesClosed) {\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n this.syncSelectionTo3d();\n return;\n }\n const seat = this.allSeats().find((s) => s.id === seatId);\n if (!seat) return;\n // Tapping an already-committed seat clears it (mirrors the 2D toggle).\n const already = this.committedSelection().some((s) => s.id === seatId);\n if (already) {\n this.controller.deselect([seatId]);\n this.dismissConfirm();\n return;\n }\n this.flashPickedSeat(seatId);\n this.controller.select([seatId]); // programmatic select is silent → confirm ourselves\n if (this.opts.confirmSelection !== false) this.showConfirm(seat);\n else this.syncTray();\n }\n\n /**\n * The venue-navigation rail inside 3D: levels and areas.\n *\n * In 2D a buyer moves through the venue by floor switcher and by the LOD\n * rungs. Both are hidden while immersed, and the 3D module's own chips only\n * cover \"go home\" and \"see the 360\" — so on a multi-floor or multi-zone chart\n * the buyer entered 3D and LOST the ability to reach the level or area they\n * were booking. The camera moves for both already exist on the handle\n * (`focusFloor` / `focusZone`); this is the surface that offers them.\n *\n * Levels are a TOGGLE (a floor stays isolated until you pick another), areas\n * are an ACTION (the camera flies there and you are then free to orbit), which\n * is why only the level pills carry a pressed state.\n */\n private buildView3dNav(overlay: HTMLElement, handle: Venue3DHandle): void {\n const floors = handle.floors();\n // An empty zone has nothing to frame and `focusZone` refuses it — offering\n // a pill that cannot move the camera is worse than offering nothing.\n const zones = handle.zones().filter((z) => z.seatCount > 0);\n // Zones are optional; sections are not. A chart that authors no zones (or\n // one) still needs a way to move around the venue, so the rail falls back to\n // the rung below. Capped, because a 51-section arena is a list, not a rail —\n // past that the buyer is better served by the 2D map's section navigation.\n const sections = zones.length > 1\n ? []\n : handle.sections().filter((s) => s.seatCount > 0).slice(0, MAX_3D_SECTION_PILLS);\n // One of anything is not a choice — a single-floor, single-zone venue gets\n // no rail rather than a rail that does nothing.\n const wantFloors = floors.length > 1;\n const wantZones = zones.length > 1;\n const wantSections = sections.length > 1;\n if (!wantFloors && !wantZones && !wantSections) return;\n\n const nav = document.createElement('div');\n nav.className = 'sl-view3d-nav';\n\n if (wantFloors) {\n const row = document.createElement('div');\n row.setAttribute('role', 'group');\n row.setAttribute('aria-label', this.tf('picker.levels', 'Levels'));\n const pills: HTMLButtonElement[] = [];\n const select = (index: number | null): void => {\n if (!handle.focusFloor(index)) return;\n pills.forEach((p) => {\n p.setAttribute('aria-pressed', String((p.dataset.floor === '' ? null : Number(p.dataset.floor)) === index));\n });\n };\n const add = (label: string, index: number | null): void => {\n const b = document.createElement('button');\n b.type = 'button';\n b.textContent = label;\n b.dataset.floor = index === null ? '' : String(index);\n b.setAttribute('aria-pressed', String(index === null));\n b.addEventListener('click', () => select(index));\n pills.push(b);\n row.appendChild(b);\n };\n add(this.tf('picker.allLevels', 'All levels'), null);\n for (const f of floors) add(f.label || `Level ${f.index + 1}`, f.index);\n nav.appendChild(row);\n }\n\n if (wantZones || wantSections) {\n const row = document.createElement('div');\n row.setAttribute('role', 'group');\n row.setAttribute('aria-label', this.tf('picker.areas', 'Areas'));\n const entries: Array<{ id: string; label: string; go: () => void }> = wantZones\n ? zones.map((z) => ({ id: z.id, label: z.label || z.id, go: () => { handle.focusZone(z.id); } }))\n : sections.map((s) => ({ id: s.id, label: s.label || s.id, go: () => { handle.focusSection(s.id); } }));\n for (const e of entries) {\n const b = document.createElement('button');\n b.type = 'button';\n b.textContent = e.label;\n b.addEventListener('click', e.go);\n row.appendChild(b);\n }\n nav.appendChild(row);\n }\n\n overlay.appendChild(nav);\n }\n\n private async enter3d(flySeatId?: string): Promise<void> {\n if (this.view3dEl || !this.canOffer3d() || !this.els.map) return;\n const doc = this.controller.doc;\n if (!doc) return;\n this.buyerView = 'venue3d';\n this.root?.setAttribute('data-view3d', 'on');\n this.dismissConfirm();\n this.syncProjection();\n\n const overlay = document.createElement('div');\n overlay.className = 'sl-view3d';\n overlay.setAttribute('role', 'group');\n overlay.setAttribute('aria-label', 'Interactive 3D venue view');\n const back = document.createElement('button');\n back.type = 'button';\n back.className = 'sl-view3d-back';\n back.innerHTML =\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M15 18l-6-6 6-6\"/></svg>'\n + `<span>${this.tf('picker.backToMap', 'Back to map')}</span>`;\n back.addEventListener('click', () => this.exit3d());\n overlay.appendChild(back);\n this.els.map.appendChild(overlay);\n this.view3dEl = overlay;\n requestAnimationFrame(() => { overlay.style.opacity = '1'; });\n\n const gen = ++this.view3dGen;\n try {\n const seats = expandChart(doc);\n const mod = await loadVenue3d();\n // Left 3D (or was torn down) while the OGL chunk loaded → abandon.\n if (gen !== this.view3dGen || this.buyerView !== 'venue3d' || this.view3dEl !== overlay) return;\n const handle = mod.mountVenue3D(overlay, { doc, seats }, {\n onSeatPick: (id) => this.onView3dSeatPick(id),\n // Deferred off the tap gesture: generateSeatPanorama walks every seat\n // (O(n) on a 13k chart), and the module prefetches at pick — by the\n // time the flight lands (~2.5s) the idle render has long finished. A\n // null view REJECTS so the module's no-panorama path keeps the buyer\n // in orbit instead of dissolving into an empty overlay.\n getSeatView: (id) =>\n new Promise((resolve, reject) => {\n const run = () => {\n void this.seatViewFor3d(id).then((view) => {\n if (view) resolve(view);\n else reject(new Error('seat_view_unavailable'));\n });\n };\n const ric = (globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => void }).requestIdleCallback;\n if (typeof ric === 'function') ric(run, { timeout: 1500 });\n else setTimeout(run, 50);\n }),\n onAnalytics: (event, props) => this.emit3dAnalytics(event, props),\n });\n this.view3dHandle = handle;\n this.pushAvailabilityTo3d();\n this.syncSelectionTo3d();\n this.buildView3dNav(overlay, handle);\n if (flySeatId) void handle.flyToSeat(flySeatId);\n } catch (err) {\n this.opts.onError?.(err);\n this.exit3d();\n }\n }\n\n private exit3d(): void {\n if (this.buyerView !== 'venue3d' && !this.view3dEl) return;\n this.view3dGen++; // supersede any in-flight mount\n this.buyerView = 'map';\n this.root?.removeAttribute('data-view3d');\n try { this.view3dHandle?.dispose(); } catch { /* GL teardown best-effort */ }\n this.view3dHandle = null;\n const overlay = this.view3dEl;\n this.view3dEl = null;\n if (overlay) {\n overlay.style.opacity = '0';\n setTimeout(() => overlay.remove(), 320);\n }\n this.syncProjection();\n // Zoom/pan of the underlying 2D stage was never touched, so the map is\n // restored exactly. Re-offer the confirm the buyer left via \"See it in 3D\".\n const seat = this.view3dReturnSeat;\n this.view3dReturnSeat = null;\n if (seat && this.committedSelection().some((s) => s.id === seat.id)\n && this.opts.confirmSelection !== false) {\n this.showConfirm(seat);\n }\n }\n\n /** Current active/restored hold reflected in the tray. */\n getCurrentHold(): HoldResult | null {\n return this.hold;\n }\n\n /** Explicit host-driven hold restore (automatic session restore is on by default). */\n async resumeHold(holdId: string): Promise<HoldResult | null> {\n return this.resumeHoldFromServer(holdId, false);\n }\n\n /** Remove one server-held ticket while keeping the rest of the hold active. */\n async removeHeldTicket(label: string): Promise<boolean> {\n return this.removeHeldLabel(label);\n }\n\n async bestAvailable(\n qty: number,\n categoryKey?: string,\n opts: { preferPremium?: boolean; zoneId?: string } = {},\n ): Promise<HoldResult | null> {\n if (this.salesClosed || this.bestAvailableBusy) return null;\n qty = Math.max(1, Math.min(this.maxTickets, Math.floor(qty)));\n if (this.confirmSeat) this.cancelConfirm();\n this.bestAvailableConfirm = false;\n this.bestAvailableBusy = true;\n const button = this.els.tray?.querySelector<HTMLButtonElement>('.sl-ba-go');\n if (button) {\n button.disabled = true;\n button.innerHTML = '<span class=\"sl-ba-spin\" aria-hidden=\"true\"></span>Finding…';\n }\n try {\n // Same checkout window as a clicked selection — see the CTA's hold() call.\n const h = await this.controller.bestAvailable(qty, categoryKey, { ...opts, ttlMs: this.opts.holdTtlMs });\n if (h) {\n this.hold = { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items };\n this.handedOff = false;\n this.bookedShown = false;\n this.gaQty.clear();\n this.startHoldTimer(h.expiresAt);\n this.flashHeldSeats(this.hold);\n this.syncTray();\n this.emitHoldChange();\n // Premium quick-pick asked for a premium block but no full block of\n // `qty` existed → we held the best overall instead. Surface a subtle note.\n if (opts.preferPremium && h.seats.length && !h.seats.every((s) => s.commercial?.premium)) {\n this.toast(t('picker.premiumFallbackNote', { count: qty }), 'neutral');\n }\n return this.hold;\n }\n return null;\n } catch (err) {\n this.opts.onError?.(err);\n const reason = (err as { reason?: string })?.reason;\n const message = reason === 'not_enough_together'\n ? `We couldn't find ${qty} seats together. Try fewer seats or another ticket type.`\n : reason === 'sold_out'\n ? 'That ticket type is sold out. Try another ticket type.'\n : reason === 'event_closed'\n ? 'Seat sales have closed for this event.'\n : 'Those seats are no longer available. Try another quantity or ticket type.';\n this.toast(message, 'error');\n return null;\n } finally {\n this.bestAvailableBusy = false;\n this.syncTray();\n }\n }\n\n async release(): Promise<void> {\n const tracked = this.hold;\n const controllerHold = this.controller.currentHold();\n let released = true;\n if (controllerHold) {\n released = await this.controller.release();\n } else if (tracked) {\n // The live controller can legitimately settle/clear its local hold before\n // the shell finishes dismissing. The shell still owns the server handoff,\n // so release from that authoritative copy instead of silently no-oping.\n const labels = [...new Set([\n ...(tracked.items ?? []).map((item) => item.label),\n ...(tracked.seats ?? []).map((seat) => seat.label),\n ])];\n if (labels.length) {\n try {\n await this.api.release(this.opts.event, labels, tracked.holdId);\n } catch (error) {\n this.opts.onError?.(error);\n released = false;\n }\n }\n }\n if (!released) {\n this.toast(\"Couldn't release your tickets. Your hold is unchanged.\", 'error');\n return;\n }\n this.hold = null;\n this.forgetHold();\n this.handedOff = false;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.stopHoldTimer();\n this.gaQty.clear();\n this.syncTray();\n this.emitHoldChange();\n }\n\n // ---- buyer access (Sales Channels) ---------------------------------------\n\n /**\n * Realtime for an access-scoped picker.\n *\n * A tokenless picker never gets here: `access` is null, `PubApi.socketUrl()`\n * returns the URL it always has, and PickerController keeps its own socket\n * and its own legacy frames. Nothing about the public path changes.\n */\n private startRealtime(): void {\n if (!this.access?.configured || !this.pubApi || this.realtime) return;\n const event = this.opts.event;\n this.realtime = new BuyerRealtimeClient({\n url: this.pubApi.subscribeUrl(event),\n mintTicket: () => this.pubApi!.subscribeTicket(event),\n onAccessUnavailable: (state) => {\n this.opts.onAccessUnavailable?.(state);\n this.showAccessPanel(state);\n },\n sink: createControllerSink(this.controller, {\n flashOnLiveChange: true,\n onStatusChange: () => {\n this.syncPrices();\n this.detectBooked();\n this.refreshMinimap();\n this.pushAvailabilityTo3d();\n },\n onSelectedObjectUnavailable: (labels, reason) => {\n this.opts.onSelectedObjectUnavailable?.({ labels, reason });\n this.syncTray();\n this.toast(\n reason === 'ineligible'\n ? this.tf(\n 'picker.seatNoLongerYours',\n 'Some seats are no longer available to you. They have been removed from your order.',\n )\n : this.tf(\n 'picker.seatTaken',\n 'Someone else took a seat you had picked. It has been removed from your order.',\n ),\n 'warning',\n );\n },\n }),\n });\n this.realtime.start();\n }\n\n /**\n * Re-acquire the buyer access session — call after your app has re-authorized\n * the buyer. A revoked session cannot recover any other way. Resolves true\n * when a fresh bearer is held; the map and the realtime feed resume with it.\n */\n async refreshAccess(): Promise<boolean> {\n if (!this.access?.configured) return false;\n const ok = await this.access.refresh('manual');\n if (!ok) return false;\n this.dismissAccessPanel();\n await this.controller.refresh();\n if (this.realtime) this.realtime.restart();\n else this.startRealtime();\n return true;\n }\n\n /**\n * The buyer-facing access state. Plain language, no internal vocabulary, and\n * never a channel name, id or count — the buyer is told what happened and\n * what to do, not which allocation they missed (guide §7, §10).\n *\n * Held seats are deliberately left alone: a hold is relinquished by its own\n * opaque capability, not by channel access, so losing access never strands\n * inventory and never silently drops a buyer's cart (guide §9).\n */\n private showAccessPanel(state: { reason: BuyerAccessUnavailableReason; retryable: boolean }): void {\n if (this.destroyed || !this.root) return;\n const copy = this.accessCopy(state.reason);\n this.dismissAccessPanel();\n const panel = document.createElement('div');\n panel.className = 'sl-access';\n panel.setAttribute('role', 'status');\n panel.setAttribute('aria-live', 'polite');\n const text = document.createElement('div');\n const title = document.createElement('div');\n title.className = 'sl-access-title';\n title.textContent = copy.title;\n const body = document.createElement('div');\n body.className = 'sl-access-body';\n body.textContent = copy.body;\n text.appendChild(title);\n text.appendChild(body);\n if (copy.action) {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'sl-access-act';\n button.textContent = copy.action;\n button.addEventListener('click', () => {\n void this.refreshAccess();\n });\n text.appendChild(button);\n }\n panel.appendChild(text);\n (this.regions?.['bottom-center'] ?? this.root).appendChild(panel);\n this.accessEl = panel;\n }\n\n private dismissAccessPanel(): void {\n this.accessEl?.remove();\n this.accessEl = null;\n }\n\n private accessCopy(reason: BuyerAccessUnavailableReason): {\n title: string;\n body: string;\n action?: string;\n } {\n switch (reason) {\n case 'paused':\n return {\n title: this.tf('picker.accessPausedTitle', 'These seats are on hold right now'),\n body: this.tf(\n 'picker.accessPausedBody',\n 'The organizer has paused this selection. Try again in a few minutes.',\n ),\n action: this.tf('picker.accessRetry', 'Try again'),\n };\n case 'revoked':\n return {\n title: this.tf('picker.accessRevokedTitle', 'This access link is no longer active'),\n body: this.tf(\n 'picker.accessRevokedBody',\n 'Ask whoever sent you here for a new link to keep booking these seats.',\n ),\n };\n case 'no_token':\n case 'provider_failed':\n return {\n title: this.tf('picker.accessExpiredTitle', 'Your access session has ended'),\n body: this.tf(\n 'picker.accessExpiredBody',\n 'Sign in again, or reload the page, to keep browsing these seats. Anything you are already holding stays yours.',\n ),\n action: this.tf('picker.accessRetry', 'Try again'),\n };\n default:\n return {\n title: this.tf('picker.accessInvalidTitle', 'We couldn’t verify your access'),\n body: this.tf(\n 'picker.accessInvalidBody',\n 'You can still book anything shown as available. Contact whoever sent you here for access to the rest.',\n ),\n };\n }\n }\n\n destroy(): void {\n this.destroyed = true;\n this.realtime?.stop();\n this.realtime = null;\n this.dismissAccessPanel();\n this.access?.clear();\n // Closing/tearing down before checkout means the buyer abandoned any\n // best-available hold. Release it server-side; a handed-off checkout keeps\n // its hold alive across the host's route transition.\n if (this.hold && !this.handedOff) void this.controller.release();\n this.closeConfirm();\n this.dismissTableDialog(false);\n this.closeSeatView();\n // A payment card outlives its own mount node (it listens on the document for\n // ESC), so it is torn down explicitly rather than left to root.remove().\n this.closeCheckoutPanel();\n this.exit3d(); // dispose GL + remove the 3D overlay if it's up\n this.stopHoldTimer();\n if (this.toastTimer) clearTimeout(this.toastTimer);\n if (this.liveTimer) clearTimeout(this.liveTimer);\n for (const timer of this.motionTimers) clearTimeout(timer);\n this.motionTimers.clear();\n this.ro?.disconnect();\n this.ro = null;\n // Don't strand a host frame pinned fullscreen across a route teardown.\n if (this.framedFs) this.setFramedFs(false);\n if (this.escHandler) document.removeEventListener('keydown', this.escHandler);\n if (this.fsChangeHandler) document.removeEventListener('fullscreenchange', this.fsChangeHandler);\n if (this.fsEscHandler) window.removeEventListener('keydown', this.fsEscHandler);\n this.controller.destroy();\n this.projectionEl = null;\n this.root?.remove();\n this.root = null;\n if (this.modalScrim) {\n this.modalScrim.remove();\n this.modalScrim = null;\n (this.prevFocus as HTMLElement | null)?.focus?.();\n }\n }\n}\n","/**\n * Host-side helper for embedding the SeatLayer picker as an iframe.\n *\n * The picker (the /e/:key page, mounted `position:fixed; inset:0`) reports its\n * desired height and fullscreen intent to whatever page frames it, using the\n * picker wire contract:\n *\n * • `{ type: 'seatlayer:height', px:number }` — grow the iframe to `px`.\n * • `{ type: 'seatlayer:fullscreen', on:boolean }` — pin/unpin over the host.\n *\n * A framed picker cannot escape its own iframe with CSS, so it delegates both\n * concerns to the host. `attachPickerFrame` wires those two behaviours onto a\n * picker iframe and returns a detach function that tears everything back down.\n */\nexport interface AttachPickerFrameOptions {\n /**\n * Origin to accept messages from. Defaults to the origin parsed from\n * `iframe.src`. Messages from any other origin (or any other window) are\n * ignored — the picker posts with `targetOrigin:'*'`, so the host is the side\n * that must verify `event.origin`.\n */\n origin?: string;\n}\n\n/**\n * Attach the picker resize + fullscreen protocol to a picker iframe.\n *\n * ```ts\n * const iframe = document.querySelector('iframe#seatlayer')!;\n * const detach = attachPickerFrame(iframe);\n * // …later, when removing the embed:\n * detach();\n * ```\n *\n * @param iframe The `<iframe>` element pointing at a SeatLayer picker embed.\n * @param opts Optional `{ origin }` override for the accepted message origin.\n * @returns A detach function: removes the listener and restores any pinned state.\n */\nexport function attachPickerFrame(\n iframe: HTMLIFrameElement,\n opts: AttachPickerFrameOptions = {},\n): () => void {\n let expectedOrigin = opts.origin ?? '';\n if (!expectedOrigin) {\n try {\n expectedOrigin = new URL(iframe.src, window.location.href).origin;\n } catch {\n expectedOrigin = '';\n }\n }\n\n let pinned = false;\n let frameStyleBeforeFs: string | null = null;\n let docOverflowBeforeFs: string | null = null;\n let bodyOverflowBeforeFs: string | null = null;\n let lastAutoHeight = '';\n let keyHandler: ((event: KeyboardEvent) => void) | null = null;\n\n const pin = (): void => {\n if (pinned) return;\n pinned = true;\n frameStyleBeforeFs = iframe.getAttribute('style');\n Object.assign(iframe.style, {\n position: 'fixed',\n inset: '0',\n width: '100vw',\n height: '100vh',\n margin: '0',\n border: '0',\n zIndex: '2147483000',\n background: '#101625',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const docEl = document.documentElement;\n docOverflowBeforeFs = docEl.style.overflow;\n docEl.style.overflow = 'hidden';\n if (document.body) {\n bodyOverflowBeforeFs = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n keyHandler = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') unpin();\n };\n window.addEventListener('keydown', keyHandler);\n };\n\n const unpin = (): void => {\n if (!pinned) return;\n pinned = false;\n if (frameStyleBeforeFs === null) iframe.removeAttribute('style');\n else iframe.setAttribute('style', frameStyleBeforeFs);\n frameStyleBeforeFs = null;\n // Re-apply any height reported while we were pinned.\n if (lastAutoHeight) iframe.style.height = lastAutoHeight;\n\n if (docOverflowBeforeFs !== null) {\n document.documentElement.style.overflow = docOverflowBeforeFs;\n docOverflowBeforeFs = null;\n }\n if (bodyOverflowBeforeFs !== null && document.body) {\n document.body.style.overflow = bodyOverflowBeforeFs;\n bodyOverflowBeforeFs = null;\n }\n if (keyHandler) {\n window.removeEventListener('keydown', keyHandler);\n keyHandler = null;\n }\n };\n\n const onMessage = (event: MessageEvent<unknown>): void => {\n if (event.source !== iframe.contentWindow) return;\n if (expectedOrigin && event.origin !== expectedOrigin) return;\n if (!event.data || typeof event.data !== 'object') return;\n const data = event.data as Record<string, unknown>;\n\n if (data.type === 'seatlayer:height') {\n if (typeof data.px === 'number' && Number.isFinite(data.px) && data.px > 0) {\n lastAutoHeight = `${Math.round(data.px)}px`;\n // While pinned the iframe fills the viewport; the height is re-applied on unpin.\n if (!pinned) iframe.style.height = lastAutoHeight;\n }\n return;\n }\n if (data.type === 'seatlayer:fullscreen') {\n if (data.on === true) pin();\n else if (data.on === false) unpin();\n }\n };\n\n window.addEventListener('message', onMessage);\n\n return (): void => {\n window.removeEventListener('message', onMessage);\n unpin();\n };\n}\n","/**\n * SeatManager — the organizer manage surface, packaged for the SDK.\n *\n * Productizes the SeatLayer dashboard's ManageEventPage into a framework-\n * agnostic class (mirrors how SeatPicker productized the buyer flow). It mounts\n * the shared engine in `manageMode`, subscribes to the event's realtime channel\n * and drives three control-room tools on one persistent canvas:\n *\n * - **view** — a live board: realtime seat repaint (flash on hold/book),\n * live KPI tallies + gross revenue, and a streaming activity\n * feed derived from the delta stream + audit log. Read-only.\n * - **inspect** — select one seat to read its live inventory context.\n * - **block** — bulk-first block/unblock: marquee-drag, ⌘A select-all,\n * whole-category / whole-section select, single-seat fallback →\n * one batched block/unblock (optimistic, reconciled by the WS),\n * and timed auto-release.\n *\n * Auth: reads (chart/objects/WS) are public; writes/reports carry a Bearer\n * event-scoped manage token (`mse_…`) or a tenant secret key (`sk_…`) via\n * {@link ManageApi}. Box office + Sections + full Reports UI are M2/M3.\n */\nimport {\n SeatmapRenderer,\n expandChart,\n computeSections,\n gaAreasOf,\n gaUnitLabels,\n UNGROUPED_ID,\n type AvailabilityRule,\n type ChartDoc,\n type ChartTheme,\n type ExpandedSeat,\n type SeatStatus,\n type SectionNode,\n} from '@seatlayer/core';\nimport {\n CHANNELS_CSS, ChannelsMode, type ChannelsCapabilities, type ChannelsRowView,\n} from './channelsMode';\nimport type { ChannelSeatStatus } from './channelPlan';\nimport {\n ManageApi,\n ManageApiError,\n type ControlRoomActivityEntry,\n type ControlRoomSnapshot,\n type LogEntry,\n type ReportResult,\n} from './manageApi';\n\nexport type SeatManagerMode = 'view' | 'inspect' | 'block' | 'sections' | 'channels';\n\n/**\n * Capabilities the cockpit's token was minted with. Channels mode is gated on\n * these and fails CLOSED: no `event:channels:view` ⇒ no Channels pill at all;\n * view without `event:channels:manage` ⇒ read-only inspection with every\n * mutation control absent, not merely disabled.\n */\nexport type SeatManagerCapability =\n | 'event:view' | 'event:block' | 'event:cancel' | 'event:reports'\n | 'event:channels:view' | 'event:channels:manage';\n\n/** The select-state of a Sections-mode availability row. An absent rule is\n * `open` (on sale); otherwise the rule's own mode. */\nexport type AvailabilityMode = 'open' | 'closed' | 'hidden' | 'timed' | 'threshold';\n\n/** One row of the Sections rail — a zone header or a single section. */\ninterface SectionRow {\n kind: 'zone' | 'section';\n id: string;\n label: string;\n seatCount: number;\n /** Seat labels the id governs (sent as the rule's `labels`). */\n seatLabels: string[];\n rule: AvailabilityRule | null;\n /** Effective-hidden right now (manual hide, or a timed/threshold window not yet due). */\n hidden: boolean;\n /** Effective-closed right now — visible to buyers but off sale. */\n closed: boolean;\n /** A section whose parent zone carries a rule — its own control is a muted \"Follows zone\". */\n followsZone: boolean;\n}\n\n/** Map an availability rule to its Sections-rail select value (null rule = on sale). */\nexport function availabilityModeOf(rule: AvailabilityRule | null | undefined): AvailabilityMode {\n return rule ? rule.mode : 'open';\n}\n\n/**\n * Build the rule a chosen select mode implies for a set of seat labels, reusing\n * an existing rule's tuning where it carries over (a timed reveal time, a\n * threshold percent). `open` clears the rule (returns null → id dropped from the\n * map). Wire-identical to the EventDO's accepted rule shapes.\n */\nexport function availabilityRuleForMode(\n mode: AvailabilityMode,\n seatLabels: string[],\n prev?: AvailabilityRule | null,\n): AvailabilityRule | null {\n switch (mode) {\n case 'open':\n return null;\n case 'hidden':\n return { mode: 'hidden', labels: seatLabels };\n case 'closed':\n return { mode: 'closed', labels: seatLabels };\n case 'timed':\n return { mode: 'timed', revealAt: prev?.revealAt ?? Date.now() + 3_600_000, labels: seatLabels };\n case 'threshold':\n return { mode: 'threshold', thresholdPct: prev?.thresholdPct ?? 80, labels: seatLabels };\n }\n}\n\n/** epoch ms → a `datetime-local` input value (local time, minute precision). */\nfunction toLocalInput(ms: number): string {\n const d = new Date(ms - new Date().getTimezoneOffset() * 60_000);\n return d.toISOString().slice(0, 16);\n}\n\n/** DO seat status — 'blocked' has no engine analogue (→ 'not_for_sale'). */\ntype DoStatus = 'free' | 'held' | 'booked' | 'blocked';\n\n/** Live KPI snapshot pushed to `onTallies` on every state change. */\nexport interface SeatManagerTallies {\n free: number;\n held: number;\n booked: number;\n blocked: number;\n /** Total seats on the chart. */\n total: number;\n /** booked / total, 0–100. */\n capacityPct: number;\n /** booked / (total − blocked), 0–100 — sell-through of sellable inventory. */\n sellThroughPct: number;\n /** Exact Σ booked unit_price snapshots from the authenticated report. */\n grossRevenue: number;\n /** Revenue is never reconstructed from chart list price. */\n revenueStatus: 'loading' | 'current' | 'stale';\n /** ISO-4217 currency for grossRevenue. */\n currency: string;\n}\n\n/** One streamed activity line for the live feed. */\nexport interface SeatManagerActivity {\n id: string;\n at: number;\n label: string;\n /** Full labels affected by this one backend/realtime operation. */\n labels: string[];\n count: number;\n /** Human verb: held / booked / released / blocked / unblocked. */\n verb: string;\n status: DoStatus;\n /** Spatial context for grouped activity when the chart defines sections. */\n sectionIds?: string[];\n sectionLabels?: string[];\n}\n\n/** Fired after a successful organizer action, for host toasts/telemetry. */\nexport interface SeatManagerActionResult {\n action: 'block' | 'unblock' | 'unblockAll' | 'cancelBooking' | 'setHoldTtl';\n labels: string[];\n count: number;\n}\n\nexport interface SeatManagerOptions {\n /** CSS selector or element to mount into. */\n container: string | HTMLElement;\n /** API origin. Defaults to https://api.seatlayer.io. */\n apiBase?: string;\n /** Event key (e.g. `ev_xxx` / `west-end-p3`). */\n eventKey: string;\n /** Bearer manage token — event-scoped `mse_…` or a tenant secret `sk_…`. */\n token: string;\n /** Absolute token expiry (epoch ms). Enables proactive in-place rotation. */\n tokenExpiresAt?: number;\n /** Initial mode. Default 'view'. */\n mode?: SeatManagerMode;\n /**\n * The capability set this token was minted with. Supply it whenever you mint\n * an `mse_…` grant — it is the only way the widget can know a delegated token\n * carries `event:channels:manage`, and without it Channels mode stays\n * read-only (fail-closed). A tenant secret (`sk_…`) is org authority and is\n * never narrowed server-side, so it is treated as fully capable.\n */\n capabilities?: SeatManagerCapability[] | string[];\n /** ISO-4217 fallback currency for revenue (chart/event currency wins). */\n currency?: string;\n /** Chart theme override for the chrome (rails/bar). Chart colors come from the doc. */\n theme?: ChartTheme;\n /**\n * Keep the canvas painting even when the tab is hidden/backgrounded (a war-room\n * board on a second monitor). Calls `forceDraw()` after each delta so Chrome's\n * rAF throttling on occluded tabs never leaves the board stale. Default true.\n */\n keepLiveWhileHidden?: boolean;\n /**\n * Opt in to camera-following for new buyer holds/bookings. Off by default so\n * a live event never steals an operator's current map context.\n */\n followLive?: boolean;\n /** Chart + first snapshot are loaded and the board is live. */\n onReady?: () => void;\n /** Live KPI tallies changed. */\n onTallies?: (tallies: SeatManagerTallies) => void;\n /** A grouped live/audit activity item arrived. */\n onActivity?: (activity: SeatManagerActivity) => void;\n /** Exact private control-room projection changed. */\n onControlRoom?: (snapshot: ControlRoomSnapshot) => void;\n /** Called before token expiry. The manager swaps the result without remounting. */\n onTokenRefresh?: () => Promise<{ token: string; expiresAt: number }>;\n /** Tool/mode changed from inside the shared cockpit. */\n onModeChange?: (mode: SeatManagerMode) => void;\n /** Follow-live preference changed from inside the cockpit. */\n onFollowLiveChange?: (enabled: boolean) => void;\n /** Block-mode selection changed (marquee / ⌘A / category / section / tap). */\n onSelectionChange?: (seats: ExpandedSeat[]) => void;\n /** A block/unblock/cancel action completed successfully. */\n onActionComplete?: (result: SeatManagerActionResult) => void;\n /**\n * The realtime link connected or dropped, with the moment the numbers on\n * screen were last known good.\n *\n * A host embedding this cockpit renders its own chrome around it, and until\n * now had no way to know the board had gone stale: the manager tracked the\n * drop internally (its own LIVE/RECONNECTING pill) and told nobody. A host\n * that polls on a timer and pauses while the tab is hidden therefore showed\n * arbitrarily old numbers that looked exactly like fresh ones.\n */\n onConnectionChange?: (state: SeatManagerConnection) => void;\n onError?: (err: unknown) => void;\n}\n\n/** Realtime link state, as reported to the embedding host. */\nexport interface SeatManagerConnection {\n /** `live` while the socket is open; `reconnecting` from drop until reopen. */\n status: 'live' | 'reconnecting';\n /**\n * `Date.now()` of the last snapshot or delta accepted from the server, or\n * null before the first one. This is the honest \"as of\" for whatever the host\n * is displaying — NOT the time the connection dropped, which is later and\n * would overstate freshness.\n */\n lastMessageAt: number | null;\n}\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container === 'string') {\n const el = document.querySelector(container);\n if (!el) throw new Error(`seatmanager: container \"${container}\" not found`);\n return el as HTMLElement;\n }\n if (!(container instanceof HTMLElement)) {\n throw new Error('seatmanager: container must be a CSS selector or an HTMLElement');\n }\n return container;\n}\n\n/** 'blocked' → renderer 'not_for_sale'; the rest pass through. */\nfunction toRenderStatus(s: DoStatus): SeatStatus {\n return s === 'blocked' ? 'not_for_sale' : s;\n}\n\nconst DEFAULT_API_BASE = 'https://api.seatlayer.io';\nconst STYLE_ID = 'seatlayer-manager-style';\nconst FEED_CAP = 80;\nconst MAX_LIVE_SEAT_PULSES = 16;\nconst MAX_LIVE_SECTION_PULSES = 4;\n\nconst LEGEND: { key: 'free' | 'held' | 'booked' | 'blocked'; label: string; color: string }[] = [\n { key: 'free', label: 'Free', color: '#6e7bff' },\n { key: 'held', label: 'Held', color: '#f4b740' },\n { key: 'booked', label: 'Booked', color: '#22a06b' },\n { key: 'blocked', label: 'Blocked', color: '#8b94ac' },\n];\n\n/** Exported so the motion contract can be asserted without a real browser —\n * see `SeatManagerMotion.test.ts`. Not part of the public package surface.\n * `@sl-css` opts it into build-time minification (cdn/minifyCssLiterals.ts). */\nexport const MANAGER_CSS = /* @sl-css */ `\n/* The floor was 480px, which trapped the cockpit in any host shorter than that:\n every ancestor here is overflow:hidden, so the bottom of the rail (Create\n channel, Show archived) was rendered but clipped away by the host and could\n not be reached by scrolling anything. 320px still keeps an unsized host from\n collapsing to the top bar, and the rail scrolls to its full content below. */\n.slm{position:relative;display:flex;flex-direction:column;width:100%;height:100%;min-height:320px;overflow:hidden;\n background:var(--slm-bg);color:var(--slm-text);font-family:var(--slm-font);border-radius:var(--slm-radius);\n /* Motion tokens (motion-system §2), declared by the cockpit ROOT rather than\n borrowed from CHANNELS_CSS. The base cockpit animates whether or not\n Channels mode is in use, so owning its own tokens is what stops a token\n edit from silently changing only half the surface. Channels mode declares\n the identical values so an embed of it stays self-contained. */\n --slm-mo-instant:80ms;--slm-mo-quick:140ms;--slm-mo-base:200ms;--slm-mo-slow:320ms;--slm-mo-ambient:2000ms;\n --slm-mo-out:cubic-bezier(.2,.8,.2,1);--slm-mo-in-out:cubic-bezier(.4,0,.2,1);--slm-mo-exit:cubic-bezier(.4,0,1,1);\n --slm-mo-spring:cubic-bezier(.34,1.3,.64,1)}\n.slm *{box-sizing:border-box;margin:0;padding:0}\n.slm button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}\n.slm input{font:inherit}\n\n/* top bar */\n.slm-bar{display:grid;grid-template-columns:auto auto minmax(0,1fr);align-items:center;column-gap:14px;row-gap:10px;\n padding:10px 16px;border-bottom:1px solid var(--slm-line);flex:none}\n.slm-modes{display:inline-flex;background:var(--slm-surface);border:1px solid var(--slm-line);border-radius:999px;padding:3px}\n.slm-mode{padding:6px 16px;border-radius:999px;font-weight:700;font-size:13px;color:var(--slm-muted)}\n.slm-mode.on{background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-live{display:inline-flex;align-items:center;gap:6px;font-size:11px;letter-spacing:.12em;font-weight:800;color:var(--slm-muted)}\n.slm-live-dot{width:8px;height:8px;border-radius:50%;background:#8b94ac}\n.slm.live .slm-live-dot{background:#22a06b;box-shadow:0 0 0 0 rgba(34,160,107,.55);\n animation:slm-pulse var(--slm-mo-ambient) infinite}\n@keyframes slm-pulse{0%{box-shadow:0 0 0 0 rgba(34,160,107,.5)}70%{box-shadow:0 0 0 7px rgba(34,160,107,0)}100%{box-shadow:0 0 0 0 rgba(34,160,107,0)}}\n.slm-kpis{grid-column:1/-1;display:grid;grid-template-columns:repeat(8,minmax(0,1fr));width:100%;padding-top:10px;\n border-top:1px solid var(--slm-line)}\n.slm-kpi{position:relative;display:flex;min-width:0;flex-direction:column;align-items:center;padding:0 5px;line-height:1.15;text-align:center}\n.slm-kpi b{display:flex;min-width:0;align-items:baseline;justify-content:center;font-size:17px;font-weight:800;\n font-variant-numeric:tabular-nums;white-space:nowrap}\n.slm-kpi span{font-size:9.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--slm-muted);font-weight:700}\n.slm-kpi .dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:5px;vertical-align:baseline}\n/* The one playful moment this surface is allowed (§2 --mo-spring). It ran at\n .58s against a 200ms catalog, which read as a different design language from\n the dashboard tile it mirrors; Channels mode's own count bump is the same\n pattern and must stay in step with it. */\n.slm-kpi.changed b{animation:slm-kpi-bump var(--slm-mo-base) var(--slm-mo-spring)}\n.slm-kpidelta{position:absolute;right:4px;top:-12px;padding:2px 5px;border-radius:999px;background:rgba(34,160,107,.17);\n color:#5bd39b!important;font-size:9px!important;letter-spacing:0!important;text-transform:none!important;white-space:nowrap;\n animation:slm-kpi-delta 1.45s ease-out both;pointer-events:none}\n.slm-kpidelta.down{background:rgba(244,183,64,.14);color:#f7ca6b!important}\n@keyframes slm-kpi-bump{0%,100%{transform:none}35%{transform:translateY(-2px) scale(1.08);text-shadow:0 0 18px rgba(255,255,255,.24)}}\n@keyframes slm-kpi-delta{0%{opacity:0;transform:translateY(5px)}18%,72%{opacity:1;transform:none}100%{opacity:0;transform:translateY(-5px)}}\n.slm-barbtn{padding:7px 13px;border-radius:9px;border:1px solid var(--slm-line);color:var(--slm-text);font-weight:700;font-size:12.5px}\n.slm-barbtn:hover{border-color:var(--slm-muted)}\n.slm-barbtn.follow.on{background:rgba(34,160,107,.13);border-color:#22a06b;color:#5bd39b}\n\n/* body */\n.slm-body{display:flex;flex:1;min-height:0}\n.slm-map{position:relative;flex:1;min-width:0}\n.slm-map-host{position:absolute;inset:0}\n.slm-hud{position:absolute;left:12px;bottom:12px;display:flex;gap:8px}\n.slm-hud-chip{padding:6px 11px;border-radius:999px;font-size:12px;font-weight:700;background:var(--slm-surface);\n border:1px solid var(--slm-line);color:var(--slm-text)}\n.slm-zoomhint{position:absolute;left:50%;top:14px;transform:translateX(-50%);padding:6px 13px;border-radius:999px;\n background:rgba(0,0,0,.55);color:#fff;font-size:12px;font-weight:700;pointer-events:none;opacity:0;\n transition:opacity var(--slm-mo-base) var(--slm-mo-out)}\n.slm-zoomhint.on{opacity:1}\n.slm-liveevent{position:absolute;left:50%;top:14px;z-index:4;display:flex;align-items:center;gap:8px;max-width:min(560px,calc(100% - 32px));\n padding:8px 12px;border:1px solid var(--slm-line);border-radius:999px;background:color-mix(in srgb,var(--slm-surface) 92%,transparent);\n box-shadow:0 10px 34px rgba(0,0,0,.32);opacity:0;transform:translate(-50%,-8px);pointer-events:none;\n transition:opacity var(--slm-mo-quick) var(--slm-mo-out),transform var(--slm-mo-base) var(--slm-mo-out);\n backdrop-filter:blur(10px)}\n.slm-liveevent.on{opacity:1;transform:translate(-50%,0)}\n.slm.block-mode .slm-liveevent{top:52px}\n.slm-liveeventdot{width:8px;height:8px;border-radius:50%;flex:none}.slm-liveeventcopy{min-width:0;overflow:hidden;text-overflow:ellipsis;\n white-space:nowrap;font-size:12px;font-weight:800}.slm-liveeventhint{color:var(--slm-muted);font-size:10px;white-space:nowrap}\n.slm-rail{width:320px;flex:none;border-left:1px solid var(--slm-line);display:flex;flex-direction:column;min-height:0}\n.slm-railscroll{flex:1;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:16px}\n.slm-eyebrow{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--slm-muted);font-weight:800;margin-bottom:6px}\n.slm-hint{font-size:12.5px;color:var(--slm-muted);line-height:1.5;margin-bottom:14px}\n\n/* legend rows */\n.slm-legend{display:flex;flex-direction:column;gap:2px;margin-bottom:16px}\n.slm-legrow{display:flex;align-items:center;gap:9px;padding:7px 2px;border-bottom:1px solid var(--slm-line)}\n.slm-legdot{width:10px;height:10px;border-radius:50%;flex:none}\n.slm-leglabel{flex:1;font-size:13px;font-weight:600}\n.slm-legcount{font-size:13px;font-weight:800;font-variant-numeric:tabular-nums}\n\n/* activity feed */\n.slm-feed{display:flex;flex-direction:column;gap:0}\n.slm-feedrow{display:flex!important;width:100%;align-items:center;gap:9px;padding:8px 2px!important;border-bottom:1px solid var(--slm-line)!important;\n border-radius:6px;font-size:12.5px;text-align:left!important;\n animation:slm-in var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-feedrow:hover{background:rgba(255,255,255,.035)!important}\n@keyframes slm-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}\n.slm-feeddot{width:8px;height:8px;border-radius:50%;flex:none}\n.slm-feedtext{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.slm-feedtext b{font-weight:800}\n.slm-feedsection{display:block;overflow:hidden;text-overflow:ellipsis;color:var(--slm-muted);font-size:10px;font-weight:750}\n.slm-feedmeta{display:flex;flex:none;flex-direction:column;align-items:flex-end;gap:1px}.slm-feedtime{font-size:10px;color:var(--slm-muted);font-variant-numeric:tabular-nums}\n.slm-feedlocate{font-size:9.5px;color:var(--slm-accent);font-weight:800}\n.slm-empty{font-size:12.5px;color:var(--slm-muted);padding:12px 0}\n\n/* block toolbar */\n.slm-selbar{display:flex;align-items:baseline;gap:8px;margin-bottom:10px}\n.slm-selnum{font-size:26px;font-weight:800;font-variant-numeric:tabular-nums}\n.slm-sellabel{font-size:12px;color:var(--slm-muted);font-weight:600}\n.slm-row{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}\n.slm-btn{flex:1;min-width:120px;padding:10px 14px;border-radius:10px;background:var(--slm-accent);color:var(--slm-accent-ink);\n font-weight:800;font-size:13px;text-align:center}\n.slm-btn:disabled{opacity:.45;cursor:not-allowed}\n.slm-btn.ghost{background:var(--slm-surface);border:1px solid var(--slm-line);color:var(--slm-text)}\n.slm-btn.danger{background:#c0392b;color:#fff}\n.slm-chiprow{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px}\n.slm-chip{padding:6px 11px;border-radius:999px;border:1px solid var(--slm-line);background:var(--slm-surface);\n font-size:12px;font-weight:700;color:var(--slm-text);display:inline-flex;align-items:center;gap:6px}\n.slm-chip:hover{border-color:var(--slm-muted)}\n.slm-chip .dot{width:8px;height:8px;border-radius:50%}\n.slm-chip .slm-chipcount{min-width:18px;padding:1px 5px;border-radius:999px;background:rgba(255,255,255,.07);\n color:var(--slm-muted);font-size:10px;font-variant-numeric:tabular-nums;text-align:center}\n.slm-chip .slm-chipcheck{display:none;font-size:11px;line-height:1}\n.slm-chip.on{border-color:var(--slm-accent);background:color-mix(in srgb,var(--slm-accent) 20%,var(--slm-surface));\n box-shadow:0 0 0 1px color-mix(in srgb,var(--slm-accent) 45%,transparent)}\n.slm-chip.on .slm-chipcount{background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-chip.on .slm-chipcheck{display:inline}\n.slm-chip.partial{border-style:dashed;border-color:var(--slm-accent)}\n.slm-chip:disabled{opacity:.42;cursor:not-allowed}\n.slm-selecthelp{margin:-1px 0 9px;color:var(--slm-muted);font-size:11px;line-height:1.4}\n.slm-field{margin:14px 0}\n.slm-field label{display:block;font-size:11px;font-weight:700;color:var(--slm-muted);margin-bottom:5px}\n.slm-input,.slm-select{width:100%;padding:8px 10px;border-radius:9px;border:1px solid var(--slm-line);\n background:var(--slm-surface);color:var(--slm-text)}\n.slm-note{font-size:11.5px;color:var(--slm-muted);margin-top:5px}\n.slm-blocked{margin-top:17px;padding-top:15px;border-top:1px solid var(--slm-line)}\n.slm-blockedhead{display:flex;align-items:baseline;justify-content:space-between;gap:10px;margin-bottom:8px}\n.slm-blockedhead .slm-eyebrow{margin-bottom:0}.slm-blockedtotal{font-size:11px;color:var(--slm-muted)}\n.slm-blockedtotal b{color:var(--slm-text);font-variant-numeric:tabular-nums}\n.slm-blockedtools{display:grid;grid-template-columns:minmax(0,1fr);gap:7px}\n.slm-blockedsummary{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:9px 0 6px;\n color:var(--slm-muted);font-size:10.5px}\n.slm-linkbtn{font-size:11px!important;font-weight:800!important;color:var(--slm-accent)!important;text-align:right}\n.slm-linkbtn:disabled{opacity:.45;cursor:not-allowed}\n.slm-blockedlist{max-height:246px;overflow:auto;overscroll-behavior:contain;border:1px solid var(--slm-line);\n border-radius:10px;background:var(--slm-surface)}\n.slm-blockeditem{display:grid!important;grid-template-columns:18px minmax(0,1fr);width:100%;gap:8px;padding:8px 9px!important;\n border-bottom:1px solid var(--slm-line)!important;text-align:left!important}\n.slm-blockeditem:last-child{border-bottom:0!important}.slm-blockeditem:hover{background:rgba(255,255,255,.035)!important}\n.slm-blockeditem.on{background:color-mix(in srgb,var(--slm-accent) 13%,var(--slm-surface))!important}\n.slm-blockedcheck{display:flex;align-items:center;justify-content:center;width:16px;height:16px;margin-top:1px;border-radius:4px;\n border:1px solid var(--slm-muted);color:transparent;font-size:10px;font-weight:900}\n.slm-blockeditem.on .slm-blockedcheck{border-color:var(--slm-accent);background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-blockedcopy{min-width:0}.slm-blockedlabel{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;\n font-size:12px;font-weight:800}.slm-blockedmeta{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;\n margin-top:2px;color:var(--slm-muted);font-size:10px}\n.slm-blockedmore{width:100%;padding:9px!important;color:var(--slm-accent)!important;font-size:11px!important;font-weight:800!important}\n.slm-blockedempty{padding:12px;color:var(--slm-muted);font-size:11.5px;line-height:1.45}\n.slm-allnote{margin-top:-4px;margin-bottom:10px}\n\n/* toast */\n.slm-toast{position:absolute;left:50%;bottom:16px;transform:translateX(-50%);padding:10px 16px;border-radius:10px;\n font-size:13px;font-weight:700;box-shadow:0 8px 24px rgba(0,0,0,.28);opacity:0;pointer-events:none;\n transition:opacity var(--slm-mo-base) var(--slm-mo-out);\n background:var(--slm-surface);color:var(--slm-text);border:1px solid var(--slm-line);z-index:5}\n.slm-toast.on{opacity:1}\n.slm-toast.err{background:#c0392b;color:#fff;border-color:#c0392b}\n.slm-toast.ok{background:#1f7a4d;color:#fff;border-color:#1f7a4d}\n\n/* control-room actions + insights */\n.slm-bar-actions{display:flex;align-items:center;justify-self:end;gap:7px}\n.slm-barbtn.on{background:rgba(244,183,64,.13);border-color:#f4b740;color:#f7ca6b}\n.slm-sectionlist{display:flex;flex-direction:column;gap:8px;margin-top:4px}\n.slm-sectionlist + .slm-eyebrow{margin-top:18px}\n.slm-sectionrow{width:100%;padding:10px!important;border:1px solid var(--slm-line)!important;border-radius:10px;\n background:var(--slm-surface)!important;text-align:left!important;\n transition:border-color var(--slm-mo-quick) var(--slm-mo-out),transform var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-sectionrow:hover{border-color:var(--slm-muted)!important;transform:translateY(-1px)}\n.slm-sectiontop,.slm-sectionmeta{display:flex;align-items:center;justify-content:space-between;gap:10px}\n.slm-sectiontop{font-size:12.5px;font-weight:800}.slm-sectionmeta{margin-top:5px;color:var(--slm-muted);font-size:11px}\n.slm-sectionmeta>span:first-child{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.slm-trend{font-size:10px;text-transform:uppercase;letter-spacing:.08em}.slm-trend.rising{color:#22a06b}.slm-trend.cooling{color:#f4b740}\n.slm-sectionlocate{color:var(--slm-accent);font-size:9.5px;font-weight:800}\n.slm-health{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px}\n.slm-healthitem{padding:10px;border:1px solid var(--slm-line);border-radius:10px;background:var(--slm-surface)}\n.slm-healthitem b{display:block;font-size:17px;font-variant-numeric:tabular-nums}.slm-healthitem span{display:block;margin-top:2px;color:var(--slm-muted);font-size:10px;text-transform:uppercase;letter-spacing:.08em}\n.slm-sectionhead{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;margin-top:18px}\n.slm-windows{display:flex;gap:3px;padding:2px;border:1px solid var(--slm-line);border-radius:8px;background:var(--slm-surface)}\n.slm-window{padding:4px 6px;border-radius:6px;font-size:10px;font-weight:800;color:var(--slm-muted)}.slm-window.on{background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-momentumhelp{margin:10px 0 14px;padding:10px;border:1px solid rgba(244,183,64,.28);border-radius:10px;background:rgba(244,183,64,.07)}\n.slm-momentumhelp[hidden]{display:none}.slm-momentumscale{display:flex;align-items:center;gap:7px;color:var(--slm-muted);font-size:10px;font-weight:750;text-transform:uppercase;letter-spacing:.07em}\n.slm-momentumgradient{height:6px;min-width:64px;flex:1;border-radius:999px;background:linear-gradient(90deg,#f4b740,#ef4444)}\n.slm-momentumcopy{margin-top:7px;color:var(--slm-muted);font-size:11px;line-height:1.45}\n/* sections: availability windows */\n.slm-availlist{display:flex;flex-direction:column;gap:8px;margin:2px 0 12px}\n.slm-availrow{padding:10px;border:1px solid var(--slm-line);border-radius:10px;background:var(--slm-surface);\n transition:border-color var(--slm-mo-quick) var(--slm-mo-out),opacity var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-availrow.zone{background:color-mix(in srgb,var(--slm-surface) 82%,#000)}\n.slm-availrow.hidden{opacity:.62}.slm-availrow.closed{opacity:.82}\n.slm-availhead{display:flex;align-items:center;gap:8px}\n.slm-availlabel{display:flex;align-items:center;gap:5px;flex:1;min-width:0;font-size:12.5px;font-weight:800;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.slm-availcaret{flex:none;color:var(--slm-muted);font-size:10px}\n.slm-availcount{flex:none;font-size:11px;font-weight:700;color:var(--slm-muted);font-variant-numeric:tabular-nums}\n.slm-availbadge{flex:none;font-size:9px;font-weight:800;letter-spacing:.04em;text-transform:uppercase;padding:2px 6px;border-radius:999px}\n.slm-availbadge.hidden{background:rgba(139,148,172,.18);color:#c2c9d8}\n.slm-availbadge.closed{background:rgba(244,183,64,.16);color:#f7ca6b}\n.slm-availselwrap{position:relative;flex:none;display:inline-flex}\n.slm-availmode{width:auto;max-width:190px;padding:6px 8px;font-size:11.5px;font-weight:700;cursor:pointer}\n.slm-availmode.on{border-color:var(--slm-accent);color:var(--slm-text)}\n.slm-availmode:disabled{opacity:.55;cursor:progress}\n.slm-availfollows{flex:none;padding:5px 10px;border:1px solid var(--slm-line);border-radius:7px;background:var(--slm-surface);color:var(--slm-muted);font-size:11px;font-weight:600;white-space:nowrap}\n.slm-availdetail{display:flex;align-items:center;gap:8px;margin-top:9px}\n.slm-availdetail .slm-input{flex:1}\n.slm-availpct{max-width:74px;flex:none!important}\n.slm-availpctlabel{font-size:11px;color:var(--slm-muted);font-weight:600;white-space:nowrap}\n.slm-availsummary{display:flex;align-items:center;gap:8px;padding:10px 12px;border:1px solid var(--slm-line);border-radius:9px;color:var(--slm-muted);font-size:12.5px}\n.slm-availdot{width:9px;height:9px;border-radius:50%;flex:none;background:#22a06b}.slm-availdot.warn{background:#f4b740}\n.slm-availcallout{display:flex;align-items:flex-start;gap:8px;margin-top:10px;padding:10px 12px;border:1px solid rgba(244,183,64,.45);border-radius:9px;background:rgba(244,183,64,.1)}\n.slm-availstar{flex:none;margin-top:1px;color:#f4b740;font-size:13px;line-height:1}\n.slm-availcallout p{font-size:11.5px;line-height:1.55;color:#f4d58a}.slm-availcallout b{color:#ffe4a3;font-weight:800}\n.slm-inspect-card{padding:16px;border:1px solid var(--slm-line);border-radius:12px;background:var(--slm-surface)}\n.slm-inspect-label{font-size:24px;font-weight:850;letter-spacing:-.02em;line-height:1.1}\n.slm-inspect-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 20px;margin-top:18px}\n.slm-inspect-grid>div{min-width:0}.slm-inspect-grid span{display:block;color:var(--slm-muted);font-size:10px;\n text-transform:uppercase;letter-spacing:.08em}.slm-inspect-grid b{display:block;margin-top:4px;font-size:13px;line-height:1.35;overflow-wrap:anywhere}\n.slm:fullscreen{border-radius:0;min-height:100vh;background:var(--slm-bg)}\n.slm:fullscreen .slm-bar{padding:14px 22px}.slm:fullscreen .slm-kpi b{font-size:21px}.slm:fullscreen .slm-rail{width:360px}\n\n.slm.compact .slm-rail{width:100%;border-left:0;border-top:1px solid var(--slm-line);height:44%}\n.slm.compact .slm-body{flex-direction:column}\n.slm.compact .slm-bar{grid-template-columns:minmax(0,1fr) auto;gap:8px;padding:8px}\n.slm.compact .slm-modes{min-width:0}.slm.compact .slm-mode{padding-inline:11px}\n.slm.compact .slm-live{justify-self:end}.slm.compact .slm-bar-actions{grid-column:1/-1;justify-self:stretch}\n.slm.compact .slm-barbtn{flex:1;padding:6px 9px}.slm.compact .slm-kpis{grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}\n.slm.compact .slm-kpi[data-kpi=\"buyers\"],.slm.compact .slm-kpi[data-kpi=\"active-holds\"],\n.slm.compact .slm-kpi[data-kpi=\"sold-pct\"],.slm.compact .slm-kpi[data-kpi=\"gross-sales\"]{display:none}\n/* Reduced motion, as a BLANKET over the cockpit subtree rather than a list of\n selectors. The list this replaces named four animations and two transitions,\n and had silently fallen behind the stylesheet: the zoom hint, the toast and\n the availability rows all still animated for a user who had asked the OS for\n none. An enumerated list has to be edited every time a rule is added, and\n nothing fails when it isn't — so it drifts. This cannot.\n\n Motion is removed, never the information it carried: Channels mode's own\n block substitutes static outlines for its shake and success states, and it\n stays authoritative for those. No JS here waits on animationend or\n transitionend, so cutting them outright strands no state. */\n@media (prefers-reduced-motion:reduce){\n .slm,.slm *,.slm *::before,.slm *::after{\n animation:none!important;\n transition:none!important;\n scroll-behavior:auto!important}\n}\n${CHANNELS_CSS}`;\n\nfunction injectStyle(): void {\n if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = MANAGER_CSS;\n document.head.appendChild(el);\n}\n\n/** Resolve chrome tokens from a chart theme (dark war-room defaults). */\nfunction themeVars(theme: ChartTheme | undefined): Record<string, string> {\n const t = theme ?? {};\n return {\n '--slm-bg': t.background ?? '#0e1017',\n '--slm-surface': '#181b24',\n '--slm-text': '#eef1f7',\n '--slm-muted': '#8b93a7',\n '--slm-line': 'rgba(255,255,255,.09)',\n '--slm-accent': t.accent ?? '#6e7bff',\n '--slm-accent-ink': t.accentInk ?? '#ffffff',\n '--slm-font': \"-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif\",\n '--slm-radius': '14px',\n };\n}\n\nfunction relTime(at: number, now: number): string {\n const s = Math.max(0, Math.round((now - at) / 1000));\n if (s < 5) return 'just now';\n if (s < 60) return `${s}s ago`;\n const m = Math.round(s / 60);\n if (m < 60) return `${m}m ago`;\n return `${Math.round(m / 60)}h ago`;\n}\n\nfunction fmtMoney(amount: number, currency: string): string {\n try {\n return new Intl.NumberFormat(undefined, { style: 'currency', currency, maximumFractionDigits: 0 }).format(amount);\n } catch {\n return `${currency} ${Math.round(amount).toLocaleString()}`;\n }\n}\n\nfunction esc(value: unknown): string {\n return String(value ?? '')\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\nexport class SeatManager {\n private readonly opts: SeatManagerOptions;\n private readonly api: ManageApi;\n private readonly key: string;\n private readonly keepLive: boolean;\n\n private host: HTMLElement;\n private root!: HTMLDivElement;\n private mapHost!: HTMLDivElement;\n private els: Record<string, HTMLElement> = {};\n\n private renderer: SeatmapRenderer | null = null;\n private doc: ChartDoc | null = null;\n private mode: SeatManagerMode;\n\n // label ⇄ id + status truth (backend speaks labels, engine speaks ids).\n private labelToId = new Map<string, string>();\n private labelToSeat = new Map<string, ExpandedSeat>();\n private allIds: string[] = [];\n /**\n * GA inventory units — real sellable labels the server counts, with NO seat\n * geometry and therefore no renderer binding. They live here rather than in\n * `labelToId`/`allIds` so every paint path keeps addressing paintable nodes\n * only, while the tally denominator finally covers the same universe the\n * numerator does. Without them a GA sale hit `booked` but not `total`:\n * Free under-reported by GA capacity and SOLD% could exceed 100%.\n */\n private gaUnitLabelSet = new Set<string>();\n private status = new Map<string, DoStatus>();\n /** Live non-free counters, moved by each delta rather than re-walked. */\n private counts: Record<Exclude<DoStatus, 'free'>, number> = { held: 0, booked: 0, blocked: 0 };\n /** Bumped whenever the seat model is replaced wholesale (a full snapshot). */\n private modelVersion = 0;\n private currency = 'USD';\n private authoritativeGrossRevenue = 0;\n private revenueStatus: SeatManagerTallies['revenueStatus'] = 'loading';\n private revenueRequest = 0;\n private controlRoomSnapshot: ControlRoomSnapshot | null = null;\n /**\n * The server's own totals, pinned to the client model they were read against.\n * Display = server baseline + (client now − client then), so the authoritative\n * numbers land exactly on arrival and deltas still move them between reads.\n * A wholesale model replacement invalidates the pairing (`model`), and the\n * client tallies — themselves a fresh authenticated read — take over.\n */\n private serverBaseline: {\n model: number;\n server: { free: number; held: number; booked: number; blocked: number };\n client: { free: number; held: number; booked: number; blocked: number };\n } | null = null;\n /** Latest presence frame, held whether or not a snapshot has landed yet. */\n private livePresence: { at: number; value: { shoppingSessions: number; activeHolds: number } } | null = null;\n /** Latest cumulative booked gross pushed on a delta frame. */\n private liveGross: { at: number; value: number } | null = null;\n /** Coalesces a burst of deltas into one KPI/rail repaint. */\n private paintHandle: number | null = null;\n private trendWindowMinutes = 15;\n private heatEnabled = false;\n private followLive: boolean;\n private lastKpiValues = new Map<string, number>();\n private activeKpiDeltas = new Map<string, { text: string; down: boolean }>();\n\n // realtime socket\n private ws: WebSocket | null = null;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private attempt = 0;\n private closed = false;\n /** Mirrors the `live` root class, so the getter never has to read the DOM. */\n private connectionStatus: SeatManagerConnection['status'] = 'reconnecting';\n /** When the server last told us something. Stamped on accepted traffic only —\n * a socket that opens and says nothing has not refreshed anything. */\n private lastMessageAt: number | null = null;\n private ready = false;\n\n private feed: SeatManagerActivity[] = [];\n private feedTimer: ReturnType<typeof setInterval> | null = null;\n private toastTimer: ReturnType<typeof setTimeout> | null = null;\n private liveEventTimer: ReturnType<typeof setTimeout> | null = null;\n private kpiCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n private followLiveTimer: ReturnType<typeof setTimeout> | null = null;\n private followSeatTimer: ReturnType<typeof setTimeout> | null = null;\n private releaseAt: number | null = null;\n private layoutObserver: ResizeObserver | null = null;\n private tokenExpiresAt: number | null = null;\n private tokenRefreshTimer: ReturnType<typeof setTimeout> | null = null;\n private tokenRefreshInFlight = false;\n private sectionByObject = new Map<string, string>();\n private sectionLabelById = new Map<string, string>();\n private sectionsBase: ReturnType<typeof computeSections> | null = null;\n // Sections mode (availability windows): organizer rules + the live effective\n // hidden/closed sets from the snapshot + WS (a timed/threshold rule fires DO-side).\n private availabilityRules: Record<string, AvailabilityRule> = {};\n private effectiveHidden = new Set<string>();\n private effectiveClosed = new Set<string>();\n private availabilitySaving = false;\n private lastSyncedAt: number | null = null;\n private blockedQuery = '';\n private blockedSection = '';\n private blockedResultLimit = 100;\n private unblockAllConfirmTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Sales channels (M6b). The mode object is built only once the token is known\n // to carry `event:channels:view`; until then there is no pill and no rail.\n private channels: ChannelsMode | null = null;\n private channelCaps: ChannelsCapabilities = { view: false, manage: false };\n\n private readonly onFullscreenChange = (): void => {\n this.paintFullscreenButton();\n this.updateContainerLayout();\n this.renderer?.forceDraw();\n };\n\n private readonly onKeyDown = (event: KeyboardEvent): void => {\n if (event.metaKey || event.ctrlKey || event.altKey) return;\n const target = event.target as HTMLElement | null;\n if (target?.matches('input,select,textarea,[contenteditable=\"true\"]')) return;\n const key = event.key.toLowerCase();\n if (key === 'm') this.setMode('view');\n else if (key === 'i') this.setMode('inspect');\n else if (key === 'b') this.setMode('block');\n else if (key === 's') this.setMode('sections');\n else if (key === 'c') { if (!this.channels) return; this.setMode('channels'); }\n else if (key === 'f') this.toggleFullscreen();\n else if (key === 'escape') { if (!this.channels?.handleBack()) return; }\n else return;\n event.preventDefault();\n };\n\n private readonly onRailClick = (event: Event): void => {\n const target = event.target as HTMLElement | null;\n const sectionButton = target?.closest<HTMLElement>('[data-section-focus]');\n if (sectionButton?.dataset.sectionFocus) {\n this.locateSection(sectionButton.dataset.sectionFocus);\n return;\n }\n const feedButton = target?.closest<HTMLElement>('[data-feed-id]');\n if (feedButton?.dataset.feedId) this.locateActivity(feedButton.dataset.feedId);\n };\n\n constructor(options: SeatManagerOptions) {\n this.opts = options;\n this.key = options.eventKey;\n this.mode = options.mode ?? 'view';\n this.keepLive = options.keepLiveWhileHidden ?? true;\n this.followLive = options.followLive ?? false;\n this.currency = options.currency ?? 'USD';\n this.tokenExpiresAt = options.tokenExpiresAt ?? null;\n this.api = new ManageApi(options.apiBase ?? DEFAULT_API_BASE, options.token);\n this.host = resolveContainer(options.container);\n }\n\n /** Build the DOM, load the chart, subscribe to realtime, mount the board. */\n async render(): Promise<this> {\n injectStyle();\n this.buildChrome();\n try {\n const res = await this.api.chart(this.key);\n this.doc = res.doc;\n this.currency = res.event.currency ?? this.opts.currency ?? this.currency;\n this.buildUnitUniverse(res.doc);\n this.buildRenderer();\n this.buildSectionOptions();\n const [, controlRoom] = await Promise.all([\n this.resnapshot(),\n this.refreshControlRoom().catch((err) => this.opts.onError?.(err)),\n this.refreshAvailability(),\n ]);\n // Restore recent activity through the view-safe control-room projection.\n // Older workers lack this field, so privileged/secret-key hosts retain the\n // legacy best-effort audit-log fallback during rolling upgrades.\n if (controlRoom?.activity) this.seedFeed(controlRoom.activity);\n else this.api.log(this.key, { limit: 24 }).then((page) => this.seedFeed(page.entries)).catch(() => {});\n void this.connect();\n this.startFeedClock();\n this.ready = true;\n // Resolve channel authority BEFORE the first rail paint so the pill either\n // exists from the start or never appears — a pill that pops in later reads\n // as a permission change that did not happen.\n await this.resolveChannelCapabilities();\n this.setMode(this.mode); // paint the right rail\n this.scheduleTokenRefresh();\n this.opts.onReady?.();\n } catch (err) {\n this.fail(err);\n }\n return this;\n }\n\n // ---- public API -----------------------------------------------------------\n\n setMode(mode: SeatManagerMode): void {\n // Fail closed: a host asking for a mode this token cannot use gets the\n // read-only board, never a half-rendered management surface.\n if (mode === 'channels' && !this.channels) mode = 'view';\n const changed = mode !== this.mode;\n const wasChannels = this.mode === 'channels';\n this.mode = mode;\n if (!this.renderer && this.doc) this.buildRenderer();\n else this.updateRendererInteraction();\n if (changed) this.renderer?.clearSelection();\n if (wasChannels && mode !== 'channels') this.channels?.leave();\n this.paintModeTabs();\n this.paintRail();\n this.applySectionCanvasTreatment();\n if (mode === 'channels') this.channels?.enter();\n if (changed) this.opts.onModeChange?.(mode);\n }\n\n /**\n * Decide what this token may do with sales channels.\n *\n * Declared capabilities win — a host that mints an `mse_…` grant knows exactly\n * what it asked for. Otherwise a tenant secret (`sk_…`) is org authority the\n * worker never narrows, so it is fully capable; and a delegated token with no\n * declaration is probed for read access and then treated as READ-ONLY, because\n * \"we could not tell\" must never render mutation controls.\n */\n private async resolveChannelCapabilities(): Promise<void> {\n const declared = this.opts.capabilities;\n if (declared) {\n const set = new Set(declared as string[]);\n this.channelCaps = {\n view: set.has('event:channels:view'),\n manage: set.has('event:channels:view') && set.has('event:channels:manage'),\n };\n } else if (/^sk_/.test(this.opts.token)) {\n this.channelCaps = { view: true, manage: true };\n } else {\n this.channelCaps = { view: false, manage: false };\n }\n if (!this.channelCaps.view && !declared && !/^sk_/.test(this.opts.token)) {\n // Undeclared delegated token: probe read access once. Read-only either way.\n try {\n await this.api.channels(this.key);\n this.channelCaps = { view: true, manage: false };\n } catch {\n this.channelCaps = { view: false, manage: false };\n }\n }\n if (!this.channelCaps.view) {\n this.channels?.destroy();\n this.channels = null;\n this.paintModeTabs();\n return;\n }\n if (this.channels) {\n this.channels.setCapabilities(this.channelCaps);\n } else {\n this.channels = new ChannelsMode(this.buildChannelsHost(), this.channelCaps);\n // Entering/leaving buyer preview flips the canvas between selectable and\n // strictly read-only, so re-arm the renderer when the view changes.\n this.channels.onInteractionChange = () => this.updateRendererInteraction();\n }\n this.paintModeTabs();\n }\n\n /** The adapter between the cockpit's internals and Channels mode. */\n private buildChannelsHost() {\n return {\n eventKey: this.key,\n api: this.api,\n rail: this.els.rail,\n mapLayer: this.root.querySelector('.slm-map') as HTMLElement,\n root: this.root,\n seats: () => [...this.labelToSeat.values()].map((seat) => ({\n id: seat.id, label: seat.label, x: seat.x, y: seat.y,\n })),\n statusOf: (label: string): ChannelSeatStatus | undefined => this.status.get(label)\n ?? (this.labelToSeat.has(label) ? 'free' : undefined),\n selectionLabels: () => this.selectionLabels(),\n selectByLabels: (labels: string[]) => { this.selectByLabels(labels); },\n clearSelection: () => this.clearSelection(),\n selectSection: (sectionId: string) => { this.selectSection(sectionId); },\n sections: () => this.sectionOptions,\n labelsInSection: (sectionId: string) =>\n this.renderer?.getSelectableInSection(sectionId).map((seat) => seat.label) ?? [],\n // Logical rows, not physical row objects: a segmented row is authored as\n // several objects sharing one `logicalRowId`, and the organizer thinks of\n // it as one row. Tables carry seats too, so they are rows here as well.\n rows: (): ChannelsRowView[] => {\n const objects = new Map((this.doc?.objects ?? []).map((object) => [object.id, object]));\n const rows = new Map<string, ChannelsRowView>();\n for (const seat of this.labelToSeat.values()) {\n const object = objects.get(seat.rowId);\n if (!object || (object.type !== 'row' && object.type !== 'table')) continue;\n const id = seat.logicalRowId ?? seat.rowId;\n const sectionId = this.sectionByObject.get(seat.rowId) ?? UNGROUPED_ID;\n const row = rows.get(id) ?? {\n id,\n label: object.type === 'row'\n ? object.segmentedRow?.displayLabel ?? object.displayLabel ?? object.label\n : object.displayLabel ?? object.label,\n sectionId,\n sectionLabel: this.sectionLabelById.get(sectionId) ?? 'Other seats',\n labels: [],\n };\n row.labels.push(seat.label);\n rows.set(id, row);\n }\n return [...rows.values()].sort((left, right) =>\n left.sectionLabel.localeCompare(right.sectionLabel, undefined, { numeric: true, sensitivity: 'base' })\n || left.label.localeCompare(right.label, undefined, { numeric: true, sensitivity: 'base' }));\n },\n categories: () => (this.doc?.categories ?? []).map((category) => ({\n key: category.key, label: category.label ?? category.key, color: category.color,\n })),\n labelsInCategory: (key: string) => [...this.labelToSeat.entries()]\n .filter(([, seat]) => seat.categoryKey === key).map(([label]) => label),\n sectionOfLabel: (label: string) => {\n const seat = this.labelToSeat.get(label);\n if (!seat) return null;\n const id = this.sectionByObject.get(seat.rowId) ?? UNGROUPED_ID;\n return { id, label: this.sectionLabelById.get(id) ?? 'Other seats' };\n },\n worldToScreen: (point: { x: number; y: number }) => this.renderer?.worldToScreen(point) ?? null,\n seatPixelSize: () => this.seatPixelSize(),\n isSeatDetail: () => this.renderer?.getRung?.() === 'seats',\n showSectionOverview: () => {\n this.renderer?.clearSectionFocus();\n this.renderer?.setRung?.('sections');\n },\n focusSection: (sectionId: string) => this.renderer?.focusSection(sectionId),\n isCompact: () => !!this.root?.classList.contains('compact'),\n setMapInert: (inert: boolean) => {\n this.mapHost.toggleAttribute('inert', inert);\n this.mapHost.setAttribute('aria-hidden', String(inert));\n },\n toast: (message: string, kind: 'ok' | 'err') => this.toast(message, kind),\n onError: (err: unknown) => this.opts.onError?.(err),\n };\n }\n\n /** Actual on-screen seat diameter, for the channel overlay's marks. The\n * renderer's base seat radius is 9 chart units; retaining the camera scale\n * (rather than capping it) keeps every preview paint aligned with the real\n * chart geometry at deep zoom. */\n private seatPixelSize(): number {\n const rect = this.renderer?.getVisibleWorldRect?.();\n const width = this.mapHost?.clientWidth ?? 0;\n if (!rect?.width || !width) return 6;\n return Math.max(3, (width / rect.width) * 18);\n }\n\n /** Toggle the normalized sales-velocity outline overlay without changing seat colors. */\n setHeatOverlay(enabled: boolean): void {\n this.heatEnabled = enabled;\n this.applyHeatOverlay();\n this.paintHeatButton();\n }\n\n /** Toggle opt-in camera following for new buyer hold/book events. */\n setFollowLive(enabled: boolean): void {\n const changed = this.followLive !== enabled;\n this.followLive = enabled;\n if (!enabled) {\n if (this.followLiveTimer) clearTimeout(this.followLiveTimer);\n if (this.followSeatTimer) clearTimeout(this.followSeatTimer);\n this.followLiveTimer = null;\n this.followSeatTimer = null;\n }\n this.paintFollowLiveButton();\n if (changed) this.opts.onFollowLiveChange?.(enabled);\n }\n\n /** Change the current-vs-previous sales window and refresh the private projection. */\n setTrendWindow(windowMinutes: number): Promise<ControlRoomSnapshot> {\n const normalized = Number.isFinite(windowMinutes) ? Math.floor(windowMinutes) : 15;\n this.trendWindowMinutes = Math.max(5, Math.min(60, normalized));\n this.paintTrendWindow();\n return this.refreshControlRoom();\n }\n\n async enterFullscreen(): Promise<void> {\n if (!this.root?.requestFullscreen || this.isFullscreen()) return;\n await this.root.requestFullscreen();\n this.root.focus({ preventScroll: true });\n }\n\n async exitFullscreen(): Promise<void> {\n if (typeof document === 'undefined' || !this.isFullscreen()) return;\n await document.exitFullscreen();\n }\n\n isFullscreen(): boolean {\n return typeof document !== 'undefined' && document.fullscreenElement === this.root;\n }\n\n private toggleFullscreen(): void {\n const request = this.isFullscreen() ? this.exitFullscreen() : this.enterFullscreen();\n void request.catch((err) => this.opts.onError?.(err));\n }\n\n /** Rotate the delegated credential without rebuilding DOM, canvas or socket. */\n setToken(token: string, expiresAt?: number): void {\n this.api.setToken(token);\n this.tokenExpiresAt = expiresAt ?? null;\n this.scheduleTokenRefresh();\n if (this.ready) void this.resolveChannelCapabilities();\n }\n\n private scheduleTokenRefresh(): void {\n if (this.tokenRefreshTimer) clearTimeout(this.tokenRefreshTimer);\n this.tokenRefreshTimer = null;\n const refresh = this.opts.onTokenRefresh;\n const expiresAt = this.tokenExpiresAt;\n if (this.closed || !refresh || !expiresAt || !Number.isFinite(expiresAt)) return;\n const remaining = expiresAt - Date.now();\n const lead = Math.min(120_000, Math.max(30_000, remaining * 0.2));\n const delay = Math.max(0, remaining - lead);\n this.tokenRefreshTimer = setTimeout(() => {\n this.tokenRefreshTimer = null;\n void this.rotateToken();\n }, delay);\n }\n\n private async rotateToken(): Promise<void> {\n if (this.closed || this.tokenRefreshInFlight || !this.opts.onTokenRefresh) return;\n this.tokenRefreshInFlight = true;\n try {\n const next = await this.opts.onTokenRefresh();\n if (!next?.token || !Number.isFinite(next.expiresAt)) throw new Error('invalid_token_refresh_result');\n this.setToken(next.token, next.expiresAt);\n } catch (err) {\n this.opts.onError?.(err);\n if (!this.closed) {\n this.tokenRefreshTimer = setTimeout(() => {\n this.tokenRefreshTimer = null;\n void this.rotateToken();\n }, 30_000);\n }\n } finally {\n this.tokenRefreshInFlight = false;\n }\n }\n\n /** Bulk block the given labels (or the current selection when omitted). */\n async block(labels?: string[], opts: { releaseAt?: number; reason?: string } = {}): Promise<void> {\n const targets = (labels ?? this.selectionLabels()).filter((l) => this.status.get(l) === 'free');\n if (!targets.length) return;\n const releaseAt = opts.releaseAt ?? this.releaseAt ?? undefined;\n // optimistic\n this.setSeatsLocal(targets, 'blocked');\n try {\n await this.api.block(this.key, targets, { ...opts, releaseAt });\n this.clearSelection();\n this.done('block', targets, releaseAt\n ? `Blocked ${targets.length} — auto-release ${new Date(releaseAt).toLocaleString()}.`\n : `Blocked ${targets.length} seat${targets.length === 1 ? '' : 's'}.`);\n } catch (err) {\n this.setSeatsLocal(targets, 'free'); // revert\n this.toastErr(err instanceof ManageApiError && err.status === 409\n ? 'Some seats were just taken. Try again.'\n : \"Couldn't block those seats.\");\n this.opts.onError?.(err);\n }\n }\n\n async unblock(labels?: string[]): Promise<void> {\n const targets = (labels ?? this.selectionLabels()).filter((l) => this.status.get(l) === 'blocked');\n if (!targets.length) return;\n this.setSeatsLocal(targets, 'free');\n try {\n await this.api.unblock(this.key, targets);\n this.clearSelection();\n this.done('unblock', targets, `Unblocked ${targets.length} seat${targets.length === 1 ? '' : 's'}.`);\n } catch (err) {\n this.setSeatsLocal(targets, 'blocked');\n this.toastErr(\"Couldn't unblock those seats.\");\n this.opts.onError?.(err);\n }\n }\n\n async unblockAll(): Promise<void> {\n const blocked = [...this.status.entries()].filter(([, s]) => s === 'blocked').map(([l]) => l);\n if (!blocked.length) return;\n this.setSeatsLocal(blocked, 'free');\n try {\n const res = await this.api.unblockAll(this.key);\n this.clearSelection();\n this.done('unblockAll', blocked, `Unblocked ${res.freed} seat${res.freed === 1 ? '' : 's'}.`);\n } catch (err) {\n await this.resnapshot();\n this.toastErr(\"Couldn't mark everything for sale.\");\n this.opts.onError?.(err);\n }\n }\n\n /** Cancel bookings (BOOKED → free), guarded by the original booking ref. */\n async cancelBooking(labels: string[], bookingRef: string): Promise<void> {\n const targets = labels.filter((l) => this.status.get(l) === 'booked');\n if (!targets.length || !bookingRef) return;\n this.setSeatsLocal(targets, 'free');\n try {\n await this.api.unbook(this.key, targets, bookingRef);\n this.clearSelection();\n this.done('cancelBooking', targets, `Cancelled ${targets.length} booking${targets.length === 1 ? '' : 's'}.`);\n } catch (err) {\n this.setSeatsLocal(targets, 'booked');\n this.toastErr(\"Couldn't cancel that booking. Check the reference.\");\n this.opts.onError?.(err);\n }\n }\n\n selectAll(): ExpandedSeat[] {\n const seats = this.renderer?.selectAllSelectable() ?? [];\n this.syncSelection();\n return seats;\n }\n\n selectSection(sectionId: string): ExpandedSeat[] {\n if (!this.renderer) return [];\n const seats = this.renderer.getSelectableInSection(sectionId);\n this.renderer.selectByLabels(seats.map((s) => s.label));\n this.syncSelection();\n return this.renderer.getSelection();\n }\n\n selectByLabels(labels: string[]): ExpandedSeat[] {\n const seats = this.renderer?.selectByLabels(labels) ?? [];\n this.syncSelection();\n return seats;\n }\n\n clearSelection(): void {\n this.renderer?.clearSelection();\n this.syncSelection();\n }\n\n getSelection(): ExpandedSeat[] {\n return this.renderer?.getSelection() ?? [];\n }\n\n getReport(): Promise<ReportResult> {\n return this.api.report(this.key).then((report) => {\n this.applyReportRevenue(report);\n return report;\n });\n }\n\n getControlRoomSnapshot(windowMinutes = this.trendWindowMinutes): Promise<ControlRoomSnapshot> {\n return this.setTrendWindow(windowMinutes);\n }\n\n /**\n * The realtime link's current state and the \"as of\" behind it.\n *\n * Pair with `onConnectionChange` for the edges: a host that mounts after a\n * drop, or re-reads on tab focus, needs to be able to ASK rather than wait\n * for the next transition that may never come.\n */\n getConnection(): SeatManagerConnection {\n return { status: this.connectionStatus, lastMessageAt: this.lastMessageAt };\n }\n\n getLog(opts: { limit?: number; before?: number } = {}): Promise<{ entries: LogEntry[]; nextBefore: number | null }> {\n return this.api.log(this.key, opts);\n }\n\n async setHoldTtl(ms: number | null): Promise<void> {\n try {\n await this.api.setHoldTtl(this.key, ms);\n this.done('setHoldTtl', [], ms ? `Checkout window set to ${Math.round(ms / 60000)} min.` : 'Checkout window reset.');\n } catch (err) {\n this.toastErr(\"Couldn't update the checkout window.\");\n this.opts.onError?.(err);\n }\n }\n\n /** M2 — box-office booking from free seats. Stubbed (route is session-only today). */\n boxBook(_labels: string[], _bookingRef: string): Promise<void> {\n this.toastErr('Box office ships in a later milestone.');\n return Promise.resolve();\n }\n\n zoomToFit(): void {\n this.renderer?.clearSectionFocus();\n this.renderer?.zoomToFit();\n }\n\n destroy(): void {\n this.closed = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n if (this.feedTimer) clearInterval(this.feedTimer);\n if (this.toastTimer) clearTimeout(this.toastTimer);\n if (this.liveEventTimer) clearTimeout(this.liveEventTimer);\n if (this.kpiCleanupTimer) clearTimeout(this.kpiCleanupTimer);\n if (this.followLiveTimer) clearTimeout(this.followLiveTimer);\n if (this.followSeatTimer) clearTimeout(this.followSeatTimer);\n if (this.unblockAllConfirmTimer) clearTimeout(this.unblockAllConfirmTimer);\n if (this.paintHandle !== null && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(this.paintHandle);\n }\n this.paintHandle = null;\n this.channels?.destroy();\n this.channels = null;\n if (this.tokenRefreshTimer) clearTimeout(this.tokenRefreshTimer);\n this.layoutObserver?.disconnect();\n this.layoutObserver = null;\n this.root?.removeEventListener('keydown', this.onKeyDown);\n this.els.rail?.removeEventListener('click', this.onRailClick);\n if (typeof document !== 'undefined') document.removeEventListener('fullscreenchange', this.onFullscreenChange);\n if (this.ws) { try { this.ws.close(); } catch { /* ignore */ } this.ws = null; }\n this.renderer?.destroy();\n this.renderer = null;\n if (this.root && this.root.parentNode === this.host) this.host.removeChild(this.root);\n }\n\n // ---- renderer lifecycle ---------------------------------------------------\n\n private buildRenderer(): void {\n if (!this.doc) return;\n const bulk = this.isBulkSelectMode();\n this.renderer = new SeatmapRenderer(this.mapHost, {\n manageMode: true,\n marqueeSelect: bulk,\n maxSelection: 1_000_000,\n selectableStatuses: this.selectableStatuses(),\n currency: this.currency,\n onSelect: (seat) => this.handleSeatSelect(seat),\n onDeselect: () => this.syncSelection(),\n onMarquee: () => this.syncSelection(),\n onSectionTap: (sectionId) => {\n this.renderer?.focusSection(sectionId);\n this.channels?.handleSectionFocus(sectionId);\n },\n onViewChange: () => { this.updateZoomHint(); this.channels?.handleViewChange(); },\n });\n this.renderer.setChart(this.doc);\n this.repaintAll();\n this.applyHeatOverlay();\n this.updateZoomHint();\n }\n\n /** Block always uses a marquee. Channels only enables its marquee after the\n * organizer deliberately chooses Assign seats; Pan map keeps desktop drag\n * available for large charts. */\n private isBulkSelectMode(): boolean {\n return this.mode === 'block' || (this.mode === 'channels' && this.channels?.usesMarqueeSelection() === true);\n }\n\n /**\n * Block never touches held or booked inventory, so it cannot select it.\n * Channels must be able to select it — the Review sheet's honesty depends on\n * counting the held and sold units inside a marquee and saying they will not\n * move, rather than silently omitting them from the selection.\n */\n private selectableStatuses(): SeatStatus[] {\n if (this.mode === 'block') return ['free', 'not_for_sale'];\n if (this.mode === 'inspect' || this.isBulkSelectMode()\n || (this.mode === 'channels' && this.channels?.canSelect() === true)) {\n return ['free', 'held', 'booked', 'not_for_sale'];\n }\n return [];\n }\n\n private updateRendererInteraction(): void {\n const bulk = this.isBulkSelectMode();\n this.renderer?.setManageInteraction({\n manageMode: true,\n marqueeSelect: bulk,\n maxSelection: 1_000_000,\n selectableStatuses: this.selectableStatuses(),\n });\n this.updateZoomHint();\n }\n\n private handleSeatSelect(seat: ExpandedSeat): void {\n if (this.mode === 'inspect') {\n const others = this.getSelection()\n .filter((selected) => selected.id !== seat.id)\n .map((selected) => selected.id);\n if (others.length) this.renderer?.deselect(others);\n }\n this.syncSelection();\n }\n\n /**\n * Build the client's inventory universe from the chart.\n *\n * `expandChart` yields SEATS — it has no output for a GA area, whose capacity\n * is sold as N synthetic unit labels. The server's seat map keys, its deltas\n * and its `totals` all speak those labels, so a client that only knows seats\n * counts GA sales in the numerator (every key of the snapshot is written into\n * `status`) while leaving them out of the denominator. Registering the GA\n * units here — labels only, never a render binding — is what makes the two\n * agree.\n */\n private buildUnitUniverse(doc: ChartDoc): void {\n for (const seat of expandChart(doc)) {\n this.labelToId.set(seat.label, seat.id);\n this.labelToSeat.set(seat.label, seat);\n this.allIds.push(seat.id);\n }\n for (const area of gaAreasOf(doc)) {\n for (const label of gaUnitLabels(area)) {\n // A GA unit never shadows a seat label, and a joined area's provenance\n // can name the same unit twice across segments — the Set settles both.\n if (!this.labelToId.has(label)) this.gaUnitLabelSet.add(label);\n }\n }\n }\n\n /** Every sellable unit the client knows: seats + GA capacity. */\n private unitTotal(): number {\n return this.allIds.length + this.gaUnitLabelSet.size;\n }\n\n /** Every label the client models, whether or not it can be painted. */\n private knownLabels(): Iterable<string> {\n return [...this.labelToId.keys(), ...this.gaUnitLabelSet];\n }\n\n private repaintAll(): void {\n const r = this.renderer;\n if (!r) return;\n if (this.allIds.length) r.setStatus(this.allIds, 'free');\n const byStatus: Record<SeatStatus, string[]> = { free: [], held: [], booked: [], not_for_sale: [] };\n for (const [label, st] of this.status.entries()) {\n const id = this.labelToId.get(label);\n if (id) byStatus[toRenderStatus(st)].push(id);\n }\n (['held', 'booked', 'not_for_sale'] as SeatStatus[]).forEach((st) => {\n if (byStatus[st].length) r.setStatus(byStatus[st], st);\n });\n }\n\n // ---- realtime -------------------------------------------------------------\n\n /**\n * Open the cockpit's realtime socket AS THE ORGANIZER.\n *\n * The scope has to be established before the upgrade, because a browser\n * `WebSocket` cannot send an Authorization header: the manage token is traded\n * over HTTPS for a one-use ticket which rides in `Sec-WebSocket-Protocol`.\n * Without it the server treats this socket as an anonymous public buyer and\n * projects its deltas, so any change inside a private channel allocation is\n * structurally suppressed and the map silently drifts.\n *\n * If the mint fails (an expired token, a worker that predates the route) we\n * still connect unticketed rather than going dark — the public-sale stream is\n * worth having, and every `resnapshot()` re-establishes physical truth from\n * the authenticated HTTP read.\n */\n private async connect(): Promise<void> {\n if (this.closed) return;\n let protocols: string[] | undefined;\n try {\n protocols = (await this.api.subscribeTicket(this.key)).protocols;\n } catch {\n protocols = undefined;\n }\n if (this.closed) return;\n let ws: WebSocket;\n try {\n ws = protocols\n ? new WebSocket(this.api.socketUrl(this.key), protocols)\n : new WebSocket(this.api.socketUrl(this.key));\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n ws.onopen = () => {\n this.attempt = 0;\n this.setLive(true);\n // Connect (and every reconnect) is where the server's own totals, gross\n // and section metrics are re-established. Between connects the delta\n // stream carries both the counts and the money, so nothing polls.\n void this.resnapshot()\n .then(() => this.refreshControlRoom())\n .catch((err) => this.opts.onError?.(err));\n void this.refreshAvailability();\n };\n ws.onmessage = (e) => this.onMessage(e);\n ws.onclose = () => {\n if (this.ws === ws) this.ws = null;\n this.setLive(false);\n this.scheduleReconnect();\n };\n ws.onerror = () => { try { ws.close(); } catch { /* ignore */ } };\n }\n\n private scheduleReconnect(): void {\n if (this.closed || this.reconnectTimer) return;\n const delay = Math.min(1000 * 2 ** Math.min(this.attempt++, 5), 15000);\n this.reconnectTimer = setTimeout(() => { this.reconnectTimer = null; void this.connect(); }, delay);\n }\n\n private onMessage(e: MessageEvent): void {\n let msg: unknown;\n try {\n msg = JSON.parse(typeof e.data === 'string' ? e.data : '');\n } catch {\n return;\n }\n if (!msg || typeof msg !== 'object') return;\n // Stamped here, after parsing: unreadable frames prove the socket is open\n // but prove nothing about the numbers, and \"as of\" must mean the data.\n this.lastMessageAt = Date.now();\n const m = msg as {\n type?: string;\n seats?: Record<string, string>;\n /** Compact (protocol 1) snapshots send the modal status once and list\n * only the seats that differ from it. Absent on legacy frames. */\n default?: string;\n changes?: { label: string; status: string }[];\n /** Organizer-scope protocol-1 deltas carry cumulative booked gross, in the\n * same unit as `ControlRoomSnapshot.revenue.gross`. Buyer scopes never\n * see it, and a worker that predates it simply omits the field. */\n revenue?: { gross?: number };\n shoppingSessions?: number;\n activeHolds?: number;\n hidden?: string[];\n closed?: string[];\n };\n // Availability state (effective hidden/closed) can ride any message and is the\n // dedicated payload of the 'hidden' broadcast — keep the Sections rail + canvas fresh.\n if (Array.isArray(m.hidden) || Array.isArray(m.closed)) {\n this.updateEffectiveAvailability(m.hidden, m.closed);\n }\n if (m.type === 'presence') {\n // Presence used to be gated on a control-room snapshot already existing,\n // which silently dropped every frame in the window right after connect —\n // the exact window the cockpit is watched in. The counts are held on their\n // own field now and merged into the snapshot whenever one lands.\n if (typeof m.shoppingSessions === 'number' && typeof m.activeHolds === 'number') {\n this.livePresence = {\n at: Date.now(),\n value: { shoppingSessions: m.shoppingSessions, activeHolds: m.activeHolds },\n };\n if (this.controlRoomSnapshot) {\n this.controlRoomSnapshot = { ...this.controlRoomSnapshot, presence: this.livePresence.value };\n this.opts.onControlRoom?.(this.controlRoomSnapshot);\n }\n this.lastSyncedAt = Date.now();\n this.recomputeTallies();\n this.paintMonitorInsights();\n }\n return;\n }\n if (m.type === 'hidden') return;\n if (m.seats && typeof m.seats === 'object') {\n this.applySnapshot(m.seats, typeof m.default === 'string' ? m.default : undefined);\n } else if (Array.isArray(m.changes)) {\n const ids: string[] = [];\n const groups = new Map<string, { labels: string[]; verb: string; status: DoStatus }>();\n for (const ch of m.changes) {\n const st = (['free', 'held', 'booked', 'blocked'].includes(ch.status) ? ch.status : 'free') as DoStatus;\n const prev = this.status.get(ch.label) ?? 'free';\n if (prev === st) continue;\n this.setStatusLabel(ch.label, st, prev);\n const id = this.labelToId.get(ch.label);\n if (id) { this.renderer?.setStatus([id], toRenderStatus(st)); ids.push(id); }\n const verb = this.verbFor(prev, st);\n const groupKey = `${verb}:${st}`;\n const group = groups.get(groupKey) ?? { labels: [], verb, status: st };\n group.labels.push(ch.label);\n groups.set(groupKey, group);\n }\n for (const group of groups.values()) {\n const activity = this.pushActivity(group.labels, group.verb, group.status);\n if (activity) this.paintSpatialActivity(activity);\n }\n if (ids.length) {\n this.lastSyncedAt = Date.now();\n this.afterPaint();\n }\n // Money rides the frame now. GA-only sales register no renderer id, so a\n // refresh gated on `ids.length` never fired for them and GROSS SALES sat\n // frozen; a frame that carries the figure needs no fetch at all.\n if (typeof m.revenue?.gross === 'number' && Number.isFinite(m.revenue.gross)) {\n this.applyLiveGross(m.revenue.gross);\n }\n this.recomputeTallies();\n }\n }\n\n /**\n * Adopt the cumulative booked gross a delta frame carried.\n *\n * Stashed with its arrival time so an in-flight control-room read can decide\n * whether it is holding the newer number: a frame that landed after the\n * request started is newer than the response, one that landed before is not.\n */\n private applyLiveGross(gross: number): void {\n this.liveGross = { at: Date.now(), value: gross };\n this.authoritativeGrossRevenue = gross;\n this.revenueStatus = 'current';\n if (this.controlRoomSnapshot) {\n this.controlRoomSnapshot = {\n ...this.controlRoomSnapshot,\n revenue: { ...this.controlRoomSnapshot.revenue, gross },\n };\n this.opts.onControlRoom?.(this.controlRoomSnapshot);\n }\n }\n\n /** The single writer for a label's status, so the counters never drift. */\n private setStatusLabel(label: string, next: DoStatus, prev = this.status.get(label) ?? 'free'): void {\n this.status.set(label, next);\n if (prev === next) return;\n if (prev !== 'free') this.counts[prev] -= 1;\n if (next !== 'free') this.counts[next] += 1;\n }\n\n private async resnapshot(): Promise<void> {\n try {\n const objs = await this.api.objects(this.key);\n this.applySnapshot(objs.seats);\n this.updateEffectiveAvailability(objs.hidden, objs.closed);\n // A full snapshot over HTTP is server truth just as much as a delta is —\n // \"as of\" would otherwise ignore the freshest read the cockpit ever does.\n this.lastMessageAt = Date.now();\n } catch {\n /* transient — the delta stream keeps us fresh */\n }\n }\n\n /**\n * Replace the whole seat model.\n *\n * `fallback` is the compact frame's modal status: those snapshots list only\n * the seats that DIFFER from it, so every other known label takes it. Without\n * this the omitted majority would silently fall back to `free` — fine when\n * the mode really is free, wrong the moment it is not.\n */\n private applySnapshot(seats: Record<string, string>, fallback?: string): void {\n const known = (st: string): DoStatus =>\n (['free', 'held', 'booked', 'blocked'].includes(st) ? st : 'free') as DoStatus;\n const next = new Map<string, DoStatus>();\n if (fallback !== undefined) {\n const base = known(fallback);\n // GA units take the modal status too — they are inventory the server sells.\n for (const label of this.knownLabels()) next.set(label, base);\n }\n for (const [label, st] of Object.entries(seats)) {\n next.set(label, known(st));\n }\n this.status = next;\n this.modelVersion += 1;\n this.recountAll();\n this.lastSyncedAt = Date.now();\n this.repaintAll();\n this.afterPaint();\n this.recomputeTallies();\n }\n\n /** The one O(n) walk left: a wholesale model replacement re-bases the counters. */\n private recountAll(): void {\n const counts: Record<Exclude<DoStatus, 'free'>, number> = { held: 0, booked: 0, blocked: 0 };\n for (const st of this.status.values()) if (st !== 'free') counts[st] += 1;\n this.counts = counts;\n }\n\n /** Optimistic local write shared by organizer actions. Paint and tally once,\n * even when an arena-sized operation changes hundreds of seats. */\n private setSeatsLocal(labels: string[], st: DoStatus): void {\n const ids: string[] = [];\n for (const label of labels) {\n this.setStatusLabel(label, st);\n const id = this.labelToId.get(label);\n if (id) ids.push(id);\n }\n if (ids.length) this.renderer?.setStatus(ids, toRenderStatus(st));\n this.afterPaint();\n this.recomputeTallies();\n }\n\n /** Keep the canvas painting on hidden/occluded tabs (war-room second monitor). */\n private afterPaint(): void {\n if (this.keepLive && typeof document !== 'undefined' && document.hidden) {\n this.renderer?.forceDraw();\n }\n }\n\n private activityColor(status: DoStatus): string {\n return status === 'held' ? '#f4b740'\n : status === 'booked' ? '#22a06b'\n : status === 'blocked' ? '#8b94ac'\n : '#6e7bff';\n }\n\n private sectionsForLabels(labels: string[]): { ids: string[]; labels: string[] } {\n const ids = new Set<string>();\n for (const label of labels) {\n const seat = this.labelToSeat.get(label);\n if (!seat) continue;\n const sectionId = this.sectionByObject.get(seat.rowId);\n if (sectionId && sectionId !== UNGROUPED_ID) ids.add(sectionId);\n }\n const sectionIds = [...ids];\n return {\n ids: sectionIds,\n labels: sectionIds.map((id) => this.sectionLabelById.get(id) ?? id),\n };\n }\n\n private pulseSeatLabels(labels: string[], status: DoStatus): void {\n const color = this.activityColor(status);\n for (const label of labels.slice(0, MAX_LIVE_SEAT_PULSES)) {\n const id = this.labelToId.get(label);\n if (id) this.renderer?.flashSeat(id, color);\n }\n }\n\n /** Render one grouped realtime operation at the right semantic zoom level. */\n private paintSpatialActivity(activity: SeatManagerActivity): void {\n const sectionIds = activity.sectionIds ?? this.sectionsForLabels(activity.labels).ids;\n const focused = this.renderer?.getFocusedSection() ?? null;\n const followable = this.followLive && sectionIds.length === 1 &&\n (activity.status === 'held' || activity.status === 'booked');\n\n if (followable && focused === sectionIds[0]) {\n this.pulseSeatLabels(activity.labels, activity.status);\n return;\n }\n if (followable) {\n if (this.followLiveTimer) clearTimeout(this.followLiveTimer);\n if (this.followSeatTimer) clearTimeout(this.followSeatTimer);\n this.followLiveTimer = setTimeout(() => {\n this.followLiveTimer = null;\n this.renderer?.focusSection(sectionIds[0]);\n this.followSeatTimer = setTimeout(() => {\n this.followSeatTimer = null;\n this.pulseSeatLabels(activity.labels, activity.status);\n }, 520);\n }, 220);\n return;\n }\n\n if (!focused && sectionIds.length) {\n const color = this.activityColor(activity.status);\n for (const sectionId of sectionIds.slice(0, MAX_LIVE_SECTION_PULSES)) {\n this.renderer?.flashSection(sectionId, color);\n }\n return;\n }\n if (!sectionIds.length || (focused && sectionIds.includes(focused))) {\n this.pulseSeatLabels(activity.labels, activity.status);\n }\n }\n\n private locateSection(sectionId: string): void {\n this.renderer?.focusSection(sectionId);\n }\n\n private locateActivity(activityId: string): void {\n const activity = this.feed.find((item) => item.id === activityId);\n if (!activity) return;\n const sectionIds = activity.sectionIds ?? this.sectionsForLabels(activity.labels).ids;\n if (this.followSeatTimer) clearTimeout(this.followSeatTimer);\n if (sectionIds.length === 1) {\n this.locateSection(sectionIds[0]);\n this.followSeatTimer = setTimeout(() => {\n this.followSeatTimer = null;\n this.pulseSeatLabels(activity.labels, activity.status);\n }, 520);\n return;\n }\n this.zoomToFit();\n this.followSeatTimer = setTimeout(() => {\n this.followSeatTimer = null;\n if (sectionIds.length) {\n const color = this.activityColor(activity.status);\n for (const sectionId of sectionIds.slice(0, MAX_LIVE_SECTION_PULSES)) {\n this.renderer?.flashSection(sectionId, color);\n }\n } else {\n this.pulseSeatLabels(activity.labels, activity.status);\n }\n }, 280);\n }\n\n private showLiveEvent(activity: SeatManagerActivity): void {\n const element = this.els.liveevent;\n if (!element) return;\n const sections = activity.sectionLabels ?? [];\n const place = sections.length === 1 ? sections[0]\n : sections.length > 1 ? `${sections.length} sections`\n : activity.label;\n const noun = activity.count === 1 ? 'seat' : 'seats';\n element.innerHTML = `<span class=\"slm-liveeventdot\" style=\"background:${this.activityColor(activity.status)}\"></span>\n <span class=\"slm-liveeventcopy\">${esc(place)} · ${activity.count.toLocaleString()} ${noun} ${esc(activity.verb)}</span>\n <span class=\"slm-liveeventhint\">Live</span>`;\n element.classList.add('on');\n if (this.liveEventTimer) clearTimeout(this.liveEventTimer);\n this.liveEventTimer = setTimeout(() => {\n this.liveEventTimer = null;\n element.classList.remove('on');\n element.innerHTML = '';\n }, 2800);\n }\n\n // ---- tallies + feed -------------------------------------------------------\n\n private applyReportRevenue(report: ReportResult): void {\n this.authoritativeGrossRevenue = report.report.byCategory.reduce(\n (sum, row) => sum + (Number.isFinite(row.bookedRevenue) ? row.bookedRevenue : 0),\n 0,\n );\n this.revenueStatus = 'current';\n this.recomputeTallies();\n }\n\n /**\n * Read the server's own control-room projection.\n *\n * Called on mount, on every socket (re)connect and after an organizer action —\n * never on a timer and never per delta frame. Presence and gross that arrived\n * on the socket AFTER this request started are newer than the response, so\n * they survive it; anything older defers to the read.\n */\n private async refreshControlRoom(): Promise<ControlRoomSnapshot> {\n const request = ++this.revenueRequest;\n const requestedAt = Date.now();\n try {\n const fetched = await this.api.controlRoom(this.key, this.trendWindowMinutes);\n let snapshot = fetched;\n if (request === this.revenueRequest) {\n if (this.livePresence && this.livePresence.at >= requestedAt) {\n snapshot = { ...snapshot, presence: this.livePresence.value };\n } else {\n this.livePresence = null;\n }\n if (this.liveGross && this.liveGross.at >= requestedAt) {\n snapshot = { ...snapshot, revenue: { ...snapshot.revenue, gross: this.liveGross.value } };\n } else {\n this.liveGross = null;\n }\n this.controlRoomSnapshot = snapshot;\n this.rebaseServerTotals(snapshot);\n this.lastSyncedAt = Date.now();\n this.authoritativeGrossRevenue = snapshot.revenue.gross;\n this.currency = snapshot.currency;\n this.revenueStatus = 'current';\n this.recomputeTallies();\n this.applyHeatOverlay();\n this.paintMonitorInsights();\n this.opts.onControlRoom?.(snapshot);\n }\n // The host is handed the same object the cockpit adopted — a public\n // getter that disagreed with `onControlRoom` would be its own defect.\n return snapshot;\n } catch (err) {\n if (request === this.revenueRequest) {\n this.revenueStatus = 'stale';\n this.recomputeTallies();\n }\n throw err;\n }\n }\n\n /** Pin the server's totals to the client model they were read against. */\n private rebaseServerTotals(snapshot: ControlRoomSnapshot): void {\n const totals = snapshot.totals;\n if (!totals || ['free', 'held', 'booked', 'blocked'].some(\n (key) => !Number.isFinite((totals as unknown as Record<string, number>)[key]),\n )) {\n this.serverBaseline = null;\n return;\n }\n this.serverBaseline = {\n model: this.modelVersion,\n server: { free: totals.free, held: totals.held, booked: totals.booked, blocked: totals.blocked },\n client: this.clientTallies(),\n };\n }\n\n /** What the client's own model says — GA units included since `render()`. */\n private clientTallies(): { free: number; held: number; booked: number; blocked: number } {\n const { held, booked, blocked } = this.counts;\n // The snapshot only carries non-free, so free is what is left over.\n return { held, booked, blocked, free: Math.max(0, this.unitTotal() - held - booked - blocked) };\n }\n\n /**\n * The numbers the KPI bar and rail render.\n *\n * The server is the authority: its totals land exactly as read, and the\n * delta-driven client model carries them forward until the next read. Before\n * the first snapshot — and after a wholesale model replacement invalidates the\n * pairing — the client model stands alone.\n */\n private buildTallies(): SeatManagerTallies {\n const client = this.clientTallies();\n const baseline = this.serverBaseline?.model === this.modelVersion ? this.serverBaseline : null;\n const of = (key: 'free' | 'held' | 'booked' | 'blocked'): number => (baseline\n ? Math.max(0, baseline.server[key] + (client[key] - baseline.client[key]))\n : client[key]);\n const seatTotal = this.controlRoomSnapshot?.event?.seatTotal;\n const t: SeatManagerTallies = {\n free: of('free'), held: of('held'), booked: of('booked'), blocked: of('blocked'),\n total: Number.isFinite(seatTotal) ? (seatTotal as number) : this.unitTotal(),\n capacityPct: 0,\n sellThroughPct: 0,\n grossRevenue: this.authoritativeGrossRevenue,\n revenueStatus: this.revenueStatus,\n currency: this.currency,\n };\n t.capacityPct = t.total ? Math.round((t.booked / t.total) * 100) : 0;\n const sellable = t.total - t.blocked;\n t.sellThroughPct = sellable > 0 ? Math.round((t.booked / sellable) * 100) : 0;\n return t;\n }\n\n /**\n * Queue one KPI/rail repaint for this burst of changes.\n *\n * A delta frame can carry hundreds of seats and `paintKpis` rebuilds eight\n * nodes from scratch, so painting per change is what made an arena-sized\n * frame expensive. Coalescing on a frame keeps the burst to a single rebuild;\n * without `requestAnimationFrame` (SSR, an older test env) it paints inline\n * rather than dropping the update.\n */\n private recomputeTallies(): void {\n if (this.closed) return;\n if (typeof requestAnimationFrame !== 'function') { this.flushTallies(); return; }\n if (this.paintHandle !== null) return;\n this.paintHandle = requestAnimationFrame(() => {\n this.paintHandle = null;\n this.flushTallies();\n });\n }\n\n private flushTallies(): void {\n if (this.closed) return;\n const t = this.buildTallies();\n this.paintKpis(t);\n if (this.mode === 'view') {\n this.paintLegend(t);\n this.paintMonitorInsights();\n } else if (this.mode === 'inspect') this.renderInspectRail(this.getSelection());\n else if (this.mode === 'block') this.paintSelBar(this.getSelection());\n else if (this.mode === 'channels') this.channels?.handleSelectionChange();\n this.opts.onTallies?.(t);\n }\n\n private verbFor(prev: DoStatus, next: DoStatus): string {\n if (next === 'held') return 'held';\n if (next === 'booked') return 'booked';\n if (next === 'blocked') return 'blocked';\n if (next === 'free') return prev === 'blocked' ? 'unblocked' : prev === 'booked' ? 'cancelled' : 'released';\n return next;\n }\n\n private pushActivity(labels: string[], verb: string, status: DoStatus, at = Date.now()): SeatManagerActivity | null {\n const label = labels[0];\n if (!label) return null;\n const sections = this.sectionsForLabels(labels);\n const item: SeatManagerActivity = {\n id: `${label}:${at}:${Math.random().toString(36).slice(2, 6)}`,\n at,\n label,\n labels: [...labels],\n count: labels.length,\n verb,\n status,\n sectionIds: sections.ids,\n sectionLabels: sections.labels,\n };\n this.feed.unshift(item);\n if (this.feed.length > FEED_CAP) this.feed.length = FEED_CAP;\n if (this.mode === 'view') this.paintFeed();\n this.showLiveEvent(item);\n this.opts.onActivity?.(item);\n return item;\n }\n\n private seedFeed(entries: ControlRoomActivityEntry[]): void {\n const verbByAction: Record<string, string> = {\n hold: 'held', book: 'booked', release: 'released', expire: 'expired', block: 'blocked', unblock: 'unblocked',\n unbook: 'cancelled',\n };\n const stByAction: Record<string, DoStatus> = {\n hold: 'held', book: 'booked', release: 'free', expire: 'free', block: 'blocked', unblock: 'free', unbook: 'free',\n };\n for (const e of entries) {\n const label = e.labels[0];\n if (!label) continue;\n const sections = this.sectionsForLabels(e.labels);\n const item: SeatManagerActivity = {\n id: `log:${e.id}`,\n at: e.at,\n label,\n labels: [...e.labels],\n count: e.labels.length,\n verb: verbByAction[e.action] ?? e.action,\n status: stByAction[e.action] ?? 'free',\n sectionIds: sections.ids,\n sectionLabels: sections.labels,\n };\n this.feed.push(item);\n this.opts.onActivity?.(item);\n }\n this.feed.sort((a, b) => b.at - a.at);\n if (this.feed.length > FEED_CAP) this.feed.length = FEED_CAP;\n if (this.mode === 'view') this.paintFeed();\n }\n\n private startFeedClock(): void {\n this.feedTimer = setInterval(() => {\n if (this.mode === 'view') {\n this.paintFeed();\n this.paintMonitorInsights();\n }\n }, 10000);\n }\n\n // ---- selection ------------------------------------------------------------\n\n private selectionLabels(): string[] {\n return this.getSelection().map((s) => s.label);\n }\n\n private syncSelection(): void {\n const seats = this.getSelection();\n if (this.mode === 'block') this.paintSelBar(seats);\n else if (this.mode === 'inspect') this.renderInspectRail(seats);\n else if (this.mode === 'channels') this.channels?.handleSelectionChange();\n this.opts.onSelectionChange?.(seats);\n }\n\n // ---- DOM: chrome ----------------------------------------------------------\n\n private buildChrome(): void {\n const root = document.createElement('div');\n root.className = 'slm';\n root.tabIndex = 0;\n root.setAttribute('role', 'region');\n root.setAttribute('aria-label', 'SeatLayer live control room');\n const vars = themeVars(this.opts.theme);\n for (const [k, v] of Object.entries(vars)) root.style.setProperty(k, v);\n root.innerHTML = `\n <div class=\"slm-bar\">\n <div class=\"slm-modes\" data-ref=\"modes\" role=\"tablist\" aria-label=\"Manager tools\">\n <button class=\"slm-mode\" role=\"tab\" data-mode=\"view\" title=\"Monitor (M)\" aria-keyshortcuts=\"M\">Monitor</button>\n <button class=\"slm-mode\" role=\"tab\" data-mode=\"inspect\" title=\"Inspect (I)\" aria-keyshortcuts=\"I\">Inspect</button>\n <button class=\"slm-mode\" role=\"tab\" data-mode=\"block\" title=\"Block (B)\" aria-keyshortcuts=\"B\">Block</button>\n <button class=\"slm-mode\" role=\"tab\" data-mode=\"sections\" title=\"Sections (S)\" aria-keyshortcuts=\"S\">Sections</button>\n <button class=\"slm-mode\" role=\"tab\" data-mode=\"channels\" title=\"Channels (C)\" aria-keyshortcuts=\"C\" hidden>Channels</button>\n </div>\n <select class=\"slm-tools\" data-ref=\"tools\" aria-label=\"Manager tools\"></select>\n <span class=\"slm-live\"><span class=\"slm-live-dot\"></span><span data-ref=\"livetext\">CONNECTING</span></span>\n <div class=\"slm-bar-actions\">\n <button class=\"slm-barbtn follow\" data-ref=\"follow\" aria-pressed=\"false\"\n title=\"Stay on the current map view unless enabled\">Follow live</button>\n <button class=\"slm-barbtn\" data-ref=\"heat\" aria-pressed=\"false\"\n aria-label=\"Sales momentum overlay off\"\n title=\"Highlight sections selling fastest in the selected time window\">Sales momentum</button>\n <button class=\"slm-barbtn\" data-ref=\"fullscreen\" title=\"Full screen (F)\" aria-keyshortcuts=\"F\">Full screen</button>\n </div>\n <div class=\"slm-kpis\" data-ref=\"kpis\"></div>\n </div>\n <div class=\"slm-body\">\n <div class=\"slm-map\">\n <div class=\"slm-map-host\" data-ref=\"maphost\"></div>\n <div class=\"slm-zoomhint\" data-ref=\"zoomhint\">Zoom in to marquee-select</div>\n <div class=\"slm-liveevent\" data-ref=\"liveevent\" role=\"status\" aria-live=\"polite\"></div>\n <div class=\"slm-hud\"><button class=\"slm-hud-chip\" data-ref=\"zfit\">Zoom to fit</button></div>\n </div>\n <aside class=\"slm-rail\"><div class=\"slm-railscroll\" data-ref=\"rail\"></div></aside>\n </div>\n <div class=\"slm-toast\" data-ref=\"toast\"></div>\n `;\n this.host.appendChild(root);\n this.root = root;\n this.updateContainerLayout();\n if (typeof ResizeObserver !== 'undefined') {\n this.layoutObserver = new ResizeObserver(() => this.updateContainerLayout());\n this.layoutObserver.observe(root);\n }\n const ref = (n: string) => root.querySelector(`[data-ref=\"${n}\"]`) as HTMLElement;\n this.mapHost = ref('maphost') as HTMLDivElement;\n this.els = {\n modes: ref('modes'), tools: ref('tools'), livetext: ref('livetext'), kpis: ref('kpis'),\n follow: ref('follow'), heat: ref('heat'), fullscreen: ref('fullscreen'),\n zoomhint: ref('zoomhint'), liveevent: ref('liveevent'), rail: ref('rail'), toast: ref('toast'), zfit: ref('zfit'),\n };\n this.els.modes.querySelectorAll('[data-mode]').forEach((b) =>\n b.addEventListener('click', () => this.setMode((b as HTMLElement).dataset.mode as SeatManagerMode)));\n // Below the compact breakpoint the pills collapse into ONE accessible Tools\n // picker (§13) — never a tab strip plus a second scrolling mechanism.\n this.els.tools.addEventListener('change', () =>\n this.setMode((this.els.tools as HTMLSelectElement).value as SeatManagerMode));\n this.els.zfit.addEventListener('click', () => this.zoomToFit());\n this.els.follow.addEventListener('click', () => this.setFollowLive(!this.followLive));\n this.els.heat.addEventListener('click', () => this.setHeatOverlay(!this.heatEnabled));\n this.els.fullscreen.addEventListener('click', () => this.toggleFullscreen());\n root.addEventListener('keydown', this.onKeyDown);\n this.els.rail.addEventListener('click', this.onRailClick);\n document.addEventListener('fullscreenchange', this.onFullscreenChange);\n this.paintModeTabs();\n this.paintFollowLiveButton();\n this.paintHeatButton();\n this.paintFullscreenButton();\n }\n\n private updateContainerLayout(): void {\n const width = this.root?.getBoundingClientRect().width || this.host.clientWidth;\n this.root?.classList.toggle('compact', width > 0 && width < 800);\n this.channels?.handleLayoutChange();\n }\n\n private sectionOptions: { id: string; label: string }[] = [];\n\n private buildSectionOptions(): void {\n if (!this.doc) return;\n try {\n const secs = computeSections(this.doc);\n this.sectionsBase = secs;\n this.sectionOptions = [];\n this.sectionByObject = new Map(secs.objectToSection);\n this.sectionLabelById.clear();\n for (const s of secs.sections) {\n this.sectionOptions.push({ id: s.id, label: s.label });\n this.sectionLabelById.set(s.id, s.label);\n }\n if (secs.ungrouped) {\n this.sectionOptions.push({ id: UNGROUPED_ID, label: secs.ungrouped.label });\n this.sectionLabelById.set(UNGROUPED_ID, secs.ungrouped.label);\n }\n } catch { /* no sections */ }\n }\n\n private paintModeTabs(): void {\n const available: Array<{ mode: SeatManagerMode; label: string }> = [];\n this.els.modes?.querySelectorAll('[data-mode]').forEach((b) => {\n const el = b as HTMLElement;\n const mode = el.dataset.mode as SeatManagerMode;\n // No channel-view capability ⇒ the pill is not rendered at all. A hidden\n // control is honest about authority; a disabled one advertises it.\n const permitted = mode !== 'channels' || !!this.channels;\n el.hidden = !permitted;\n if (!permitted) return;\n available.push({ mode, label: el.textContent ?? mode });\n const active = mode === this.mode;\n el.classList.toggle('on', active);\n el.setAttribute('aria-selected', String(active));\n el.tabIndex = active ? 0 : -1;\n });\n const tools = this.els.tools as HTMLSelectElement | undefined;\n if (tools) {\n tools.innerHTML = available.map((entry) =>\n `<option value=\"${entry.mode}\"${entry.mode === this.mode ? ' selected' : ''}>${esc(entry.label)}</option>`).join('');\n tools.value = this.mode;\n }\n this.root?.classList.toggle('block-mode', this.mode === 'block');\n }\n\n private paintFollowLiveButton(): void {\n const button = this.els.follow;\n if (!button) return;\n button.classList.toggle('on', this.followLive);\n button.setAttribute('aria-pressed', String(this.followLive));\n button.setAttribute('title', this.followLive\n ? 'Following new buyer holds and bookings. Turn off to keep the current view.'\n : 'Stay on the current map view. Enable to follow new buyer holds and bookings.');\n }\n\n private paintHeatButton(): void {\n const button = this.els.heat;\n if (!button) return;\n button.classList.toggle('on', this.heatEnabled);\n button.setAttribute('aria-pressed', String(this.heatEnabled));\n button.setAttribute('aria-label', `Sales momentum overlay ${this.heatEnabled ? 'on' : 'off'}`);\n button.setAttribute('title', `${this.heatEnabled ? 'Hide' : 'Highlight'} sections selling fastest in the selected time window`);\n button.textContent = 'Sales momentum';\n this.paintMomentumHelp();\n }\n\n private paintMomentumHelp(): void {\n const help = this.els.rail?.querySelector('[data-ref=\"momentumhelp\"]') as HTMLElement | null;\n if (!help) return;\n help.hidden = !this.heatEnabled;\n const copy = help.querySelector('[data-ref=\"momentumcopy\"]');\n if (!copy) return;\n const hasRecentSales = this.controlRoomSnapshot?.velocity.bySection.some((row) => row.netBooked > 0);\n copy.textContent = hasRecentSales\n ? 'Warmer sections have more completed bookings, adjusted for section size. Holds and viewers are not counted.'\n : `No completed bookings in the last ${this.trendWindowMinutes} minutes.`;\n }\n\n private paintFullscreenButton(): void {\n if (!this.els.fullscreen) return;\n this.els.fullscreen.textContent = this.isFullscreen() ? 'Exit full screen' : 'Full screen';\n }\n\n private paintTrendWindow(): void {\n this.els.rail?.querySelectorAll('[data-window]').forEach((button) => {\n const value = Number((button as HTMLElement).dataset.window);\n button.classList.toggle('on', value === this.trendWindowMinutes);\n });\n }\n\n private setLive(on: boolean): void {\n this.root?.classList.toggle('live', on);\n if (this.els.livetext) this.els.livetext.textContent = on ? 'LIVE' : 'RECONNECTING';\n this.paintMonitorInsights();\n\n // Tell the host only on a real edge. `connect()` can call this with the\n // same value it already had (an open that follows a reconnect attempt),\n // and a banner that re-announces itself on every retry is noise.\n const next: SeatManagerConnection['status'] = on ? 'live' : 'reconnecting';\n if (next === this.connectionStatus) return;\n this.connectionStatus = next;\n try {\n this.opts.onConnectionChange?.(this.getConnection());\n } catch (err) {\n // A host callback must never take the socket down with it.\n this.opts.onError?.(err);\n }\n }\n\n private updateZoomHint(): void {\n const hint = this.els.zoomhint;\n if (!hint) return;\n const show = this.mode === 'block' && this.renderer?.getRung?.() !== 'seats';\n hint.classList.toggle('on', !!show);\n }\n\n private formatKpiDelta(key: string, delta: number, currency: string): string {\n const sign = delta > 0 ? '+' : '−';\n const absolute = Math.abs(delta);\n if (key === 'gross-sales') return `${sign}${fmtMoney(absolute, currency)}`;\n if (key === 'sold-pct') return `${sign}${absolute.toLocaleString()}pt`;\n return `${sign}${absolute.toLocaleString()}`;\n }\n\n private paintKpis(t: SeatManagerTallies): void {\n if (!this.els.kpis) return;\n const rev = t.revenueStatus === 'current' ? fmtMoney(t.grossRevenue, t.currency) : '—';\n const presence = this.presenceCounts();\n // Two different units share this bar and used to be interleaved: \"Held\n // seats\" (seat units) sat next to \"Active holds\" (checkout sessions), which\n // read as the same quantity counted twice. Seat tallies are grouped, the\n // session-scale pair is grouped, and the session one is named for what it\n // is — a cart.\n const items: { key: string; raw: number | null; n: string; l: string; dot?: string; title: string }[] = [\n { key: 'sold-seats', raw: t.booked, n: t.booked.toLocaleString(), l: 'Sold seats', dot: '#22a06b', title: 'Seats booked' },\n { key: 'held-seats', raw: t.held, n: t.held.toLocaleString(), l: 'Held seats', dot: '#f4b740', title: 'Seats held in a checkout right now' },\n { key: 'free-seats', raw: t.free, n: t.free.toLocaleString(), l: 'Free seats', dot: '#6e7bff', title: 'Seats on sale and unsold' },\n { key: 'blocked', raw: t.blocked, n: t.blocked.toLocaleString(), l: 'Blocked', dot: '#8b94ac', title: 'Seats withheld from sale' },\n { key: 'buyers', raw: presence?.shoppingSessions ?? null, n: presence ? presence.shoppingSessions.toLocaleString() : '—', l: 'Buyers', title: 'People on the map right now' },\n { key: 'carts', raw: presence?.activeHolds ?? null, n: presence ? presence.activeHolds.toLocaleString() : '—', l: 'Carts', title: 'Checkouts holding seats right now — sessions, not seats' },\n { key: 'sold-pct', raw: t.capacityPct, n: `${t.capacityPct}%`, l: 'Sold', title: 'Sold seats as a share of the whole event' },\n { key: 'gross-sales', raw: t.revenueStatus === 'current' ? t.grossRevenue : null, n: rev, l: 'Gross sales', title: 'Exact booked gross' },\n ];\n let hasChanges = false;\n this.els.kpis.innerHTML = items.map((item) => {\n const previous = this.lastKpiValues.get(item.key);\n const changed = item.raw != null && previous != null && item.raw !== previous;\n const delta = changed ? item.raw! - previous! : 0;\n if (changed) {\n hasChanges = true;\n this.activeKpiDeltas.set(item.key, {\n text: this.formatKpiDelta(item.key, delta, t.currency),\n down: delta < 0,\n });\n }\n if (item.raw != null) this.lastKpiValues.set(item.key, item.raw);\n const activeDelta = this.activeKpiDeltas.get(item.key);\n return `<div class=\"slm-kpi${activeDelta ? ' changed' : ''}\" data-kpi=\"${item.key}\" title=\"${esc(item.title)}\">\n <b>${item.dot ? `<span class=\"dot\" style=\"background:${item.dot}\"></span>` : ''}${item.n}</b><span>${item.l}</span>\n ${activeDelta ? `<span class=\"slm-kpidelta${activeDelta.down ? ' down' : ''}\">${activeDelta.text}</span>` : ''}\n </div>`;\n }).join('');\n if (hasChanges) {\n // The map above has already adopted the new values, so detect the rendered\n // change markers directly and remove their accessibility footprint after\n // the visual cue completes.\n if (this.kpiCleanupTimer) clearTimeout(this.kpiCleanupTimer);\n this.kpiCleanupTimer = setTimeout(() => {\n this.kpiCleanupTimer = null;\n this.activeKpiDeltas.clear();\n this.els.kpis?.querySelectorAll('.slm-kpidelta').forEach((element) => element.remove());\n this.els.kpis?.querySelectorAll('.slm-kpi.changed').forEach((element) => element.classList.remove('changed'));\n }, 1500);\n }\n }\n\n // ---- DOM: rails -----------------------------------------------------------\n\n private paintRail(): void {\n if (this.mode === 'view') this.renderViewRail();\n else if (this.mode === 'inspect') this.renderInspectRail(this.getSelection());\n else if (this.mode === 'sections') this.renderSectionsRail();\n else if (this.mode === 'channels') this.channels?.paintRail();\n else this.renderBlockRail();\n this.updateZoomHint();\n }\n\n private renderViewRail(): void {\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">Monitor</p>\n <p class=\"slm-hint\">Read-only. Inventory, buyer presence and sales movement update on the same live board.</p>\n <div class=\"slm-health\" data-ref=\"presence\"></div>\n <div class=\"slm-legend\" data-ref=\"legend\"></div>\n <div class=\"slm-sectionhead\">\n <div><p class=\"slm-eyebrow\">Section performance</p><p class=\"slm-note\">Exact booked revenue · net sales velocity</p></div>\n <div class=\"slm-windows\" aria-label=\"Sales velocity window\">\n ${[5, 15, 30, 60].map((window) => `<button class=\"slm-window\" data-window=\"${window}\">${window}m</button>`).join('')}\n </div>\n </div>\n <div class=\"slm-momentumhelp\" data-ref=\"momentumhelp\" ${this.heatEnabled ? '' : 'hidden'}>\n <div class=\"slm-momentumscale\"><span>Warm</span><span class=\"slm-momentumgradient\"></span><span>Hot</span></div>\n <p class=\"slm-momentumcopy\" data-ref=\"momentumcopy\"></p>\n </div>\n <div class=\"slm-sectionlist\" data-ref=\"sections\"></div>\n <p class=\"slm-eyebrow\">Activity</p>\n <div class=\"slm-feed\" data-ref=\"feed\"></div>\n `;\n this.els.presence = this.els.rail.querySelector('[data-ref=\"presence\"]') as HTMLElement;\n this.els.legend = this.els.rail.querySelector('[data-ref=\"legend\"]') as HTMLElement;\n this.els.sections = this.els.rail.querySelector('[data-ref=\"sections\"]') as HTMLElement;\n this.els.feed = this.els.rail.querySelector('[data-ref=\"feed\"]') as HTMLElement;\n this.els.rail.querySelectorAll('[data-window]').forEach((button) => button.addEventListener('click', () => {\n const windowMinutes = Number((button as HTMLElement).dataset.window);\n void this.setTrendWindow(windowMinutes).catch((err) => this.opts.onError?.(err));\n }));\n this.recomputeTallies();\n this.paintMonitorInsights();\n this.paintTrendWindow();\n this.paintMomentumHelp();\n this.paintFeed();\n }\n\n /** Live presence wins over the snapshot's copy — it is the fresher channel,\n * and it exists from the first frame rather than the first fetch. */\n private presenceCounts(): { shoppingSessions: number; activeHolds: number } | null {\n return this.livePresence?.value ?? this.controlRoomSnapshot?.presence ?? null;\n }\n\n private paintMonitorInsights(): void {\n if (this.mode !== 'view') return;\n const snapshot = this.controlRoomSnapshot;\n if (this.els.presence) {\n const connected = this.root?.classList.contains('live');\n const sync = this.lastSyncedAt ? relTime(this.lastSyncedAt, Date.now()) : 'waiting';\n const presence = this.presenceCounts();\n this.els.presence.innerHTML = `\n <div class=\"slm-healthitem\" title=\"People on the map right now\"><b>${presence ? presence.shoppingSessions.toLocaleString() : '—'}</b><span>Buyers</span></div>\n <div class=\"slm-healthitem\" title=\"Checkouts holding seats right now — sessions, not seats\"><b>${presence ? presence.activeHolds.toLocaleString() : '—'}</b><span>Carts</span></div>\n <div class=\"slm-healthitem\"><b>${connected ? 'Healthy' : 'Reconnecting'}</b><span>Live connection</span></div>\n <div class=\"slm-healthitem\"><b>${sync}</b><span>Last sync</span></div>`;\n }\n if (!this.els.sections) return;\n if (!snapshot) {\n this.els.sections.innerHTML = '<div class=\"slm-empty\">Loading authoritative section metrics…</div>';\n return;\n }\n const velocity = new Map(snapshot.velocity.bySection.map((row) => [row.sectionId, row]));\n const rows = [...snapshot.revenue.bySection].sort((a, b) => {\n const av = velocity.get(a.sectionId)?.netBooked ?? 0;\n const bv = velocity.get(b.sectionId)?.netBooked ?? 0;\n return bv - av || b.bookedRevenue - a.bookedRevenue;\n });\n this.els.sections.innerHTML = rows.length ? rows.map((row) => {\n const speed = velocity.get(row.sectionId);\n const net = speed?.netBooked ?? 0;\n const netLabel = `${net > 0 ? '+' : ''}${net}`;\n const trend = speed?.trend === 'rising' || speed?.trend === 'cooling' ? speed.trend : 'steady';\n return `<button type=\"button\" class=\"slm-sectionrow\" data-section-focus=\"${esc(row.sectionId)}\" title=\"Focus ${esc(row.sectionLabel)} on the map\">\n <span class=\"slm-sectiontop\"><span>${esc(row.sectionLabel)}</span><span>${fmtMoney(row.bookedRevenue, snapshot.currency)}</span></span>\n <span class=\"slm-sectionmeta\"><span>${row.booked.toLocaleString()}/${row.total.toLocaleString()} sold · ${netLabel} in ${snapshot.velocity.windowMinutes}m</span><span class=\"slm-trend ${trend}\">${trend}</span><span class=\"slm-sectionlocate\">Locate</span></span>\n </button>`;\n }).join('') : '<div class=\"slm-empty\">No section metrics are available for this chart.</div>';\n this.paintTrendWindow();\n this.paintMomentumHelp();\n }\n\n private applyHeatOverlay(): void {\n const snapshot = this.controlRoomSnapshot;\n if (!this.heatEnabled || !snapshot) {\n this.renderer?.setSectionHeat(null);\n return;\n }\n const capacity = new Map(snapshot.revenue.bySection.map((row) => [row.sectionId, Math.max(1, row.total)]));\n const rates = snapshot.velocity.bySection.map((row) => ({\n sectionId: row.sectionId,\n rate: Math.max(0, row.netBooked) / (capacity.get(row.sectionId) ?? 1) / snapshot.velocity.windowMinutes,\n }));\n const max = Math.max(0, ...rates.map((row) => row.rate));\n const scores: Record<string, number> = {};\n for (const row of rates) scores[row.sectionId] = max > 0 ? Math.sqrt(row.rate / max) : 0;\n this.renderer?.setSectionHeat(scores);\n }\n\n private renderInspectRail(seats: ExpandedSeat[]): void {\n const seat = seats[seats.length - 1];\n if (!seat) {\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">Inspect seats</p>\n <p class=\"slm-hint\">Select a seat to see its availability and sales context. Nothing changes in this view.</p>\n <div class=\"slm-empty\">Select a seat on the map.</div>`;\n return;\n }\n const status = this.status.get(seat.label) ?? 'free';\n const statusLabel: Record<DoStatus, string> = { free: 'Free', held: 'Held', booked: 'Booked', blocked: 'Blocked' };\n const sectionId = this.sectionByObject.get(seat.rowId) ?? UNGROUPED_ID;\n const sectionLabel = this.sectionLabelById.get(sectionId) ?? 'Other seats';\n const category = this.doc?.categories.find((item) => item.key === seat.categoryKey);\n const sectionMetric = this.controlRoomSnapshot?.revenue.bySection.find((row) => row.sectionId === sectionId);\n const object = this.doc?.objects.find((item) => item.id === seat.rowId);\n const location = object?.type === 'row'\n ? { label: 'Row', value: object.label }\n : object?.type === 'table'\n ? { label: 'Table', value: object.label }\n : seat.kind === 'booth'\n ? { label: 'Type', value: 'Booth' }\n : null;\n const itemKind = seat.kind === 'booth' ? 'Booth' : 'Seat';\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">${itemKind} details</p>\n <p class=\"slm-hint\">Live availability and section performance.</p>\n <div class=\"slm-inspect-card\">\n <div class=\"slm-inspect-label\">${esc(seat.label)}</div>\n <div class=\"slm-inspect-grid\">\n <div><span>Status</span><b>${statusLabel[status]}</b></div>\n <div><span>Section</span><b>${esc(sectionLabel)}</b></div>\n ${location ? `<div><span>${location.label}</span><b>${esc(location.value)}</b></div>` : ''}\n <div><span>Category</span><b>${esc(category?.label ?? seat.categoryKey)}</b></div>\n <div><span>Sold in section</span><b>${sectionMetric ? `${sectionMetric.booked} of ${sectionMetric.total}` : '—'}</b></div>\n <div><span>Section revenue</span><b>${sectionMetric && this.controlRoomSnapshot ? fmtMoney(sectionMetric.bookedRevenue, this.controlRoomSnapshot.currency) : '—'}</b></div>\n </div>\n </div>`;\n }\n\n // ---- sections: availability windows --------------------------------------\n\n /** Pull the organizer's availability rules (event:view). Called on load and on\n * every WS (re)connect, mirroring how the other panels re-hydrate. `closed` is\n * deterministic from the rules; `hidden` (which folds in already-due timed /\n * threshold windows) comes from the snapshot + WS effective set. */\n private async refreshAvailability(): Promise<void> {\n try {\n const res = await this.withAuthRetry(() => this.api.availability(this.key));\n this.availabilityRules = res.rules ?? {};\n this.effectiveClosed = new Set(this.closedIdsFromRules(this.availabilityRules));\n if (this.mode === 'sections') this.renderSectionsRail();\n this.applySectionCanvasTreatment();\n } catch (err) {\n this.opts.onError?.(err);\n }\n }\n\n /** Run a token-authed op; on a 401 re-mint via onTokenRefresh and retry once. */\n private async withAuthRetry<T>(op: () => Promise<T>): Promise<T> {\n try {\n return await op();\n } catch (err) {\n if (err instanceof ManageApiError && err.status === 401 && this.opts.onTokenRefresh && !this.tokenRefreshInFlight) {\n await this.rotateToken();\n return op();\n }\n throw err;\n }\n }\n\n private closedIdsFromRules(rules: Record<string, AvailabilityRule>): string[] {\n return Object.entries(rules).filter(([, r]) => r.mode === 'closed').map(([id]) => id);\n }\n\n /** Adopt a new effective hidden/closed set (from a snapshot or WS broadcast) and\n * repaint the rail + canvas when it actually moves. */\n private updateEffectiveAvailability(hidden?: string[], closed?: string[]): void {\n let changed = false;\n if (Array.isArray(hidden)) {\n this.effectiveHidden = new Set(hidden.filter((x): x is string => typeof x === 'string'));\n changed = true;\n }\n if (Array.isArray(closed)) {\n this.effectiveClosed = new Set(closed.filter((x): x is string => typeof x === 'string'));\n changed = true;\n }\n if (!changed) return;\n if (this.mode === 'sections') this.renderSectionsRail();\n this.applySectionCanvasTreatment();\n }\n\n /** Canvas read of the availability state: dim hidden sections to a whisper,\n * half-light closed sections, leave open sections normal. Only in Sections mode;\n * cleared in every other tool. */\n private applySectionCanvasTreatment(): void {\n if (!this.renderer) return;\n if (this.mode === 'sections') {\n this.renderer.setDimmedSections([...this.effectiveHidden]);\n this.renderer.setClosedSections([...this.effectiveClosed]);\n } else {\n this.renderer.setDimmedSections(null);\n this.renderer.setClosedSections(null);\n }\n }\n\n /** Zone-grouped render tree: each zone header then its sections (which follow the\n * zone window), then loose sections + the ungrouped bucket. Effective hidden /\n * closed come from the live sets, rules from the organizer map. */\n private buildSectionRows(): { rows: SectionRow[]; hiddenSections: number; closedSections: number } {\n const base = this.sectionsBase;\n if (!base) return { rows: [], hiddenSections: 0, closedSections: 0 };\n const zones = this.doc?.zones ?? [];\n const byZone = new Map<string, SectionNode[]>();\n const loose: SectionNode[] = [];\n for (const s of base.sections) {\n if (s.zone && zones.some((z) => z.id === s.zone)) {\n const list = byZone.get(s.zone) ?? [];\n list.push(s);\n byZone.set(s.zone, list);\n } else {\n loose.push(s);\n }\n }\n const rows: SectionRow[] = [];\n let hiddenSections = 0;\n let closedSections = 0;\n const push = (\n kind: 'zone' | 'section',\n node: { id: string; label: string; seatCount: number; seatLabels: string[] },\n zoneRuled: boolean,\n parentClosed = false,\n ): void => {\n const rule = this.availabilityRules[node.id] ?? null;\n const effClosed = this.effectiveClosed.has(node.id) || parentClosed;\n // A closed section stays visible-but-off-sale, never counted as hidden.\n const effHidden = this.effectiveHidden.has(node.id) || (zoneRuled && !effClosed);\n if (kind === 'section' && effHidden) hiddenSections += 1;\n if (kind === 'section' && effClosed) closedSections += 1;\n rows.push({\n kind, id: node.id, label: node.label, seatCount: node.seatCount, seatLabels: node.seatLabels,\n rule, hidden: effHidden, closed: effClosed, followsZone: kind === 'section' && zoneRuled,\n });\n };\n for (const z of zones) {\n const secs = byZone.get(z.id);\n if (!secs || !secs.length) continue;\n const zoneNode = {\n id: z.id,\n label: z.label || 'Zone',\n seatCount: secs.reduce((sum, s) => sum + s.seatCount, 0),\n seatLabels: secs.flatMap((s) => s.seatLabels),\n };\n const zoneRuled = !!this.availabilityRules[z.id];\n const zoneClosed = this.availabilityRules[z.id]?.mode === 'closed';\n push('zone', zoneNode, false);\n for (const s of secs) push('section', s, zoneRuled, zoneClosed);\n }\n for (const s of loose) push('section', s, false);\n if (base.ungrouped) {\n const u = base.ungrouped;\n push('section', { id: UNGROUPED_ID, label: u.label, seatCount: u.seatCount, seatLabels: u.seatLabels }, false);\n }\n return { rows, hiddenSections, closedSections };\n }\n\n private renderSectionsRail(): void {\n const { rows, hiddenSections, closedSections } = this.buildSectionRows();\n if (!rows.length) {\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">Availability windows</p>\n <p class=\"slm-hint\">Draw sections or zones in the designer to schedule availability per area. This chart has none yet.</p>\n <div class=\"slm-empty\">No sections on this chart.</div>`;\n return;\n }\n const parts: string[] = [];\n if (hiddenSections) parts.push(`${hiddenSections} hidden`);\n if (closedSections) parts.push(`${closedSections} closed`);\n const summary = parts.length ? parts.join(' · ') : 'All sections open and on sale';\n const warn = hiddenSections > 0 || closedSections > 0;\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">Availability windows</p>\n <p class=\"slm-hint\">Control when each zone or section goes on sale. Keep it hidden, reveal it at a set time, or <b>auto-reveal once the rest sells past a threshold</b>. Hidden seats vanish for buyers; closed seats stay on the map (flat grey) but can't be bought.</p>\n <div class=\"slm-availlist\" data-ref=\"availlist\">${rows.map((row) => this.sectionRowHtml(row)).join('')}</div>\n <div class=\"slm-availsummary\">\n <span class=\"slm-availdot${warn ? ' warn' : ''}\"></span>\n <span>${esc(summary)}</span>\n </div>\n <div class=\"slm-availcallout\">\n <span class=\"slm-availstar\" aria-hidden=\"true\">✦</span>\n <p><b>Auto-reveal at % sold</b> is our differentiator — demand-triggered release: the balcony opens itself the moment the stalls hit the threshold. Neither seats.io nor Ticketmaster ships this.</p>\n </div>`;\n this.wireSectionRail();\n this.applySectionCanvasTreatment();\n }\n\n private sectionRowHtml(row: SectionRow): string {\n const mode = availabilityModeOf(row.rule);\n const cls = `slm-availrow${row.kind === 'zone' ? ' zone' : ''}${row.hidden ? ' hidden' : ''}${row.closed ? ' closed' : ''}`;\n const disabled = this.availabilitySaving ? ' disabled' : '';\n const option = (value: AvailabilityMode, text: string): string =>\n `<option value=\"${value}\"${mode === value ? ' selected' : ''}>${text}</option>`;\n const control = row.followsZone\n ? '<span class=\"slm-availfollows\">Follows zone</span>'\n : `<span class=\"slm-availselwrap\">\n <select class=\"slm-select slm-availmode${mode !== 'open' ? ' on' : ''}\" data-avail-id=\"${esc(row.id)}\"${disabled} aria-label=\"Availability for ${esc(row.label)}\">\n ${option('open', 'Open — on sale')}\n ${option('closed', 'Closed — visible, not on sale')}\n ${option('hidden', 'Hidden — off the buyer map')}\n ${option('timed', 'Reveal at a time')}\n ${option('threshold', 'Auto-reveal at % sold')}\n </select>\n </span>`;\n let detail = '';\n if (!row.followsZone && mode === 'timed') {\n const value = row.rule?.revealAt ? esc(toLocalInput(row.rule.revealAt)) : '';\n detail = `<div class=\"slm-availdetail\">\n <input type=\"datetime-local\" class=\"slm-input\" data-avail-reveal=\"${esc(row.id)}\" value=\"${value}\"${disabled} aria-label=\"Reveal time for ${esc(row.label)}\" />\n </div>`;\n } else if (!row.followsZone && mode === 'threshold') {\n const pct = row.rule?.thresholdPct ?? 80;\n detail = `<div class=\"slm-availdetail\">\n <span class=\"slm-availpctlabel\">Reveal at</span>\n <input type=\"number\" min=\"1\" max=\"100\" class=\"slm-input slm-availpct\" data-avail-pct=\"${esc(row.id)}\" value=\"${esc(pct)}\"${disabled} aria-label=\"Percent sold to reveal ${esc(row.label)}\" />\n <span class=\"slm-availpctlabel\">% sold</span>\n </div>`;\n }\n const badge = row.closed\n ? '<span class=\"slm-availbadge closed\">Closed</span>'\n : row.hidden ? '<span class=\"slm-availbadge hidden\">Hidden</span>' : '';\n const caret = row.kind === 'zone' ? `<span class=\"slm-availcaret\" aria-hidden=\"true\">${row.hidden ? '▸' : '▾'}</span>` : '';\n return `<div class=\"${cls}\">\n <div class=\"slm-availhead\">\n <span class=\"slm-availlabel\">${caret}${esc(row.label)}</span>\n ${badge}\n <span class=\"slm-availcount\">${row.seatCount.toLocaleString()}</span>\n ${control}\n </div>\n ${detail}\n </div>`;\n }\n\n private wireSectionRail(): void {\n const rail = this.els.rail;\n if (!rail) return;\n rail.querySelectorAll<HTMLSelectElement>('[data-avail-id]').forEach((select) => {\n select.addEventListener('change', () => this.setSectionMode(select.dataset.availId!, select.value as AvailabilityMode));\n });\n rail.querySelectorAll<HTMLInputElement>('[data-avail-reveal]').forEach((input) => {\n input.addEventListener('change', () => {\n const ms = new Date(input.value).getTime();\n if (Number.isFinite(ms)) this.setSectionRulePatch(input.dataset.availReveal!, { revealAt: ms });\n });\n });\n rail.querySelectorAll<HTMLInputElement>('[data-avail-pct]').forEach((input) => {\n input.addEventListener('change', () => {\n const pct = Math.max(1, Math.min(100, Number(input.value) || 0));\n this.setSectionRulePatch(input.dataset.availPct!, { thresholdPct: pct });\n });\n });\n }\n\n /** Change one row's availability mode. A zone rule subsumes its child section\n * rules, so those are dropped from the map (the zone window is the truth). */\n private setSectionMode(id: string, mode: AvailabilityMode): void {\n const row = this.buildSectionRows().rows.find((r) => r.id === id);\n const seatLabels = row?.seatLabels ?? this.availabilityRules[id]?.labels ?? [];\n const next = { ...this.availabilityRules };\n const rule = availabilityRuleForMode(mode, seatLabels, this.availabilityRules[id]);\n if (rule) next[id] = rule;\n else delete next[id];\n if (row?.kind === 'zone' && this.sectionsBase) {\n for (const s of this.sectionsBase.sections) if (s.zone === id) delete next[s.id];\n }\n void this.persistAvailability(next);\n }\n\n /** Edit a timed reveal time / threshold percent on an existing row rule. */\n private setSectionRulePatch(id: string, patch: Partial<AvailabilityRule>): void {\n const cur = this.availabilityRules[id];\n if (!cur) return;\n const row = this.buildSectionRows().rows.find((r) => r.id === id);\n const labels = row?.seatLabels ?? cur.labels ?? [];\n void this.persistAvailability({ ...this.availabilityRules, [id]: { ...cur, ...patch, labels } });\n }\n\n /** Optimistically adopt the new rules, then reconcile with the server-cleaned\n * map + effective hidden/closed sets. Rolls back the rules on failure. */\n private async persistAvailability(next: Record<string, AvailabilityRule>): Promise<void> {\n const prev = this.availabilityRules;\n this.availabilityRules = next;\n this.availabilitySaving = true;\n if (this.mode === 'sections') this.renderSectionsRail();\n try {\n const res = await this.withAuthRetry(() => this.api.setAvailability(this.key, next));\n this.availabilityRules = res.rules;\n this.effectiveHidden = new Set(res.hidden);\n this.effectiveClosed = new Set(this.closedIdsFromRules(res.rules));\n this.availabilitySaving = false;\n if (this.mode === 'sections') this.renderSectionsRail();\n this.applySectionCanvasTreatment();\n } catch (err) {\n this.availabilityRules = prev;\n this.availabilitySaving = false;\n if (this.mode === 'sections') this.renderSectionsRail();\n this.toastErr(\"Couldn't update availability. Try again.\");\n this.opts.onError?.(err);\n }\n }\n\n private paintLegend(t: SeatManagerTallies): void {\n if (!this.els.legend) return;\n this.els.legend.innerHTML = LEGEND.map((l) =>\n `<div class=\"slm-legrow\"><span class=\"slm-legdot\" style=\"background:${l.color}\"></span>\n <span class=\"slm-leglabel\">${l.label}</span><span class=\"slm-legcount\">${t[l.key].toLocaleString()}</span></div>`).join('');\n }\n\n private paintFeed(): void {\n if (!this.els.feed) return;\n if (!this.feed.length) { this.els.feed.innerHTML = `<div class=\"slm-empty\">No activity yet — it'll stream in live.</div>`; return; }\n const now = Date.now();\n const color: Record<DoStatus, string> = { free: '#6e7bff', held: '#f4b740', booked: '#22a06b', blocked: '#8b94ac' };\n this.els.feed.innerHTML = this.feed.map((a) => {\n const extra = a.count > 1 ? ` +${a.count - 1}` : '';\n const sections = a.sectionLabels ?? [];\n const sectionCopy = sections.length === 1 ? sections[0] : sections.length > 1 ? `${sections.length} sections` : '';\n return `<button type=\"button\" class=\"slm-feedrow\" data-feed-id=\"${esc(a.id)}\" title=\"Locate this activity on the map\">\n <span class=\"slm-feeddot\" style=\"background:${color[a.status]}\"></span>\n <span class=\"slm-feedtext\">${sectionCopy ? `<span class=\"slm-feedsection\">${esc(sectionCopy)}</span>` : ''}${a.count === 1 ? 'Seat' : 'Seats'} <b>${esc(a.label)}${extra}</b> ${esc(a.verb)}</span>\n <span class=\"slm-feedmeta\"><span class=\"slm-feedtime\">${relTime(a.at, now)}</span><span class=\"slm-feedlocate\">Locate</span></span>\n </button>`;\n }).join('');\n }\n\n private renderBlockRail(): void {\n const cats = this.doc?.categories ?? [];\n const catChips = cats.map((c) =>\n `<button class=\"slm-chip\" type=\"button\" data-cat=\"${esc(c.key)}\" aria-pressed=\"false\">\n <span class=\"dot\" style=\"background:${esc(c.color ?? '#6e7bff')}\"></span>\n <span>${esc(c.label ?? c.key)}</span>\n <span class=\"slm-chipcount\" data-cat-count>0</span>\n <span class=\"slm-chipcheck\" aria-hidden=\"true\">✓</span>\n </button>`).join('');\n const sectionField = this.sectionOptions.length\n ? `<div class=\"slm-field\"><label>Select a whole section</label>\n <select class=\"slm-select\" data-ref=\"section\"><option value=\"\">Choose a section…</option>\n ${this.sectionOptions.map((s) => `<option value=\"${esc(s.id)}\">${esc(s.label)}</option>`).join('')}</select></div>`\n : '';\n const blockedSectionOptions = this.sectionOptions.map((s) =>\n `<option value=\"${esc(s.id)}\">${esc(s.label)}</option>`).join('');\n this.els.rail.innerHTML = `\n <p class=\"slm-eyebrow\">Block & unblock</p>\n <p class=\"slm-hint\">Drag a box on the map to marquee-select, ⌘A for all, or pick a category/section. Booked and held inventory is never actionable here.</p>\n <div class=\"slm-selbar\" aria-live=\"polite\"><span class=\"slm-selnum\" data-ref=\"selnum\">0</span><span class=\"slm-sellabel\" data-ref=\"selmeta\">selected</span></div>\n <div class=\"slm-row\">\n <button class=\"slm-btn\" data-ref=\"doblock\" disabled>Block</button>\n <button class=\"slm-btn ghost\" data-ref=\"dounblock\" disabled>Put back on sale</button>\n </div>\n <div class=\"slm-row\">\n <button class=\"slm-btn ghost\" data-ref=\"selall\">Select all</button>\n <button class=\"slm-btn ghost\" data-ref=\"clearsel\">Clear</button>\n </div>\n <p class=\"slm-eyebrow\" style=\"margin-top:8px\">Select by category</p>\n <p class=\"slm-selecthelp\">Choose one or more. A checked category is selected; click it again to remove it.</p>\n <div class=\"slm-chiprow\">${catChips || '<span class=\"slm-empty\">No categories.</span>'}</div>\n ${sectionField}\n <div class=\"slm-field\">\n <label>Auto-release blocks at (optional)</label>\n <input type=\"datetime-local\" class=\"slm-input\" data-ref=\"release\" />\n <p class=\"slm-note\" data-ref=\"releasenote\">Leave empty to block permanently.</p>\n </div>\n <section class=\"slm-blocked\" aria-labelledby=\"slm-blocked-title\">\n <div class=\"slm-blockedhead\">\n <p class=\"slm-eyebrow\" id=\"slm-blocked-title\">Blocked inventory</p>\n <span class=\"slm-blockedtotal\"><b data-ref=\"blockedcount\">0</b> out of sale</span>\n </div>\n <p class=\"slm-selecthelp\">Find blocked seats, select only the ones you need, then use “Put back on sale”.</p>\n <div class=\"slm-blockedtools\">\n <input type=\"search\" class=\"slm-input\" data-ref=\"blockedsearch\" placeholder=\"Find seat, row or category\" aria-label=\"Search blocked seats\" />\n <select class=\"slm-select\" data-ref=\"blockedsection\" aria-label=\"Filter blocked seats by section\">\n <option value=\"\">All sections</option>${blockedSectionOptions}\n </select>\n </div>\n <div class=\"slm-blockedsummary\">\n <span data-ref=\"blockedshowing\">No blocked seats</span>\n <button type=\"button\" class=\"slm-linkbtn\" data-ref=\"selblocked\" disabled>Select results</button>\n </div>\n <div class=\"slm-blockedlist\" data-ref=\"blockedlist\"></div>\n </section>\n <div class=\"slm-field\">\n <button class=\"slm-btn ghost\" data-ref=\"markall\" style=\"width:100%\" disabled>Put all blocked seats on sale</button>\n <p class=\"slm-note slm-allnote\" data-ref=\"markallnote\">For a full reset only. You will be asked to confirm.</p>\n </div>\n `;\n const r = (n: string) => this.els.rail.querySelector(`[data-ref=\"${n}\"]`) as HTMLElement;\n this.els.selnum = r('selnum'); this.els.doblock = r('doblock'); this.els.dounblock = r('dounblock');\n this.els.selmeta = r('selmeta'); this.els.blockedcount = r('blockedcount');\n this.els.blockedshowing = r('blockedshowing'); this.els.blockedlist = r('blockedlist');\n this.els.selblocked = r('selblocked'); this.els.markall = r('markall'); this.els.markallnote = r('markallnote');\n r('doblock').addEventListener('click', () => void this.block());\n r('dounblock').addEventListener('click', () => void this.unblock());\n r('selall').addEventListener('click', () => this.selectAll());\n r('clearsel').addEventListener('click', () => this.clearSelection());\n r('markall').addEventListener('click', () => this.confirmUnblockAll());\n this.els.rail.querySelectorAll('[data-cat]').forEach((b) =>\n b.addEventListener('click', () => this.toggleCategory((b as HTMLElement).dataset.cat!)));\n const sectionSel = this.els.rail.querySelector('[data-ref=\"section\"]') as HTMLSelectElement | null;\n sectionSel?.addEventListener('change', () => { if (sectionSel.value) { this.selectSection(sectionSel.value); sectionSel.value = ''; } });\n const blockedSearch = r('blockedsearch') as HTMLInputElement;\n const blockedSection = r('blockedsection') as HTMLSelectElement;\n blockedSearch.value = this.blockedQuery;\n blockedSection.value = this.blockedSection;\n blockedSearch.addEventListener('input', () => {\n this.blockedQuery = blockedSearch.value;\n this.blockedResultLimit = 100;\n this.paintBlockedInventory();\n });\n blockedSection.addEventListener('change', () => {\n this.blockedSection = blockedSection.value;\n this.blockedResultLimit = 100;\n this.paintBlockedInventory();\n });\n r('selblocked').addEventListener('click', () => {\n this.toggleLabels(this.filteredBlockedSeats().map((seat) => seat.label));\n });\n r('blockedlist').addEventListener('click', (event) => {\n const target = event.target as HTMLElement;\n const seatButton = target.closest<HTMLElement>('[data-blocked-label]');\n if (seatButton?.dataset.blockedLabel) this.toggleLabels([seatButton.dataset.blockedLabel]);\n else if (target.closest('[data-blocked-more]')) {\n this.blockedResultLimit += 100;\n this.paintBlockedInventory();\n }\n });\n const rel = r('release') as HTMLInputElement;\n rel.addEventListener('change', () => {\n const ms = rel.value ? new Date(rel.value).getTime() : NaN;\n this.releaseAt = Number.isFinite(ms) && ms > Date.now() ? ms : null;\n const note = r('releasenote');\n note.textContent = this.releaseAt\n ? `New blocks auto-release ${new Date(this.releaseAt).toLocaleString()}.`\n : rel.value ? 'Pick a time in the future.' : 'Leave empty to block permanently.';\n });\n this.paintSelBar(this.getSelection());\n }\n\n private toggleCategory(catKey: string): void {\n const labels: string[] = [];\n for (const [label, seat] of this.labelToSeat.entries()) {\n if (seat.categoryKey === catKey && this.isBlockSelectable(label)) labels.push(label);\n }\n this.toggleLabels(labels);\n }\n\n /** A category/filter is a real toggle: add the missing seats, or remove the\n * whole group when every eligible seat in it is already selected. */\n private toggleLabels(labels: string[]): void {\n if (!this.renderer) return;\n const eligible = labels.filter((label) => this.labelToSeat.has(label) && this.isBlockSelectable(label));\n if (!eligible.length) return;\n const selected = new Set(this.selectionLabels());\n const allSelected = eligible.every((label) => selected.has(label));\n if (allSelected) {\n const ids = eligible.map((label) => this.labelToId.get(label)).filter((id): id is string => Boolean(id));\n this.renderer.deselect(ids);\n } else {\n this.renderer.selectByLabels(eligible);\n }\n this.syncSelection();\n }\n\n private isBlockSelectable(label: string): boolean {\n const status = this.status.get(label) ?? 'free';\n return status === 'free' || status === 'blocked';\n }\n\n private paintSelBar(seats: ExpandedSeat[]): void {\n if (!this.els.selnum) return;\n this.els.selnum.textContent = seats.length.toLocaleString();\n const freeCount = seats.filter((s) => (this.status.get(s.label) ?? 'free') === 'free').length;\n const blockedCount = seats.filter((s) => this.status.get(s.label) === 'blocked').length;\n this.els.selmeta.textContent = seats.length\n ? `${freeCount.toLocaleString()} available · ${blockedCount.toLocaleString()} blocked`\n : 'selected';\n const blockButton = this.els.doblock as HTMLButtonElement;\n const unblockButton = this.els.dounblock as HTMLButtonElement;\n blockButton.disabled = freeCount === 0;\n unblockButton.disabled = blockedCount === 0;\n blockButton.textContent = freeCount ? `Block ${freeCount.toLocaleString()}` : 'Block selected';\n unblockButton.textContent = blockedCount ? `Put ${blockedCount.toLocaleString()} on sale` : 'Put back on sale';\n this.paintCategoryControls(seats);\n this.paintBlockedInventory();\n }\n\n private paintCategoryControls(seats: ExpandedSeat[]): void {\n const selected = new Set(seats.map((seat) => seat.label));\n this.els.rail?.querySelectorAll<HTMLButtonElement>('[data-cat]').forEach((button) => {\n const catKey = button.dataset.cat;\n const labels: string[] = [];\n for (const [label, seat] of this.labelToSeat.entries()) {\n if (seat.categoryKey === catKey && this.isBlockSelectable(label)) labels.push(label);\n }\n const picked = labels.filter((label) => selected.has(label)).length;\n const full = labels.length > 0 && picked === labels.length;\n const partial = picked > 0 && !full;\n button.disabled = labels.length === 0;\n button.classList.toggle('on', full);\n button.classList.toggle('partial', partial);\n button.setAttribute('aria-pressed', full ? 'true' : partial ? 'mixed' : 'false');\n button.setAttribute('title', full\n ? `Remove all ${labels.length.toLocaleString()} seats in this category from the selection`\n : partial\n ? `Select the remaining ${(labels.length - picked).toLocaleString()} seats in this category`\n : `Select all ${labels.length.toLocaleString()} seats in this category`);\n const count = button.querySelector<HTMLElement>('[data-cat-count]');\n if (count) count.textContent = picked ? `${picked.toLocaleString()}/${labels.length.toLocaleString()}` : labels.length.toLocaleString();\n });\n }\n\n private filteredBlockedSeats(): ExpandedSeat[] {\n const query = this.blockedQuery.trim().toLocaleLowerCase();\n const seats: ExpandedSeat[] = [];\n for (const [label, seat] of this.labelToSeat.entries()) {\n if (this.status.get(label) !== 'blocked') continue;\n const sectionId = this.sectionByObject.get(seat.rowId) ?? UNGROUPED_ID;\n if (this.blockedSection && sectionId !== this.blockedSection) continue;\n if (query) {\n const category = this.doc?.categories.find((item) => item.key === seat.categoryKey)?.label ?? seat.categoryKey;\n const section = this.sectionLabelById.get(sectionId) ?? 'Other seats';\n const object = this.doc?.objects.find((item) => item.id === seat.rowId);\n const objectLabel = object?.type === 'row' || object?.type === 'table' ? object.label : '';\n const haystack = `${label} ${category} ${section} ${objectLabel}`.toLocaleLowerCase();\n if (!haystack.includes(query)) continue;\n }\n seats.push(seat);\n }\n return seats.sort((a, b) => a.label.localeCompare(b.label, undefined, { numeric: true, sensitivity: 'base' }));\n }\n\n private paintBlockedInventory(): void {\n if (!this.els.blockedlist) return;\n const allBlocked = [...this.status.entries()].filter(([, status]) => status === 'blocked').length;\n const filtered = this.filteredBlockedSeats();\n const visible = filtered.slice(0, this.blockedResultLimit);\n const selected = new Set(this.selectionLabels());\n const selectedResults = filtered.filter((seat) => selected.has(seat.label)).length;\n const allResultsSelected = filtered.length > 0 && selectedResults === filtered.length;\n this.els.blockedcount.textContent = allBlocked.toLocaleString();\n this.els.blockedshowing.textContent = filtered.length\n ? `Showing ${visible.length.toLocaleString()} of ${filtered.length.toLocaleString()}`\n : allBlocked ? 'No matches' : 'No blocked seats';\n const selectResults = this.els.selblocked as HTMLButtonElement;\n selectResults.disabled = filtered.length === 0;\n selectResults.textContent = allResultsSelected\n ? `Remove ${filtered.length.toLocaleString()} results`\n : `Select ${filtered.length.toLocaleString()} results`;\n\n this.els.blockedlist.innerHTML = visible.length ? visible.map((seat) => {\n const sectionId = this.sectionByObject.get(seat.rowId) ?? UNGROUPED_ID;\n const section = this.sectionLabelById.get(sectionId) ?? 'Other seats';\n const category = this.doc?.categories.find((item) => item.key === seat.categoryKey)?.label ?? seat.categoryKey;\n const isSelected = selected.has(seat.label);\n return `<button type=\"button\" class=\"slm-blockeditem${isSelected ? ' on' : ''}\" data-blocked-label=\"${esc(seat.label)}\" aria-pressed=\"${isSelected}\">\n <span class=\"slm-blockedcheck\" aria-hidden=\"true\">✓</span>\n <span class=\"slm-blockedcopy\"><span class=\"slm-blockedlabel\">${esc(seat.label)}</span>\n <span class=\"slm-blockedmeta\">${esc(section)} · ${esc(category)}</span></span>\n </button>`;\n }).join('') + (filtered.length > visible.length\n ? `<button type=\"button\" class=\"slm-blockedmore\" data-blocked-more>Show 100 more</button>` : '')\n : `<div class=\"slm-blockedempty\">${allBlocked\n ? 'No blocked seats match this search or section.'\n : 'No seats are blocked. Newly blocked seats will appear here.'}</div>`;\n\n const markAll = this.els.markall as HTMLButtonElement;\n const armed = markAll.dataset.confirm === 'true';\n markAll.disabled = allBlocked === 0;\n markAll.textContent = armed\n ? `Confirm: put all ${allBlocked.toLocaleString()} on sale`\n : `Put all ${allBlocked.toLocaleString()} blocked seats on sale`;\n }\n\n private confirmUnblockAll(): void {\n const button = this.els.markall as HTMLButtonElement;\n if (!button || button.disabled) return;\n if (button.dataset.confirm === 'true') {\n this.resetUnblockAllConfirm();\n void this.unblockAll();\n return;\n }\n button.dataset.confirm = 'true';\n button.classList.add('danger');\n this.els.markallnote.textContent = 'This changes every blocked seat. Click the red button again to confirm.';\n this.paintBlockedInventory();\n if (this.unblockAllConfirmTimer) clearTimeout(this.unblockAllConfirmTimer);\n this.unblockAllConfirmTimer = setTimeout(() => this.resetUnblockAllConfirm(), 6000);\n }\n\n private resetUnblockAllConfirm(): void {\n if (this.unblockAllConfirmTimer) clearTimeout(this.unblockAllConfirmTimer);\n this.unblockAllConfirmTimer = null;\n const button = this.els.markall as HTMLButtonElement | undefined;\n if (!button) return;\n delete button.dataset.confirm;\n button.classList.remove('danger');\n if (this.els.markallnote) this.els.markallnote.textContent = 'For a full reset only. You will be asked to confirm.';\n this.paintBlockedInventory();\n }\n\n // ---- toast / done / fail --------------------------------------------------\n\n private done(action: SeatManagerActionResult['action'], labels: string[], msg: string): void {\n this.toastOk(msg);\n if (labels.length) {\n const activity = action === 'block'\n ? this.pushActivity(labels, 'blocked', 'blocked')\n : action === 'unblock' || action === 'unblockAll'\n ? this.pushActivity(labels, 'unblocked', 'free')\n : action === 'cancelBooking'\n ? this.pushActivity(labels, 'cancelled', 'free')\n : null;\n if (activity) this.paintSpatialActivity(activity);\n }\n // An explicit organizer action is one of the three moments the server's own\n // totals and money are re-read (mount, (re)connect, action) — the cockpit\n // does not poll for them.\n if (action !== 'setHoldTtl') void this.refreshControlRoom().catch((err) => this.opts.onError?.(err));\n this.opts.onActionComplete?.({ action, labels, count: labels.length });\n }\n\n private toastOk(msg: string): void { this.toast(msg, 'ok'); }\n private toastErr(msg: string): void { this.toast(msg, 'err'); }\n\n private toast(msg: string, kind: 'ok' | 'err'): void {\n const el = this.els.toast;\n if (!el) return;\n el.textContent = msg;\n el.className = `slm-toast on ${kind}`;\n if (this.toastTimer) clearTimeout(this.toastTimer);\n this.toastTimer = setTimeout(() => { el.className = 'slm-toast'; }, 3200);\n }\n\n private fail(err: unknown): void {\n this.opts.onError?.(err);\n if (this.els.rail) this.els.rail.innerHTML = `<div class=\"slm-empty\">Couldn't load this event. Check the event key and token.</div>`;\n }\n}\n","/**\n * Sales-channel planning — the pure, DOM-free half of Channels mode.\n *\n * Everything here is deterministic and testable without a canvas: the marker\n * palette, the mixed-source selection summary, the LOCAL staged preview of an\n * assignment, and the bucket rows the Review sheet renders.\n *\n * The local preview deliberately produces the SAME `AssignmentBuckets` shape the\n * server returns from `POST /channels/assignments`. There is no dry-run endpoint,\n * so the review sheet is drawn from this local computation and then REDRAWN from\n * the authoritative server response after Apply. One renderer, two sources —\n * which is why the shapes must match exactly.\n *\n * Spec: sales-channels-product-ux-spec §8.4–8.5.\n */\n\n/**\n * Public sale is a built-in pseudo-channel. The server's sentinel for it is the\n * literal string `'public'` — it is what `GET /channels` returns as\n * `publicSale.id`, what `GET /channels/allocation` reports for an unallocated\n * unit, and what `POST /channels/assignments` accepts (alongside `null`) as the\n * target meaning \"send these back to public sale\".\n *\n * This constant was `''` until 2026-08-02, which silently made every public unit\n * look like an unknown PRIVATE channel to `planAssignment` and `markerOf` — the\n * cause of the Review sheet's phantom \"moved out of another channel\" line and\n * the rail's \"?\" marker. Keep it byte-identical to the server's\n * `eventChannels.PUBLIC_CHANNEL_ID`.\n */\nexport const PUBLIC_CHANNEL_ID = 'public';\nexport const PUBLIC_CHANNEL_NAME = 'Public sale';\n\n/** True for every spelling of \"public sale\" a worker may hand us. */\nexport function isPublicChannelId(id: string | null | undefined): boolean {\n return id == null || id === '' || id === PUBLIC_CHANNEL_ID;\n}\n\nexport type ChannelState = 'active' | 'paused' | 'archived';\n\n/** Physical inventory status, as the manage surface speaks it. */\nexport type ChannelSeatStatus = 'free' | 'held' | 'booked' | 'blocked';\n\nexport interface ChannelCounts {\n allocated: number;\n free: number;\n held: number;\n booked: number;\n blocked: number;\n units: number;\n}\n\n/** Buyer-access intents the server stores per channel. */\nexport type ChannelAccessIntent = 'none' | 'internal' | 'server' | 'hosted_link';\n\n/**\n * Buyer-access summary on a channel row. Shipped by the access hardening branch\n * (merged to app main). Still optional in this type: a worker that predates the\n * merge simply omits it and the rail reads \"—\" rather than inventing a state.\n */\nexport interface ChannelAccessSummary {\n intent?: ChannelAccessIntent | string;\n hasActiveGrants?: boolean;\n lastMintAt?: number | null;\n /** Free-text detail (partner host, who paused it) when the server offers one. */\n detail?: string | null;\n}\n\nexport interface ChannelRecord {\n id: string;\n name: string;\n color: string | null;\n marker: string | null;\n externalRef: string | null;\n state: ChannelState;\n archiveDestination: string | null;\n createdAt: number;\n updatedAt: number;\n archivedAt: number | null;\n counts: ChannelCounts;\n access?: ChannelAccessSummary | null;\n}\n\nexport interface PublicSaleChannel {\n /** `'public'` on every shipped worker; typed loosely so an older build that\n * still answers `''` is normalised rather than rejected. */\n id: string;\n name: string;\n state: 'active';\n counts: ChannelCounts;\n access?: ChannelAccessSummary | null;\n}\n\nexport interface ChannelListResult {\n assignmentVersion: number;\n publicSale: PublicSaleChannel;\n channels: ChannelRecord[];\n}\n\nexport interface AssignmentBucketCount {\n count: number;\n}\n\nexport interface AssignmentSkippedBucket extends AssignmentBucketCount {\n labels: string[];\n truncated: boolean;\n}\n\nexport interface AssignmentBuckets {\n changedFromPublic: AssignmentBucketCount;\n movedFromOtherChannel: AssignmentBucketCount & {\n channels: Array<{ channelId: string; name: string | null; count: number }>;\n };\n alreadyInTarget: AssignmentBucketCount;\n skippedHeld: AssignmentSkippedBucket;\n skippedBooked: AssignmentSkippedBucket;\n /** Requested labels that are not inventory in this event. */\n notFound: AssignmentSkippedBucket;\n}\n\nexport interface AssignmentResult {\n ok: true;\n targetChannelId: string;\n assignmentVersion: number;\n requested: number;\n applied: number;\n buckets: AssignmentBuckets;\n}\n\nexport interface ArchiveBlockedDetails {\n activeHolds?: number;\n heldUnits?: number;\n latestHoldExpiresAt?: number | null;\n retryAfterMs?: number;\n}\n\n/**\n * Administrative colors. Always paired with a LETTER on every surface — the\n * comp's rule and spec §13's: channel identity never rests on hue alone.\n */\nexport const CHANNEL_COLORS = [\n '#a78bfa', '#2dd4bf', '#fb923c', '#60a5fa', '#f472b6',\n '#a3e635', '#f87171', '#38bdf8', '#c084fc', '#facc15',\n] as const;\n\n/** Public sale keeps the cockpit's gold, distinct from every private channel. */\nexport const PUBLIC_CHANNEL_COLOR = '#f4b740';\n\nconst LETTERS = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // no I/O — they read as 1/0\n\n/**\n * Clamp any marker text down to the ONE uppercase character every surface draws.\n *\n * The server stores `marker` as free text (it only length-caps it), so a channel\n * created outside this widget can carry \"star\" or \"VIP\". The comp's marker chip\n * is a single glyph: taking two characters (\"ST\") overflows the 22px chip and\n * stops reading as a letter. Non-letter leading characters (an emoji, a digit,\n * punctuation) are skipped in favour of the first real letter.\n */\nexport function markerLetter(raw: string | null | undefined, fallback: string): string {\n const text = (raw ?? '').trim();\n const letter = /\\p{L}/u.exec(text)?.[0] ?? text[0] ?? '';\n return (letter || fallback).toUpperCase().slice(0, 1);\n}\n\n/**\n * Suggest a marker for a new channel: the first letter of its name when that\n * letter is still free, otherwise the next unused letter. Deterministic so the\n * Create dialog's preview matches what actually gets stored.\n */\nexport function suggestMarker(\n name: string,\n taken: Iterable<string>,\n): { letter: string; color: string } {\n const used = new Set([...taken].map((m) => markerLetter(m, '')).filter(Boolean));\n const first = markerLetter(name, '');\n const letter = LETTERS.includes(first) && !used.has(first)\n ? first\n : ([...LETTERS].find((candidate) => !used.has(candidate)) ?? (first || 'X'));\n return { letter, color: CHANNEL_COLORS[used.size % CHANNEL_COLORS.length] };\n}\n\n/** The letter + color a channel actually renders with (server value wins). */\nexport function markerOf(\n channel: { id: string; name: string; marker?: string | null; color?: string | null },\n index = 0,\n): { letter: string; color: string } {\n if (isPublicChannelId(channel.id)) {\n return {\n letter: markerLetter(channel.marker, 'P'),\n color: channel.color || PUBLIC_CHANNEL_COLOR,\n };\n }\n const letter = markerLetter(channel.marker || channel.name, '?');\n return { letter, color: channel.color || CHANNEL_COLORS[index % CHANNEL_COLORS.length] };\n}\n\n/** One line of the rail's mixed-source selection summary (§8.4). */\nexport interface SelectionSourceRow {\n channelId: string;\n name: string;\n count: number;\n}\n\n/**\n * Group the current selection by the channel each unit is allocated to today.\n * Public sale is listed first; the rest follow in list order so the rail's\n * ordering never jitters as the selection changes.\n */\nexport function selectionSources(\n labels: string[],\n allocation: Map<string, string>,\n list: ChannelListResult | null,\n): SelectionSourceRow[] {\n const counts = new Map<string, number>();\n for (const label of labels) {\n const channelId = normalizeChannelId(allocation.get(label));\n counts.set(channelId, (counts.get(channelId) ?? 0) + 1);\n }\n const order: Array<{ id: string; name: string }> = [\n { id: PUBLIC_CHANNEL_ID, name: list?.publicSale?.name ?? PUBLIC_CHANNEL_NAME },\n ...(list?.channels ?? []).map((channel) => ({ id: channel.id, name: channel.name })),\n ];\n const rows: SelectionSourceRow[] = [];\n for (const entry of order) {\n const count = counts.get(entry.id);\n if (count) rows.push({ channelId: entry.id, name: entry.name, count });\n counts.delete(entry.id);\n }\n // Anything the list does not know about (archived, or a mid-flight rename).\n for (const [channelId, count] of counts) {\n rows.push({\n channelId,\n name: isPublicChannelId(channelId) ? PUBLIC_CHANNEL_NAME : 'Another channel',\n count,\n });\n }\n return rows;\n}\n\n/**\n * Fold every \"this unit is on public sale\" spelling onto ONE id.\n *\n * The allocation map is built from `GET /channels/allocation`, which reports an\n * unallocated unit as the server's `'public'` sentinel; a missing entry means\n * the same thing. Comparing raw values here is what made public units classify\n * as `movedFromOtherChannel` in the staged preview while the server's\n * authoritative reply said `changedFromPublic`.\n */\nfunction normalizeChannelId(id: string | null | undefined): string {\n return isPublicChannelId(id) ? PUBLIC_CHANNEL_ID : id as string;\n}\n\nconst SKIP_SAMPLE = 12;\n\nfunction skipBucket(labels: string[]): AssignmentSkippedBucket {\n return {\n count: labels.length,\n labels: labels.slice(0, SKIP_SAMPLE),\n truncated: labels.length > SKIP_SAMPLE,\n };\n}\n\n/**\n * The LOCAL staged preview of \"move these labels to this channel\".\n *\n * Mirrors the DO's rules exactly (eventChannels.applyAssignment):\n * - a unit already in the target is `alreadyInTarget`, whatever its status;\n * - otherwise held and booked units are skipped and never rewritten;\n * - otherwise a public unit is `changedFromPublic`, a private one is\n * `movedFromOtherChannel` (itemised per source);\n * - a label that is not inventory in this event is `notFound`.\n *\n * Every requested label lands in exactly one bucket — the property the Review\n * sheet's \"every selected seat is in exactly one line\" promise depends on.\n */\nexport function planAssignment(input: {\n labels: string[];\n targetChannelId: string;\n allocation: Map<string, string>;\n statusOf: (label: string) => ChannelSeatStatus | undefined;\n nameOf: (channelId: string) => string | null;\n}): AssignmentBuckets {\n const { labels, allocation, statusOf, nameOf } = input;\n const targetChannelId = normalizeChannelId(input.targetChannelId);\n const seen = new Set<string>();\n let fromPublic = 0;\n let alreadyIn = 0;\n const movedBySource = new Map<string, number>();\n const held: string[] = [];\n const booked: string[] = [];\n const missing: string[] = [];\n\n for (const label of labels) {\n if (seen.has(label)) continue;\n seen.add(label);\n const status = statusOf(label);\n if (!status) { missing.push(label); continue; }\n const current = normalizeChannelId(allocation.get(label));\n if (current === targetChannelId) { alreadyIn += 1; continue; }\n if (status === 'held') { held.push(label); continue; }\n if (status === 'booked') { booked.push(label); continue; }\n if (current === PUBLIC_CHANNEL_ID) fromPublic += 1;\n else movedBySource.set(current, (movedBySource.get(current) ?? 0) + 1);\n }\n\n const channels = [...movedBySource.entries()].map(([channelId, count]) => ({\n channelId,\n name: nameOf(channelId),\n count,\n }));\n return {\n changedFromPublic: { count: fromPublic },\n movedFromOtherChannel: {\n count: channels.reduce((sum, row) => sum + row.count, 0),\n channels,\n },\n alreadyInTarget: { count: alreadyIn },\n skippedHeld: skipBucket(held),\n skippedBooked: skipBucket(booked),\n notFound: skipBucket(missing),\n };\n}\n\n/** Units this plan will actually mutate — what the Apply button counts. */\nexport function mutationCount(buckets: AssignmentBuckets): number {\n return buckets.changedFromPublic.count + buckets.movedFromOtherChannel.count;\n}\n\n/** True when moving inventory out of another PRIVATE channel — §8.5 requires an\n * explicit confirmation line for exactly this case. */\nexport function needsMoveConfirmation(buckets: AssignmentBuckets): boolean {\n return buckets.movedFromOtherChannel.count > 0;\n}\n\nexport interface BucketRow {\n kind: 'add' | 'move' | 'same' | 'skip';\n icon: string;\n count: number;\n text: string;\n why?: string;\n /** Sampled seat labels for a skipped bucket, when the server sent any. */\n peek?: string;\n}\n\n/**\n * Render-ready rows for the Review sheet. The comp shows five lines; the server\n * carries a sixth bucket (`notFound`) which is emitted only when it is non-zero,\n * so a normal review still reads exactly like the approved design.\n *\n * Empty buckets are dropped — a zero line is noise, not honesty.\n */\nexport function bucketRows(buckets: AssignmentBuckets, targetName: string): BucketRow[] {\n const rows: BucketRow[] = [];\n if (buckets.changedFromPublic.count) {\n rows.push({\n kind: 'add', icon: '+', count: buckets.changedFromPublic.count,\n text: `${buckets.changedFromPublic.count.toLocaleString()} from ${PUBLIC_CHANNEL_NAME}`,\n });\n }\n for (const source of buckets.movedFromOtherChannel.channels) {\n rows.push({\n kind: 'move', icon: '⇄', count: source.count,\n text: `${source.count.toLocaleString()} moved out of ${source.name ?? 'another channel'}`,\n why: 'needs this confirmation',\n });\n }\n if (buckets.alreadyInTarget.count) {\n rows.push({\n kind: 'same', icon: '=', count: buckets.alreadyInTarget.count,\n text: `${buckets.alreadyInTarget.count.toLocaleString()} already in ${targetName}`,\n why: 'unchanged',\n });\n }\n if (buckets.skippedHeld.count) {\n rows.push({\n kind: 'skip', icon: '⏸', count: buckets.skippedHeld.count,\n text: `${buckets.skippedHeld.count.toLocaleString()} in a buyer's checkout`,\n why: \"can't move while held\",\n peek: peekOf(buckets.skippedHeld),\n });\n }\n if (buckets.skippedBooked.count) {\n rows.push({\n kind: 'skip', icon: '🔒', count: buckets.skippedBooked.count,\n text: `${buckets.skippedBooked.count.toLocaleString()} already sold`,\n why: 'sales are never rewritten',\n peek: peekOf(buckets.skippedBooked),\n });\n }\n if (buckets.notFound.count) {\n rows.push({\n kind: 'skip', icon: '?', count: buckets.notFound.count,\n text: `${buckets.notFound.count.toLocaleString()} not on this map`,\n why: 'these seats are no longer part of the event',\n peek: peekOf(buckets.notFound),\n });\n }\n return rows;\n}\n\nfunction peekOf(bucket: AssignmentSkippedBucket): string | undefined {\n if (!bucket.labels.length) return undefined;\n const shown = bucket.labels.slice(0, 4).join(', ');\n return bucket.truncated || bucket.labels.length > 4 ? `${shown}…` : shown;\n}\n\n/**\n * \"try again in ~N minutes\" for the archive-blocked-by-holds 409 (§8.8).\n * Rounds up so the organizer never comes back one tick early.\n */\nexport function retryAfterCopy(details: ArchiveBlockedDetails | null | undefined): string {\n const ms = details?.retryAfterMs ?? (details?.latestHoldExpiresAt\n ? Math.max(0, details.latestHoldExpiresAt - Date.now())\n : 0);\n if (!ms) return 'in a moment';\n const minutes = Math.ceil(ms / 60_000);\n if (minutes <= 1) return 'in about a minute';\n return `in about ${minutes} minutes`;\n}\n\n/** The access line under a channel row. Falls back to \"—\" before the hardening\n * branch lands the `access` field, never to a guess. */\nexport function accessLine(access: ChannelAccessSummary | null | undefined): string {\n if (!access || !access.intent) return '—';\n // Every one of the four is a real, enforced answer now (server 2026-08-06), so\n // each gets its own line. 'none' and 'internal' used to collapse into \"not\n // distributed yet\" because nothing read them; today `none` refuses every buyer\n // path and `internal` opens the staff one, and those are different facts.\n const base = access.intent === 'server' ? 'Website integration'\n : access.intent === 'hosted_link' ? 'Buyer link'\n : access.intent === 'internal' ? 'Your staff sell these'\n : 'Protected reserve';\n const grants = access.hasActiveGrants ? 'in use now'\n : access.lastMintAt ? `last used ${new Date(access.lastMintAt).toLocaleDateString()}` : null;\n const detail = access.detail ?? grants;\n return detail ? `${base} · ${detail}` : base;\n}\n\n/**\n * The name of each sale route, WORD FOR WORD as the server says it.\n *\n * `eventChannels.ts` builds its refusal sentences from an `INTENT_LABEL` map\n * with exactly these four strings. Diverging here would mean the picker calls a\n * route one thing and the refusal it produces calls it another, so these are\n * copied deliberately rather than paraphrased.\n */\nexport function accessIntentLabel(intent: ChannelAccessIntent): string {\n return intent === 'internal' ? 'Sell through your own staff'\n : intent === 'server' ? 'Integrate a website or app'\n : intent === 'hosted_link' ? 'Sell with a buyer link'\n : 'Keep as protected reserve';\n}\n\n/**\n * What choosing this route actually DOES, now that the server enforces it.\n *\n * Written against the enforcement matrix, not against intent: each route opens\n * exactly one way to reach a buyer and refuses the other three, so each sentence\n * says both halves. The old copy for these values promised nothing and delivered\n * nothing; it was deleted in 0.42.0 and is not coming back.\n */\nexport function accessIntentDescription(intent: ChannelAccessIntent): string {\n switch (intent) {\n case 'internal':\n return 'Only your own box office can sell these seats, through your secret key. '\n + 'Buyer links and website integrations are refused.';\n case 'server':\n return \"Your website's backend mints each buyer a short-lived session for these seats. \"\n + 'Buyer links are refused; the code lives on the Embed page.';\n case 'hosted_link':\n return 'SeatLayer makes a link you send to a named group. They open it and buy only these seats. '\n + 'No other route can sell them.';\n default:\n return 'Nobody can buy these seats. Every way of letting a buyer in — a buyer link, your website, '\n + 'even your own staff — is refused while this is the route. The seats stay out of public sale.';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Access-intent enforcement refusals (server 2026-08-06)\n// ---------------------------------------------------------------------------\n\n/** `channel_access_intent_forbids` (409) — the route this channel declares is\n * not the one the action needed. */\nexport interface AccessIntentForbidsDetails {\n channelId?: string;\n accessIntent?: ChannelAccessIntent | string;\n /** The route the refused action arrived on: `hosted_link` | `server` | `staff` | `public`. */\n route?: string;\n}\n\n/** Which declaration would have let the refused route through. The server's\n * matrix is one route per intent, so this inverts cleanly. */\nfunction intentForRoute(route: string | undefined): ChannelAccessIntent | null {\n return route === 'hosted_link' ? 'hosted_link'\n : route === 'server' ? 'server'\n : route === 'staff' ? 'internal' : null;\n}\n\n/**\n * The refusal, said as a decision the organizer can act on.\n *\n * The server's own sentence stops at \"…so it cannot be sold through a buyer\n * link\" — true, but it leaves the reader to work out what to do. This adds the\n * second half: which route to switch to. The code itself is never shown.\n */\nexport function intentForbidsCopy(details: AccessIntentForbidsDetails | null | undefined): string {\n const current = parseIntent(details?.accessIntent);\n const wanted = intentForRoute(details?.route);\n const head = `This channel is set to \"${accessIntentLabel(current)}\"`;\n return wanted\n ? `${head}, so it cannot do that. Switch it to \"${accessIntentLabel(wanted)}\" first.`\n : `${head}, so it cannot do that. Choose a different route for this channel first.`;\n}\n\n/** `channel_intent_switch_blocked` (409) — buyers are inside the current route. */\nexport interface IntentSwitchBlockedDetails {\n channelId?: string;\n from?: ChannelAccessIntent | string;\n to?: ChannelAccessIntent | string;\n liveAccessLinks?: number;\n activeSessions?: number;\n acknowledgeWith?: { acknowledgeLiveAccess?: boolean };\n}\n\nfunction parseIntent(value: unknown): ChannelAccessIntent {\n return value === 'internal' || value === 'server' || value === 'hosted_link' || value === 'none'\n ? value : 'none';\n}\n\nfunction plural(count: number, one: string, many: string): string {\n return `${count.toLocaleString()} ${count === 1 ? one : many}`;\n}\n\n/**\n * What is live right now, and what acknowledging would do to it.\n *\n * Both halves are checked against the server rather than guessed: an\n * acknowledged switch REVOKES the channel's hosted links (redemption refuses\n * from that moment, so a link left listed as active would be a door the\n * management surface advertises and the buyer path denies), and deliberately\n * LEAVES buyer sessions and their holds alone — nobody is thrown out of a\n * checkout. Sessions cap at 12 hours (30 minutes by default) and no new ones can\n * be minted, so the old route drains on its own.\n */\nexport function intentSwitchBlockedCopy(\n details: IntentSwitchBlockedDetails | null | undefined,\n): { headline: string; consequences: string[] } {\n const links = Math.max(0, details?.liveAccessLinks ?? 0);\n const sessions = Math.max(0, details?.activeSessions ?? 0);\n const from = parseIntent(details?.from);\n const to = parseIntent(details?.to);\n const live = [\n links ? plural(links, 'buyer link is live', 'buyer links are live') : null,\n sessions ? plural(sessions, 'buyer is in a checkout', 'buyers are in a checkout') : null,\n ].filter(Boolean).join(', and ');\n const headline = `${live || 'Buyers are inside this channel'} on \"${accessIntentLabel(from)}\". `\n + `Moving it to \"${accessIntentLabel(to)}\" changes what happens to them.`;\n const consequences: string[] = [];\n if (links) {\n consequences.push(`${plural(links, 'buyer link closes', 'buyer links close')} immediately. `\n + 'Anyone who has not opened it yet never will — send a new link if you still need one.');\n }\n if (sessions) {\n consequences.push(`${plural(sessions, 'buyer who is already in a checkout keeps', 'buyers who are already in a checkout keep')} `\n + 'their seats and can finish paying. Nobody is thrown out. No new buyers come in this way, '\n + 'so the old route empties on its own within 12 hours.');\n }\n return { headline, consequences };\n}\n\n// ---------------------------------------------------------------------------\n// Hosted access links (M8)\n// ---------------------------------------------------------------------------\n\n/** Lifecycle the server stores. `rotated` means a newer link replaced this one. */\nexport type AccessLinkState = 'active' | 'revoked' | 'rotated';\n\n/** What the organizer surface renders: `state`, unless an active link has run\n * out of time or out of redemptions. Never a capability, never a hash. */\nexport type AccessLinkStatus = AccessLinkState | 'expired' | 'exhausted';\n\n/**\n * One hosted link, exactly as `GET …/access-links` projects it.\n *\n * There is deliberately NO `url` and NO `capability` field here — the listing\n * route does not return them, no other route returns them, and this type must\n * not tempt a caller into believing otherwise. The secret exists in exactly one\n * place for exactly one moment: the create/rotate response (`AccessLinkReveal`).\n */\nexport interface AccessLinkRecord {\n id: string;\n channelId: string;\n label: string | null;\n includePublic: boolean;\n expiresAt: number;\n maxRedemptions: number;\n redemptions: number;\n /** Guest-weighted per-buyer ceiling handed to every session this link mints. */\n maxQuantity: number;\n sessionTtlSeconds: number;\n state: AccessLinkState;\n status: AccessLinkStatus;\n createdAt: number;\n createdBy: string | null;\n revokedAt: number | null;\n lastRedeemedAt: number | null;\n /** Rotation lineage: the link this replaced, and the one that replaced it. */\n rotatedFrom: string | null;\n rotatedTo: string | null;\n}\n\n/** A listed link, with the live session count the rotate dialog needs to state\n * \"N buyers got in with this link and still have access\". */\nexport interface AccessLinkStatusRecord extends AccessLinkRecord {\n activeSessions?: number;\n}\n\n/**\n * The ONE-TIME reveal. `url` and `capability` are on the wire exactly once, in\n * the create/rotate response, and are unrecoverable afterwards: SeatLayer stores\n * only a hash. Nothing may persist this — see `ChannelsMode.revealLink`.\n */\nexport interface AccessLinkReveal {\n link: AccessLinkRecord;\n url: string;\n capability: string;\n revealedOnce: true;\n /** Rotation only: the link that just stopped working, and how many live buyer\n * sessions from it were ended (0 when the organizer let them finish). */\n previous?: AccessLinkRecord;\n endedSessions?: number;\n}\n\n/**\n * Owner-set defaults for a new link. Expiry is NOT here: \"when the event starts\"\n * is the server's own default (it knows `starts_at`; the cockpit does not), so\n * the create form expresses that choice by omitting `expiresAt` entirely rather\n * than by guessing a timestamp the server would then have to correct.\n */\nexport const ACCESS_LINK_DEFAULTS = {\n maxRedemptions: 100,\n maxQuantity: 4,\n} as const;\n\n/** Plain-language state badge for a hosted link (§9: no internal vocabulary). */\nexport function accessLinkBadge(link: Pick<AccessLinkRecord, 'status' | 'state'>): {\n text: string; kind: 'active' | 'paused' | 'archived';\n} {\n switch (link.status ?? link.state) {\n case 'active': return { text: 'Active', kind: 'active' };\n case 'expired': return { text: 'Expired', kind: 'archived' };\n case 'exhausted': return { text: 'All used', kind: 'paused' };\n case 'rotated': return { text: 'Replaced', kind: 'archived' };\n default: return { text: 'Revoked', kind: 'archived' };\n }\n}\n\n/** Only an `active` link can be rotated or revoked; the server agrees (409\n * `access_link_not_active`), so the buttons are absent rather than failing. */\nexport function accessLinkIsLive(link: Pick<AccessLinkRecord, 'status' | 'state'>): boolean {\n return link.state === 'active' && link.status === 'active';\n}\n\nfunction formatMoment(ms: number): string {\n if (!Number.isFinite(ms)) return '—';\n return new Date(ms).toLocaleString(undefined, {\n day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: '2-digit',\n });\n}\n\n/**\n * The policy an organizer is agreeing to, in one list. Used by BOTH the reveal\n * (what you just created) and the status card (what is live), so the two can\n * never drift into describing the same link differently.\n */\nexport function accessLinkPolicyLines(link: AccessLinkRecord): Array<{ k: string; v: string }> {\n return [\n { k: 'Expires', v: formatMoment(link.expiresAt) },\n {\n k: 'Redemptions',\n v: `${link.redemptions.toLocaleString()} of ${link.maxRedemptions.toLocaleString()} used`,\n },\n {\n k: 'Seats per buyer',\n v: `${link.maxQuantity.toLocaleString()} seat${link.maxQuantity === 1 ? '' : 's'} maximum`,\n },\n {\n k: 'Covers',\n v: link.includePublic\n ? \"This channel's allocation and Public sale seats\"\n : \"This channel's allocation only\",\n },\n ];\n}\n\n/**\n * Plain language for a refused hosted-link call.\n *\n * The PLATFORM BOUNDS live on the server (60s–180d expiry, 1–10 000 redemptions,\n * 1–100 seats per buyer, 20 live links per channel) and the server states them\n * in `message`. We surface that sentence rather than re-encoding the numbers\n * here, so the client can never disagree with the rule it is reporting.\n */\nexport function accessLinkErrorCopy(\n err: {\n code?: string; serverMessage?: string; status?: number; details?: Record<string, unknown>;\n } | null | undefined,\n): string {\n const fromServer = err?.serverMessage?.trim();\n switch (err?.code) {\n case 'invalid_expiry':\n case 'invalid_max_redemptions':\n case 'invalid_max_quantity':\n case 'invalid_session_ttl':\n case 'invalid_label':\n return fromServer || 'That setting is outside what a hosted link allows. Adjust it and try again.';\n case 'too_many_access_links':\n return fromServer\n || 'This channel already has as many live links as it can hold. Revoke one before creating another.';\n case 'access_link_not_active':\n return 'That link is no longer active, so it cannot be rotated or revoked.';\n case 'channel_unavailable':\n return 'This channel is paused or archived, so it cannot let new buyers in. Resume it first.';\n // The channel declares a different sale route. The UI declares `hosted_link`\n // before it creates, so reaching this means the declaration itself was\n // refused or raced — say which route is in the way, not the code.\n case 'channel_access_intent_forbids':\n return intentForbidsCopy(err?.details as AccessIntentForbidsDetails | undefined);\n case 'end_active_sessions_required':\n return 'Choose what happens to the buyers who already came in through this link.';\n case 'not_found':\n return 'That link is no longer here. Refresh and try again.';\n default:\n if (err?.status === 403) return 'Hosted access links need channel-management permission.';\n return fromServer || 'That did not go through. Try again.';\n }\n}\n\n/**\n * The chart-update refusal `channel_assignment_would_drop` (409) deliberately\n * mirrors the Apply skipped buckets, so ONE review component renders both.\n * This adapts it into the same `BucketRow[]` the Review sheet already draws.\n */\nexport interface AssignmentDropDetails {\n droppedUnits?: number;\n channels?: Array<{ channelId: string; name: string | null; count: number; labels?: string[]; truncated?: boolean }>;\n acknowledgeWith?: string;\n}\n\nexport function dropReviewRows(details: AssignmentDropDetails | null | undefined): BucketRow[] {\n return (details?.channels ?? []).map((channel) => ({\n kind: 'skip' as const,\n icon: '⚠',\n count: channel.count,\n text: `${channel.count.toLocaleString()} would leave ${channel.name ?? 'a channel'}`,\n why: 'the new chart no longer has these seats',\n peek: channel.labels?.length\n ? peekOf({ count: channel.count, labels: channel.labels, truncated: channel.truncated ?? false })\n : undefined,\n }));\n}\n\n/** Plain-language state badge text (§9: no internal vocabulary on user surfaces). */\nexport function stateBadge(state: ChannelState | 'builtin'): string {\n return state === 'builtin' ? 'Built-in'\n : state === 'active' ? 'Active'\n : state === 'paused' ? 'Paused' : 'Archived';\n}\n","/**\n * Organizer manage-surface client for workers/api (the `/v1/events/:key/*`\n * inventory routes + the public realtime channel). Companion to api.ts (the\n * buyer `/pub/*` client) — kept separate because the manage surface is\n * token-authed (Bearer) and cross-origin from the CMS:\n *\n * - Writes + reports send `Authorization: Bearer <token>` where the token is\n * a short-lived, event-scoped organizer manage token (`mse_…`, minted by\n * NestJS) OR a tenant secret key (`sk_…`). Both are accepted by the worker's\n * `eitherAuth` on block / unblock / unblock-all / unbook / hold-ttl / report\n * / log. The Authorization header also exempts the call from the worker's\n * cookie-CSRF gate, so no extra client header is needed.\n * - `credentials: 'omit'` — there is no session cookie; the CMS runs\n * cross-origin. The worker's credentialed CORS still echoes the CMS origin.\n * - `/pub/events/:key/chart` stays public: geometry is the same map buyers\n * see. The seat STATE reads are not. `/pub/.../objects` and an unticketed\n * `/pub/.../subscribe` both answer with the BUYER projection, which shows\n * inventory the caller may not buy as a neutral `blocked` — so an organizer\n * reading them sees its own channel allocations as blocked seats. Both now\n * go through the token: `/v1/events/:key/objects` for the snapshot, and a\n * `/v1/events/:key/subscribe-tickets` mint for the socket's scope.\n *\n * `box-book` is intentionally omitted for M1 (box office ships in M2, and the\n * route is still session-only server-side).\n */\nimport type { AvailabilityRule, ChartDoc } from '@seatlayer/core';\nimport type {\n AccessLinkRecord,\n AccessLinkReveal,\n AccessLinkStatusRecord,\n AssignmentResult,\n ChannelAccessIntent,\n ChannelListResult,\n ChannelRecord,\n} from './channelPlan';\n\nexport type { AvailabilityRule } from '@seatlayer/core';\n\n/** One page of the organizer-only label → channel projection. */\nexport interface ChannelAllocationPage {\n assignmentVersion: number;\n allocations: Array<{ label: string; channelId: string }>;\n nextAfterLabel: string | null;\n}\n\nexport interface ChannelAuditEntry {\n id: number;\n at: number;\n actor: string | null;\n action: string;\n channelId: string | null;\n assignmentVersion: number;\n before: unknown;\n after: unknown;\n reason: string | null;\n}\n\nexport interface ChannelAuditPage {\n entries: ChannelAuditEntry[];\n nextBefore: number | null;\n}\n\n/**\n * Buyer projection for a preview audience — the same scoped server view the\n * buyer SDK receives. When an audience cannot be previewed (a paused or\n * archived channel), the server answers `{available:false, unavailable:[…]}`\n * and the UI shows the real paused/unavailable landing state instead of\n * rendering those seats as eligible.\n *\n * Fields stay optional: a worker that predates the hardening merge 404s here,\n * and Channels mode says the preview needs a newer server rather than faking a\n * projection client-side.\n */\nexport interface ChannelPreviewProjection {\n available?: boolean;\n unavailable?: Array<{ channelId: string; state: 'paused' | 'archived' | string }>;\n channelIds?: string[];\n includePublic?: boolean;\n /** Labels this audience may buy. Everything else renders as ONE neutral\n * unavailable state so preview never leaks which channel holds a seat. */\n eligible?: string[];\n counts?: { eligible?: number; free?: number; held?: number; booked?: number };\n}\n\nexport class ManageApiError extends Error {\n status: number;\n code?: string;\n /** Present when a block/unbook 409s because seats were just taken. */\n conflicts?: { label: string; reason?: string }[];\n /**\n * Structured refusal detail. The channel routes use it for the two 409s a UI\n * must render rather than merely report: `channel_archive_blocked_by_holds`\n * carries {activeHolds, heldUnits, latestHoldExpiresAt, retryAfterMs}, and\n * `channel_assignment_conflict` carries the current assignmentVersion.\n */\n details?: Record<string, unknown>;\n /**\n * The server's own human sentence, when it sent one. `message` is the machine\n * code (that is what `error` carries), so a UI that wants to state a PLATFORM\n * RULE — \"redemptions must be between 1 and 10 000\" — reads this instead of\n * re-encoding the bound locally and risking disagreement with the server.\n */\n serverMessage?: string;\n\n constructor(\n status: number,\n message: string,\n code?: string,\n conflicts?: { label: string; reason?: string }[],\n details?: Record<string, unknown>,\n serverMessage?: string,\n ) {\n super(message);\n this.name = 'ManageApiError';\n this.status = status;\n this.code = code;\n this.conflicts = conflicts;\n this.details = details;\n this.serverMessage = serverMessage;\n }\n}\n\nexport interface ReportByStatus {\n free: number;\n held: number;\n booked: number;\n not_for_sale: number;\n}\n\nexport interface ReportCategoryRow {\n category: string;\n total: number;\n free: number;\n held: number;\n booked: number;\n not_for_sale: number;\n /** Exact sum of booked unit_price snapshots, in major currency units. */\n bookedRevenue: number;\n}\n\nexport interface ReportCategoryMeta {\n key: string;\n label: string;\n color: string;\n price: number;\n}\n\nexport interface ReportResult {\n report: { byStatus: ReportByStatus; byCategory: ReportCategoryRow[]; bySection?: ControlRoomSectionMetric[] };\n event: { key: string; name: string; seatTotal: number; currency?: string };\n categories: ReportCategoryMeta[];\n}\n\nexport interface ControlRoomSectionMetric {\n sectionId: string;\n sectionLabel: string;\n zoneId: string | null;\n total: number;\n free: number;\n held: number;\n booked: number;\n not_for_sale: number;\n bookedRevenue: number;\n}\n\n/** Recent seat-state change safe for an event:view control-room grant. Full\n * audit references remain available only through the event:reports log API. */\nexport interface ControlRoomActivityEntry {\n id: number;\n at: number;\n action: string;\n labels: string[];\n}\n\nexport interface ControlRoomSnapshot {\n version: number;\n currency: string;\n totals: { free: number; held: number; booked: number; blocked: number };\n revenue: { gross: number; bySection: ControlRoomSectionMetric[] };\n velocity: {\n windowMinutes: number;\n bySection: Array<{\n sectionId: string;\n netBooked: number;\n grossRevenue: number;\n previousNetBooked: number;\n trend: 'rising' | 'steady' | 'cooling';\n }>;\n };\n presence: { shoppingSessions: number; activeHolds: number };\n /** Present on workers that support reload-safe activity hydration. */\n activity?: ControlRoomActivityEntry[];\n event: { key: string; name: string; seatTotal: number; currency?: string };\n}\n\nexport interface LogEntry {\n id: number;\n at: number;\n action: string;\n labels: string[];\n ref: string | null;\n}\n\nexport interface LogPage {\n entries: LogEntry[];\n nextBefore: number | null;\n}\n\n/**\n * A one-use WebSocket subscribe ticket. `protocols` is exactly what to hand\n * `new WebSocket(url, protocols)` — the ticket rides in `Sec-WebSocket-Protocol`\n * because a browser socket cannot carry an Authorization header and a bearer\n * must never travel in a URL.\n */\nexport interface SubscribeTicket {\n ticket: string;\n expiresAt: number;\n protocol: string;\n protocols: string[];\n}\n\nexport interface PubObjectsResult {\n /** Every non-free seat's status keyed by label (free seats omitted). */\n seats: Record<string, string>;\n hidden?: string[];\n closed?: string[];\n updatedAt: number;\n}\n\nexport interface PubChartResult {\n event: {\n key: string;\n name: string;\n status?: string;\n venue?: string | null;\n startsAt?: number | null;\n currency?: string;\n mode?: string;\n };\n doc: ChartDoc;\n}\n\nasync function parse<T>(res: Response): Promise<T> {\n const isJson = (res.headers.get('content-type') ?? '').includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : null;\n if (!res.ok) {\n const err = data as {\n error?: string;\n code?: string;\n conflicts?: { label: string; reason?: string }[];\n details?: Record<string, unknown>;\n message?: string;\n } | null;\n throw new ManageApiError(\n res.status,\n err?.error ?? `request_failed_${res.status}`,\n err?.code,\n err?.conflicts,\n err?.details,\n typeof err?.message === 'string' ? err.message : undefined,\n );\n }\n return data as T;\n}\n\n/**\n * Bound to one apiBase + one event-scoped token. Rebuild (or `setToken`) when a\n * token is re-minted on 401.\n */\nexport class ManageApi {\n private base: string;\n private token: string;\n\n constructor(apiBase: string, token: string) {\n this.base = apiBase.replace(/\\/+$/, '');\n this.token = token;\n }\n\n /** Swap the Bearer token in place (SeatManager re-mints on 401). */\n setToken(token: string): void {\n this.token = token;\n }\n\n private auth<T>(\n path: string,\n init: { method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'; body?: unknown } = {},\n ): Promise<T> {\n const method = init.method ?? 'GET';\n const headers: Record<string, string> = { Authorization: `Bearer ${this.token}` };\n let body: string | undefined;\n if (init.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(init.body);\n }\n return fetch(`${this.base}${path}`, { method, headers, body, credentials: 'omit' }).then((r) => parse<T>(r));\n }\n\n private pub<T>(path: string): Promise<T> {\n return fetch(`${this.base}${path}`, { credentials: 'omit' }).then((r) => parse<T>(r));\n }\n\n // ---- realtime read ----\n\n /** The chart geometry. Genuinely public — it is the same map buyers see. */\n chart(key: string): Promise<PubChartResult> {\n return this.pub(`/pub/events/${encodeURIComponent(key)}/chart`);\n }\n\n /**\n * The ORGANIZER's seat map: physical state, token-authed.\n *\n * This used to read `/pub/events/:key/objects` with no credential, which\n * answers with the BUYER projection — every unit the caller may not buy\n * collapses to a neutral `blocked`. An anonymous caller may buy only Public\n * sale inventory, so the cockpit rendered every channel-allocated seat as\n * blocked and then computed its KPIs, sell-through and (worse) its\n * block/unblock target sets from that. `/v1/events/:key/objects` returns the\n * unprojected snapshot the control-room read model already trusts.\n */\n objects(key: string): Promise<PubObjectsResult> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/objects`);\n }\n\n /**\n * Exchange the manage token for a one-use organizer socket ticket.\n *\n * A browser `WebSocket` cannot send an Authorization header, so the socket's\n * scope is established here, over ordinary HTTPS. Without it the DO treats a\n * manager socket as an anonymous public buyer and projects its deltas — so a\n * hold inside a private allocation is structurally suppressed and the map\n * drifts away from the truth `objects()` just established.\n *\n * Tickets are single-redemption and expire in ~30s: mint one per connect.\n */\n subscribeTicket(key: string): Promise<SubscribeTicket> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/subscribe-tickets`, { method: 'POST' });\n }\n\n socketUrl(key: string): string {\n return `${this.base.replace(/^http/, 'ws')}/pub/events/${encodeURIComponent(key)}/subscribe?surface=manager`;\n }\n\n // ---- inventory writes (token) ----\n\n /** Take FREE seats off sale in one batched call. Optional `releaseAt` (epoch\n * ms, future) auto-returns them to sale; `reason` tags the block (M3 uses it).\n * Throws ManageApiError 409 (conflicts) if any seat was just taken. */\n block(\n key: string,\n labels: string[],\n opts: { releaseAt?: number; reason?: string } = {},\n ): Promise<{ ok: true; blocked: string[] }> {\n const body: Record<string, unknown> = { labels };\n if (typeof opts.releaseAt === 'number') body.releaseAt = opts.releaseAt;\n if (opts.reason) body.reason = opts.reason;\n return this.auth(`/v1/events/${encodeURIComponent(key)}/block`, { method: 'POST', body });\n }\n\n /** Return specific blocked seats to sale (one batched call). */\n unblock(key: string, labels: string[]): Promise<{ ok: true; unblocked: string[] }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/unblock`, { method: 'POST', body: { labels } });\n }\n\n /** Return every blocked seat to sale; resolves with the freed count. */\n unblockAll(key: string): Promise<{ ok: true; freed: number }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/unblock-all`, { method: 'POST' });\n }\n\n /** Cancel bookings — return BOOKED seats to free (credit not refunded).\n * Guarded by the original booking reference. */\n unbook(key: string, labels: string[], bookingRef: string): Promise<{ ok: true; unbooked: string[] }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/unbook`, { method: 'POST', body: { labels, bookingRef } });\n }\n\n /** Set (ms, clamped 1–60 min server-side) or clear (null) the hold TTL. */\n setHoldTtl(key: string, holdTtlMs: number | null): Promise<{ ok: true; holdTtlMs: number | null }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/hold-ttl`, { method: 'POST', body: { holdTtlMs } });\n }\n\n // ---- availability windows (token) ----\n\n /** The organizer's current per section/zone availability windows (needs\n * `event:view`). Ids absent from `rules` are open / on sale. */\n availability(key: string): Promise<{ rules: Record<string, AvailabilityRule> }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/availability`);\n }\n\n /** Replace the availability windows for a set of section/zone ids (needs\n * `event:block`). Ids absent from `rules` become open / on sale; a zone rule\n * cascades to its sections. The worker derives each id's seat labels, so\n * `labels` on the sent rules is best-effort. Resolves with the authoritative\n * effective `hidden` set (a due rule may fire at once) and the server-cleaned\n * `rules` map (fired timed/threshold windows dropped). */\n setAvailability(\n key: string,\n rules: Record<string, AvailabilityRule>,\n ): Promise<{ ok: true; hidden: string[]; rules: Record<string, AvailabilityRule> }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/availability`, { method: 'POST', body: { rules } });\n }\n\n // ---- sales channels (token, capability-gated) ----\n // Reads need `event:channels:view`, mutations `event:channels:manage`.\n // `event:block` grants NEITHER (spec §10), so a Block-only cockpit token gets\n // a 403 here and Channels mode never renders.\n\n /** Allocation list with exact per-channel counts. `includeArchived` adds the\n * read-only archived rows behind the rail's \"Show archived\" control. */\n channels(key: string, opts: { includeArchived?: boolean } = {}): Promise<ChannelListResult> {\n const qs = opts.includeArchived ? '?includeArchived=1' : '';\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels${qs}`);\n }\n\n /** One page of the label → channel map that paints the allocation overlay.\n * Paged by label; follow `nextAfterLabel` until it is null. */\n channelAllocation(\n key: string,\n opts: { afterLabel?: string; limit?: number } = {},\n ): Promise<ChannelAllocationPage> {\n const params = new URLSearchParams();\n if (opts.afterLabel) params.set('afterLabel', opts.afterLabel);\n if (opts.limit != null) params.set('limit', String(opts.limit));\n const qs = params.toString();\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/allocation${qs ? `?${qs}` : ''}`);\n }\n\n channelAudit(key: string, opts: { limit?: number; before?: number } = {}): Promise<ChannelAuditPage> {\n const params = new URLSearchParams();\n if (opts.limit != null) params.set('limit', String(opts.limit));\n if (opts.before != null) params.set('before', String(opts.before));\n const qs = params.toString();\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/audit${qs ? `?${qs}` : ''}`);\n }\n\n createChannel(\n key: string,\n input: { name: string; color?: string | null; marker?: string | null; externalRef?: string | null },\n ): Promise<{ ok: true; channel: ChannelRecord }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels`, { method: 'POST', body: input });\n }\n\n renameChannel(key: string, channelId: string, name: string): Promise<{ ok: true; channel: ChannelRecord }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}`, {\n method: 'PATCH', body: { name },\n });\n }\n\n setChannelPaused(key: string, channelId: string, paused: boolean): Promise<{ ok: true; channel: ChannelRecord }> {\n const path = paused ? 'pause' : 'unpause';\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/${path}`,\n { method: 'POST', body: {} },\n );\n }\n\n /** Archive with a mandatory destination for the remaining allocation.\n * Throws ManageApiError 409 `channel_archive_blocked_by_holds` while any hold\n * is live; `err.details` carries the exact counts + retry window. */\n archiveChannel(\n key: string,\n channelId: string,\n destination: string | null,\n ): Promise<{ ok: true; channel: ChannelRecord; assignmentVersion: number; moved: number }> {\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/archive`,\n { method: 'POST', body: { destination } },\n );\n }\n\n /**\n * Versioned Apply. A stale `assignmentVersion` mutates NOTHING and throws\n * ManageApiError 409 `channel_assignment_conflict` — the caller keeps its\n * selection and offers \"Refresh and review\". There is no dry-run: the review\n * sheet previews locally, this call returns the authoritative buckets.\n */\n applyChannelAssignment(\n key: string,\n input: { targetChannelId: string | null; labels: string[]; assignmentVersion: number },\n ): Promise<AssignmentResult> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/assignments`, {\n method: 'POST',\n body: {\n targetChannelId: input.targetChannelId || null,\n labels: input.labels,\n assignmentVersion: input.assignmentVersion,\n },\n });\n }\n\n /**\n * Read-only buyer projection for an audience (§8.6) — the SAME scoped server\n * view the buyer SDK receives, never a local approximation.\n *\n * Ships on the access-hardening branch. Older workers 404/405 here; callers\n * MUST feature-detect and quietly say the preview needs a newer server rather\n * than faking a projection client-side.\n */\n channelPreview(\n key: string,\n channelIds: string[],\n opts: { includePublic?: boolean } = {},\n ): Promise<ChannelPreviewProjection> {\n const params = new URLSearchParams();\n if (channelIds.length) params.set('channelIds', channelIds.join(','));\n if (opts.includePublic != null) params.set('includePublic', opts.includePublic ? '1' : '0');\n const qs = params.toString();\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/preview${qs ? `?${qs}` : ''}`);\n }\n\n /**\n * Choose which sale route this channel opens.\n *\n * Since the server's 2026-08-06 change this is AUTHORIZATION, not a label:\n * exactly one of the four routes may mint buyer access for the channel and the\n * other three refuse with 409 `channel_access_intent_forbids`. The default is\n * `none`, which refuses all four — so a route has to be declared before any\n * buyer-facing action on the channel can succeed.\n *\n * Switching the route while buyers are already inside the current one is\n * refused with 409 `channel_intent_switch_blocked`, whose `details` name what\n * is live (`liveAccessLinks`, `activeSessions`). Retry with\n * `acknowledgeLiveAccess: true`: hosted links on the channel are revoked,\n * while sessions already minted keep their holds and drain on their own.\n * `intentSwitch` is present on the response ONLY when the switch disturbed\n * something, so the ordinary case stays the two-key body it has always been.\n */\n setChannelAccessIntent(\n key: string,\n channelId: string,\n accessIntent: ChannelAccessIntent,\n opts: { acknowledgeLiveAccess?: boolean; reason?: string } = {},\n ): Promise<{\n ok: true;\n channel: ChannelRecord;\n intentSwitch?: { closedLinks: number; keptSessions: number };\n }> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}`, {\n method: 'PATCH',\n body: {\n accessIntent,\n ...(opts.acknowledgeLiveAccess ? { acknowledgeLiveAccess: true } : {}),\n ...(opts.reason ? { reason: opts.reason } : {}),\n },\n });\n }\n\n // ---- hosted access links (M8) ----\n\n /**\n * Mint a hosted access link. The 201 is the ONE and ONLY time `url` and\n * `capability` exist outside the buyer's browser — SeatLayer keeps a hash, so\n * there is no route, cache, or support escalation that can produce this string\n * again. Callers must reveal it immediately and then let it go.\n *\n * Every omitted field takes the server's default: expiry = when the event\n * starts, 100 redemptions, 4 seats per buyer, this channel's allocation only.\n * Platform bounds are enforced server-side and reported as 422 with the rule\n * spelled out in `ManageApiError.serverMessage`.\n *\n * NOT a side effect any more. This used to SET the channel's access intent to\n * `hosted_link`; since 2026-08-06 it REQUIRES it, and a channel declaring any\n * other route refuses with 409 `channel_access_intent_forbids`. Callers must\n * declare the route first — `ChannelsMode` does exactly that before it\n * creates, so a first buyer link on a fresh channel is still one gesture.\n */\n createAccessLink(\n key: string,\n channelId: string,\n input: {\n label?: string | null;\n /** Absolute epoch ms. Omit for \"when the event starts\". */\n expiresAt?: number;\n maxRedemptions?: number;\n maxQuantity?: number;\n includePublic?: boolean;\n } = {},\n ): Promise<AccessLinkReveal> {\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/access-links`,\n { method: 'POST', body: input },\n );\n }\n\n /** Status only — label, expiry, redemptions, per-buyer cap, lineage, and the\n * live session count. Never the url, never the capability. Needs `:view`. */\n accessLinks(key: string, channelId: string): Promise<{ links: AccessLinkStatusRecord[] }> {\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/access-links`,\n );\n }\n\n /**\n * Rotate — the ONLY recovery for a link nobody kept. The old URL stops opening\n * immediately and the response is a fresh one-time reveal.\n *\n * `endActiveSessions` is REQUIRED, not defaulted: the organizer must say\n * whether buyers already inside finish their checkout or lose access now. The\n * server answers 422 `end_active_sessions_required` if it is omitted, and that\n * refusal is correct — a UI must not pick either branch on their behalf.\n */\n rotateAccessLink(\n key: string,\n channelId: string,\n linkId: string,\n endActiveSessions: boolean,\n ): Promise<AccessLinkReveal & { previous: AccessLinkRecord; endedSessions: number }> {\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}`\n + `/access-links/${encodeURIComponent(linkId)}/rotate`,\n { method: 'POST', body: { endActiveSessions } },\n );\n }\n\n /** Revoke. The link stops opening immediately; `endActiveSessions` decides\n * whether the buyers already inside keep their sessions. */\n revokeAccessLink(\n key: string,\n channelId: string,\n linkId: string,\n endActiveSessions = false,\n ): Promise<{ ok: true; link: AccessLinkRecord; endedSessions: number }> {\n const qs = endActiveSessions ? '?endActiveSessions=1' : '';\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}`\n + `/access-links/${encodeURIComponent(linkId)}${qs}`,\n { method: 'DELETE' },\n );\n }\n\n // ---- reports (token) ----\n\n report(key: string): Promise<ReportResult> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/report`);\n }\n\n controlRoom(key: string, windowMinutes = 15): Promise<ControlRoomSnapshot> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/control-room?window=${windowMinutes}`);\n }\n\n log(key: string, opts: { limit?: number; before?: number } = {}): Promise<LogPage> {\n const params = new URLSearchParams();\n if (opts.limit != null) params.set('limit', String(opts.limit));\n if (opts.before != null) params.set('before', String(opts.before));\n const qs = params.toString();\n return this.auth(`/v1/events/${encodeURIComponent(key)}/log${qs ? `?${qs}` : ''}`);\n }\n\n /** CSV report as a Blob (Bearer auth can't ride a plain <a href>). Host builds\n * an object URL for download. */\n async reportCsv(key: string): Promise<Blob> {\n const res = await fetch(`${this.base}/v1/events/${encodeURIComponent(key)}/report.csv`, {\n headers: { Authorization: `Bearer ${this.token}` },\n credentials: 'omit',\n });\n if (!res.ok) throw new ManageApiError(res.status, `request_failed_${res.status}`);\n return res.blob();\n }\n}\n","/**\n * Channels mode — the sales-channel management surface inside the SeatManager\n * cockpit. It ships in the SDK, so every embedding platform (and our own Control\n * Room) gets the same organizer experience.\n *\n * Design contract: `SeatmapUX/05 Event Manager.dc.html` (all 8 desktop states +\n * the mobile artboard). Behaviour: sales-channels-product-ux-spec §8 (states),\n * §9 (language), §13 (a11y + compact detents). Motion: motion-system §2 tokens,\n * mirrored here as `--slm-mo-*` so an embed is self-contained, and §3 cockpit\n * choreography.\n *\n * Boundaries this module keeps:\n *\n * - **Capability gating is fail-closed.** Without `event:channels:view` the\n * cockpit never renders the pill (SeatManager's job). Without\n * `event:channels:manage` every mutation control is ABSENT — not disabled —\n * so a read-only operator is never shown authority they do not have.\n * - **Nothing here mutates physical inventory.** Assignment moves an\n * allocation; held and booked units are never rewritten.\n * - **Staging is local, truth is the server.** There is no dry-run endpoint,\n * so the Review sheet previews the buckets client-side and then re-renders\n * the AUTHORITATIVE bucket counts from the Apply response. A stale\n * `assignmentVersion` mutates nothing: the selection survives and the only\n * action offered is Refresh and review.\n * - **Forward-compatible reads.** The `access` field and the buyer-preview\n * projection land on the access-hardening branch. Both are feature-detected;\n * absent, the access line reads \"—\" and the Preview segment says it needs a\n * newer server. Neither ever blocks allocation work.\n */\nimport {\n ACCESS_LINK_DEFAULTS,\n PUBLIC_CHANNEL_ID,\n PUBLIC_CHANNEL_NAME,\n accessIntentDescription,\n accessIntentLabel,\n accessLine,\n accessLinkBadge,\n accessLinkErrorCopy,\n accessLinkIsLive,\n accessLinkPolicyLines,\n bucketRows,\n isPublicChannelId,\n markerLetter,\n markerOf,\n mutationCount,\n needsMoveConfirmation,\n planAssignment,\n intentForbidsCopy,\n intentSwitchBlockedCopy,\n retryAfterCopy,\n selectionSources,\n stateBadge,\n suggestMarker,\n type AccessIntentForbidsDetails,\n type AccessLinkReveal,\n type AccessLinkStatusRecord,\n type AssignmentBuckets,\n type AssignmentResult,\n type ArchiveBlockedDetails,\n type BucketRow,\n type IntentSwitchBlockedDetails,\n type ChannelAccessIntent,\n type ChannelListResult,\n type ChannelRecord,\n type ChannelSeatStatus,\n} from './channelPlan';\nimport type {\n ChannelAllocationPage,\n ChannelPreviewProjection,\n} from './manageApi';\nimport { ManageApiError } from './manageApi';\n\n/** The seat facts the overlay needs. Chart space, not screen space. */\nexport interface ChannelsSeatView {\n id: string;\n label: string;\n x: number;\n y: number;\n}\n\n/** One row offered to the bulk assignment chooser. A physically segmented row\n * (one label split across several row objects) shares one logical id, so the\n * organizer picks \"Row AA\" once rather than three fragments of it. */\nexport interface ChannelsRowView {\n id: string;\n label: string;\n sectionId: string;\n sectionLabel: string;\n labels: string[];\n}\n\n/** The `ManageApi` subset Channels mode uses — structural so tests can pass a\n * hand-rolled double without constructing a real client. */\nexport interface ChannelsClient {\n channels(key: string, opts?: { includeArchived?: boolean }): Promise<ChannelListResult>;\n channelAllocation(key: string, opts?: { afterLabel?: string; limit?: number }): Promise<ChannelAllocationPage>;\n createChannel(\n key: string,\n input: { name: string; color?: string | null; marker?: string | null; externalRef?: string | null },\n ): Promise<{ ok: true; channel: ChannelRecord }>;\n renameChannel(key: string, channelId: string, name: string): Promise<{ ok: true; channel: ChannelRecord }>;\n setChannelPaused(key: string, channelId: string, paused: boolean): Promise<{ ok: true; channel: ChannelRecord }>;\n archiveChannel(\n key: string,\n channelId: string,\n destination: string | null,\n ): Promise<{ ok: true; channel: ChannelRecord; assignmentVersion: number; moved: number }>;\n applyChannelAssignment(\n key: string,\n input: { targetChannelId: string | null; labels: string[]; assignmentVersion: number },\n ): Promise<AssignmentResult>;\n channelPreview(\n key: string,\n channelIds: string[],\n opts?: { includePublic?: boolean },\n ): Promise<ChannelPreviewProjection>;\n /** Choose the channel's sale route. Authorization since 2026-08-06, so this is\n * a precondition of every buyer-facing action, not a label. `opts` carries the\n * acknowledgement that unblocks a switch with live buyer access. */\n setChannelAccessIntent(\n key: string,\n channelId: string,\n accessIntent: ChannelAccessIntent,\n opts?: { acknowledgeLiveAccess?: boolean; reason?: string },\n ): Promise<{\n ok: true;\n channel: ChannelRecord;\n intentSwitch?: { closedLinks: number; keptSessions: number };\n }>;\n /** 201 with the ONE-TIME reveal. Every omitted field takes the server default\n * (expiry = event start, 100 redemptions, 4 seats per buyer). */\n createAccessLink(\n key: string,\n channelId: string,\n input: {\n label?: string | null;\n expiresAt?: number;\n maxRedemptions?: number;\n maxQuantity?: number;\n includePublic?: boolean;\n },\n ): Promise<AccessLinkReveal>;\n /** Status only. This response has no url and no capability, by contract. */\n accessLinks(key: string, channelId: string): Promise<{ links: AccessLinkStatusRecord[] }>;\n /** `endActiveSessions` is required — the server 422s without it, deliberately. */\n rotateAccessLink(\n key: string,\n channelId: string,\n linkId: string,\n endActiveSessions: boolean,\n ): Promise<AccessLinkReveal>;\n revokeAccessLink(\n key: string,\n channelId: string,\n linkId: string,\n endActiveSessions?: boolean,\n ): Promise<{ ok: true; link: unknown; endedSessions: number }>;\n}\n\nexport interface ChannelsCapabilities {\n view: boolean;\n manage: boolean;\n}\n\n/** Everything Channels mode needs from the cockpit around it. */\nexport interface ChannelsModeHost {\n eventKey: string;\n api: ChannelsClient;\n /** The rail scroll container the mode paints into. */\n rail: HTMLElement;\n /** An absolutely-positioned layer over the map (overlay canvas, flags, bars). */\n mapLayer: HTMLElement;\n /** The widget root — dialogs mount here so they inherit the widget's tokens. */\n root: HTMLElement;\n seats(): ChannelsSeatView[];\n statusOf(label: string): ChannelSeatStatus | undefined;\n selectionLabels(): string[];\n selectByLabels(labels: string[]): void;\n clearSelection(): void;\n selectSection(sectionId: string): void;\n sections(): Array<{ id: string; label: string }>;\n /** Every selectable label inside one section, for the additive scope chooser. */\n labelsInSection(sectionId: string): string[];\n /** Logical rows across the whole chart, grouped by their section. */\n rows(): ChannelsRowView[];\n categories(): Array<{ key: string; label: string; color?: string }>;\n labelsInCategory(key: string): string[];\n sectionOfLabel(label: string): { id: string; label: string } | null;\n /** Chart-space → container pixels. Null when there is no live renderer. */\n worldToScreen(point: { x: number; y: number }): { x: number; y: number } | null;\n /** Approximate on-screen seat size in CSS pixels, for the overlay marks. */\n seatPixelSize(): number;\n /** Whether the live renderer is currently showing individual seats. */\n isSeatDetail(): boolean;\n /** Return a sectional venue to its section-only overview. */\n showSectionOverview(): void;\n /** Focus one section using the renderer's real camera transition. */\n focusSection(sectionId: string): void;\n isCompact(): boolean;\n /** Make the canvas non-interactive behind a full-detent sheet (§13). */\n setMapInert(inert: boolean): void;\n toast(message: string, kind: 'ok' | 'err'): void;\n onError(err: unknown): void;\n /** Fired whenever the staged mutation count changes, for host telemetry. */\n onStagedChange?(staged: number): void;\n}\n\n/**\n * Live-count refresh cadence. Organizer realtime (M5's per-scope socket) plugs\n * in at `applyRealtimeHint`, so this clock is a safety net, not the transport —\n * it was 10s, which cost every idle cockpit six list+allocation walks a minute\n * for counts that rarely move. Ticks are skipped entirely while the tab is\n * hidden and one runs immediately when it comes back.\n */\nconst POLL_MS = 30_000;\nconst MAX_FLAGS = 8;\nconst SEAT_LIST_PAGE = 300;\n\n/**\n * The most seats one Apply may carry. The assignment route rewrites every label\n * in a single transaction, so an unbounded selection is a request that times out\n * halfway and leaves the organizer guessing what moved. The ceiling is stated in\n * the UI *before* Apply — in the staged bar, the selection rail, the scope\n * chooser and the review sheet — so it is never discovered as a failure.\n */\nconst MAX_ASSIGNMENT_UNITS = 5_000;\n\n/**\n * Buyer-preview colours are deliberately independent of a chart's category\n * palette. A channel is an access scope, not a price category: retaining the\n * underlying category colour made a buyer's eligible seats indistinguishable\n * from the rest of a section, while a square grey overlay left a coloured rim\n * around unavailable seats. The two explicit states below make the scope\n * readable without disclosing which other channel owns an unavailable seat.\n */\nconst PREVIEW_ELIGIBLE_FILL = '#6e7bff';\nconst PREVIEW_ELIGIBLE_STROKE = '#b9c0ff';\nconst PREVIEW_UNAVAILABLE_FILL = '#303846';\nconst PREVIEW_UNAVAILABLE_STROKE = '#4b5669';\nconst ALLOCATION_STROKE = '#101723';\n\n/**\n * Motion tokens (motion-system §2) plus Channels choreography (§3). Declared on\n * the widget root as `--slm-mo-*` so an embed never inherits host motion CSS.\n * Every keyframe below has its `prefers-reduced-motion` override in this block.\n * `@sl-css` opts it into build-time minification (cdn/minifyCssLiterals.ts).\n */\nexport const CHANNELS_CSS = /* @sl-css */ `\n.slm{--slm-mo-instant:80ms;--slm-mo-quick:140ms;--slm-mo-base:200ms;--slm-mo-slow:320ms;--slm-mo-ambient:2000ms;\n --slm-mo-out:cubic-bezier(.2,.8,.2,1);--slm-mo-in-out:cubic-bezier(.4,0,.2,1);--slm-mo-exit:cubic-bezier(.4,0,1,1);\n --slm-mo-spring:cubic-bezier(.34,1.3,.64,1)}\n\n/* map overlay: ONE layer, faded in as a whole (never per seat) */\n.slm-ch-layer{position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity var(--slm-mo-base) var(--slm-mo-out)}\n.slm-ch-layer.on{opacity:1}\n.slm-ch-canvas{position:absolute;inset:0;width:100%;height:100%}\n.slm-ch-flag{position:absolute;display:flex;align-items:center;gap:5px;padding:3px 8px;border-radius:999px;\n background:rgba(14,16,23,.88);border:1px solid var(--slm-line);font-size:10px;font-weight:800;letter-spacing:.04em;\n transform:translate(-50%,-50%);white-space:nowrap}\n.slm-ch-flag .mk{width:14px;height:14px;border-radius:4px;display:grid;place-items:center;font-size:8.5px;font-weight:800;color:#0e1017}\n.slm-ch-section-target{position:absolute;pointer-events:auto;padding:0;border:0;border-radius:8px;background:transparent;cursor:zoom-in}\n.slm-ch-section-target:focus-visible{outline:2px solid var(--slm-accent);outline-offset:-3px;background:color-mix(in srgb,var(--slm-accent) 12%,transparent)}\n\n/* preview banner — raised with the organizer chrome dim, as one transition */\n.slm-ch-banner{position:absolute;left:50%;top:14px;z-index:6;display:flex;align-items:center;gap:9px;padding:8px 14px;\n border-radius:999px;background:rgba(14,16,23,.92);border:1px solid var(--slm-line);font-size:12px;font-weight:700;\n transform:translate(-50%,-8px);opacity:0;pointer-events:none;\n transition:opacity var(--slm-mo-base) var(--slm-mo-out),transform var(--slm-mo-base) var(--slm-mo-out)}\n.slm-ch-banner.on{opacity:1;transform:translate(-50%,0);pointer-events:auto}\n.slm-ch-banner .dot{width:8px;height:8px;border-radius:50%}\n.slm-ch-banner button{color:var(--slm-accent);font-weight:800;font-size:11.5px;min-height:32px}\n.slm.ch-preview .slm-ch-flag{opacity:0;transition:opacity var(--slm-mo-base) var(--slm-mo-out)}\n\n/* sticky staged bar */\n.slm-ch-staged{position:absolute;left:12px;right:12px;bottom:12px;z-index:6;display:flex;align-items:center;gap:12px;\n padding:10px 14px;min-height:44px;border-radius:12px;background:rgba(24,27,36,.96);border:1px solid var(--slm-line);\n box-shadow:0 12px 34px rgba(0,0,0,.45);font-size:12.5px;pointer-events:auto;\n transform:translateY(calc(100% + 18px));opacity:0;\n transition:transform var(--slm-mo-slow) var(--slm-mo-out),opacity var(--slm-mo-base) var(--slm-mo-out)}\n.slm-ch-staged.on{transform:none;opacity:1}\n.slm-ch-staged.done{background:rgba(31,122,77,.96);border-color:#1f7a4d}\n.slm-ch-staged.shake{animation:slm-ch-shake var(--slm-mo-slow) var(--slm-mo-in-out) 2}\n.slm-ch-staged b{font-variant-numeric:tabular-nums}\n.slm-ch-staged .grow{flex:1}\n.slm-ch-staged .go{padding:9px 16px;min-height:44px;display:inline-flex;align-items:center;border-radius:9px;\n background:#f4b740;color:#1a1200;font-weight:800;font-size:12.5px}\n.slm-ch-staged .go:disabled{opacity:.48;cursor:not-allowed}\n.slm-ch-staged .drop{color:var(--slm-muted);font-weight:700;font-size:11.5px;min-height:44px;padding-inline:8px}\n.slm-ch-tick{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;\n background:#fff;color:#1f7a4d;font-weight:900;font-size:11px;animation:slm-ch-tick var(--slm-mo-base) var(--slm-mo-spring)}\n@keyframes slm-ch-shake{0%,100%{transform:none}25%{transform:translateX(-4px)}75%{transform:translateX(4px)}}\n@keyframes slm-ch-tick{from{transform:scale(.4);opacity:0}to{transform:scale(1);opacity:1}}\n\n/* rail */\n.slm-ch-viewseg{display:flex;gap:3px;padding:3px;border:1px solid var(--slm-line);border-radius:9px;\n background:var(--slm-surface);margin-bottom:12px}\n.slm-ch-viewseg button{flex:1;padding:6px 8px;min-height:34px;border-radius:7px;font-size:11px;font-weight:800;color:var(--slm-muted)}\n.slm-ch-viewseg button.on{background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-ch-viewseg button:disabled{opacity:.5;cursor:not-allowed}\n.slm-ch-mapnav{margin:-2px 0 12px;padding:10px;border:1px solid var(--slm-line);border-radius:10px;background:var(--slm-surface)}\n.slm-ch-mapnav-head{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--slm-muted)}\n.slm-ch-mapnav-head button{color:var(--slm-accent);font-size:11px;font-weight:800;letter-spacing:0;text-transform:none;min-height:30px}\n.slm-ch-mapnav .slm-ch-viewseg{margin:8px 0 5px}\n.slm-ch-mapnav p{margin:0;font-size:11px;line-height:1.45;color:var(--slm-muted)}\n.slm-ch-list{display:flex;flex-direction:column;gap:8px;margin-bottom:12px}\n.slm-ch-row{padding:10px 11px;border:1px solid var(--slm-line);border-radius:10px;background:var(--slm-surface);\n text-align:left;width:100%;display:block;transition:border-color var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-ch-row:hover{border-color:var(--slm-muted)}\n.slm-ch-row.on{border-color:var(--slm-accent);box-shadow:0 0 0 1px color-mix(in srgb,var(--slm-accent) 40%,transparent)}\n.slm-ch-row.public{background:linear-gradient(100deg,rgba(244,183,64,.09),var(--slm-surface) 60%)}\n.slm-ch-row.archived{opacity:.68}\n.slm-ch-head{display:flex;align-items:center;gap:8px}\n.slm-ch-mk{width:20px;height:20px;border-radius:6px;display:grid;place-items:center;font-size:10px;font-weight:800;\n color:#0e1017;flex:none}\n.slm-ch-mk.dim{opacity:.55}\n.slm-ch-name{flex:1;min-width:0;font-size:13px;font-weight:800;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.slm-ch-badge{flex:none;font-size:9px;font-weight:800;letter-spacing:.05em;text-transform:uppercase;padding:2px 7px;border-radius:999px}\n.slm-ch-badge.active{background:rgba(34,160,107,.16);color:#5bd39b}\n.slm-ch-badge.paused,.slm-ch-badge.builtin{background:rgba(244,183,64,.15);color:#f7ca6b}\n.slm-ch-badge.archived{background:rgba(139,148,172,.18);color:#c2c9d8}\n.slm-ch-counts{display:flex;gap:10px;flex-wrap:wrap;margin-top:7px;font-size:11px;color:var(--slm-muted);\n font-variant-numeric:tabular-nums}\n.slm-ch-counts b{color:var(--slm-text);font-weight:800}\n.slm-ch-counts .free b{color:#5bd39b}\n.slm-ch-counts b.bump{animation:slm-ch-bump var(--slm-mo-base) var(--slm-mo-spring)}\n@keyframes slm-ch-bump{0%,100%{transform:none}35%{transform:translateY(-2px) scale(1.08)}}\n.slm-ch-access{margin-top:6px;font-size:10.5px;color:var(--slm-muted)}\n/* A row that opens its channel must READ as pressable, and be one for a keyboard\n too. It is a role=\"button\" div rather than a <button> because the ⋯ control\n lives inside it, and a button inside a button is not valid HTML. */\n.slm-ch-row.open{cursor:pointer}\n.slm-ch-row.open:hover{border-color:var(--slm-accent);background:color-mix(in srgb,var(--slm-accent) 6%,var(--slm-surface))}\n.slm-ch-row.open:focus-visible{outline:2px solid var(--slm-accent);outline-offset:2px}\n.slm-ch-row.open:active{border-color:var(--slm-accent)}\n.slm-ch-more{flex:none;color:var(--slm-muted);font-weight:800;padding:0 4px;min-height:28px;border-radius:6px}\n.slm-ch-more:hover{color:var(--slm-text)}\n.slm-ch-more:focus-visible{outline:2px solid var(--slm-accent);outline-offset:1px;color:var(--slm-text)}\n.slm-ch-menu{display:flex;flex-direction:column;gap:8px}\n.slm-ch-menu .slm-btn{width:100%}\n/* loading is a state, never a flash of empty: same slot, visibly working */\n.slm-ch-busy{display:flex;align-items:center;gap:9px;font-size:12.5px;color:var(--slm-muted);padding:12px 0}\n.slm-ch-busy::before{content:\"\";width:9px;height:9px;border-radius:50%;background:var(--slm-accent);flex:none;\n animation:slm-ch-pulse var(--slm-mo-ambient) var(--slm-mo-in-out) infinite}\n@keyframes slm-ch-pulse{0%,100%{opacity:.25;transform:scale(.7)}50%{opacity:1;transform:scale(1)}}\n.slm-ch-selsrc{display:flex;flex-direction:column;gap:5px;margin:8px 0 12px}\n.slm-ch-selsrc-row{display:flex;align-items:center;gap:8px;font-size:12px;font-variant-numeric:tabular-nums}\n.slm-ch-selsrc-row .mk{width:15px;height:15px;border-radius:4px;display:grid;place-items:center;font-size:8px;\n font-weight:800;color:#0e1017}\n.slm-ch-selsrc-row b{min-width:30px;text-align:right;font-weight:800}\n.slm-ch-selsrc-row span{color:var(--slm-muted)}\n.slm-ch-selnum.bump{animation:slm-ch-bump var(--slm-mo-base) var(--slm-mo-spring)}\n.slm-ch-row2{display:flex;gap:8px;margin-top:8px}\n.slm-ch-row2 .slm-btn{flex:1;min-width:0}\n/* distribute routes — four choices, each with the one sentence that explains it.\n The current one is NAMED in its own card, never signalled by colour alone. */\n.slm-ch-dist{display:flex;flex-direction:column;gap:6px;padding:12px;margin-bottom:8px;border:1px solid var(--slm-line);\n border-radius:10px;background:var(--slm-surface)}\n.slm-ch-dist.on{border-color:var(--slm-accent,#8b7cf6)}\n.slm-ch-dist b{font-size:13px;font-weight:800;display:flex;align-items:center;gap:8px;justify-content:space-between}\n.slm-ch-dist b .cur{font-size:10.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n color:var(--slm-accent,#8b7cf6);white-space:nowrap}\n.slm-ch-dist .why{color:var(--slm-muted);font-size:11.5px;line-height:1.45}\n.slm-ch-dist .slm-btn{width:100%;margin-top:2px}\n.slm-ch-alert{display:flex;align-items:flex-start;gap:9px;padding:11px 13px;border-radius:10px;font-size:12.5px;\n line-height:1.5;margin-bottom:12px}\n.slm-ch-alert.warn{background:rgba(244,183,64,.1);border:1px solid rgba(244,183,64,.4);color:#f4d58a}\n.slm-ch-alert.info{background:rgba(110,123,255,.12);border:1px solid rgba(110,123,255,.44);color:#c5cbff}\n.slm-ch-alert.err{background:rgba(229,72,77,.1);border:1px solid rgba(229,72,77,.45);color:#f1a4a6}\n.slm-ch-alert b{color:#fff}\n.slm-ch-alert button{display:block;margin-top:6px;color:#fff;font-weight:800;min-height:36px}\n.slm-ch-legend{display:flex;flex-direction:column;gap:6px;margin-top:10px}\n.slm-ch-legend .r{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--slm-muted)}\n.slm-ch-legend .sw{width:13px;height:13px;border-radius:3.5px;flex:none}\n.slm-ch-live{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n\n/* dialogs */\n.slm-ch-scrim{position:absolute;inset:0;z-index:12;background:rgba(4,6,12,.62);display:grid;place-items:center;\n padding:18px;animation:slm-ch-fade var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-ch-dialog{width:min(460px,100%);max-height:100%;overflow:auto;overscroll-behavior:contain;background:#12151f;border:1px solid var(--slm-line);\n border-radius:14px;padding:20px;box-shadow:0 24px 70px rgba(0,0,0,.6);\n animation:slm-ch-rise var(--slm-mo-base) var(--slm-mo-out)}\n.slm-ch-dialog h3{margin:0 0 4px;font-size:16px;font-weight:800;letter-spacing:-.01em}\n.slm-ch-dialog .sub{font-size:12.5px;color:var(--slm-muted);line-height:1.5;margin-bottom:14px}\n.slm-ch-dialog .foot{display:flex;gap:8px;margin-top:16px}\n.slm-ch-dialog .foot .slm-btn{flex:1;min-width:0}\n.slm-ch-dialog .foot .quiet{flex:none;padding:10px 14px;min-height:44px;color:var(--slm-muted);font-weight:700;font-size:13px}\n@keyframes slm-ch-fade{from{opacity:0}to{opacity:1}}\n@keyframes slm-ch-rise{from{opacity:0;transform:translateY(10px) scale(.985)}to{opacity:1;transform:none}}\n.slm-ch-bucket{display:grid;grid-template-columns:24px 1fr auto;align-items:center;gap:10px;padding:9px 4px;\n border-top:1px solid var(--slm-line);font-size:12.5px;animation:slm-ch-bucket var(--slm-mo-base) var(--slm-mo-out) both}\n.slm-ch-bucket:first-of-type{border-top:0}\n.slm-ch-bucket .ico{width:20px;height:20px;border-radius:6px;display:grid;place-items:center;font-size:10px;font-weight:800}\n.slm-ch-bucket .ico.add{background:rgba(34,160,107,.18);color:#5bd39b}\n.slm-ch-bucket .ico.move{background:rgba(167,139,250,.18);color:#c4b5fd}\n.slm-ch-bucket .ico.same{background:rgba(139,148,172,.14);color:#aab2c4}\n.slm-ch-bucket .ico.skip{background:rgba(244,183,64,.16);color:#f7ca6b}\n.slm-ch-bucket b{font-variant-numeric:tabular-nums;font-weight:800}\n.slm-ch-bucket .why{color:var(--slm-muted);font-size:11px}\n.slm-ch-bucket .peek{color:var(--slm-muted);font-size:11px;font-variant-numeric:tabular-nums}\n@keyframes slm-ch-bucket{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}\n.slm-ch-secret{display:flex;align-items:center;gap:8px;padding:10px 12px;border:1px dashed rgba(244,183,64,.55);\n border-radius:10px;background:rgba(244,183,64,.06);font-family:ui-monospace,Menlo,monospace;font-size:11px;\n overflow:hidden;white-space:nowrap;text-overflow:ellipsis}\n.slm-ch-err{color:#f1a4a6;font-size:11.5px;margin-top:6px}\n\n/* buyer links — STATUS only; there is no Copy control on this card */\n.slm-ch-link{padding:10px 11px;border:1px solid var(--slm-line);border-radius:10px;background:var(--slm-surface);\n margin-bottom:8px}\n.slm-ch-link .lk-head{display:flex;align-items:center;gap:8px}\n.slm-ch-link .lk-name{flex:1;min-width:0;font-size:12.5px;font-weight:800;overflow:hidden;text-overflow:ellipsis;\n white-space:nowrap}\n.slm-ch-lkrow{display:flex;gap:8px;margin-top:5px;font-size:11px;color:var(--slm-muted)}\n.slm-ch-lkrow .k{flex:none;min-width:104px}\n.slm-ch-lkrow .v{color:var(--slm-text);font-variant-numeric:tabular-nums}\n.slm-ch-meter{height:5px;border-radius:3px;background:rgba(255,255,255,.09);overflow:hidden;margin-top:8px}\n.slm-ch-meter i{display:block;height:100%;background:var(--slm-accent);\n transition:width var(--slm-mo-base) var(--slm-mo-out)}\n.slm-ch-radio{display:flex;gap:9px;align-items:flex-start;padding:11px 12px;border:1px solid var(--slm-line);\n border-radius:10px;margin-top:8px;font-size:12.5px;cursor:pointer;\n transition:border-color var(--slm-mo-quick) var(--slm-mo-out)}\n.slm-ch-radio:hover{border-color:var(--slm-muted)}\n.slm-ch-radio input{flex:none;margin-top:2px}\n.slm-ch-radio b{display:block;font-weight:800;margin-bottom:2px}\n.slm-ch-radio .why{display:block;color:var(--slm-muted);font-size:11.5px;line-height:1.45}\n.slm-ch-seatlist{max-height:44vh;overflow:auto;overscroll-behavior:contain;border:1px solid var(--slm-line);\n border-radius:10px;background:var(--slm-surface);margin-top:10px}\n.slm-ch-seatgroup{padding:8px 10px;border-bottom:1px solid var(--slm-line);display:flex;align-items:center;\n justify-content:space-between;gap:8px;font-size:11px;font-weight:800;color:var(--slm-muted);position:sticky;top:0;\n background:var(--slm-surface)}\n.slm-ch-seatgroup button{color:var(--slm-accent);font-weight:800;font-size:11px;min-height:32px}\n.slm-ch-seatitem{display:flex;width:100%;align-items:center;gap:9px;padding:8px 10px;border-bottom:1px solid var(--slm-line);\n text-align:left;font-size:12px}\n.slm-ch-seatitem .box{width:16px;height:16px;border-radius:4px;border:1px solid var(--slm-muted);display:grid;\n place-items:center;font-size:10px;font-weight:900;color:transparent;flex:none}\n.slm-ch-seatitem[aria-checked=\"true\"] .box{border-color:var(--slm-accent);background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-ch-seatitem .meta{margin-left:auto;color:var(--slm-muted);font-size:10.5px}\n\n/* scope chooser: whole sections or many rows in one additive pass */\n.slm-ch-scopebar{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;margin-top:12px}\n.slm-ch-scopebar label{display:grid;gap:5px;color:var(--slm-muted);font-size:10.5px;font-weight:800}\n.slm-ch-scopebar input{width:100%;min-height:40px;padding:8px 10px;border:1px solid var(--slm-line);border-radius:8px;\n background:var(--slm-surface);color:var(--slm-text);font:inherit}\n.slm-ch-scopesummary{padding-bottom:10px;color:var(--slm-muted);font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap}\n.slm-ch-scopegroup{position:sticky;top:0;z-index:1;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;\n gap:6px;padding:6px 8px;border-bottom:1px solid var(--slm-line);background:var(--slm-surface)}\n.slm-ch-groupcheck{display:flex;min-width:0;align-items:center;gap:8px;padding:5px 2px;text-align:left;font-size:11px;font-weight:800}\n.slm-ch-groupcheck .box{width:16px;height:16px;flex:none;display:grid;place-items:center;border:1px solid var(--slm-muted);border-radius:4px;\n color:transparent;font-size:10px}\n.slm-ch-groupcheck[aria-checked=\"true\"] .box,.slm-ch-groupcheck[aria-checked=\"mixed\"] .box{border-color:var(--slm-accent);\n background:var(--slm-accent);color:var(--slm-accent-ink)}\n.slm-ch-groupcheck .meta{min-width:0;margin-left:auto;color:var(--slm-muted);font-size:10.5px;font-weight:600;white-space:nowrap}\n.slm-ch-grouptoggle{min-height:32px;padding:5px 8px;color:var(--slm-accent);font-size:11px;font-weight:800}\n.slm-ch-scopehint{padding:8px 10px;color:var(--slm-muted);font-size:10.5px;border-bottom:1px solid var(--slm-line)}\n.slm-ch-scope-empty{padding:18px 12px;color:var(--slm-muted);font-size:11.5px;text-align:center}\n@media(max-width:560px){.slm-ch-scopebar{grid-template-columns:1fr}.slm-ch-scopesummary{padding-bottom:0}}\n\n/* compact: bottom sheet with three detents (§13) */\n.slm.compact.ch-sheet .slm-rail{position:absolute;left:0;right:0;bottom:0;z-index:8;border-top:1px solid var(--slm-line);\n border-radius:18px 18px 0 0;background:#12151f;\n transition:height var(--slm-mo-slow) var(--slm-mo-in-out)}\n.slm.compact.ch-sheet.detent-collapsed .slm-rail{height:132px}\n.slm.compact.ch-sheet.detent-medium .slm-rail{height:46%}\n.slm.compact.ch-sheet.detent-full .slm-rail{height:92%}\n.slm.compact.ch-sheet .slm-railscroll{padding:8px 14px calc(12px + env(safe-area-inset-bottom,0px))}\n.slm-ch-grab{display:none}\n.slm.compact.ch-sheet .slm-ch-grab{display:flex;align-items:center;gap:10px;width:100%;padding:6px 0 10px}\n.slm-ch-grabbar{width:42px;height:4px;border-radius:2px;background:rgba(255,255,255,.22);margin:0 auto}\n.slm.compact .slm-ch-staged{bottom:auto;top:8px}\n.slm.compact .slm-btn,.slm.compact .slm-ch-row,.slm.compact .slm-ch-viewseg button{min-height:44px}\n.slm-tools{display:none}\n.slm.compact .slm-tools{display:block;width:100%;padding:9px 13px;min-height:44px;border:1px solid var(--slm-line);\n border-radius:10px;background:var(--slm-surface);color:var(--slm-text);font-size:13px;font-weight:800}\n.slm.compact .slm-modes{display:none}\n\n@media (prefers-reduced-motion:reduce){\n .slm-ch-layer,.slm-ch-banner,.slm-ch-staged,.slm-ch-row,.slm.compact.ch-sheet .slm-rail,\n .slm-ch-meter i,.slm-ch-radio{transition:none!important}\n .slm-ch-staged.shake,.slm-ch-tick,.slm-ch-bucket,.slm-ch-scrim,.slm-ch-dialog,\n .slm-ch-counts b.bump,.slm-ch-selnum.bump{animation:none!important}\n .slm-ch-busy::before{animation:none!important;opacity:1}\n .slm-ch-staged.shake{outline:2px solid #e5484d;outline-offset:2px}\n .slm-ch-staged.done{outline:2px solid #5bd39b;outline-offset:2px}\n}\n`;\n\n/**\n * Render bucket rows to markup. Deliberately generic over `BucketRow`, because\n * three different refusals share this exact presentation: the local staged\n * preview, the authoritative Apply response, and the chart-update\n * `channel_assignment_would_drop` review (via `dropReviewRows`). One component,\n * one visual language for \"here is every affected unit, in exactly one line\".\n */\nexport function bucketRowsHtml(rows: BucketRow[]): string {\n return rows.map((row, index) => `\n <div class=\"slm-ch-bucket\" style=\"animation-delay:${Math.min(index, 4) * 30}ms\">\n <span class=\"ico ${row.kind}\" aria-hidden=\"true\">${esc(row.icon)}</span>\n <span><b>${row.count.toLocaleString()}</b> ${esc(row.text.replace(/^[\\d,.\\s]+/, ''))}\n ${row.why ? `<span class=\"why\">— ${esc(row.why)}</span>` : ''}</span>\n ${row.peek ? `<span class=\"peek\">${esc(row.peek)}</span>` : '<span></span>'}\n </div>`).join('');\n}\n\n/**\n * Website integration is a BACKEND integration, so there is no screen to build\n * and this block is deliberately informational.\n *\n * It replaces a disabled \"Configure server integration · Coming soon\" button\n * that promised a wizard which does not exist and is not planned. A control that\n * can never do anything is worse than a sentence explaining why it isn't there:\n * the honest answer is \"nothing to configure here, and here is the guide\".\n *\n * It is shown only once the organizer has chosen this route (`intent: 'server'`),\n * because that is also the flag the dashboard's Embed page reads to offer the\n * snippet. Before that choice it would be an unasked-for wall of backend talk.\n */\nconst SERVER_INTEGRATION_HTML = `\n <p class=\"slm-eyebrow\" style=\"margin-top:18px\">On your website</p>\n <p class=\"slm-hint\">There is nothing more to set up on this screen. Your own server mints a short-lived buyer\n access session for this channel with the SeatLayer server SDK and hands it to the widget. A channel name\n on its own never grants access.</p>\n <p class=\"slm-note\"><a class=\"slm-linkbtn\" href=\"https://docs.seatlayer.io/server-api/channels\"\n target=\"_blank\" rel=\"noreferrer noopener\">Read the website integration guide →</a></p>`;\n\nfunction esc(value: unknown): string {\n return String(value ?? '')\n .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n .replace(/\"/g, '"').replace(/'/g, ''');\n}\n\n/** `<input type=\"datetime-local\">` wants local wall-clock, not an ISO instant. */\nfunction datetimeLocalValue(ms: number): string {\n const local = new Date(ms - new Date(ms).getTimezoneOffset() * 60_000);\n return local.toISOString().slice(0, 16);\n}\n\n/** A whole number from a numeric field, or null when it is not one. This is the\n * ONLY client-side validation on link policy — the ranges belong to the server. */\nfunction intField(root: HTMLElement, selector: string): number | null {\n const raw = root.querySelector<HTMLInputElement>(selector)?.value.trim() ?? '';\n const value = Number(raw);\n return raw !== '' && Number.isInteger(value) ? value : null;\n}\n\n/** Clipboard-less fallback: put the revealed URL under the caret so it can still\n * be copied by hand. Selection dies with the node, like the string itself. */\nfunction selectSecret(dialog: HTMLElement): void {\n const node = dialog.querySelector<HTMLElement>('[data-ch-lk-url]');\n if (!node) return;\n try {\n const range = document.createRange();\n range.selectNodeContents(node);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n } catch { /* selection is a nicety; the URL is on screen regardless */ }\n}\n\ntype Detent = 'collapsed' | 'medium' | 'full';\n\ntype DialogKind =\n | 'create' | 'review' | 'archive' | 'rename' | 'seatlist' | 'scope' | 'menu'\n | 'linkCreate' | 'linkRotate' | 'linkRevoke' | 'intentSwitch';\n\n/** The link the organizer asked for, held while a blocked route switch is\n * reviewed, so acknowledging resumes the SAME gesture instead of making them\n * fill the form in again. It carries no secret — the reveal is still one-time. */\nexport interface PendingLinkInput {\n label: string | null;\n includePublic: boolean;\n expiresAt?: number;\n maxRedemptions: number;\n maxQuantity: number;\n}\n\n/**\n * There is deliberately NO `reveal` dialog kind. A one-time reveal is not a\n * re-renderable state: `renderDialog()` rebuilds a sheet from this object, so\n * anything reachable from here is by definition recoverable. The reveal is\n * mounted directly, holds its URL in a closure, and dies with its DOM node.\n */\ninterface DialogState {\n kind: DialogKind;\n channelId?: string;\n linkId?: string;\n /** Authoritative result rendered after Apply (review dialog only). */\n applied?: AssignmentResult | null;\n archiveBlocked?: ArchiveBlockedDetails | null;\n /** The refused route switch, and where it was headed (intentSwitch only). */\n switchBlocked?: IntentSwitchBlockedDetails | null;\n intentTo?: ChannelAccessIntent;\n /** Set when the blocked switch was the declare half of a declare-then-create,\n * so acknowledging finishes the link the organizer actually asked for. */\n pendingLink?: PendingLinkInput | null;\n /** Which unit the scope chooser is picking (scope dialog only). */\n scope?: 'sections' | 'rows';\n busy?: boolean;\n error?: string | null;\n}\n\nexport class ChannelsMode {\n private readonly host: ChannelsModeHost;\n private caps: ChannelsCapabilities;\n\n private active = false;\n private list: ChannelListResult | null = null;\n private allocation = new Map<string, string>();\n private assignmentVersion = 0;\n private loadError: unknown = null;\n private loading = true;\n\n private view: 'inspect' | 'preview' = 'inspect';\n /** Pan is intentionally the initial desktop interaction. Assignment's\n * marquee is powerful, but must never make an organizer lose map navigation. */\n private mapIntent: 'pan' | 'assign' = 'pan';\n private focusedSectionId: string | null = null;\n private showArchived = false;\n private detailChannelId: string | null = null;\n /**\n * Whether the organizer has asked to assign seats.\n *\n * The list rail leads with the CHANNELS. The assignment tooling — destination\n * picker plus five select-by routes — used to paint unconditionally above that\n * list, so a first-time organizer met a workbench for a job they had not asked\n * to do, with the thing they came for pushed below the fold. It is now\n * disclosed on intent: the \"Assign seats to a channel\" action under the list,\n * the map's own \"Assign seats\" segment, or simply having a selection. The\n * selection rail always shows the tools, because there the intent is proven.\n */\n private assignOpen = false;\n private targetChannelId = '';\n private conflict = false;\n private dialog: DialogState | null = null;\n private detent: Detent = 'medium';\n private seatListLimit = SEAT_LIST_PAGE;\n\n /**\n * Hosted-link STATUS for the channel whose detail panel is open. This is the\n * listing projection — it carries no url and no capability, because no route\n * returns one. `unsupported` is the honest answer for a worker that predates\n * M8, exactly like the buyer-preview probe.\n */\n private links: AccessLinkStatusRecord[] = [];\n private linksChannelId: string | null = null;\n private linksState: 'idle' | 'loading' | 'ready' | 'unsupported' | 'error' = 'idle';\n\n /**\n * Monotonic read generations — one for the channel list + allocation, one for\n * the open channel's links. Reads are concurrent (a 10s poll versus a\n * mutation's own reload), and the network does not promise to answer them in\n * order. Only the NEWEST read of each kind may write to state; an older\n * answer that arrives late is dropped, never painted.\n */\n private listSeq = 0;\n private linksSeq = 0;\n\n private previewAudience: string[] = [];\n private previewIncludePublic = false;\n private previewProjection: ChannelPreviewProjection | null = null;\n /**\n * The buyer-preview read, as one honest state rather than a boolean.\n *\n * `previewSupported: boolean | null` could say \"this worker has no projection\n * route\", but it could not say \"the read is in flight\" or \"the read failed\" —\n * both of those painted an audience picker with no result underneath, which\n * reads as \"this audience can buy nothing\". Loading and error are now states\n * of their own, and the error one offers a retry.\n */\n private previewState: 'idle' | 'loading' | 'ready' | 'unsupported' | 'error' = 'idle';\n\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private layer: HTMLDivElement | null = null;\n private canvas: HTMLCanvasElement | null = null;\n /** undefined = not resolved yet, null = this environment has no 2d canvas. */\n private ctx: CanvasRenderingContext2D | null | undefined = undefined;\n private bannerEl: HTMLDivElement | null = null;\n private stagedEl: HTMLDivElement | null = null;\n private liveEl: HTMLDivElement | null = null;\n private scrimEl: HTMLDivElement | null = null;\n private lastFocus: HTMLElement | null = null;\n private stagedDoneTimer: ReturnType<typeof setTimeout> | null = null;\n private lastSelectionCount = 0;\n private lastCounts = new Map<string, number>();\n /** Rows are structural chart data — they do not move while the organizer is\n * allocating. Deriving them walks every seat, so the view is cached for the\n * lifetime of this mode entry and ordinary selection repaints stay O(1). */\n private assignmentRowsCache: ChannelsRowView[] | null = null;\n /** The markup currently in the rail. An identical repaint is skipped, which is\n * what keeps the organizer's scroll position (and open <select>) alive. */\n private railHtml: string | null = null;\n /**\n * The `assignmentVersion` the allocation map was built from. Walking every\n * allocation page is the expensive half of a refresh and the server already\n * tells us, in the channels response, whether ANY seat moved. Unchanged\n * version, unchanged allocation — so the walk is skipped entirely.\n */\n private allocationVersion: number | null = null;\n private onVisibility: (() => void) | null = null;\n\n constructor(host: ChannelsModeHost, capabilities: ChannelsCapabilities) {\n this.host = host;\n this.caps = capabilities;\n }\n\n // ---- lifecycle ------------------------------------------------------------\n\n /** Called when the cockpit switches into Channels mode. */\n enter(): void {\n if (this.active) return;\n this.active = true;\n this.mapIntent = 'pan';\n this.assignOpen = false; // every entry starts on the channels, not the tools\n this.focusedSectionId = null;\n this.assignmentRowsCache = null; // the chart may have changed since last entry\n this.railHtml = null; // the rail belonged to another mode a moment ago\n this.ensureLayer();\n this.host.root.classList.add('ch-mode');\n this.applySheetClasses();\n // A sectioned venue begins at semantic overview. The renderer owns the\n // camera and turns this into a real section-only rung, not a fake card UI.\n if (this.host.sections().length > 1) this.host.showSectionOverview();\n this.paintRail();\n this.onInteractionChange?.();\n void this.refresh();\n // A hidden tab has no organizer looking at it. Polling it burns the event's\n // rate budget to repaint pixels nobody can see — and browsers throttle the\n // timer anyway, so the ticks that do land arrive in a clump. Skip them, and\n // catch up with exactly one read when the tab comes back.\n this.pollTimer = setInterval(() => {\n if (typeof document !== 'undefined' && document.hidden) return;\n void this.refresh({ quiet: true });\n }, POLL_MS);\n if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {\n this.onVisibility = () => {\n if (this.active && !document.hidden) void this.refresh({ quiet: true });\n };\n document.addEventListener('visibilitychange', this.onVisibility);\n }\n }\n\n /** Called when the cockpit leaves Channels mode. Everything this mode painted\n * over the map goes with it — no other tool ever inherits a channel overlay. */\n leave(): void {\n if (!this.active) return;\n this.active = false;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = null;\n if (this.onVisibility && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', this.onVisibility);\n }\n this.onVisibility = null;\n this.railHtml = null;\n this.closeDialog({ restoreFocus: false });\n // Link status is per-channel and short-lived; nothing about it survives the\n // mode, and there was never a secret in it to survive.\n this.links = [];\n this.linksChannelId = null;\n this.linksState = 'idle';\n this.layer?.classList.remove('on');\n this.host.root.classList.remove('ch-mode', 'ch-preview', 'ch-sheet',\n 'detent-collapsed', 'detent-medium', 'detent-full');\n this.setBanner(false);\n this.setStaged(null);\n }\n\n destroy(): void {\n this.leave();\n if (this.stagedDoneTimer) clearTimeout(this.stagedDoneTimer);\n this.layer?.remove();\n this.layer = null;\n }\n\n /** Capabilities can change when a token rotates. Re-render, fail-closed. */\n setCapabilities(capabilities: ChannelsCapabilities): void {\n this.caps = capabilities;\n if (this.active) this.paintRail();\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n /**\n * Whether the map should accept bulk selection right now. Preview is a\n * read-only simulation of somebody else's view, and a view-only token has no\n * assignment to stage — in both cases the canvas must not offer selection at\n * all rather than collect a selection nothing can act on.\n */\n canSelect(): boolean {\n return this.caps.manage && this.view === 'inspect';\n }\n\n /** Bulk seat assignment is explicit. In Pan map, clicks can still inspect a\n * single seat, while a primary-button drag always moves the camera. */\n usesMarqueeSelection(): boolean {\n return this.canSelect() && this.mapIntent === 'assign';\n }\n\n /** The renderer calls this when the organizer opens a section from overview. */\n handleSectionFocus(sectionId: string): void {\n if (!this.active) return;\n this.focusedSectionId = sectionId;\n this.paintRail();\n }\n\n /**\n * Organizer realtime integration point. M5 ships a per-scope socket for\n * buyers; the organizer channel-count stream is a later milestone. When it\n * arrives, call this from the cockpit's WS handler instead of waiting for the\n * poll — everything downstream already reacts to a fresh list.\n */\n applyRealtimeHint(): void {\n if (this.active) void this.refresh({ quiet: true });\n }\n\n /** The cockpit's selection changed (marquee / click / section / category). */\n handleSelectionChange(): void {\n if (!this.active) return;\n this.paintSelection();\n this.paintStagedBar();\n }\n\n /** Camera moved or the container resized — the overlay is screen-space. */\n handleViewChange(): void {\n if (this.active) this.paintOverlay();\n }\n\n handleLayoutChange(): void {\n if (!this.active) return;\n this.applySheetClasses();\n this.paintOverlay();\n }\n\n // ---- data -----------------------------------------------------------------\n\n private async refresh(opts: { quiet?: boolean } = {}): Promise<void> {\n if (!this.caps.view) return;\n // A ten-second poll runs alongside every mutation, so two refreshes are\n // routinely in flight at once. Without a generation the slower FIRST one\n // lands last and repaints the panel with what the channel looked like\n // BEFORE the mutation — the create/rotate/revoke result silently reverts.\n const seq = ++this.listSeq;\n const superseded = (): boolean => seq !== this.listSeq;\n try {\n const list = await this.host.api.channels(this.host.eventKey, { includeArchived: this.showArchived });\n if (superseded()) return;\n this.list = list;\n this.assignmentVersion = list.assignmentVersion;\n this.loadError = null;\n if (!this.targetChannelId) {\n this.targetChannelId = list.channels.find((c) => c.state === 'active')?.id ?? PUBLIC_CHANNEL_ID;\n }\n // The allocation walk is the expensive half of this refresh (one request\n // per 1,000 seats). `assignmentVersion` is bumped by the server on every\n // assignment, so an unchanged version means an unchanged map — re-reading\n // it would spend an arena's worth of round trips to rebuild an identical\n // Map every poll tick.\n if (this.allocationVersion !== list.assignmentVersion) {\n await this.loadAllocation(seq);\n if (superseded()) return;\n this.allocationVersion = list.assignmentVersion;\n }\n // Redemptions and live-session counts move on their own, so the open\n // channel's link status rides the same clock as its seat counts.\n if (this.detailChannelId) await this.loadLinks(this.detailChannelId);\n if (superseded()) return;\n this.loading = false;\n if (this.active) {\n this.paintRail();\n this.paintOverlay();\n }\n } catch (err) {\n if (superseded()) return;\n this.loading = false;\n // A 403 on a mutation route means the token lost manage authority; a 403\n // here means it lost view. Either way, fail closed rather than guess.\n if (err instanceof ManageApiError && err.status === 403) {\n this.caps = { view: false, manage: false };\n }\n this.loadError = err;\n if (!opts.quiet) this.host.onError(err);\n if (this.active) this.paintRail();\n }\n }\n\n /** Walk every allocation page. Bounded by the event's seat count, and the\n * server caps each page, so an arena is a handful of round trips. */\n private async loadAllocation(seq?: number): Promise<void> {\n const next = new Map<string, string>();\n let afterLabel: string | undefined;\n for (let page = 0; page < 200; page += 1) {\n // A superseded walk stops paging rather than finishing a read nobody will use.\n if (seq !== undefined && seq !== this.listSeq) return;\n const res: ChannelAllocationPage = await this.host.api.channelAllocation(this.host.eventKey, {\n afterLabel, limit: 1000,\n });\n for (const row of res.allocations) {\n // The server names public sale explicitly on every row, so the map holds\n // PRIVATE ids only — absence is what \"on public sale\" means downstream.\n if (!isPublicChannelId(row.channelId)) next.set(row.label, row.channelId);\n }\n this.assignmentVersion = res.assignmentVersion;\n if (!res.nextAfterLabel) break;\n afterLabel = res.nextAfterLabel;\n }\n if (seq !== undefined && seq !== this.listSeq) return;\n this.allocation = next;\n }\n\n // ---- lookups --------------------------------------------------------------\n\n private channelById(id: string): { id: string; name: string; marker: string | null; color: string | null } | null {\n if (isPublicChannelId(id)) {\n return {\n id: PUBLIC_CHANNEL_ID,\n name: this.list?.publicSale?.name ?? PUBLIC_CHANNEL_NAME,\n marker: 'P',\n color: null,\n };\n }\n const found = this.list?.channels.find((channel) => channel.id === id);\n return found ? { id, name: found.name, marker: found.marker, color: found.color } : null;\n }\n\n private nameOf(id: string): string | null {\n return this.channelById(id)?.name ?? null;\n }\n\n private markerFor(id: string): { letter: string; color: string } {\n const index = Math.max(0, this.list?.channels.findIndex((channel) => channel.id === id) ?? 0);\n const channel = this.channelById(id);\n return markerOf(channel ?? { id, name: '?', marker: null, color: null }, index);\n }\n\n /** Channels an organizer may assign INTO: public sale plus every live channel. */\n private assignableChannels(): Array<{ id: string; name: string }> {\n return [\n { id: PUBLIC_CHANNEL_ID, name: this.list?.publicSale.name ?? PUBLIC_CHANNEL_NAME },\n ...(this.list?.channels ?? [])\n .filter((channel) => channel.state !== 'archived')\n .map((channel) => ({ id: channel.id, name: channel.name })),\n ];\n }\n\n private currentPlan(): { labels: string[]; buckets: AssignmentBuckets; target: string } {\n const labels = this.host.selectionLabels();\n const buckets = planAssignment({\n labels,\n targetChannelId: this.targetChannelId,\n allocation: this.allocation,\n statusOf: (label) => this.host.statusOf(label),\n nameOf: (id) => this.nameOf(id),\n });\n return { labels, buckets, target: this.targetChannelId };\n }\n\n // ---- map overlay ----------------------------------------------------------\n\n private ensureLayer(): void {\n if (this.layer) return;\n const layer = document.createElement('div');\n layer.className = 'slm-ch-layer';\n layer.innerHTML = `\n <canvas class=\"slm-ch-canvas\" data-ch=\"canvas\" aria-hidden=\"true\"></canvas>\n <div class=\"slm-ch-banner\" data-ch=\"banner\" role=\"status\"></div>\n <div class=\"slm-ch-staged\" data-ch=\"staged\" role=\"group\" aria-label=\"Staged channel changes\"></div>\n <div class=\"slm-ch-live\" data-ch=\"live\" role=\"status\" aria-live=\"polite\"></div>`;\n this.host.mapLayer.appendChild(layer);\n this.layer = layer;\n this.canvas = layer.querySelector('[data-ch=\"canvas\"]');\n this.bannerEl = layer.querySelector('[data-ch=\"banner\"]');\n this.stagedEl = layer.querySelector('[data-ch=\"staged\"]');\n this.liveEl = layer.querySelector('[data-ch=\"live\"]');\n requestAnimationFrame(() => layer.classList.add('on'));\n }\n\n private announce(message: string): void {\n if (this.liveEl) this.liveEl.textContent = message;\n }\n\n /**\n * Repaint the allocation (or preview) overlay in ONE canvas pass.\n *\n * Channel identity on the map is a fill in the administrative color PLUS the\n * letter flags below — never color alone. In buyer preview the map instead\n * uses two explicit, channel-neutral access states. Physical status keeps its\n * own cue: only FREE units are repainted, so sold/held/blocked seats still\n * read exactly as they do in every other tool.\n */\n private paintOverlay(): void {\n const canvas = this.canvas;\n const layer = this.layer;\n if (!canvas || !layer) return;\n const rect = this.host.mapLayer.getBoundingClientRect();\n const width = Math.max(1, Math.round(rect.width));\n const height = Math.max(1, Math.round(rect.height));\n const dpr = typeof devicePixelRatio === 'number' ? Math.min(3, Math.max(1, devicePixelRatio)) : 1;\n if (canvas.width !== width * dpr || canvas.height !== height * dpr) {\n canvas.width = width * dpr;\n canvas.height = height * dpr;\n }\n // jsdom (and any canvas-less environment) has no 2d context; the overlay is\n // purely decorative there and the rail stays fully functional. Resolve it\n // once so a headless run is not spammed on every repaint.\n if (this.ctx === undefined) {\n try { this.ctx = canvas.getContext('2d'); } catch { this.ctx = null; }\n }\n const ctx = this.ctx;\n if (!ctx) return;\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n ctx.clearRect(0, 0, width, height);\n\n const seatDetail = this.host.isSeatDetail();\n const size = Math.max(3, this.host.seatPixelSize());\n const half = size / 2;\n // A paused/archived audience answers `available:false`: nothing is buyable\n // through it, so every seat takes the one neutral unavailable treatment\n // rather than rendering the allocation as if it were on sale.\n const projection = this.view === 'preview' ? this.previewProjection : null;\n const eligible = projection\n ? new Set(projection.available === false ? [] : projection.eligible ?? [])\n : null;\n const clusters = new Map<string, { x: number; y: number; n: number }>();\n const sectionTargets = !seatDetail && this.host.sections().length > 1\n ? new Map<string, { label: string; minX: number; minY: number; maxX: number; maxY: number }>()\n : null;\n // At a wide zoom the renderer centres section names over the seat field.\n // Re-draw those names above the access marks so visual availability never\n // competes with the section identity the organizer needs to navigate.\n const previewSections = this.view === 'preview' && seatDetail && size <= 15\n ? new Map<string, { label: string; minX: number; minY: number; maxX: number; maxY: number }>()\n : null;\n\n for (const seat of this.host.seats()) {\n const status = this.host.statusOf(seat.label) ?? 'free';\n const channelId = this.allocation.get(seat.label) ?? PUBLIC_CHANNEL_ID;\n if (channelId !== PUBLIC_CHANNEL_ID) {\n const cluster = clusters.get(channelId) ?? { x: 0, y: 0, n: 0 };\n cluster.x += seat.x; cluster.y += seat.y; cluster.n += 1;\n clusters.set(channelId, cluster);\n }\n // The base renderer presents named section shells at the overview rung.\n // Do not redraw thousands of seat dots above those shells; click a\n // section to enter its seats, where the precise allocation paint resumes.\n if (!seatDetail) {\n const section = this.host.sectionOfLabel(seat.label);\n const point = section ? this.host.worldToScreen({ x: seat.x, y: seat.y }) : null;\n if (sectionTargets && section && point) {\n const bounds = sectionTargets.get(section.id) ?? {\n label: section.label, minX: point.x, minY: point.y, maxX: point.x, maxY: point.y,\n };\n bounds.minX = Math.min(bounds.minX, point.x);\n bounds.minY = Math.min(bounds.minY, point.y);\n bounds.maxX = Math.max(bounds.maxX, point.x);\n bounds.maxY = Math.max(bounds.maxY, point.y);\n sectionTargets.set(section.id, bounds);\n }\n continue;\n }\n if (status !== 'free') continue; // physical state always wins the paint\n let fill: string | null = null;\n let stroke: string | null = null;\n if (this.view === 'preview') {\n // ONE neutral unavailable state for everything this audience can't buy —\n // preview must never leak which private channel holds a seat. Both\n // states are painted, rather than leaving eligible seats in their\n // category colour: the exact allocation must be obvious at a glance.\n if (eligible?.has(seat.label)) {\n fill = PREVIEW_ELIGIBLE_FILL;\n stroke = PREVIEW_ELIGIBLE_STROKE;\n } else {\n fill = PREVIEW_UNAVAILABLE_FILL;\n stroke = PREVIEW_UNAVAILABLE_STROKE;\n }\n } else if (channelId !== PUBLIC_CHANNEL_ID) {\n fill = this.markerFor(channelId).color;\n stroke = ALLOCATION_STROKE;\n }\n if (!fill) continue;\n const point = this.host.worldToScreen({ x: seat.x, y: seat.y });\n if (!point) continue;\n if (point.x < -size || point.y < -size || point.x > width + size || point.y > height + size) continue;\n if (previewSections) {\n const section = this.host.sectionOfLabel(seat.label);\n if (section) {\n const bounds = previewSections.get(section.id) ?? {\n label: section.label, minX: point.x, minY: point.y, maxX: point.x, maxY: point.y,\n };\n bounds.minX = Math.min(bounds.minX, point.x);\n bounds.minY = Math.min(bounds.minY, point.y);\n bounds.maxX = Math.max(bounds.maxX, point.x);\n bounds.maxY = Math.max(bounds.maxY, point.y);\n previewSections.set(section.id, bounds);\n }\n }\n ctx.fillStyle = fill;\n if (this.view === 'preview' || channelId !== PUBLIC_CHANNEL_ID) {\n // Seats in the shared 2D renderer are circular. A generously covering\n // circular paint keeps Inspect allocation's channel colour independent\n // of the chart category, and replaces preview's former inner square so\n // there is no coloured rim or distracting grey-box effect.\n // `seatPixelSize` is the renderer's actual seat diameter. Match that\n // geometry (with only the stroke allowance), rather than inflating a\n // little status marker. That preserves the chart's configured row and\n // column gaps at every zoom and prevents category-colour rims leaking\n // through around a buyer-preview state.\n const radius = Math.max(2, half + Math.min(1.5, half * 0.06));\n ctx.globalAlpha = 1;\n ctx.beginPath();\n ctx.arc(point.x, point.y, radius, 0, Math.PI * 2);\n ctx.fill();\n ctx.strokeStyle = stroke ?? fill;\n ctx.lineWidth = this.view === 'preview'\n ? Math.max(1, Math.min(1.75, size * 0.13))\n : Math.max(1, Math.min(1.5, size * 0.1));\n ctx.stroke();\n // The overlay sits above the renderer, so it must restore the chart's\n // real label after painting an eligible buyer seat. Use the source\n // label verbatim and only when it remains legible inside the seat.\n if (this.view === 'preview' && eligible?.has(seat.label) && size >= 22) {\n this.paintPreviewSeatLabel(ctx, seat.label, point.x, point.y, radius);\n }\n } else {\n ctx.globalAlpha = 0.85;\n ctx.fillRect(point.x - half, point.y - half, size, size);\n }\n }\n ctx.globalAlpha = 1;\n if (previewSections) this.paintPreviewSectionLabels(ctx, previewSections);\n this.paintSectionTargets(sectionTargets);\n this.paintFlags(clusters);\n }\n\n /** Draw an eligible seat's actual chart label without inventing a new buyer\n * identifier. Long labels scale down and are omitted rather than overflowing\n * into an adjacent seat. */\n private paintPreviewSeatLabel(\n ctx: CanvasRenderingContext2D,\n label: string,\n x: number,\n y: number,\n radius: number,\n ): void {\n const maxWidth = radius * 1.55;\n let fontSize = Math.min(13, Math.max(7, radius * 0.55));\n const minFontSize = 6;\n while (fontSize >= minFontSize) {\n ctx.font = `800 ${fontSize}px var(--slm-font, system-ui, sans-serif)`;\n if (ctx.measureText(label).width <= maxWidth) break;\n fontSize -= 0.5;\n }\n if (fontSize < minFontSize) return;\n ctx.fillStyle = '#ffffff';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText(label, x, y);\n }\n\n /** A section overview is a navigation map. These transparent, keyboardable\n * hit areas sit over the renderer's section shells so both mouse and keyboard\n * always take the organizer into the real focused-section camera state. */\n private paintSectionTargets(\n sections: Map<string, { label: string; minX: number; minY: number; maxX: number; maxY: number }> | null,\n ): void {\n const layer = this.layer;\n if (!layer) return;\n layer.querySelectorAll('.slm-ch-section-target').forEach((el) => el.remove());\n if (!sections) return;\n for (const [id, section] of sections) {\n const width = section.maxX - section.minX;\n const height = section.maxY - section.minY;\n if (width < 20 || height < 20) continue;\n const target = document.createElement('button');\n target.type = 'button';\n target.className = 'slm-ch-section-target';\n target.style.left = `${section.minX - 8}px`;\n target.style.top = `${section.minY - 8}px`;\n target.style.width = `${width + 16}px`;\n target.style.height = `${height + 16}px`;\n target.setAttribute('aria-label', `Open ${section.label} seats`);\n target.addEventListener('click', () => {\n this.focusedSectionId = id;\n this.host.focusSection(id);\n this.paintRail();\n });\n layer.appendChild(target);\n }\n }\n\n /** Keep renderer section names legible over a dense, zoomed-out preview. */\n private paintPreviewSectionLabels(\n ctx: CanvasRenderingContext2D,\n sections: Map<string, { label: string; minX: number; minY: number; maxX: number; maxY: number }>,\n ): void {\n for (const section of sections.values()) {\n const width = section.maxX - section.minX;\n const height = section.maxY - section.minY;\n // A single row/seat has no overlaid central renderer label to protect.\n if (width < 52 || height < 26) continue;\n const centerX = (section.minX + section.maxX) / 2;\n const centerY = (section.minY + section.maxY) / 2;\n const fontSize = Math.max(11, Math.min(15, height * 0.16));\n ctx.font = `800 ${fontSize}px var(--slm-font, system-ui, sans-serif)`;\n const labelWidth = Math.min(width - 8, ctx.measureText(section.label).width + 18);\n const labelHeight = fontSize + 10;\n // This small backplate deliberately covers the renderer's original\n // label before the high-contrast replacement is drawn above it.\n ctx.fillStyle = 'rgba(11, 16, 28, .88)';\n ctx.fillRect(centerX - labelWidth / 2, centerY - labelHeight / 2, labelWidth, labelHeight);\n ctx.fillStyle = '#f8fafc';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText(section.label, centerX, centerY);\n }\n }\n\n /** Letter flags at each channel's centroid — the non-color identity cue. */\n private paintFlags(clusters: Map<string, { x: number; y: number; n: number }>): void {\n const layer = this.layer;\n if (!layer) return;\n layer.querySelectorAll('.slm-ch-flag').forEach((el) => el.remove());\n if (this.view === 'preview') return;\n const ranked = [...clusters.entries()].sort((a, b) => b[1].n - a[1].n).slice(0, MAX_FLAGS);\n for (const [channelId, cluster] of ranked) {\n const channel = this.list?.channels.find((item) => item.id === channelId);\n if (!channel) continue;\n const point = this.host.worldToScreen({ x: cluster.x / cluster.n, y: cluster.y / cluster.n });\n if (!point) continue;\n const marker = this.markerFor(channelId);\n const flag = document.createElement('span');\n flag.className = 'slm-ch-flag';\n flag.style.left = `${point.x}px`;\n flag.style.top = `${point.y}px`;\n flag.innerHTML = `<span class=\"mk\" style=\"background:${esc(marker.color)}\">${esc(marker.letter)}</span>`\n + `${esc(channel.name)}${channel.state === 'paused' ? ' · Paused' : ''}`;\n layer.appendChild(flag);\n }\n }\n\n // ---- staged bar -----------------------------------------------------------\n\n private setStaged(html: string | null, cls = ''): void {\n const bar = this.stagedEl;\n if (!bar) return;\n if (!html) {\n bar.classList.remove('on', 'done', 'shake');\n bar.innerHTML = '';\n return;\n }\n bar.innerHTML = html;\n bar.className = `slm-ch-staged on${cls ? ` ${cls}` : ''}`;\n }\n\n private paintStagedBar(): void {\n if (!this.active || this.view === 'preview' || !this.caps.manage) { this.setStaged(null); return; }\n const { labels, buckets } = this.currentPlan();\n this.host.onStagedChange?.(mutationCount(buckets));\n if (!labels.length) { this.setStaged(null); return; }\n const target = this.nameOf(this.targetChannelId) ?? PUBLIC_CHANNEL_NAME;\n const mutations = mutationCount(buckets);\n const tooLarge = labels.length > MAX_ASSIGNMENT_UNITS;\n const skipped = buckets.skippedHeld.count + buckets.skippedBooked.count;\n const parts = [\n `<b>${labels.length.toLocaleString()}</b> selected`,\n `<b>+${mutations.toLocaleString()}</b> to ${esc(target)}`,\n ];\n if (buckets.alreadyInTarget.count) parts.push(`<b>${buckets.alreadyInTarget.count.toLocaleString()}</b> already in`);\n if (skipped) parts.push(`<b>${skipped.toLocaleString()}</b> can't move now`);\n this.setStaged(`\n <span>${parts.join(' · ')}</span>\n <span class=\"grow\"></span>\n <button type=\"button\" class=\"drop\" data-ch-act=\"discard\">Discard</button>\n <button type=\"button\" class=\"go\" data-ch-act=\"review\"${tooLarge ? ' disabled' : ''}>\n ${tooLarge ? `Maximum ${MAX_ASSIGNMENT_UNITS.toLocaleString()} seats` : 'Review changes'}\n </button>`);\n this.stagedEl?.querySelectorAll<HTMLElement>('[data-ch-act]').forEach((button) => {\n button.addEventListener('click', () => {\n if (button.dataset.chAct === 'discard') this.host.clearSelection();\n else this.openDialog({ kind: 'review' });\n });\n });\n }\n\n private setBanner(on: boolean, name = '', eligibleSeats?: number): void {\n const banner = this.bannerEl;\n if (!banner) return;\n this.host.root.classList.toggle('ch-preview', on);\n if (!on) { banner.classList.remove('on'); banner.innerHTML = ''; return; }\n const marker = this.previewAudience.length === 1\n ? this.markerFor(this.previewAudience[0])\n : { color: 'var(--slm-accent)', letter: '' };\n const availability = eligibleSeats == null\n ? ''\n : ` · ${eligibleSeats.toLocaleString()} ${eligibleSeats === 1 ? 'seat' : 'seats'} available now`;\n banner.innerHTML = `<span class=\"dot\" style=\"background:${esc(marker.color)}\"></span>\n Previewing buyer access · ${esc(name)}${availability} · read-only\n <button type=\"button\" data-ch-act=\"exit-preview\">Exit preview</button>`;\n banner.classList.add('on');\n banner.querySelector('[data-ch-act=\"exit-preview\"]')\n ?.addEventListener('click', () => this.setView('inspect'));\n }\n\n // ---- rail -----------------------------------------------------------------\n\n private setView(view: 'inspect' | 'preview'): void {\n this.view = view;\n if (view === 'inspect') {\n this.previewProjection = null;\n this.previewState = 'idle';\n this.setBanner(false);\n } else {\n if (!this.previewAudience.length) {\n const first = this.list?.channels.find((channel) => channel.state === 'active');\n this.previewAudience = [first ? first.id : PUBLIC_CHANNEL_ID];\n }\n void this.loadPreview();\n }\n this.paintRail();\n this.paintOverlay();\n this.paintStagedBar();\n this.onInteractionChange?.();\n }\n\n /** Set by the cockpit so a view switch can re-arm canvas selection. */\n onInteractionChange?: () => void;\n\n private async loadPreview(): Promise<void> {\n const audience = [...this.previewAudience];\n const names = audience.map((id) => this.nameOf(id) ?? PUBLIC_CHANNEL_NAME).join(' + ');\n this.setBanner(true, names);\n // Switching audience must not leave the previous audience's projection on\n // screen under the new name — that is a wrong answer, not a stale one.\n this.previewProjection = null;\n this.previewState = 'loading';\n if (this.active) this.paintRail();\n try {\n this.previewProjection = await this.host.api.channelPreview(this.host.eventKey, audience, {\n // Naming Public sale as the audience IS asking for public inventory; the\n // route filters the 'public' sentinel out of `channelIds`, so without\n // this the request would resolve to an empty scope and 422.\n includePublic: this.previewIncludePublic || audience.some(isPublicChannelId),\n });\n this.previewState = 'ready';\n // `eligible` is the server's exact current buyer scope. Older workers may\n // omit its redundant aggregate count, so use the returned label count\n // rather than hiding the organiser's most useful confirmation.\n const eligibleSeats = this.previewProjection.available === false\n ? undefined\n : this.previewProjection.counts?.eligible ?? this.previewProjection.eligible?.length;\n this.setBanner(true, names, eligibleSeats);\n } catch (err) {\n // 404/405 = the projection endpoint has not shipped on this worker yet.\n // Say so plainly; never substitute a local approximation for a server view.\n const status = err instanceof ManageApiError ? err.status : 0;\n this.previewState = status === 404 || status === 405 || status === 501 ? 'unsupported' : 'error';\n this.previewProjection = null;\n if (this.previewState === 'error') this.host.onError(err);\n }\n if (this.active) { this.paintRail(); this.paintOverlay(); }\n }\n\n /**\n * Replace the rail's markup — but only when it actually differs, and never at\n * the cost of where the organizer had scrolled to.\n *\n * The rail repaints on a clock, on every selection change and after every\n * mutation. Rewriting `innerHTML` each time resets `scrollTop`, which is\n * exactly what \"the rail gets stuck\" was: scroll down to Create channel, the\n * poll ticks, and the list snaps back to the top under the cursor. So skip the\n * write when the markup is byte-identical, and restore the offset when it is\n * not.\n *\n * Returns whether the DOM was rewritten. Callers must only re-wire listeners\n * when it was — a skipped paint keeps the old nodes AND their listeners, so\n * re-wiring would double every handler.\n */\n private setRailHtml(html: string): boolean {\n if (html === this.railHtml) return false;\n const rail = this.host.rail;\n const scrollTop = rail.scrollTop;\n rail.innerHTML = html;\n this.railHtml = html;\n if (scrollTop) rail.scrollTop = scrollTop;\n return true;\n }\n\n paintRail(): void {\n if (!this.active) return;\n const rail = this.host.rail;\n if (!this.caps.view) {\n this.setRailHtml(`<p class=\"slm-eyebrow\">Sales channels</p>\n <p class=\"slm-hint\">You need channel-management permission on this event to see allocations.</p>`);\n return;\n }\n if (this.loading && !this.list) {\n this.setRailHtml(`<p class=\"slm-eyebrow\">Sales channels</p>\n <div class=\"slm-ch-busy\" role=\"status\" data-ch-state=\"list-loading\">Loading channels and allocations…</div>`);\n return;\n }\n if (!this.list && this.loadError) {\n if (this.setRailHtml(`<p class=\"slm-eyebrow\">Sales channels</p>\n <div class=\"slm-ch-alert err\" role=\"alert\" data-ch-state=\"list-error\"><span>⚠</span>\n <span><b>Couldn't load sales channels.</b> This event may well have channels — we could not read them.\n Everything else on this event still works.\n <button type=\"button\" data-ch-act=\"retry\">Try again</button></span></div>`)) {\n rail.querySelector('[data-ch-act=\"retry\"]')?.addEventListener('click', () => { void this.refresh(); });\n }\n return;\n }\n\n const selection = this.host.selectionLabels();\n const grab = this.host.isCompact()\n ? `<div class=\"slm-ch-grab\"><span class=\"slm-ch-grabbar\"></span></div>`\n : '';\n const segment = this.viewSegmentHtml();\n const body = this.view === 'preview'\n ? this.previewRailHtml()\n : this.detailChannelId\n ? this.detailRailHtml(this.detailChannelId)\n : selection.length && this.caps.manage\n ? this.selectionRailHtml(selection)\n : this.listRailHtml();\n if (this.setRailHtml(`${grab}${segment}${body}`)) this.wireRail();\n this.paintStagedBar();\n }\n\n private viewSegmentHtml(): string {\n // The preview segment is offered even before the projection endpoint exists —\n // choosing it explains the gap rather than hiding the concept.\n const inspectOn = this.view === 'inspect' ? ' on' : '';\n const previewOn = this.view === 'preview' ? ' on' : '';\n return `<div class=\"slm-ch-viewseg\" role=\"group\" aria-label=\"Channels view\">\n <button type=\"button\" class=\"${inspectOn.trim()}\" data-ch-view=\"inspect\"\n aria-pressed=\"${this.view === 'inspect'}\">Inspect allocation</button>\n <button type=\"button\" class=\"${previewOn.trim()}\" data-ch-view=\"preview\"\n aria-pressed=\"${this.view === 'preview'}\">Preview buyer access</button>\n </div>${this.mapNavigationHtml()}`;\n }\n\n private mapNavigationHtml(): string {\n if (this.host.sections().length < 2) return '';\n const focused = this.focusedSectionId\n ? this.host.sections().find((section) => section.id === this.focusedSectionId)?.label ?? 'section'\n : null;\n const panOn = this.mapIntent === 'pan' ? ' on' : '';\n const assignOn = this.mapIntent === 'assign' ? ' on' : '';\n const intent = this.view === 'inspect' && this.caps.manage\n ? `<div class=\"slm-ch-viewseg\" role=\"group\" aria-label=\"Map interaction\">\n <button type=\"button\" class=\"${panOn.trim()}\" data-ch-map=\"pan\" aria-pressed=\"${this.mapIntent === 'pan'}\">Pan map</button>\n <button type=\"button\" class=\"${assignOn.trim()}\" data-ch-map=\"assign\" aria-pressed=\"${this.mapIntent === 'assign'}\">Assign seats</button>\n </div>\n <p>${this.mapIntent === 'pan'\n ? 'Drag to explore. Click a section to open its seats.'\n : 'Drag across seats to select them for allocation.'}</p>`\n : '<p>Drag to explore. Click a section to open its seats.</p>';\n return `<div class=\"slm-ch-mapnav\">\n <div class=\"slm-ch-mapnav-head\"><span>${focused ? `Viewing ${esc(focused)}` : 'Section overview'}</span>\n <button type=\"button\" data-ch-act=\"sections\">All sections</button></div>\n ${intent}\n </div>`;\n }\n\n private countsHtml(counts: { allocated: number; free: number; booked: number; held: number }, key: string): string {\n const cell = (id: string, value: number, label: string, cls = ''): string => {\n const previous = this.lastCounts.get(`${key}:${id}`);\n const bump = previous != null && previous !== value ? ' bump' : '';\n this.lastCounts.set(`${key}:${id}`, value);\n return `<span class=\"${cls}\"><b class=\"${bump.trim()}\">${value.toLocaleString()}</b> ${label}</span>`;\n };\n return `<span class=\"slm-ch-counts\">\n ${cell('allocated', counts.allocated, 'allocated')}\n ${cell('free', counts.free, 'free', 'free')}\n ${cell('booked', counts.booked, 'sold')}\n ${counts.held ? cell('held', counts.held, 'held') : ''}\n </span>`;\n }\n\n private channelRowHtml(\n channel: { id: string; name: string; state: string; counts: ChannelRecord['counts']; access?: ChannelRecord['access'] },\n opts: { builtin?: boolean; index?: number } = {},\n ): string {\n const marker = this.markerFor(channel.id);\n const badgeKind = opts.builtin ? 'builtin' : channel.state;\n const dim = channel.state === 'paused' || channel.state === 'archived' ? ' dim' : '';\n // The whole row opens the channel. It is only a control where there is a\n // channel to open and authority to act on it: Public sale is built in and\n // has no detail panel, and the detail panel is where every mutation lives,\n // so a view-only token is shown a card, not a door it cannot use.\n const opens = !opts.builtin && this.caps.manage && this.detailChannelId !== channel.id;\n const cls = `slm-ch-row${opts.builtin ? ' public' : ''}${channel.state === 'archived' ? ' archived' : ''}`\n + `${this.detailChannelId === channel.id ? ' on' : ''}${opens ? ' open' : ''}`;\n // Mutation affordances are ABSENT for a view-only token, never disabled.\n // ⋯ is now the SECONDARY route: rename, pause and archive live behind it,\n // while opening the channel is the row itself.\n const more = !opts.builtin && this.caps.manage\n ? `<button type=\"button\" class=\"slm-ch-more\" data-ch-menu=\"${esc(channel.id)}\"\n aria-label=\"More actions for ${esc(channel.name)}\" aria-haspopup=\"dialog\">⋯</button>`\n : '';\n const rowAttrs = opens\n ? ` role=\"button\" tabindex=\"0\" data-ch-open=\"${esc(channel.id)}\"\n aria-label=\"Open ${esc(channel.name)}\"`\n : '';\n return `<div class=\"${cls}\"${rowAttrs}>\n <span class=\"slm-ch-head\">\n <span class=\"slm-ch-mk${dim}\" style=\"background:${esc(marker.color)}\" aria-hidden=\"true\">${esc(marker.letter)}</span>\n <span class=\"slm-ch-name\">${esc(channel.name)}</span>\n <span class=\"slm-ch-badge ${badgeKind}\">${esc(stateBadge(opts.builtin ? 'builtin' : channel.state as 'active'))}</span>\n ${more}\n </span>\n ${this.countsHtml(channel.counts, channel.id || 'public')}\n ${opts.builtin ? '' : `<span class=\"slm-ch-access\">${esc(accessLine(channel.access))}</span>`}\n </div>`;\n }\n\n private listRailHtml(): string {\n const list = this.list!;\n const archivedCount = list.channels.filter((channel) => channel.state === 'archived').length;\n const visible = list.channels.filter((channel) => this.showArchived || channel.state !== 'archived');\n const rows = [\n this.channelRowHtml(list.publicSale, { builtin: true }),\n ...visible.map((channel, index) => this.channelRowHtml(channel, { index })),\n ].join('');\n // An event with no private channel is not an error and not a blank slot: every\n // seat is on public sale, which is a real and correct answer. Say that, and\n // put the one action that changes it directly underneath.\n const empty = visible.length ? '' : `<p class=\"slm-note\" data-ch-state=\"list-empty\">${\n archivedCount && !this.showArchived\n ? `No open channels — every seat is on public sale. ${archivedCount.toLocaleString()} archived channel${archivedCount === 1 ? ' is' : 's are'} hidden below.`\n : 'No private channels yet — every seat is on public sale.'}</p>`;\n const create = this.caps.manage\n ? `<button type=\"button\" class=\"slm-btn ghost\" style=\"width:100%\" data-ch-act=\"create\">+ Create channel</button>`\n : '';\n const readOnly = this.caps.manage ? '' :\n `<p class=\"slm-note\">You can see how inventory is allocated. Changing it needs channel-management permission.</p>`;\n return `\n <p class=\"slm-eyebrow\">Sales channels</p>\n <p class=\"slm-hint\">Channel colours and names are only visible to organizers, never to buyers.</p>\n <div class=\"slm-ch-list\">${rows}</div>\n ${empty}\n ${create}\n ${readOnly}\n ${this.assignEntryHtml()}\n <p class=\"slm-note\" style=\"margin-top:10px\">\n <button type=\"button\" class=\"slm-linkbtn\" data-ch-act=\"toggle-archived\" aria-pressed=\"${this.showArchived}\"\n style=\"text-align:left\">${this.showArchived ? 'Hide' : 'Show'} archived${archivedCount ? ` (${archivedCount})` : ''}</button>\n </p>`;\n }\n\n /**\n * The assignment entry point on the list rail.\n *\n * Collapsed it is ONE plain-language action, so the channels the organizer came\n * for stay at the top of the panel. Opened it is the same tool set that has\n * always worked, in the same order, plus the way back out — and opening it is\n * also what the map's \"Assign seats\" segment does, so the two routes into the\n * job cannot disagree about whether it is running.\n */\n private assignEntryHtml(): string {\n if (!this.caps.manage) return '';\n if (!this.assignOpen) {\n return `\n <button type=\"button\" class=\"slm-btn ghost\" style=\"width:100%;margin-top:8px\"\n data-ch-act=\"assign-open\" aria-expanded=\"false\">Assign seats to a channel</button>\n <p class=\"slm-note\">Move whole sections, rows, a dragged area or single seats out of public sale\n and into a channel. Nothing moves until you review and apply.</p>`;\n }\n return `<div style=\"margin-top:8px\">${this.assignmentToolsHtml({ collapsible: true })}</div>`;\n }\n\n /**\n * Destination-first assignment controls.\n *\n * These used to live only inside the selection rail, which meant every route\n * into them was gated behind \"select a seat on the map first\" — the section,\n * row and category choosers were invisible until the organizer had already\n * done the work by hand. They are still reachable before a seat is selected,\n * but they are no longer the first thing in the panel: on the list rail they\n * are disclosed by `assignEntryHtml`, and there they carry a way back out\n * (`collapsible`). In the selection rail there is nothing to disclose — a\n * selection IS the intent — so they paint unconditionally and without Done.\n */\n private assignmentToolsHtml(opts: { collapsible?: boolean } = {}): string {\n const options = this.assignableChannels()\n .map((channel) => `<option value=\"${esc(channel.id)}\"${channel.id === this.targetChannelId ? ' selected' : ''}>${esc(channel.name)}</option>`)\n .join('');\n const sections = this.host.sections().length\n ? '<button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"pick-sections\">Sections</button>' : '';\n const rows = this.assignmentRows().length\n ? '<button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"pick-rows\">Rows</button>' : '';\n // Drag box is a map INTENT, not a dialog: it arms the marquee, so it shows\n // its armed state the same way the map-navigation segment does.\n const dragClass = this.mapIntent === 'assign' ? 'slm-btn' : 'slm-btn ghost';\n const done = opts.collapsible\n ? `<button type=\"button\" class=\"slm-linkbtn\" data-ch-act=\"assign-close\"\n aria-expanded=\"true\" style=\"float:right;font-weight:800\">Done</button>`\n : '';\n return `\n <p class=\"slm-eyebrow\">${done}Assign inventory</p>\n <div class=\"slm-field\">\n <label for=\"slm-ch-target\">Assign to</label>\n <select class=\"slm-select\" id=\"slm-ch-target\" data-ch-target>${options}</select>\n </div>\n <p class=\"slm-eyebrow\" style=\"margin-top:12px\">Select by</p>\n <div class=\"slm-ch-row2\" style=\"margin-top:2px\">\n ${sections}${rows}\n <button type=\"button\" class=\"${dragClass}\" data-ch-act=\"drag-select\">Drag box</button>\n </div>\n <div class=\"slm-ch-row2\">\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"pick-category\">Category</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"seatlist\">Seat list ⌨</button>\n </div>\n <p class=\"slm-note\" style=\"margin-bottom:18px\">Choose a destination, then add whole sections,\n multiple rows, a dragged area, or individual seats.</p>`;\n }\n\n private selectionRailHtml(selection: string[]): string {\n const sources = selectionSources(selection, this.allocation, this.list);\n const conflict = this.conflict\n ? `<div class=\"slm-ch-alert err\" role=\"alert\"><span>⚠</span>\n <span><b>Assignments changed while you were editing.</b> Nothing was applied.\n Your ${selection.length.toLocaleString()}-seat selection is kept.\n <button type=\"button\" data-ch-act=\"refresh-review\">Refresh and review →</button></span></div>`\n : '';\n const bump = selection.length !== this.lastSelectionCount ? ' bump' : '';\n this.lastSelectionCount = selection.length;\n const tooLarge = selection.length > MAX_ASSIGNMENT_UNITS;\n const sourceRows = sources.map((row) => {\n const marker = this.markerFor(row.channelId);\n return `<div class=\"slm-ch-selsrc-row\">\n <span class=\"mk\" style=\"background:${esc(marker.color)}\" aria-hidden=\"true\">${esc(marker.letter)}</span>\n <b>${row.count.toLocaleString()}</b><span>${esc(row.name)}</span></div>`;\n }).join('');\n return `\n ${conflict}\n ${this.assignmentToolsHtml()}\n <div class=\"slm-selbar\"><span class=\"slm-selnum slm-ch-selnum${bump}\">${selection.length.toLocaleString()}</span>\n <span class=\"slm-sellabel\">selected</span></div>\n <div class=\"slm-ch-selsrc\" aria-live=\"polite\" aria-label=\"Selection sources\">${sourceRows}</div>\n ${tooLarge ? `<div class=\"slm-ch-alert warn\" role=\"alert\"><span>ℹ</span><span>\n <b>This selection is too large to apply at once.</b> Choose at most ${MAX_ASSIGNMENT_UNITS.toLocaleString()}\n seats, for example by splitting the venue into row groups.</span></div>` : ''}\n <p class=\"slm-note\">Changes are staged — nothing moves until you review and apply.\n Seats in checkout or already sold are never moved.</p>\n <div class=\"slm-ch-row2\">\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"discard\">Clear selection</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-act=\"review\"${tooLarge ? ' disabled' : ''}>Review changes</button>\n </div>\n <p class=\"slm-note\">The seat list offers the same selection with checkboxes for keyboard and screen-reader use.</p>`;\n }\n\n private detailRailHtml(channelId: string): string {\n const back = `<p class=\"slm-eyebrow\">\n <button type=\"button\" class=\"slm-linkbtn\" data-ch-act=\"back\" style=\"text-align:left\">‹ All channels</button>\n </p>`;\n const channel = this.list?.channels.find((item) => item.id === channelId);\n // Silently falling back to the list here was a lie of omission: an organizer\n // who opened a channel that has since been archived (by them elsewhere, or by\n // a colleague) was returned to the list with no explanation, as though the\n // press had missed. The channel is gone; say so, and leave the way back.\n if (!channel) {\n return `${back}\n <div class=\"slm-ch-alert warn\" role=\"status\" data-ch-state=\"detail-gone\"><span>ℹ</span>\n <span><b>This channel is no longer on this event.</b> It was archived or removed while you had it open.\n ${this.showArchived ? '' : 'Archived channels are hidden — use “Show archived” on the list to see it.'}</span></div>`;\n }\n const lifecycle = this.caps.manage ? `\n <p class=\"slm-eyebrow\" style=\"margin-top:18px\">Lifecycle</p>\n <div class=\"slm-ch-row2\" style=\"margin-top:2px\">\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"rename\">Rename</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"pause\">${channel.state === 'paused' ? 'Resume' : 'Pause'}</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-act=\"archive\">Archive…</button>\n </div>\n <p class=\"slm-note\">Archive returns the allocation to a destination you choose. Nothing is ever deleted silently.</p>` : '';\n const access = this.caps.manage ? this.distributeHtml(channel) : '';\n return `\n ${back}\n <p class=\"slm-eyebrow\">Channel · ${esc(channel.name)}</p>\n <div class=\"slm-ch-list\">${this.channelRowHtml(channel)}</div>\n ${access}\n ${lifecycle}`;\n }\n\n /**\n * \"Distribute\" — the ONE way this channel's seats reach a buyer.\n *\n * All four routes are here, and this is a real chooser again. It was cut down\n * to two actions in 0.42.0 for a good reason: `access_intent` was stored,\n * audited, and read by nothing, so \"Keep as protected reserve\" and \"Sell\n * through your own staff\" were labels an organizer could set and then wait\n * forever for something to happen. The server closed that hole on 2026-08-06 —\n * each declaration now opens exactly one route and REFUSES the other three —\n * so all four are honest choices and belong on the surface.\n *\n * None of the old copy came back with them. These sentences are written\n * against the enforcement matrix (`accessIntentDescription`), which is why\n * each one says what the route refuses as well as what it allows.\n *\n * The current route is stated, not merely styled: a chooser whose selection\n * you have to infer from a border is not a chooser. Its card carries a\n * \"Current route\" marker and drops its own select button, because pressing it\n * would do nothing.\n */\n private distributeHtml(channel: ChannelRecord): string {\n const intent = (channel.access?.intent ?? 'none') as ChannelAccessIntent;\n const live = channel.access?.hasActiveGrants === true;\n // A worker that predates buyer links answers 404 on the listing route, and\n // would answer 404 on the create too. Offering the action there would be a\n // button that can only fail; the status block below says why it is absent.\n const linksSupported = this.linksState !== 'unsupported';\n const hasLiveLink = this.links.some(accessLinkIsLive);\n // What is true RIGHT NOW — the route plus whether anyone has actually come\n // through it. \"Seats stay reserved\" is not a consolation: an allocated seat\n // is withheld from public sale either way, and that IS the useful fact.\n const state = intent === 'none'\n ? 'Protected reserve — no route can sell these seats. Every buyer path is refused.'\n : intent === 'internal'\n ? 'Your staff sell these seats. No buyer-facing route is open.'\n : live\n ? intent === 'server'\n ? 'Your website is letting buyers in. Only they can buy these seats.'\n : 'A buyer link is live. Only people with that link can buy these seats.'\n : intent === 'server'\n ? 'Set up for your website — no buyer has come through yet. Seats stay reserved.'\n : 'Set up for buyer links — no buyer has come through yet. Seats stay reserved.';\n const option = (\n route: ChannelAccessIntent, action: string, cta: string, primary: boolean,\n ): string => {\n const current = route === intent;\n return `<div class=\"slm-ch-dist${current ? ' on' : ''}\" data-ch-route=\"${esc(route)}\">\n <b>${esc(accessIntentLabel(route))}${current ? '<span class=\"cur\">Current route</span>' : ''}</b>\n <span class=\"why\">${esc(accessIntentDescription(route))}</span>\n ${current && !cta ? '' : `<button type=\"button\" class=\"slm-btn${primary && !current ? '' : ' ghost'}\"\n data-ch-act=\"${esc(action)}\">${esc(cta)}</button>`}\n </div>`;\n };\n return `\n <p class=\"slm-eyebrow\" style=\"margin-top:14px\">Distribute</p>\n <p class=\"slm-hint\">${esc(state)}</p>\n ${linksSupported ? option(\n 'hosted_link', 'link-create',\n hasLiveLink ? 'Create another buyer link' : 'Create buyer link', true,\n ) : ''}\n ${option('server', 'embed-code', intent === 'server' ? 'Get embed code' : 'Use a website or app', false)}\n ${option('internal', 'route-internal', intent === 'internal' ? '' : 'Hand to your staff', false)}\n ${option('none', 'route-none', intent === 'none' ? '' : 'Keep as reserve', false)}\n ${this.hostedLinksHtml()}\n ${intent === 'server' ? SERVER_INTEGRATION_HTML : ''}`;\n }\n\n // ---- buyer links ----------------------------------------------------------\n\n /**\n * Read the status projection for the open channel. Never paints — the caller\n * decides when the rail repaints, so a poll-driven reload does not fight a\n * user-driven one. A worker without M8 answers 404/405 and gets the honest\n * \"needs a newer server\" line rather than an error toast.\n */\n private async loadLinks(channelId: string): Promise<void> {\n if (!this.caps.view) return;\n const seq = ++this.linksSeq;\n // Superseded by a newer read of the same channel — a poll that started\n // before the mutation must not overwrite the mutation's own answer.\n const superseded = (): boolean => seq !== this.linksSeq || this.linksChannelId !== channelId;\n if (this.linksChannelId !== channelId) {\n this.links = [];\n this.linksChannelId = channelId;\n this.linksState = 'loading';\n }\n try {\n const res = await this.host.api.accessLinks(this.host.eventKey, channelId);\n if (superseded()) return; // the organizer moved on, or a fresher read won\n this.links = res.links ?? [];\n this.linksState = 'ready';\n } catch (err) {\n if (superseded()) return;\n const status = err instanceof ManageApiError ? err.status : 0;\n this.links = [];\n this.linksState = status === 404 || status === 405 || status === 501 ? 'unsupported' : 'error';\n if (this.linksState === 'error') this.host.onError(err);\n }\n }\n\n /**\n * The buyer-link status section of the detail panel.\n *\n * STATUS ONLY, by design (comp 06 `hosted`): label, state, expiry,\n * redemptions, seats per buyer, live sessions. There is no Copy control here\n * and no field to hang one on — the URL was shown once at creation and cannot\n * be produced again. Rotation is the recovery path, and it says so.\n *\n * Creating a link is the Distribute card's action, not this section's, so a\n * channel with no links renders nothing here rather than an empty heading and\n * a second button saying the same thing.\n */\n private hostedLinksHtml(): string {\n const eyebrow = `<p class=\"slm-eyebrow\" style=\"margin-top:18px\">Buyer links</p>`;\n if (this.linksState === 'unsupported') {\n return `${eyebrow}<div class=\"slm-ch-alert warn\" data-ch-state=\"links-unsupported\"><span>ℹ</span>\n <span><b>Buyer links need a newer server.</b> Everything else on this channel works normally.</span></div>`;\n }\n if (this.linksState === 'error') {\n return `${eyebrow}<div class=\"slm-ch-alert err\" role=\"alert\" data-ch-state=\"links-error\"><span>⚠</span>\n <span><b>Couldn't load this channel's links.</b> This is a failed read, not an empty list —\n any live link is still working.\n <button type=\"button\" data-ch-act=\"link-reload\">Try again</button></span></div>`;\n }\n // `idle` is the first paint of a channel the organizer has only just opened —\n // `openChannel` paints before `loadLinks` has even been awaited. Rendering\n // nothing there was a flash of empty that reads as \"this channel has no\n // links\", one tick before the real answer arrives.\n if (this.linksState === 'idle' || (this.linksState === 'loading' && !this.links.length)) {\n return `${eyebrow}<div class=\"slm-ch-busy\" role=\"status\" data-ch-state=\"links-loading\">Loading buyer links…</div>`;\n }\n if (!this.links.length) return '';\n return `${eyebrow}\n ${this.links.map((link) => this.linkCardHtml(link)).join('')}\n <p class=\"slm-note\">A link is shown once, when you create it. SeatLayer keeps only a fingerprint of it, so it\n can never be shown again — if a link is lost, rotate it and send the fresh one.</p>`;\n }\n\n private linkCardHtml(link: AccessLinkStatusRecord): string {\n const badge = accessLinkBadge(link);\n const used = link.maxRedemptions > 0\n ? Math.min(100, Math.round((link.redemptions / link.maxRedemptions) * 100))\n : 0;\n const rows = accessLinkPolicyLines(link)\n .map((row) => `<div class=\"slm-ch-lkrow\"><span class=\"k\">${esc(row.k)}</span>\n <span class=\"v\">${esc(row.v)}</span></div>`).join('');\n const sessions = link.activeSessions\n ? `<div class=\"slm-ch-lkrow\"><span class=\"k\">Buyers inside now</span>\n <span class=\"v\">${link.activeSessions.toLocaleString()}</span></div>`\n : '';\n const lastUsed = link.lastRedeemedAt\n ? `<div class=\"slm-ch-lkrow\"><span class=\"k\">Last opened</span>\n <span class=\"v\">${esc(new Date(link.lastRedeemedAt).toLocaleString())}</span></div>`\n : '';\n const actions = this.caps.manage && accessLinkIsLive(link)\n ? `<div class=\"slm-ch-row2\">\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-rotate=\"${esc(link.id)}\">Rotate</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-revoke=\"${esc(link.id)}\">Revoke</button>\n </div>`\n : '';\n return `<div class=\"slm-ch-link\">\n <span class=\"lk-head\">\n <span class=\"lk-name\">${esc(link.label || 'Buyer link')}</span>\n <span class=\"slm-ch-badge ${badge.kind}\">${esc(badge.text)}</span>\n </span>\n <div class=\"slm-ch-meter\" role=\"img\"\n aria-label=\"${link.redemptions.toLocaleString()} of ${link.maxRedemptions.toLocaleString()} redemptions used\">\n <i style=\"width:${used}%\"></i></div>\n ${rows}${sessions}${lastUsed}\n <div class=\"slm-ch-lkrow\"><span class=\"k\">The URL</span>\n <span class=\"v\">Revealed once at creation — not recoverable</span></div>\n ${actions}\n </div>`;\n }\n\n private previewRailHtml(): string {\n const audienceOptions = [\n { id: PUBLIC_CHANNEL_ID, name: this.list?.publicSale.name ?? PUBLIC_CHANNEL_NAME },\n ...(this.list?.channels ?? [])\n .filter((channel) => channel.state !== 'archived')\n .map((channel) => ({ id: channel.id, name: channel.name })),\n ];\n const current = this.previewAudience[0] ?? PUBLIC_CHANNEL_ID;\n const options = audienceOptions\n .map((entry) => `<option value=\"${esc(entry.id)}\"${entry.id === current ? ' selected' : ''}>${esc(entry.name)}</option>`)\n .join('');\n const unsupported = this.previewState === 'unsupported'\n ? `<div class=\"slm-ch-alert warn\" data-ch-state=\"preview-unsupported\"><span>ℹ</span>\n <span><b>Preview needs a newer server.</b> Allocation management works normally;\n the buyer-view simulation will appear once this event's API is updated.</span></div>`\n : '';\n // Loading and failure are distinct from \"this audience can buy nothing\",\n // which is what an empty result area used to imply for all three.\n const busy = this.previewState === 'loading'\n ? `<div class=\"slm-ch-busy\" role=\"status\" data-ch-state=\"preview-loading\">Asking the server what this audience sees…</div>`\n : '';\n const failed = this.previewState === 'error'\n ? `<div class=\"slm-ch-alert err\" role=\"alert\" data-ch-state=\"preview-error\"><span>⚠</span>\n <span><b>Couldn't load the buyer preview.</b> Nothing is wrong with this audience's seats —\n the simulation itself failed to load.\n <button type=\"button\" data-ch-act=\"preview-retry\">Try again</button></span></div>`\n : '';\n // The server decides an audience is unpreviewable, not the client: a paused\n // or archived channel comes back `available:false` and we show the landing\n // state a real buyer would hit.\n const unavailable = this.previewProjection?.available === false\n ? `<div class=\"slm-ch-alert warn\" role=\"status\"><span>⏸</span>\n <span><b>This private sale is not available.</b> ${esc((this.previewProjection.unavailable ?? [])\n .map((entry) => `${this.nameOf(entry.channelId) ?? 'This channel'} is ${entry.state}`)\n .join('; ') || 'The audience cannot buy right now')}.\n A buyer arriving with this access sees this message, not these seats.</span></div>`\n : '';\n const eligibleSeats = this.previewProjection?.counts?.eligible ?? this.previewProjection?.eligible?.length;\n const summary = eligibleSeats != null && this.previewProjection?.available !== false\n ? `<div class=\"slm-ch-alert info\"><span>✓</span><span><b>${eligibleSeats.toLocaleString()} ${eligibleSeats === 1 ? 'seat is' : 'seats are'} available now.</b>\n This is the exact buyer-visible allocation.${this.previewProjection?.includePublic === false\n ? ' Public sale seats are <b>not</b> included in this access.' : ''}</span></div>`\n : '';\n const includePublic = isPublicChannelId(current) ? '' : `\n <label class=\"slm-note\" style=\"display:flex;gap:8px;align-items:center;margin:10px 0\">\n <input type=\"checkbox\" data-ch-includepublic ${this.previewIncludePublic ? 'checked' : ''} />\n Also include Public sale seats in this grant\n </label>`;\n return `\n <p class=\"slm-eyebrow\">Preview buyer access</p>\n <div class=\"slm-field\">\n <label for=\"slm-ch-audience\">Audience</label>\n <select class=\"slm-select\" id=\"slm-ch-audience\" data-ch-audience>${options}</select>\n </div>\n ${includePublic}\n <p class=\"slm-hint\">This is the same projection the buyer SDK receives for this audience — not a local\n approximation. It is read-only: clicks open seat details, and no holds are created.</p>\n ${busy}${failed}${unsupported}${unavailable}\n <div class=\"slm-ch-legend\">\n <div class=\"r\"><span class=\"sw\" style=\"background:#6e7bff\"></span> Eligible & free — buyable by this audience</div>\n <div class=\"r\"><span class=\"sw\" style=\"background:#3a4051\"></span> Unavailable to this audience (one neutral state)</div>\n <div class=\"r\"><span class=\"sw\" style=\"background:#22a06b\"></span> Sold — same as any buyer sees</div>\n </div>\n ${summary}`;\n }\n\n private paintSelection(): void {\n // A selection proves the intent the disclosure was waiting for, so clearing\n // it later returns the organizer to the tools rather than to the collapsed\n // action they would have to press again.\n if (this.caps.manage && this.host.selectionLabels().length) this.assignOpen = true;\n // A selection change swaps the rail between list and staged-selection bodies,\n // so repaint rather than patch — the rail is small and this keeps one path.\n if (this.view === 'inspect' && !this.detailChannelId) this.paintRail();\n }\n\n private wireRail(): void {\n const rail = this.host.rail;\n rail.querySelectorAll<HTMLElement>('[data-ch-view]').forEach((button) => {\n button.addEventListener('click', () => this.setView(button.dataset.chView as 'inspect' | 'preview'));\n });\n rail.querySelectorAll<HTMLElement>('[data-ch-map]').forEach((button) => {\n button.addEventListener('click', () => {\n this.mapIntent = button.dataset.chMap === 'assign' ? 'assign' : 'pan';\n // Arming the marquee IS asking to assign, so the tools that finish the\n // job come with it. This is the discoverable route for an organizer who\n // never pressed \"Assign seats to a channel\" under the list.\n if (this.mapIntent === 'assign') this.assignOpen = true;\n this.paintRail();\n this.onInteractionChange?.();\n });\n });\n // The whole row is the door. It is a role=\"button\" element, so it owes the\n // keyboard the two keys a real button answers to — and Space must not scroll\n // the rail on the way.\n rail.querySelectorAll<HTMLElement>('[data-ch-open]').forEach((row) => {\n const open = (): void => this.openChannel(row.dataset.chOpen!);\n row.addEventListener('click', open);\n row.addEventListener('keydown', (event) => {\n if (event.key !== 'Enter' && event.key !== ' ' && event.key !== 'Spacebar') return;\n event.preventDefault();\n open();\n });\n });\n // ⋯ sits INSIDE that door, so it must not also open it.\n rail.querySelectorAll<HTMLElement>('[data-ch-menu]').forEach((button) => {\n button.addEventListener('click', (event) => {\n event.stopPropagation();\n this.openDialog({ kind: 'menu', channelId: button.dataset.chMenu! });\n });\n button.addEventListener('keydown', (event) => { event.stopPropagation(); });\n });\n rail.querySelectorAll<HTMLElement>('[data-ch-rotate]').forEach((button) => {\n button.addEventListener('click', () => this.openDialog({\n kind: 'linkRotate', channelId: this.detailChannelId!, linkId: button.dataset.chRotate!,\n }));\n });\n rail.querySelectorAll<HTMLElement>('[data-ch-revoke]').forEach((button) => {\n button.addEventListener('click', () => this.openDialog({\n kind: 'linkRevoke', channelId: this.detailChannelId!, linkId: button.dataset.chRevoke!,\n }));\n });\n const target = rail.querySelector<HTMLSelectElement>('[data-ch-target]');\n target?.addEventListener('change', () => {\n this.targetChannelId = target.value;\n this.conflict = false;\n this.paintRail();\n });\n const audience = rail.querySelector<HTMLSelectElement>('[data-ch-audience]');\n audience?.addEventListener('change', () => {\n this.previewAudience = [audience.value];\n void this.loadPreview();\n });\n const includePublic = rail.querySelector<HTMLInputElement>('[data-ch-includepublic]');\n includePublic?.addEventListener('change', () => {\n this.previewIncludePublic = includePublic.checked;\n void this.loadPreview();\n });\n const grab = rail.querySelector<HTMLElement>('.slm-ch-grab');\n grab?.addEventListener('click', () => this.cycleDetent());\n rail.querySelectorAll<HTMLElement>('[data-ch-act]').forEach((button) => {\n button.addEventListener('click', () => this.railAction(button.dataset.chAct!));\n });\n }\n\n /** Open a channel's detail panel and start its buyer-link read. */\n private openChannel(channelId: string): void {\n this.detailChannelId = channelId;\n // Paint the panel FIRST so the organizer lands on the channel immediately,\n // with the links section showing its own loading state, rather than waiting\n // on a network read behind an unchanged rail.\n this.paintRail();\n void this.loadLinks(channelId).then(() => this.paintRail());\n }\n\n private railAction(action: string): void {\n switch (action) {\n case 'sections':\n this.focusedSectionId = null;\n this.host.showSectionOverview();\n this.paintRail();\n break;\n case 'create': this.openDialog({ kind: 'create' }); break;\n case 'review': this.openDialog({ kind: 'review' }); break;\n case 'rename': this.openDialog({ kind: 'rename', channelId: this.detailChannelId! }); break;\n case 'archive': this.openDialog({ kind: 'archive', channelId: this.detailChannelId! }); break;\n case 'seatlist': this.openDialog({ kind: 'seatlist' }); break;\n case 'pause': void this.togglePause(); break;\n case 'discard': this.host.clearSelection(); break;\n case 'back':\n this.detailChannelId = null;\n this.linksChannelId = null;\n this.links = [];\n this.linksState = 'idle';\n this.paintRail();\n break;\n // Choosing the buyer-link route IS creating the first link — the dialog\n // declares the route on submit (see `createLink`), so this stays one\n // gesture whether the channel is already on `hosted_link` or not.\n case 'link-create':\n this.openDialog({ kind: 'linkCreate', channelId: this.detailChannelId! });\n break;\n // The one thing this screen can actually do for a website integration is\n // record that the channel is meant for one — and since 2026-08-06 that\n // record is what AUTHORIZES the integration to mint buyer sessions at all,\n // so it is the substantive half of the job, not a flag.\n case 'embed-code': void this.chooseWebsiteIntegration(); break;\n case 'route-internal': void this.setAccessIntent('internal'); break;\n case 'route-none': void this.setAccessIntent('none'); break;\n case 'link-reload':\n if (this.detailChannelId) void this.reloadLinks();\n break;\n case 'retry': void this.refresh(); break;\n case 'toggle-archived':\n this.showArchived = !this.showArchived;\n void this.refresh();\n break;\n case 'refresh-review':\n this.conflict = false;\n void this.refresh().then(() => this.openDialog({ kind: 'review' }));\n break;\n case 'pick-sections': this.openDialog({ kind: 'scope', scope: 'sections' }); break;\n case 'pick-rows': this.openDialog({ kind: 'scope', scope: 'rows' }); break;\n case 'drag-select':\n this.mapIntent = 'assign';\n this.paintRail();\n this.onInteractionChange?.();\n break;\n case 'pick-category': this.pickCategory(); break;\n case 'assign-open':\n this.assignOpen = true;\n this.paintRail();\n break;\n // Collapsing the tools must also disarm the marquee. Leaving it armed\n // would hide a mode the map is still in — the organizer would drag to pan\n // and select seats instead, with no control on screen saying why.\n case 'assign-close':\n this.assignOpen = false;\n this.mapIntent = 'pan';\n this.paintRail();\n this.onInteractionChange?.();\n break;\n case 'preview-retry': void this.loadPreview(); break;\n default: break;\n }\n }\n\n // ---- selection helpers ----------------------------------------------------\n\n /** Derived once per mode entry — see `assignmentRowsCache`. */\n private assignmentRows(): ChannelsRowView[] {\n if (!this.assignmentRowsCache) this.assignmentRowsCache = this.host.rows();\n return this.assignmentRowsCache;\n }\n\n private pickCategory(): void {\n const categories = this.host.categories();\n if (!categories.length) return;\n this.promptChoice('Select a whole category', categories.map((c) => ({ value: c.key, label: c.label })), (value) => {\n this.host.selectByLabels(this.host.labelsInCategory(value));\n });\n }\n\n /** A tiny modal chooser reusing the dialog primitive (focus trap + Escape). */\n private promptChoice(\n title: string,\n options: Array<{ value: string; label: string }>,\n onPick: (value: string) => void,\n ): void {\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">${esc(title)}</h3>\n <div class=\"slm-field\">\n <label for=\"slm-ch-choice\">Choose one</label>\n <select class=\"slm-select\" id=\"slm-ch-choice\">\n ${options.map((option) => `<option value=\"${esc(option.value)}\">${esc(option.label)}</option>`).join('')}\n </select>\n </div>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-confirm>Select</button>\n </div>`, (root) => {\n root.querySelector('[data-ch-confirm]')?.addEventListener('click', () => {\n const select = root.querySelector<HTMLSelectElement>('#slm-ch-choice');\n const value = select?.value;\n this.closeDialog();\n if (value) onPick(value);\n });\n });\n }\n\n /**\n * Add several whole sections, or several whole rows, in one operation.\n *\n * ADDITIVE by contract: the chooser starts from the labels already selected\n * and only ever grows that set, so opening it never destroys a hard-won\n * marquee or seat-list selection. The confirm button always states the net\n * number of seats it will add, and refuses to exceed `MAX_ASSIGNMENT_UNITS`.\n *\n * Rows get the richer variant. A large venue has thousands of them, so they\n * arrive collapsed under their section, with a section-level tri-state\n * checkbox, a search across every row, and a render cap — the flat list used\n * for sections would be an unusable wall of buttons.\n */\n private renderScopeDialog(state: DialogState): void {\n const scope = state.scope === 'rows' ? 'rows' : 'sections';\n const options = scope === 'sections'\n ? this.host.sections().map((section) => ({\n id: section.id,\n label: section.label,\n group: 'Sections',\n labels: this.host.labelsInSection(section.id),\n }))\n : this.assignmentRows().map((row) => ({\n id: row.id,\n label: row.label,\n group: row.sectionLabel,\n labels: row.labels,\n }));\n // A section or row with nothing selectable in it is a dead entry, not a\n // choice — offering it would produce an \"Add 0 seats\" button.\n const available = options.filter((option) => option.labels.length > 0);\n const grouped = new Map<string, typeof available>();\n for (const option of available) {\n const group = grouped.get(option.group) ?? [];\n group.push(option);\n grouped.set(option.group, group);\n }\n\n if (scope === 'rows') {\n const groups = [...grouped.entries()];\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Add multiple rows</h3>\n <p class=\"sub\">Sections stay collapsed for speed. Select a whole section, expand only the rows you need, or search across every row.</p>\n <div class=\"slm-ch-scopebar\">\n <label>Find section or row<input type=\"search\" data-ch-scope-search placeholder=\"e.g. Orchestra or AA\"></label>\n <span class=\"slm-ch-scopesummary\" data-ch-scope-summary aria-live=\"polite\">0 rows selected</span>\n </div>\n <p class=\"slm-ch-scopehint\" data-ch-scope-filter>Showing section groups. Expand one or search to see rows.</p>\n <div class=\"slm-ch-seatlist\" data-ch-scope-list></div>\n <p class=\"slm-ch-err\" data-ch-error hidden></p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-add-scope disabled>Add seats</button>\n </div>`, (dialog) => {\n const byId = new Map(available.map((option) => [option.id, option]));\n const picked = new Set<string>();\n const expanded = new Set<number>();\n const current = new Set(this.host.selectionLabels());\n const confirm = dialog.querySelector<HTMLButtonElement>('[data-ch-add-scope]')!;\n const error = dialog.querySelector<HTMLElement>('[data-ch-error]')!;\n const list = dialog.querySelector<HTMLElement>('[data-ch-scope-list]')!;\n const search = dialog.querySelector<HTMLInputElement>('[data-ch-scope-search]')!;\n const summary = dialog.querySelector<HTMLElement>('[data-ch-scope-summary]')!;\n const filterHint = dialog.querySelector<HTMLElement>('[data-ch-scope-filter]')!;\n const renderLimit = 200;\n let query = '';\n\n const selectedLabels = (): Set<string> => {\n const labels = new Set(current);\n for (const id of picked) for (const label of byId.get(id)?.labels ?? []) labels.add(label);\n return labels;\n };\n const update = (): void => {\n const labels = selectedLabels();\n const added = labels.size - current.size;\n const tooLarge = labels.size > MAX_ASSIGNMENT_UNITS;\n confirm.disabled = added === 0 || tooLarge;\n confirm.textContent = tooLarge\n ? `Maximum ${MAX_ASSIGNMENT_UNITS.toLocaleString()} seats`\n : `Add ${added.toLocaleString()} seat${added === 1 ? '' : 's'}`;\n error.hidden = !tooLarge;\n error.textContent = tooLarge\n ? `That would make ${labels.size.toLocaleString()} selected seats. Choose fewer rows or sections.`\n : '';\n summary.textContent = `${picked.size.toLocaleString()} row${picked.size === 1 ? '' : 's'} · ${added.toLocaleString()} seat${added === 1 ? '' : 's'} added`;\n };\n const renderList = (): void => {\n const blocks: string[] = [];\n let totalMatches = 0;\n let rendered = 0;\n groups.forEach(([group, items], groupIndex) => {\n const normalizedGroup = group.toLocaleLowerCase();\n const matches = query\n ? items.filter((item) => `${normalizedGroup} ${item.label.toLocaleLowerCase()}`.includes(query))\n : items;\n if (query && !matches.length) return;\n totalMatches += matches.length;\n const allPicked = items.every((item) => picked.has(item.id));\n const somePicked = !allPicked && items.some((item) => picked.has(item.id));\n const open = Boolean(query) || expanded.has(groupIndex);\n const room = Math.max(0, renderLimit - rendered);\n const visible = open ? matches.slice(0, room) : [];\n rendered += visible.length;\n const seatCount = items.reduce((sum, item) => sum + item.labels.length, 0);\n blocks.push(`<div class=\"slm-ch-scopegroup\">\n <button type=\"button\" class=\"slm-ch-groupcheck\" role=\"checkbox\" aria-checked=\"${allPicked ? 'true' : somePicked ? 'mixed' : 'false'}\"\n aria-label=\"Select all ${items.length.toLocaleString()} rows in ${esc(group)}\" data-ch-scope-group=\"${groupIndex}\">\n <span class=\"box\" aria-hidden=\"true\">✓</span><span>${esc(group)}</span>\n <span class=\"meta\">${items.length.toLocaleString()} rows · ${seatCount.toLocaleString()} seats</span>\n </button>\n <button type=\"button\" class=\"slm-ch-grouptoggle\" aria-expanded=\"${open}\" aria-label=\"${open ? 'Hide' : 'Show'} rows in ${esc(group)}\"\n data-ch-scope-toggle=\"${groupIndex}\">${open ? 'Hide' : 'Show'}</button>\n </div>`);\n blocks.push(...visible.map((option) => `<button type=\"button\" class=\"slm-ch-seatitem\" role=\"checkbox\"\n aria-checked=\"${picked.has(option.id)}\" data-ch-scope-id=\"${esc(option.id)}\">\n <span class=\"box\" aria-hidden=\"true\">✓</span><span>${esc(option.label)}</span>\n <span class=\"meta\">${option.labels.length.toLocaleString()} seat${option.labels.length === 1 ? '' : 's'}</span>\n </button>`));\n if (open && matches.length > visible.length) {\n blocks.push(`<p class=\"slm-ch-scopehint\">${(matches.length - visible.length).toLocaleString()} more row${matches.length - visible.length === 1 ? '' : 's'}. Search to narrow the list.</p>`);\n }\n });\n // Two different nothings: nothing matched the search, versus this chart\n // has no assignable rows at all. The second one is not a search result.\n list.innerHTML = blocks.join('')\n || (query\n ? `<div class=\"slm-ch-scope-empty\" data-ch-state=\"scope-nomatch\">No sections or rows match “${esc(query)}”.</div>`\n : `<div class=\"slm-ch-scope-empty\" data-ch-state=\"scope-empty\">This chart has no rows with selectable seats.\n Use Drag box or the seat list instead.</div>`);\n filterHint.textContent = query\n ? `Showing ${rendered.toLocaleString()} of ${totalMatches.toLocaleString()} matching rows. Section checkboxes still select every row in that section.`\n : 'Showing section groups. Expand one or search to see rows.';\n list.querySelectorAll<HTMLElement>('[data-ch-scope-group]').forEach((button) => button.addEventListener('click', () => {\n const items = groups[Number(button.dataset.chScopeGroup)]?.[1] ?? [];\n const remove = items.every((item) => picked.has(item.id));\n for (const item of items) remove ? picked.delete(item.id) : picked.add(item.id);\n renderList();\n update();\n }));\n list.querySelectorAll<HTMLElement>('[data-ch-scope-toggle]').forEach((button) => button.addEventListener('click', () => {\n const index = Number(button.dataset.chScopeToggle);\n if (expanded.has(index)) expanded.delete(index);\n else expanded.add(index);\n renderList();\n }));\n list.querySelectorAll<HTMLElement>('[data-ch-scope-id]').forEach((button) => button.addEventListener('click', () => {\n const id = button.dataset.chScopeId!;\n if (picked.has(id)) picked.delete(id);\n else picked.add(id);\n renderList();\n update();\n }));\n };\n\n search.addEventListener('input', () => {\n query = search.value.trim().toLocaleLowerCase();\n renderList();\n update();\n });\n confirm.addEventListener('click', () => {\n const labels = [...selectedLabels()];\n if (!picked.size || labels.length > MAX_ASSIGNMENT_UNITS) return;\n this.closeDialog();\n this.host.selectByLabels(labels);\n });\n renderList();\n update();\n });\n return;\n }\n\n const body = [...grouped.entries()].map(([group, items]) => `\n <div class=\"slm-ch-seatgroup\"><span>${esc(group)}</span></div>\n ${items.map((option) => `<button type=\"button\" class=\"slm-ch-seatitem\" role=\"checkbox\"\n aria-checked=\"false\" data-ch-scope-id=\"${esc(option.id)}\">\n <span class=\"box\" aria-hidden=\"true\">✓</span>\n <span>${esc(option.label)}</span>\n <span class=\"meta\">${option.labels.length.toLocaleString()} seat${option.labels.length === 1 ? '' : 's'}</span>\n </button>`).join('')}`).join('');\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Add whole sections</h3>\n <p class=\"sub\">Choose one or more. They are added to the seats already selected on the map.</p>\n <div class=\"slm-ch-seatlist\">${body || `<div class=\"slm-ch-scope-empty\" data-ch-state=\"scope-empty\">This chart has no sections with selectable seats.\n Use Drag box or the seat list instead.</div>`}</div>\n <p class=\"slm-ch-err\" data-ch-error hidden></p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-add-scope disabled>Add seats</button>\n </div>`, (dialog) => {\n const byId = new Map(available.map((option) => [option.id, option]));\n const picked = new Set<string>();\n const current = new Set(this.host.selectionLabels());\n const confirm = dialog.querySelector<HTMLButtonElement>('[data-ch-add-scope]')!;\n const error = dialog.querySelector<HTMLElement>('[data-ch-error]')!;\n const selectedLabels = (): Set<string> => {\n const labels = new Set(current);\n for (const id of picked) for (const label of byId.get(id)?.labels ?? []) labels.add(label);\n return labels;\n };\n const update = (): void => {\n const labels = selectedLabels();\n const added = labels.size - current.size;\n const tooLarge = labels.size > MAX_ASSIGNMENT_UNITS;\n confirm.disabled = added === 0 || tooLarge;\n confirm.textContent = tooLarge\n ? `Maximum ${MAX_ASSIGNMENT_UNITS.toLocaleString()} seats`\n : `Add ${added.toLocaleString()} seat${added === 1 ? '' : 's'}`;\n error.hidden = !tooLarge;\n error.textContent = tooLarge\n ? `That would make ${labels.size.toLocaleString()} selected seats. Choose fewer rows or sections.`\n : '';\n };\n dialog.querySelectorAll<HTMLElement>('[data-ch-scope-id]').forEach((button) => {\n button.addEventListener('click', () => {\n const id = button.dataset.chScopeId!;\n if (picked.has(id)) picked.delete(id);\n else picked.add(id);\n button.setAttribute('aria-checked', String(picked.has(id)));\n update();\n });\n });\n confirm.addEventListener('click', () => {\n const labels = [...selectedLabels()];\n if (!picked.size || labels.length > MAX_ASSIGNMENT_UNITS) return;\n this.closeDialog();\n this.host.selectByLabels(labels);\n });\n update();\n });\n }\n\n // ---- dialogs --------------------------------------------------------------\n\n private openDialog(state: DialogState): void {\n this.dialog = state;\n this.renderDialog();\n }\n\n private renderDialog(): void {\n const state = this.dialog;\n if (!state) return;\n if (state.kind === 'create') this.renderCreateDialog(state);\n else if (state.kind === 'review') this.renderReviewDialog(state);\n else if (state.kind === 'scope') this.renderScopeDialog(state);\n else if (state.kind === 'archive') this.renderArchiveDialog(state);\n else if (state.kind === 'rename') this.renderRenameDialog(state);\n else if (state.kind === 'seatlist') this.renderSeatListDialog();\n else if (state.kind === 'menu') this.renderMenuDialog(state);\n else if (state.kind === 'linkCreate') this.renderLinkCreateDialog(state);\n else if (state.kind === 'linkRotate') this.renderLinkRotateDialog(state);\n else if (state.kind === 'linkRevoke') this.renderLinkRevokeDialog(state);\n else if (state.kind === 'intentSwitch') this.renderIntentSwitchDialog(state);\n }\n\n /**\n * `channel_intent_switch_blocked` — buyers are inside the route being left.\n *\n * The same review-then-acknowledge shape as the archive and chart-drop guards,\n * because it is the same kind of decision: the server refuses once, names\n * exactly what is at stake, and only a deliberate second press goes through.\n * What acknowledging does is spelled out per consequence — links close now,\n * checkouts already running survive and drain — rather than hidden behind a\n * word like \"force\".\n */\n private renderIntentSwitchDialog(state: DialogState): void {\n const channel = this.list?.channels.find((item) => item.id === state.channelId);\n const to = state.intentTo;\n if (!channel || !to || !this.caps.manage) { this.closeDialog(); return; }\n const { headline, consequences } = intentSwitchBlockedCopy(state.switchBlocked);\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Change how ${esc(channel.name)} reaches buyers?</h3>\n <p class=\"sub\">${esc(headline)}</p>\n <div class=\"slm-ch-alert warn\" role=\"alert\"><span>⚠</span><span>\n ${consequences.map((line) => `<span style=\"display:block;margin-bottom:6px\">${esc(line)}</span>`).join('')}\n </span></div>\n ${state.pendingLink ? `<p class=\"slm-note\">Your new buyer link is created as soon as\n the route changes — you will not have to fill the form in again.</p>` : ''}\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Leave it as it is</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-intent-ack${state.busy ? ' disabled' : ''}>\n ${state.busy ? 'Changing…' : `Change to \"${esc(accessIntentLabel(to))}\"`}</button>\n </div>`, (dialog) => {\n dialog.querySelector('[data-ch-intent-ack]')?.addEventListener('click', () => {\n void this.acknowledgeIntentSwitch(to, state.pendingLink ?? null);\n });\n });\n }\n\n /**\n * The acknowledged retry. The declare and the create stay one gesture across\n * the sheet: if this switch was the first half of a declare-then-create, the\n * held form finishes on the far side of the acknowledgement.\n */\n private async acknowledgeIntentSwitch(\n intent: ChannelAccessIntent, pendingLink: PendingLinkInput | null,\n ): Promise<void> {\n const channelId = this.detailChannelId;\n if (!channelId) { this.closeDialog(); return; }\n if (this.dialog) { this.dialog.busy = true; this.renderDialog(); }\n const ok = await this.setAccessIntent(intent, { acknowledgeLiveAccess: true });\n if (!ok) {\n // `setAccessIntent` has already said why, through the toast lane or by\n // re-opening this sheet with fresher counts. Never leave a stuck spinner.\n if (this.dialog?.kind === 'intentSwitch') { this.dialog.busy = false; this.renderDialog(); }\n return;\n }\n if (!pendingLink) { this.closeDialog(); return; }\n // Un-busy BEFORE the create: `showDialogError` paints into the mounted\n // sheet without re-rendering it, so a create that fails here would otherwise\n // report itself under a permanently disabled \"Changing…\" button. Pressing\n // again re-acknowledges (idempotent) and retries the link.\n if (this.dialog?.kind === 'intentSwitch') { this.dialog.busy = false; this.renderDialog(); }\n await this.mintLink(channelId, pendingLink);\n }\n\n /**\n * Mount a modal: `aria-modal` dialog, programmatic name, focus moved inside,\n * Tab trapped, Escape closes WITHOUT mutating, focus restored on close (§13).\n */\n private renderScrim(inner: string, wire: (dialog: HTMLElement) => void): void {\n const existing = this.scrimEl;\n if (!existing) this.lastFocus = (document.activeElement as HTMLElement | null) ?? null;\n existing?.remove();\n const scrim = document.createElement('div');\n scrim.className = 'slm-ch-scrim';\n scrim.innerHTML = `<div class=\"slm-ch-dialog\" role=\"dialog\" aria-modal=\"true\"\n aria-labelledby=\"slm-ch-dlg-title\" tabindex=\"-1\">${inner}</div>`;\n this.host.root.appendChild(scrim);\n this.scrimEl = scrim;\n const dialog = scrim.firstElementChild as HTMLElement;\n dialog.querySelectorAll<HTMLElement>('[data-ch-close]').forEach((button) => {\n button.addEventListener('click', () => this.closeDialog());\n });\n scrim.addEventListener('keydown', (event) => {\n if (event.key === 'Escape') { event.stopPropagation(); this.closeDialog(); return; }\n if (event.key !== 'Tab') return;\n const focusable = [...dialog.querySelectorAll<HTMLElement>(\n 'button:not([disabled]),select,input,textarea,a[href],[tabindex]:not([tabindex=\"-1\"])',\n )];\n if (!focusable.length) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }\n else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }\n });\n wire(dialog);\n const autofocus = dialog.querySelector<HTMLElement>('input,select,button');\n (autofocus ?? dialog).focus();\n }\n\n private closeDialog(opts: { restoreFocus?: boolean } = {}): void {\n this.dialog = null;\n this.scrimEl?.remove();\n this.scrimEl = null;\n if (opts.restoreFocus !== false) this.lastFocus?.focus?.();\n this.lastFocus = null;\n }\n\n private renderCreateDialog(state: DialogState): void {\n // Markers are compared as the single letter each one RENDERS as, so a stored\n // \"star\" occupies 'S' and the next channel is offered a free letter instead.\n const taken = (this.list?.channels ?? []).map((channel) => markerLetter(channel.marker || channel.name, ''));\n const suggestion = suggestMarker('', taken);\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Create channel</h3>\n <p class=\"sub\">A named allocation only the right audience can buy from. You'll pick the seats next.</p>\n <div class=\"slm-field\">\n <label for=\"slm-ch-name\">Name</label>\n <input class=\"slm-input\" id=\"slm-ch-name\" maxlength=\"80\" />\n <p class=\"slm-note\">Shown to your team and in reports — never to buyers.</p>\n </div>\n <div class=\"slm-field\">\n <label>Marker</label>\n <div style=\"display:flex;gap:8px;align-items:center\">\n <span class=\"slm-ch-mk\" data-ch-marker style=\"background:${esc(suggestion.color)};width:28px;height:28px;font-size:13px\">${esc(suggestion.letter)}</span>\n <span class=\"slm-note\" style=\"margin:0\">Letter comes from the name; colour is chosen automatically from the next available palette. Buyers never see either.</span>\n </div>\n </div>\n <div class=\"slm-field\">\n <label for=\"slm-ch-ref\">Reference <span style=\"text-transform:none;font-weight:500\">(optional)</span></label>\n <input class=\"slm-input\" id=\"slm-ch-ref\" maxlength=\"120\" placeholder=\"e.g. travel-agency-a\" />\n <p class=\"slm-note\">A stable ID for your own system and webhooks.</p>\n </div>\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-create=\"plain\">Create without allocating</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-create=\"allocate\">Create and allocate seats</button>\n </div>`, (dialog) => {\n const name = dialog.querySelector<HTMLInputElement>('#slm-ch-name')!;\n const marker = dialog.querySelector<HTMLElement>('[data-ch-marker]')!;\n name.addEventListener('input', () => {\n const next = suggestMarker(name.value, taken);\n marker.textContent = next.letter;\n marker.style.background = next.color;\n });\n dialog.querySelectorAll<HTMLElement>('[data-ch-create]').forEach((button) => {\n button.addEventListener('click', () => {\n const allocate = button.dataset.chCreate === 'allocate';\n void this.createChannel(\n name.value,\n marker.textContent ?? '',\n marker.style.background,\n dialog.querySelector<HTMLInputElement>('#slm-ch-ref')?.value ?? '',\n allocate,\n );\n });\n });\n });\n }\n\n private async createChannel(\n name: string,\n letter: string,\n color: string,\n externalRef: string,\n allocate: boolean,\n ): Promise<void> {\n const trimmed = name.trim();\n if (!trimmed) {\n this.showDialogError('Give the channel a name your team will recognise.');\n return;\n }\n try {\n const res = await this.host.api.createChannel(this.host.eventKey, {\n name: trimmed,\n // The column is free text; we only ever store what the chip can draw.\n marker: markerLetter(letter, '') || null,\n color: color || null,\n externalRef: externalRef.trim() || null,\n });\n this.closeDialog();\n await this.refresh();\n this.targetChannelId = res.channel.id;\n this.detailChannelId = allocate ? null : res.channel.id;\n this.announce(`Channel ${trimmed} created with 0 seats allocated.`);\n this.host.toast(allocate\n ? `${trimmed} created. Select seats on the map to allocate them.`\n : `${trimmed} created.`, 'ok');\n this.paintRail();\n } catch (err) {\n const code = err instanceof ManageApiError ? err.code : undefined;\n this.showDialogError(code === 'channel_name_taken'\n ? 'That name is already used on this event. Pick another.'\n : \"Couldn't create the channel. Try again.\");\n this.host.onError(err);\n }\n }\n\n private showDialogError(message: string): void {\n const field = this.scrimEl?.querySelector<HTMLElement>('[data-ch-error]');\n if (!field) return;\n field.textContent = message;\n field.hidden = false;\n }\n\n private renderReviewDialog(state: DialogState): void {\n const { labels, buckets } = this.currentPlan();\n const authoritative = state.applied;\n const shown = authoritative ? authoritative.buckets : buckets;\n // An authoritative result names the channel the SERVER moved seats into.\n // Reading `targetChannelId` off the mode would relabel a completed result\n // if the organizer changed the destination picker before opening Details.\n const targetName = this.nameOf(authoritative?.targetChannelId ?? this.targetChannelId) ?? PUBLIC_CHANNEL_NAME;\n const rows = bucketRows(shown, targetName);\n const mutations = authoritative ? authoritative.applied : mutationCount(buckets);\n const allSkipped = !authoritative && labels.length > 0 && mutations === 0;\n const tooLarge = !authoritative && labels.length > MAX_ASSIGNMENT_UNITS;\n const rowsHtml = bucketRowsHtml(rows);\n\n const foot = authoritative\n ? `<div class=\"foot\"><button type=\"button\" class=\"slm-btn\" data-ch-close>Done</button></div>`\n : `<div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Back</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-apply ${allSkipped || tooLarge || state.busy ? 'disabled' : ''}>\n ${state.busy ? 'Applying…' : `Apply ${mutations.toLocaleString()} change${mutations === 1 ? '' : 's'}`}\n </button>\n </div>`;\n const confirmNote = !authoritative && needsMoveConfirmation(buckets)\n ? `<p class=\"slm-note\">Applying moves inventory out of another private channel. That is the line marked above.</p>`\n : '';\n const skippedNote = allSkipped\n ? `<div class=\"slm-ch-alert warn\"><span>ℹ</span><span>Nothing in this selection can move right now —\n every seat is in a buyer's checkout, already sold, or already in ${esc(targetName)}.</span></div>`\n : '';\n const limitNote = tooLarge\n ? `<div class=\"slm-ch-alert warn\" role=\"alert\"><span>ℹ</span><span><b>Choose fewer seats.</b>\n One Apply can cover at most ${MAX_ASSIGNMENT_UNITS.toLocaleString()} seats.</span></div>`\n : '';\n\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">${authoritative\n ? `Moved ${authoritative.applied.toLocaleString()} seat${authoritative.applied === 1 ? '' : 's'} to ${esc(targetName)}`\n : `Move ${labels.length.toLocaleString()} selected seat${labels.length === 1 ? '' : 's'} to ${esc(targetName)}`}</h3>\n <p class=\"sub\">${authoritative\n ? 'These are the exact counts the server applied.'\n : 'Every selected seat is in exactly one line below.'}</p>\n ${skippedNote}\n ${limitNote}\n ${rowsHtml || '<div class=\"slm-empty\">Nothing selected.</div>'}\n ${confirmNote}\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n ${foot}`, (dialog) => {\n dialog.querySelector('[data-ch-apply]')?.addEventListener('click', () => void this.apply());\n });\n if (authoritative) {\n this.announce(`Applied ${authoritative.applied} change${authoritative.applied === 1 ? '' : 's'} to ${targetName}.`);\n }\n }\n\n /**\n * Apply. On success the sheet CLOSES and the staged bar confirms what moved,\n * naming the destination and any skipped seats, with the AUTHORITATIVE server\n * buckets still one Details press away. Leaving the modal up on success made\n * the organizer dismiss a sheet to get back to a map they had just changed.\n * On a stale version the server mutated nothing: keep the selection, shake\n * the bar once, and offer exactly one action — Refresh and review.\n */\n private async apply(): Promise<void> {\n if (!this.dialog || !this.caps.manage) return;\n const { labels } = this.currentPlan();\n if (!labels.length) return;\n if (labels.length > MAX_ASSIGNMENT_UNITS) {\n this.showDialogError(`Choose at most ${MAX_ASSIGNMENT_UNITS.toLocaleString()} seats for one Apply.`);\n return;\n }\n this.dialog = { ...this.dialog, busy: true, error: null };\n this.renderDialog();\n try {\n const result = await this.host.api.applyChannelAssignment(this.host.eventKey, {\n // `null` is the wire spelling of \"back to public sale\" every worker\n // accepts, including ones that predate the 'public' sentinel.\n targetChannelId: isPublicChannelId(this.targetChannelId) ? null : this.targetChannelId,\n labels,\n assignmentVersion: this.assignmentVersion,\n });\n this.assignmentVersion = result.assignmentVersion;\n this.conflict = false;\n await this.refresh({ quiet: true });\n this.closeDialog({ restoreFocus: false });\n this.host.clearSelection();\n this.showApplied(result);\n } catch (err) {\n const conflict = err instanceof ManageApiError && err.status === 409\n && err.code === 'channel_assignment_conflict';\n if (conflict) {\n this.conflict = true;\n this.closeDialog();\n this.shakeStaged();\n this.paintRail();\n this.announce('Assignments changed while you were editing. Nothing was applied and your selection is kept.');\n return;\n }\n if (err instanceof ManageApiError && err.status === 403) {\n this.caps = { view: this.caps.view, manage: false };\n this.closeDialog();\n this.paintRail();\n this.host.toast('Changing channels needs channel-management permission.', 'err');\n return;\n }\n this.dialog = { kind: 'review', busy: false, error: \"Couldn't apply those changes. Try again.\" };\n this.renderDialog();\n this.host.onError(err);\n }\n }\n\n /**\n * The success receipt, now that the review sheet closes on Apply. It names the\n * destination and the seats that could not move, keeps the authoritative\n * buckets reachable through Details, and stays up long enough to be read —\n * 1.2s was tuned for a confirmation the organizer was already looking at.\n */\n private showApplied(result: AssignmentResult): void {\n const targetName = this.nameOf(result.targetChannelId) ?? PUBLIC_CHANNEL_NAME;\n const skipped = result.buckets.skippedHeld.count + result.buckets.skippedBooked.count\n + result.buckets.notFound.count;\n this.setStaged(`<span class=\"slm-ch-tick\" aria-hidden=\"true\">✓</span>\n <span>Assigned <b>${result.applied.toLocaleString()}</b> seat${result.applied === 1 ? '' : 's'} to ${esc(targetName)}\n ${skipped ? ` · ${skipped.toLocaleString()} skipped` : ''}</span>\n <span class=\"grow\"></span>\n <button type=\"button\" class=\"drop\" data-ch-applied-details>Details</button>`, 'done');\n this.stagedEl?.querySelector<HTMLElement>('[data-ch-applied-details]')?.addEventListener('click', () => {\n this.openDialog({ kind: 'review', applied: result });\n });\n this.announce(`Assigned ${result.applied} seat${result.applied === 1 ? '' : 's'} to ${targetName}${skipped ? `; ${skipped} skipped` : ''}.`);\n if (this.stagedDoneTimer) clearTimeout(this.stagedDoneTimer);\n this.stagedDoneTimer = setTimeout(() => this.setStaged(null), 5_000);\n }\n\n private shakeStaged(): void {\n const bar = this.stagedEl;\n if (!bar || !bar.classList.contains('on')) return;\n bar.classList.remove('shake');\n void bar.offsetWidth; // restart the animation\n bar.classList.add('shake');\n }\n\n /**\n * The ⋯ menu.\n *\n * Opening a channel is the ROW's job now, so ⋯ carries what is left: the\n * secondary and destructive lifecycle actions. It is rendered through the same\n * scrim primitive as every other sheet, which is what gives it a focus trap,\n * Escape, and a name — a bare absolutely-positioned popup would have had none\n * of those. Archive keeps its own confirmation dialog; this menu never\n * destroys anything by itself.\n */\n private renderMenuDialog(state: DialogState): void {\n const channel = this.list?.channels.find((item) => item.id === state.channelId);\n if (!channel || !this.caps.manage) { this.closeDialog(); return; }\n const paused = channel.state === 'paused';\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">${esc(channel.name)}</h3>\n <p class=\"sub\">Open the channel to allocate seats and hand out buyer access.\n These are the rest of its actions.</p>\n <div class=\"slm-ch-menu\">\n <button type=\"button\" class=\"slm-btn\" data-ch-menu-act=\"open\">Open channel</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-menu-act=\"rename\">Rename</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-menu-act=\"pause\">${paused ? 'Resume selling' : 'Pause selling'}</button>\n <button type=\"button\" class=\"slm-btn ghost\" data-ch-menu-act=\"archive\">Archive…</button>\n </div>\n <p class=\"slm-note\">Pausing stops new buyer access; checkouts already running can finish.\n Archiving closes the channel for good and returns its free seats to a destination you choose.\n Nothing is ever deleted silently.</p>\n <div class=\"foot\"><button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button></div>`, (dialog) => {\n dialog.querySelectorAll<HTMLElement>('[data-ch-menu-act]').forEach((button) => {\n button.addEventListener('click', () => {\n const act = button.dataset.chMenuAct;\n if (act === 'open') { this.closeDialog(); this.openChannel(channel.id); return; }\n if (act === 'rename') { this.openDialog({ kind: 'rename', channelId: channel.id }); return; }\n if (act === 'archive') { this.openDialog({ kind: 'archive', channelId: channel.id }); return; }\n this.closeDialog();\n void this.togglePause(channel.id);\n });\n });\n });\n }\n\n private renderRenameDialog(state: DialogState): void {\n const channel = this.list?.channels.find((item) => item.id === state.channelId);\n if (!channel) { this.closeDialog(); return; }\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Rename ${esc(channel.name)}</h3>\n <p class=\"sub\">Only your team and your reports see this name.</p>\n <div class=\"slm-field\">\n <label for=\"slm-ch-newname\">Name</label>\n <input class=\"slm-input\" id=\"slm-ch-newname\" maxlength=\"80\" value=\"${esc(channel.name)}\" />\n </div>\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-rename>Save name</button>\n </div>`, (dialog) => {\n dialog.querySelector('[data-ch-rename]')?.addEventListener('click', () => {\n const value = dialog.querySelector<HTMLInputElement>('#slm-ch-newname')?.value ?? '';\n if (!value.trim()) { this.showDialogError('A channel needs a name.'); return; }\n void this.host.api.renameChannel(this.host.eventKey, channel.id, value.trim())\n .then(() => { this.closeDialog(); return this.refresh(); })\n .catch((err) => {\n this.showDialogError(err instanceof ManageApiError && err.code === 'channel_name_taken'\n ? 'That name is already used on this event.'\n : \"Couldn't rename the channel.\");\n this.host.onError(err);\n });\n });\n });\n }\n\n /**\n * \"Use a website or app\" — declare the channel's route as `server`.\n *\n * This is no longer a flag the Embed page happens to read: since 2026-08-06 it\n * is what AUTHORIZES `POST /v1/events/:key/buyer-access-sessions` to mint for\n * this channel at all. Without it, an integration that is otherwise perfectly\n * wired up gets a 409 on every buyer.\n */\n private async chooseWebsiteIntegration(): Promise<void> {\n const channelId = this.detailChannelId;\n if (!channelId) return;\n await this.setAccessIntent('server');\n }\n\n /**\n * Declare this channel's sale route.\n *\n * Reports through the toast lane the rest of the rail's direct actions use.\n * The two enforcement refusals get real answers rather than a generic failure:\n * `channel_intent_switch_blocked` opens the review sheet (there is a decision\n * to make, and a sheet is where decisions live), and\n * `channel_access_intent_forbids` — which the organizer can hit by racing\n * their own second tab — says which route is in the way.\n */\n private async setAccessIntent(\n accessIntent: ChannelAccessIntent,\n opts: { acknowledgeLiveAccess?: boolean } = {},\n ): Promise<boolean> {\n const channelId = this.detailChannelId;\n if (!channelId || !this.caps.manage) return false;\n try {\n // `intentSwitch` is present only when the switch actually disturbed\n // something, and the whole response is read defensively because the client\n // is host-supplied — a thin proxy that resolves void must not crash the rail.\n const result = await this.host.api.setChannelAccessIntent(\n this.host.eventKey, channelId, accessIntent, opts,\n ) as { intentSwitch?: { closedLinks: number; keptSessions: number } } | undefined;\n await this.refresh();\n this.host.toast(this.intentSavedCopy(accessIntent, result?.intentSwitch), 'ok');\n return true;\n } catch (err) {\n if (err instanceof ManageApiError && err.code === 'channel_intent_switch_blocked') {\n this.openDialog({\n kind: 'intentSwitch',\n channelId,\n intentTo: accessIntent,\n switchBlocked: err.details as IntentSwitchBlockedDetails,\n });\n return false;\n }\n if (err instanceof ManageApiError && err.code === 'channel_access_intent_forbids') {\n this.host.toast(intentForbidsCopy(err.details as AccessIntentForbidsDetails), 'err');\n return false;\n }\n this.host.toast(\"Couldn't change how this channel reaches buyers.\", 'err');\n this.host.onError(err);\n return false;\n }\n }\n\n /** What just happened, including anything the switch took down with it — the\n * server reports `intentSwitch` only when it actually disturbed something. */\n private intentSavedCopy(\n intent: ChannelAccessIntent,\n disturbed: { closedLinks: number; keptSessions: number } | undefined,\n ): string {\n const head = intent === 'server'\n ? 'Set to your website or app. The embed code is on the Embed page.'\n : intent === 'internal'\n ? 'Only your own staff can sell this channel now.'\n : intent === 'hosted_link'\n ? 'Set to buyer links. Create one to let buyers in.'\n : 'Kept as a protected reserve. No route can sell these seats.';\n if (!disturbed) return head;\n const closed = disturbed.closedLinks\n ? ` ${disturbed.closedLinks.toLocaleString()} buyer link${disturbed.closedLinks === 1 ? '' : 's'} closed.` : '';\n const kept = disturbed.keptSessions\n ? ` ${disturbed.keptSessions.toLocaleString()} buyer${disturbed.keptSessions === 1 ? '' : 's'} already in a checkout can still finish.` : '';\n return `${head}${closed}${kept}`;\n }\n\n /** `channelId` is explicit because this is reachable from the ⋯ menu on a row\n * that is NOT the open channel, as well as from the detail panel itself. */\n private async togglePause(channelId = this.detailChannelId): Promise<void> {\n const channel = this.list?.channels.find((item) => item.id === channelId);\n if (!channel || !this.caps.manage) return;\n const paused = channel.state !== 'paused';\n try {\n await this.host.api.setChannelPaused(this.host.eventKey, channel.id, paused);\n await this.refresh();\n this.host.toast(paused\n ? `${channel.name} paused. Existing checkouts can finish; no new buyer access is issued.`\n : `${channel.name} resumed.`, 'ok');\n } catch (err) {\n this.host.toast(\"Couldn't change that channel.\", 'err');\n this.host.onError(err);\n }\n }\n\n private renderArchiveDialog(state: DialogState): void {\n const channel = this.list?.channels.find((item) => item.id === state.channelId);\n if (!channel) { this.closeDialog(); return; }\n // The server is the authority on whether archive is possible. The rail's\n // poll can be seconds stale, so a local hold count is a WARNING; only the\n // server's 409 (which carries the exact retry window) disables the action.\n const blocked = state.archiveBlocked ?? null;\n const heads_up = !blocked && channel.counts.held > 0;\n const destinations = this.assignableChannels().filter((entry) => entry.id !== channel.id);\n const blockedAlert = blocked\n ? `<div class=\"slm-ch-alert warn\" role=\"alert\"><span>⏳</span>\n <span><b>${(blocked.heldUnits ?? blocked.activeHolds ?? 0).toLocaleString()} seats are in a buyer's checkout right now.</b>\n Archive is unavailable while seats are held — try again ${esc(retryAfterCopy(blocked))}.</span></div>`\n : heads_up\n ? `<div class=\"slm-ch-alert warn\"><span>⏳</span>\n <span>${channel.counts.held.toLocaleString()} seats are in a buyer's checkout right now.\n Archive is refused while any seat is held — you can try, and we'll tell you when to come back.</span></div>`\n : '';\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Archive ${esc(channel.name)}</h3>\n <p class=\"sub\">The channel closes for good. Its seats move to a destination you choose;\n sales history keeps its attribution.</p>\n ${blockedAlert}\n <div class=\"slm-field\">\n <label for=\"slm-ch-dest\">Move the ${channel.counts.free.toLocaleString()} remaining free seats to</label>\n <select class=\"slm-select\" id=\"slm-ch-dest\">\n ${destinations.map((entry) => `<option value=\"${esc(entry.id)}\">${esc(entry.name)}</option>`).join('')}\n </select>\n </div>\n <p class=\"slm-note\">${channel.counts.booked.toLocaleString()} sold seats keep \"${esc(channel.name)}\" on their sale\n record. If one is cancelled later it returns to the destination above. Any buyer access for this channel\n stops working.</p>\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn danger\" data-ch-archive ${blocked ? 'disabled' : ''}>Archive channel</button>\n </div>`, (dialog) => {\n dialog.querySelector('[data-ch-archive]')?.addEventListener('click', () => {\n const destination = dialog.querySelector<HTMLSelectElement>('#slm-ch-dest')?.value ?? '';\n void this.archive(channel.id, destination || null);\n });\n });\n }\n\n private async archive(channelId: string, destination: string | null): Promise<void> {\n try {\n await this.host.api.archiveChannel(this.host.eventKey, channelId, destination);\n this.closeDialog();\n this.detailChannelId = null;\n await this.refresh();\n this.host.toast('Channel archived. Its remaining seats moved to the destination you chose.', 'ok');\n } catch (err) {\n if (err instanceof ManageApiError && err.status === 409\n && err.code === 'channel_archive_blocked_by_holds') {\n this.dialog = {\n kind: 'archive',\n channelId,\n archiveBlocked: (err.details ?? {}) as ArchiveBlockedDetails,\n };\n this.renderDialog();\n return;\n }\n this.showDialogError(\"Couldn't archive that channel. Try again.\");\n this.host.onError(err);\n }\n }\n\n /**\n * The synchronized inventory list (§13): the keyboard and screen-reader\n * equivalent of canvas click / marquee / brush, grouped by section with\n * per-section select actions.\n */\n private renderSeatListDialog(): void {\n const selected = new Set(this.host.selectionLabels());\n const groups = new Map<string, { label: string; seats: Array<{ label: string; status: string }> }>();\n let total = 0;\n for (const seat of this.host.seats()) {\n total += 1;\n if (total > this.seatListLimit) break;\n const section = this.host.sectionOfLabel(seat.label);\n const key = section?.id ?? '';\n const group = groups.get(key) ?? { label: section?.label ?? 'Other seats', seats: [] };\n group.seats.push({ label: seat.label, status: this.host.statusOf(seat.label) ?? 'free' });\n groups.set(key, group);\n }\n const body = [...groups.entries()].map(([id, group]) => `\n <div class=\"slm-ch-seatgroup\">\n <span>${esc(group.label)}</span>\n ${id ? `<button type=\"button\" data-ch-section=\"${esc(id)}\">Select section</button>` : ''}\n </div>\n ${group.seats.map((seat) => {\n const channelId = this.allocation.get(seat.label) ?? PUBLIC_CHANNEL_ID;\n const channelName = this.nameOf(channelId) ?? PUBLIC_CHANNEL_NAME;\n return `<button type=\"button\" class=\"slm-ch-seatitem\" role=\"checkbox\"\n aria-checked=\"${selected.has(seat.label)}\" data-ch-seat=\"${esc(seat.label)}\">\n <span class=\"box\" aria-hidden=\"true\">✓</span>\n <span>${esc(seat.label)}</span>\n <span class=\"meta\">${esc(channelName)} · ${esc(seat.status)}</span>\n </button>`;\n }).join('')}`).join('');\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Seat list</h3>\n <p class=\"sub\">The same selection as the map, with checkboxes. Space or Enter toggles a seat.</p>\n <div class=\"slm-ch-seatlist\">${body || '<div class=\"slm-empty\">No seats on this chart.</div>'}</div>\n ${total > this.seatListLimit\n ? `<div class=\"foot\"><button type=\"button\" class=\"slm-btn ghost\" data-ch-more>Show more seats</button></div>` : ''}\n <div class=\"foot\"><button type=\"button\" class=\"slm-btn\" data-ch-close>Done</button></div>`, (dialog) => {\n dialog.querySelectorAll<HTMLElement>('[data-ch-seat]').forEach((button) => {\n button.addEventListener('click', () => {\n const label = button.dataset.chSeat!;\n const next = new Set(this.host.selectionLabels());\n if (next.has(label)) next.delete(label);\n else next.add(label);\n this.host.clearSelection();\n if (next.size) this.host.selectByLabels([...next]);\n this.renderSeatListDialog();\n });\n });\n dialog.querySelectorAll<HTMLElement>('[data-ch-section]').forEach((button) => {\n button.addEventListener('click', () => {\n this.host.selectSection(button.dataset.chSection!);\n this.renderSeatListDialog();\n });\n });\n dialog.querySelector('[data-ch-more]')?.addEventListener('click', () => {\n this.seatListLimit += SEAT_LIST_PAGE;\n this.renderSeatListDialog();\n });\n });\n }\n\n // ---- buyer-link dialogs ---------------------------------------------------\n\n private async reloadLinks(): Promise<void> {\n const channelId = this.detailChannelId;\n if (!channelId) return;\n this.linksState = this.links.length ? this.linksState : 'loading';\n await this.loadLinks(channelId);\n this.paintRail();\n }\n\n /**\n * The reload EVERY link mutation owes the panel.\n *\n * A create/rotate/revoke changes two things the detail panel renders: the\n * channel's access line (the server sets `access.intent` on create, and clears\n * it when the last live link goes) and the link status list. Both are re-read\n * here and the rail repainted, so the panel the organizer is already looking\n * at is current the moment the mutation lands — no reload, and no dependence\n * on HOW the one-time reveal was dismissed (the button, Escape, or never).\n */\n private async reloadAfterLinkChange(channelId: string): Promise<void> {\n // `refresh` re-reads the links of the OPEN channel as part of its pass, so\n // the common case is one round of reads, not two.\n if (this.detailChannelId === channelId) {\n await this.refresh({ quiet: true });\n return;\n }\n await this.loadLinks(channelId);\n if (this.active) this.paintRail();\n }\n\n private linkById(linkId: string | undefined): AccessLinkStatusRecord | null {\n return this.links.find((link) => link.id === linkId) ?? null;\n }\n\n /**\n * Create. The three policy fields carry the owner's defaults and every one of\n * them is editable; the PLATFORM bounds (60s–180d, 1–10 000, 1–100, 20 live\n * links) are the server's to enforce and the server's to explain, so this form\n * checks only that a number is a number and surfaces the server's sentence for\n * everything else.\n */\n private renderLinkCreateDialog(state: DialogState): void {\n const channel = this.list?.channels.find((item) => item.id === state.channelId);\n if (!channel || !this.caps.manage) { this.closeDialog(); return; }\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Create a buyer link for ${esc(channel.name)}</h3>\n <p class=\"sub\">Anyone who opens the link can buy from this channel's allocation — and only from it.\n You'll see the link once, right after you create it.</p>\n <div class=\"slm-field\">\n <label for=\"slm-ch-lk-label\">Label <span style=\"text-transform:none;font-weight:500\">(optional)</span></label>\n <input class=\"slm-input\" id=\"slm-ch-lk-label\" maxlength=\"80\" placeholder=\"e.g. VIP list Nov 14\" />\n <p class=\"slm-note\">So you can tell your links apart later. Buyers never see it.</p>\n </div>\n <div class=\"slm-field\">\n <label for=\"slm-ch-lk-expiry\">Stops working</label>\n <select class=\"slm-select\" id=\"slm-ch-lk-expiry\" data-ch-lk-expiry>\n <option value=\"event\" selected>When the event starts</option>\n <option value=\"custom\">On a date I choose</option>\n </select>\n </div>\n <div class=\"slm-field\" data-ch-lk-when-field hidden>\n <label for=\"slm-ch-lk-when\">Date and time</label>\n <input class=\"slm-input\" type=\"datetime-local\" id=\"slm-ch-lk-when\" />\n </div>\n <div class=\"slm-field\">\n <label for=\"slm-ch-lk-redemptions\">How many people can use it</label>\n <input class=\"slm-input\" type=\"number\" id=\"slm-ch-lk-redemptions\" inputmode=\"numeric\"\n value=\"${ACCESS_LINK_DEFAULTS.maxRedemptions}\" />\n <p class=\"slm-note\">Each buyer who opens the link uses one.</p>\n </div>\n <div class=\"slm-field\">\n <label for=\"slm-ch-lk-quantity\">Seats per buyer</label>\n <input class=\"slm-input\" type=\"number\" id=\"slm-ch-lk-quantity\" inputmode=\"numeric\"\n value=\"${ACCESS_LINK_DEFAULTS.maxQuantity}\" />\n </div>\n <label class=\"slm-note\" style=\"display:flex;gap:8px;align-items:center;margin:2px 0 6px\">\n <input type=\"checkbox\" id=\"slm-ch-lk-public\" />\n Also let this link buy Public sale seats\n </label>\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-lk-create>Create link</button>\n </div>`, (dialog) => {\n const expiry = dialog.querySelector<HTMLSelectElement>('[data-ch-lk-expiry]')!;\n const whenField = dialog.querySelector<HTMLElement>('[data-ch-lk-when-field]')!;\n const when = dialog.querySelector<HTMLInputElement>('#slm-ch-lk-when')!;\n expiry.addEventListener('change', () => {\n const custom = expiry.value === 'custom';\n whenField.hidden = !custom;\n if (custom && !when.value) when.value = datetimeLocalValue(Date.now() + 7 * 86_400_000);\n });\n dialog.querySelector('[data-ch-lk-create]')?.addEventListener('click', () => {\n const maxRedemptions = intField(dialog, '#slm-ch-lk-redemptions');\n const maxQuantity = intField(dialog, '#slm-ch-lk-quantity');\n if (maxRedemptions == null || maxQuantity == null) {\n this.showDialogError('Those two settings need to be whole numbers.');\n return;\n }\n let expiresAt: number | undefined;\n if (expiry.value === 'custom') {\n expiresAt = Date.parse(when.value);\n if (!Number.isFinite(expiresAt)) {\n this.showDialogError('Pick the date and time the link should stop working.');\n return;\n }\n }\n void this.createLink(channel.id, {\n label: dialog.querySelector<HTMLInputElement>('#slm-ch-lk-label')?.value.trim() || null,\n includePublic: dialog.querySelector<HTMLInputElement>('#slm-ch-lk-public')?.checked ?? false,\n ...(expiresAt === undefined ? {} : { expiresAt }),\n maxRedemptions,\n maxQuantity,\n });\n });\n });\n }\n\n /**\n * DECLARE, then create.\n *\n * `createAccessLink` used to set the channel's route to `hosted_link` as a\n * side effect, which is exactly why the picker could never refuse anything.\n * The server took that side effect away and now REQUIRES the declaration —\n * and channels default to `none`, so a create that did not declare first\n * would 409 on the organizer's very first \"Create buyer link\".\n *\n * So the route is declared here, immediately before the create. It stays ONE\n * gesture: nothing is declared while the organizer is still filling the form\n * in (cancelling changes nothing), and if the declaration is the part that is\n * refused, the review sheet holds this form and finishes the job on the far\n * side of the acknowledgement.\n */\n private async createLink(channelId: string, input: PendingLinkInput): Promise<void> {\n if (!(await this.ensureHostedLinkRoute(channelId, input))) return;\n await this.mintLink(channelId, input);\n }\n\n /**\n * The create half, on its own.\n *\n * Separate from `createLink` because the acknowledge path has ALREADY declared\n * the route — with the very acknowledgement the plain declaration was refused\n * for. Sending it back through `ensureHostedLinkRoute` would re-derive the\n * route from a channel list that has not necessarily caught up, and could\n * refuse the organizer a second time for a decision they just made.\n */\n private async mintLink(channelId: string, input: PendingLinkInput): Promise<void> {\n try {\n const reveal = await this.host.api.createAccessLink(this.host.eventKey, channelId, input);\n this.revealLink(reveal, { channelId });\n await this.reloadAfterLinkChange(channelId);\n } catch (err) {\n this.showDialogError(accessLinkErrorCopy(err instanceof ManageApiError ? err : undefined));\n if (!(err instanceof ManageApiError)) this.host.onError(err);\n }\n }\n\n /**\n * Make sure the channel declares the buyer-link route before a link is minted.\n *\n * Returns false when the create must NOT proceed — either it was refused, or\n * the decision has been handed to the switch-review sheet, which resumes it.\n * A channel already on `hosted_link` costs no request at all, so creating a\n * second link is the same single call it has always been.\n */\n private async ensureHostedLinkRoute(channelId: string, pendingLink: PendingLinkInput): Promise<boolean> {\n const channel = this.list?.channels.find((item) => item.id === channelId);\n if ((channel?.access?.intent ?? 'none') === 'hosted_link') return true;\n try {\n await this.host.api.setChannelAccessIntent(this.host.eventKey, channelId, 'hosted_link');\n await this.refresh();\n return true;\n } catch (err) {\n if (err instanceof ManageApiError && err.code === 'channel_intent_switch_blocked') {\n this.openDialog({\n kind: 'intentSwitch',\n channelId,\n intentTo: 'hosted_link',\n switchBlocked: err.details as IntentSwitchBlockedDetails,\n pendingLink,\n });\n return false;\n }\n this.showDialogError(err instanceof ManageApiError && err.code === 'channel_access_intent_forbids'\n ? intentForbidsCopy(err.details as AccessIntentForbidsDetails)\n : \"Couldn't set this channel up for buyer links. Try again.\");\n if (!(err instanceof ManageApiError)) this.host.onError(err);\n return false;\n }\n }\n\n /**\n * The ONE-TIME reveal.\n *\n * Three things make this unrecoverable rather than merely \"not shown twice\":\n *\n * 1. `url` is a local const. It is never assigned to a field on this class,\n * never handed to the host, never put in a `DialogState`.\n * 2. `this.dialog` is cleared FIRST, so `renderDialog()` — the only function\n * that rebuilds a sheet — has nothing to rebuild this one from.\n * 3. The string exists in exactly one DOM node inside the scrim. Dismissing\n * the dialog removes the scrim, and the closure goes with it.\n *\n * The server holds only a hash, so even a compromised client cannot ask for it\n * again. Rotation is the recovery path, and the copy says so.\n */\n private revealLink(reveal: AccessLinkReveal, opts: { channelId: string; rotated?: boolean }): void {\n const url = reveal.url;\n this.dialog = null;\n const rotated = opts.rotated\n ? `<div class=\"slm-ch-alert warn\" role=\"status\"><span>⚠</span><span>\n <b>The old link has stopped working.</b> ${reveal.endedSessions\n ? `${reveal.endedSessions.toLocaleString()} buyer${reveal.endedSessions === 1 ? '' : 's'} lost access immediately.`\n : 'Buyers who already came in can finish; every new visit needs this link.'}</span></div>`\n : '';\n const policy = accessLinkPolicyLines(reveal.link)\n .map((row) => `<div class=\"slm-ch-lkrow\"><span class=\"k\">${esc(row.k)}</span>\n <span class=\"v\">${esc(row.v)}</span></div>`).join('');\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Copy this link now</h3>\n <p class=\"sub\">This is the only time SeatLayer can show it. We keep just a fingerprint, so it cannot be\n shown again — if it is lost, rotate the link for a fresh one.</p>\n ${rotated}\n <div class=\"slm-ch-secret\" data-ch-lk-url>${esc(url)}</div>\n <div class=\"slm-ch-row2\" style=\"margin-top:8px\">\n <button type=\"button\" class=\"slm-btn\" data-ch-lk-copy>Copy link</button>\n </div>\n <div class=\"slm-ch-alert warn\" style=\"margin-top:12px\"><span>⚠</span>\n <span>Anyone who opens this link can buy from this allocation. Send it only to the people it is meant\n for — forwarding it hands on the same access, and SeatLayer cannot tell the difference.</span></div>\n <p class=\"slm-eyebrow\" style=\"margin-top:14px\">What this link allows</p>\n ${policy}\n <div class=\"foot\">\n <button type=\"button\" class=\"slm-btn\" data-ch-close data-ch-lk-done>I've copied it</button>\n </div>`, (dialog) => {\n const copy = dialog.querySelector<HTMLElement>('[data-ch-lk-copy]');\n copy?.addEventListener('click', () => {\n const ok = (): void => {\n copy.textContent = 'Copied';\n this.announce('Buyer link copied.');\n };\n const clipboard = typeof navigator === 'undefined' ? null : navigator.clipboard;\n if (clipboard?.writeText) {\n clipboard.writeText(url).then(ok, () => selectSecret(dialog));\n return;\n }\n // No clipboard API (older embeds, insecure context): select the text so\n // the organizer can copy it by hand rather than lose it entirely.\n selectSecret(dialog);\n });\n // Dismissal only dismisses. The mutation that opened this sheet already\n // owns the reload (`reloadAfterLinkChange`), so the panel behind the scrim\n // is current whichever way the organizer leaves — including Escape.\n });\n this.announce('Your buyer link is ready and is shown once.');\n }\n\n /**\n * Rotate. The organizer must SAY what happens to the buyers already inside —\n * the confirm stays disabled until one of the two choices is picked, because\n * the gentle branch and the destructive branch are both real decisions and the\n * server refuses (422 `end_active_sessions_required`) to guess either.\n */\n private renderLinkRotateDialog(state: DialogState): void {\n const link = this.linkById(state.linkId);\n if (!link || !this.caps.manage) { this.closeDialog(); return; }\n const sessions = link.activeSessions ?? 0;\n const warning = sessions\n ? `<div class=\"slm-ch-alert warn\"><span>⚠</span>\n <span><b>${sessions.toLocaleString()} buyer${sessions === 1 ? '' : 's'}</b> got in with the current link\n and still ${sessions === 1 ? 'has' : 'have'} active access.</span></div>`\n : '';\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Rotate the ${esc(link.label || 'buyer')} link?</h3>\n <p class=\"sub\">The current link stops opening immediately and cannot be restored. You will get a new\n link to copy — shown once.</p>\n ${warning}\n <label class=\"slm-ch-radio\">\n <input type=\"radio\" name=\"slm-ch-rot\" value=\"keep\" data-ch-rot />\n <span><b>Let them finish</b><span class=\"why\">Access already handed out expires on its own; seats in\n checkout are untouched. Every new visit needs the new link.</span></span>\n </label>\n <label class=\"slm-ch-radio\">\n <input type=\"radio\" name=\"slm-ch-rot\" value=\"end\" data-ch-rot />\n <span><b>End their access now</b><span class=\"why\">All access from the old link ends immediately.\n Buyers part-way through choosing seats lose access.</span></span>\n </label>\n <p class=\"slm-note\">Choose one — SeatLayer will not decide this for you.</p>\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn\" data-ch-lk-rotate disabled>Rotate and copy new link</button>\n </div>`, (dialog) => {\n const confirm = dialog.querySelector<HTMLButtonElement>('[data-ch-lk-rotate]')!;\n dialog.querySelectorAll<HTMLInputElement>('[data-ch-rot]').forEach((radio) => {\n radio.addEventListener('change', () => { confirm.disabled = false; });\n });\n confirm.addEventListener('click', () => {\n const picked = [...dialog.querySelectorAll<HTMLInputElement>('[data-ch-rot]')]\n .find((radio) => radio.checked);\n // Belt and braces: the button is disabled until a choice exists, and a\n // programmatic path still cannot skip the decision.\n if (!picked) {\n this.showDialogError(accessLinkErrorCopy({ code: 'end_active_sessions_required' }));\n return;\n }\n void this.rotateLink(state.channelId!, link.id, picked.value === 'end');\n });\n });\n }\n\n private async rotateLink(channelId: string, linkId: string, endActiveSessions: boolean): Promise<void> {\n try {\n const reveal = await this.host.api.rotateAccessLink(\n this.host.eventKey, channelId, linkId, endActiveSessions,\n );\n this.revealLink(reveal, { channelId, rotated: true });\n await this.reloadAfterLinkChange(channelId);\n } catch (err) {\n this.showDialogError(accessLinkErrorCopy(err instanceof ManageApiError ? err : undefined));\n if (!(err instanceof ManageApiError)) this.host.onError(err);\n }\n }\n\n private renderLinkRevokeDialog(state: DialogState): void {\n const link = this.linkById(state.linkId);\n if (!link || !this.caps.manage) { this.closeDialog(); return; }\n const sessions = link.activeSessions ?? 0;\n this.renderScrim(`\n <h3 id=\"slm-ch-dlg-title\">Revoke the ${esc(link.label || 'buyer')} link?</h3>\n <p class=\"sub\">It stops opening immediately and cannot be restored — there is no undo, and no way to\n bring the same URL back. Seats already bought through it keep their sale.</p>\n ${sessions ? `<label class=\"slm-ch-radio\">\n <input type=\"checkbox\" data-ch-lk-endsessions />\n <span><b>Also end access for the ${sessions.toLocaleString()}\n buyer${sessions === 1 ? '' : 's'} already inside</b><span class=\"why\">Leave this off and they can\n finish what they started; new visits are refused either way.</span></span>\n </label>` : ''}\n <p class=\"slm-ch-err\" data-ch-error ${state.error ? '' : 'hidden'}>${esc(state.error ?? '')}</p>\n <div class=\"foot\">\n <button type=\"button\" class=\"quiet\" data-ch-close>Cancel</button>\n <button type=\"button\" class=\"slm-btn danger\" data-ch-lk-revoke>Revoke link</button>\n </div>`, (dialog) => {\n dialog.querySelector('[data-ch-lk-revoke]')?.addEventListener('click', () => {\n const end = dialog.querySelector<HTMLInputElement>('[data-ch-lk-endsessions]')?.checked ?? false;\n void this.revokeLink(state.channelId!, link.id, end);\n });\n });\n }\n\n private async revokeLink(channelId: string, linkId: string, endActiveSessions: boolean): Promise<void> {\n try {\n const res = await this.host.api.revokeAccessLink(\n this.host.eventKey, channelId, linkId, endActiveSessions,\n );\n this.closeDialog();\n await this.reloadAfterLinkChange(channelId);\n this.host.toast(res.endedSessions\n ? `Link revoked. ${res.endedSessions.toLocaleString()} buyer${res.endedSessions === 1 ? '' : 's'} lost access.`\n : 'Link revoked. It no longer opens for anyone.', 'ok');\n } catch (err) {\n this.showDialogError(accessLinkErrorCopy(err instanceof ManageApiError ? err : undefined));\n if (!(err instanceof ManageApiError)) this.host.onError(err);\n }\n }\n\n // ---- compact detents ------------------------------------------------------\n\n private applySheetClasses(): void {\n const root = this.host.root;\n const compact = this.host.isCompact();\n root.classList.toggle('ch-sheet', compact && this.active);\n for (const detent of ['collapsed', 'medium', 'full'] as Detent[]) {\n root.classList.toggle(`detent-${detent}`, compact && this.active && this.detent === detent);\n }\n // At the full detent the map behind the sheet is inert: selection is\n // preserved, but the background cannot be touched until Back/Close.\n this.host.setMapInert(compact && this.active && this.detent === 'full');\n }\n\n private cycleDetent(): void {\n const order: Detent[] = ['collapsed', 'medium', 'full'];\n this.detent = order[(order.indexOf(this.detent) + 1) % order.length];\n this.applySheetClasses();\n }\n\n /** Back/Close from the full detent returns to the previous one and keeps the\n * selection — losing a hard-won selection to a Back press is unforgivable. */\n handleBack(): boolean {\n if (this.scrimEl) { this.closeDialog(); return true; }\n if (this.host.isCompact() && this.detent === 'full') {\n this.detent = 'medium';\n this.applySheetClasses();\n return true;\n }\n return false;\n }\n}\n"],"mappings":";;;;;;;;AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;;;ACgEA,IAAM,eAAe;AAO5B,IAAM,MAAM;AAGL,IAAM,uBAAuB;AAEpC,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AACzB,I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;AACnC,QAAI,KAAK,WAAY,cAAa,KAAK,UAAU;AACjD,SAAK,aAAa,WAAW,MAAM;AAAE,SAAG,YAAY;AAAA,IAAa,GAAG,IAAI;AAAA,EAC1E;AAAA,EAEQ,KAAK,KAAoB;AAC/B,SAAK,KAAK,UAAU,GAAG;AACvB,QAAI,KAAK,IAAI,KAAM,MAAK,IAAI,KAAK,YAAY;AAAA,EAC/C;AACF;","names":["resolveContainer","target","PickerController","loadLocale","setStringOverrides","t","DEFAULT_API_BASE","DEFAULT_MAX_SELECTION","resolveContainer","PickerController","t","loadLocale","setStringOverrides","esc","pano","canView","expandChart","channel","point","resolveContainer","DEFAULT_API_BASE","STYLE_ID","t","esc","expandChart","window","location"]}
|
|
1
|
+
{"version":3,"sources":["../src/SeatingChart.ts","../src/buyerRealtime.ts","../src/api.ts","../src/buyerAccess.ts","../src/seatLayerBrand.ts","../src/EmbeddedDesigner.ts","../src/SeatPicker.ts","../src/attachPickerFrame.ts"],"sourcesContent":["/**\n * SeatingChart — the embeddable buyer picker.\n *\n * A thin wrapper over the shared PickerController (src/picker/PickerController):\n * it owns the mount <div> + the public embed contract (hold-only — the SDK hands\n * the holdId to the host page for a server-side book) and delegates all transport\n * + booking to the controller, so the SDK inherits every fix made for the live\n * buyer page and the demo picker.\n */\nimport {\n PickerController,\n loadLocale,\n setStringOverrides,\n t,\n type PickerSeat,\n type RendererViewMode,\n type SeatHoverDetails,\n} from '@seatlayer/core';\nimport { PubApi, type BestAvailableResult, type HoldResult } from './api';\nimport {\n createBuyerAccessContext,\n type BuyerAccessContext,\n type BuyerAccessExpiredEvent,\n type BuyerAccessToken,\n type BuyerAccessTokenProvider,\n type BuyerAccessUnavailableEvent,\n type SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, createControllerSink } from './buyerRealtime';\nimport { SEATLAYER_ATTRIBUTION_MARK_SVG } from './seatLayerBrand';\n\nconst DEFAULT_API_BASE = 'https://api.seatlayer.io';\nconst DEFAULT_MAX_SELECTION = 10;\n\n/** A seat as surfaced to the host page (prices resolved from the chart's categories). */\nexport type SelectedSeat = PickerSeat;\nexport interface GAAreaAvailability {\n id: string; label: string; capacity: number; available: number; categoryKey: string; price: number; currency: string;\n /** Buyer-facing copy authored separately from stable inventory identity. */\n displayLabel?: string;\n displayType?: string;\n tiers?: Array<{ id: string; name: string; price: number }>;\n}\n\nexport interface SeatingChartOptions {\n /** CSS selector or an HTMLElement to render into. */\n container: string | HTMLElement;\n /** Event key, e.g. `ev_xxx`. */\n event: string;\n /** API origin. Defaults to https://api.seatlayer.io. */\n apiBase?: string;\n /** Reserved for future authenticated rendering — accepted + stored, not yet sent.\n * NOT the channel-access credential: a buyer access session is a different\n * thing with different authority, and uses the two options below. */\n publicKey?: string;\n /**\n * Buyer access session provider — the recommended way to render private\n * channel inventory (Sales Channels guide §6).\n *\n * Called with a `reason` whenever the SDK needs a bearer: first acquisition,\n * a near/actual expiry, a 401 `buyer_access_expired`, a realtime reconnect,\n * or `refreshAccess()`. It should POST to YOUR backend, which mints the\n * session with your secret key and returns `{ token, expiresAt }`.\n *\n * The token lives in memory for the widget's lifetime and nowhere else: never\n * in storage, never in a URL, never in a log or an error message. Refresh\n * returns the same or a narrower scope — the SDK never widens to Public sale\n * on its own, and a failed refresh stops the scoped operation rather than\n * retrying it anonymously.\n */\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n /**\n * One-shot escape hatch for hosts that already own the session lifecycle.\n * Cannot be renewed — when it lapses the widget reports `onAccessExpired`\n * and then `onAccessUnavailable`. Prefer `buyerAccessTokenProvider`.\n */\n buyerAccessToken?: string | BuyerAccessToken;\n /** Max seats selectable at once (default 10). */\n maxSelection?: number;\n /**\n * BCP 47 language for the widget UI — `'de'`, `'es-MX'`, etc. Falls back to\n * the browser language, then English. Built-in: en, es, de, fr. The German\n * bundle (etc.) is fetched on demand so unused languages cost nothing.\n */\n locale?: string;\n /**\n * Per-key string overrides layered over the active locale — white-label copy\n * without shipping a whole bundle, e.g. `{ 'map.fromPrice': 'ab {price}' }`.\n */\n messages?: Record<string, string>;\n /** ISO 4217 currency for on-map prices (default USD). */\n currency?: string;\n /**\n * Colorblind-safe rendering: category hues switch to an Okabe-Ito palette\n * and booked seats render hollow, so state never relies on hue alone.\n * Toggleable later with setColorblindSafe().\n */\n colorblindSafe?: boolean;\n /** Initial canvas projection.\n * @deprecated `'isometric'` and `'perspective'` are retired in favour of the\n * real 3D venue view (`setBuyerView('venue3d')`); they remain accepted for\n * source compatibility and will be removed in the next major. Use `'flat'`. */\n initialView?: RendererViewMode;\n /**\n * Built-in seat tooltip on mouse hover (seat · category · price · status).\n * Rendered inside the widget so every host gets it; default true. Turn off\n * to draw your own popover from onSeatHover.\n */\n seatTooltip?: boolean;\n /**\n * Seat hover with everything a popover needs (category label/color, resolved\n * tier-aware price, live status, currency); null on hover-out. Fires whether\n * or not the built-in tooltip is enabled.\n */\n onSeatHover?: (details: SeatHoverDetails | null) => void;\n onSelectionChange?: (seats: SelectedSeat[]) => void;\n onHold?: (result: HoldResult) => void;\n /** A prior active hold was restored with resumeHold(). */\n onHoldRestored?: (result: HoldResult) => void;\n onHoldExpired?: () => void;\n onGAClick?: (area: GAAreaAvailability) => void;\n /**\n * The buyer access session lapsed. `refreshed` says whether the provider\n * already recovered it — false means private inventory is now unavailable and\n * `onAccessUnavailable` follows. Distinct from `onError` on purpose: this is\n * never a network failure (guide §10).\n */\n onAccessExpired?: (event: BuyerAccessExpiredEvent) => void;\n /**\n * Private inventory is unavailable and refreshing will not fix it — revoked,\n * paused, wrong origin/event/mode, or the provider failed. Carries a reason,\n * never a channel name, id, colour or count.\n */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /**\n * Selected-but-unheld units stopped being selectable — someone else took\n * them, or an allocation change moved them out of this buyer's scope. The\n * widget has already dropped them from the selection.\n */\n onSelectedObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n onError?: (err: unknown) => void;\n /**\n * What the BUYER sees when the chart cannot load.\n *\n * `'message'` (the default) renders a plain, styleable notice with a Try\n * again button. This used to be silent unconditionally: `render()` returned\n * with an EMPTY mounted div and only `onError` fired, so a host that had not\n * wired `onError` — or had wired it to a logger — showed buyers a blank\n * rectangle where the seat map belongs, on the host's own domain, which\n * reads as a broken website rather than a temporary fault. `SeatPicker` has\n * always failed loud with a retry; this is the embed class catching up.\n *\n * `'none'` restores the silent behaviour for hosts that render their own\n * failure UI from `onError`.\n */\n errorDisplay?: 'message' | 'none';\n /**\n * Multi-floor charts only: fires when the buyer taps a deck in the stacked\n * 3D view, after the picker switches to that floor — lets the host page sync\n * its own floor UI (tabs, labels) with the map.\n */\n onDeckTap?: (floorId: string) => void;\n /**\n * Non-blocking, localized selection advice — currently the orphan-seat hint\n * (the selection would strand a single free seat between taken neighbors).\n * `null` clears it. Purely informational; nothing is ever prevented.\n */\n onHint?: (message: string | null) => void;\n}\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container === 'string') {\n const el = document.querySelector(container);\n if (!el) throw new Error(`seatmap: container \"${container}\" not found`);\n return el as HTMLElement;\n }\n if (!(container instanceof HTMLElement)) {\n throw new Error('seatmap: container must be a CSS selector or an HTMLElement');\n }\n return container;\n}\n\nexport class SeatingChart {\n private readonly opts: SeatingChartOptions;\n private readonly controller: PickerController;\n /** Reserved for future authenticated rendering — stored, not yet sent on any request. */\n readonly publicKey?: string;\n\n private mount: HTMLElement | null = null;\n private hostEl: HTMLDivElement | null = null;\n private rendered = false;\n private retryBtn: HTMLButtonElement | null = null;\n private mode_: 'live' | 'test' | null = null;\n private tipEl: HTMLDivElement | null = null;\n private tipPos = { x: 0, y: 0 };\n private onTipMove: ((e: MouseEvent) => void) | null = null;\n /** Null for the ordinary public chart — the tokenless path is untouched. */\n private readonly access: BuyerAccessContext | null;\n private readonly api: PubApi;\n private realtime: BuyerRealtimeClient | null = null;\n\n constructor(options: SeatingChartOptions) {\n if (!options || typeof options !== 'object') throw new Error('seatmap: options object is required');\n if (!options.container) throw new Error('seatmap: `container` is required');\n if (!options.event || typeof options.event !== 'string') throw new Error('seatmap: `event` key is required');\n\n this.opts = options;\n this.publicKey = options.publicKey;\n this.access = createBuyerAccessContext(options, {\n onExpired: (event) => this.opts.onAccessExpired?.(event),\n onUnavailable: (event) => this.opts.onAccessUnavailable?.(event),\n });\n const api = new PubApi((options.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, ''), {\n access: this.access ?? undefined,\n onObjectUnavailable: (event) => this.opts.onSelectedObjectUnavailable?.(event),\n });\n this.api = api;\n this.controller = new PickerController({\n transport: api,\n eventKey: options.event,\n maxSelection: options.maxSelection ?? DEFAULT_MAX_SELECTION,\n currency: options.currency,\n onSelectionChange: (seats) => this.opts.onSelectionChange?.(seats),\n onHold: (h) => this.opts.onHold?.({ holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items }),\n onHoldRestored: (h) => this.opts.onHoldRestored?.({ holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items }),\n onHoldExpired: () => this.opts.onHoldExpired?.(),\n onGAClick: (areaId) => {\n const area = this.controller.getGAAreas().find((candidate) => candidate.id === areaId);\n if (area) this.opts.onGAClick?.(area);\n },\n onError: (err) => this.opts.onError?.(err),\n onDeckTap: (floorId) => this.opts.onDeckTap?.(floorId),\n onHint: (message) => this.opts.onHint?.(message),\n // Live-activity cue: pulse seats that other buyers take while the map is\n // open — the WS feed already streams the status change, this makes it felt.\n flashOnLiveChange: true,\n onSeatHover: (details) => {\n this.opts.onSeatHover?.(details);\n if (this.opts.seatTooltip !== false) this.updateTooltip(details);\n },\n colorblindSafe: options.colorblindSafe,\n });\n }\n\n /** Fetch the chart, mount the renderer, seed statuses and go live. Idempotent. */\n async render(): Promise<this> {\n if (this.rendered) return this;\n this.rendered = true;\n\n // Resolve + load the UI language before the first paint so on-map labels\n // (\"N LEFT\", \"FROM …\", the map aria-label) render translated. English and\n // already-loaded locales resolve synchronously; others fetch one small chunk.\n await loadLocale(this.opts.locale);\n if (this.opts.messages) setStringOverrides(this.opts.messages);\n\n // Mount an owned <div> inside the caller's container so we never fight their\n // layout and can cleanly remove it on destroy().\n this.mount = resolveContainer(this.opts.container);\n const host = document.createElement('div');\n host.style.width = '100%';\n host.style.height = '100%';\n host.style.position = 'relative';\n this.mount.appendChild(host);\n this.hostEl = host;\n\n const info = await this.controller.render(host);\n if (!info) {\n this.rendered = false;\n if (this.opts.errorDisplay !== 'none') this.showLoadFailure(host);\n return this;\n }\n this.controller.setViewMode(this.opts.initialView ?? 'flat');\n this.startRealtime();\n // The served event's mode. Anything the API does not explicitly mark as a\n // test event is a live one — the same rule the test-mode ribbon below uses.\n this.mode_ = info.mode === 'test' ? 'test' : 'live';\n\n // Tooltip element + cursor tracking (mouse only — touch selects directly and\n // reviews seats in the host tray). Positioned at the cursor, flipped at edges.\n // Appended AFTER controller.render — mounting the canvas replaces the host's\n // prior children, so anything added earlier would be wiped.\n if (this.opts.seatTooltip !== false) {\n const tip = document.createElement('div');\n tip.setAttribute('role', 'tooltip');\n tip.style.cssText =\n 'position:absolute;z-index:7;pointer-events:none;display:none;max-width:240px;' +\n 'background:#10162a;color:#fff;border-radius:10px;padding:9px 12px;' +\n 'font:500 12px/1.45 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;' +\n 'box-shadow:0 10px 30px -10px rgba(0,0,0,.5);';\n host.appendChild(tip);\n this.tipEl = tip;\n this.onTipMove = (e: MouseEvent) => {\n const r = host.getBoundingClientRect();\n this.tipPos = { x: e.clientX - r.left, y: e.clientY - r.top };\n if (this.tipEl && this.tipEl.style.display !== 'none') this.placeTooltip();\n };\n host.addEventListener('mousemove', this.onTipMove);\n }\n if (info.mode === 'test') {\n host.style.overflow = 'hidden';\n const ribbon = document.createElement('div');\n ribbon.textContent = t('picker.testMode');\n ribbon.setAttribute('aria-label', t('picker.testMode'));\n ribbon.style.cssText =\n 'position:absolute;top:18px;right:-34px;z-index:6;transform:rotate(45deg);' +\n 'width:140px;text-align:center;padding:4px 0;background:#f4b740;color:#1a1200;' +\n 'font:800 10.5px/1.4 -apple-system,BlinkMacSystemFont,sans-serif;letter-spacing:.12em;' +\n 'box-shadow:0 2px 8px rgba(0,0,0,.25);pointer-events:none;';\n host.appendChild(ribbon);\n }\n\n // \"Powered by SeatLayer\" attribution — the SDK embed is canvas-only, so\n // (unlike the full SeatPicker widget) nothing else renders this badge; no\n // duplication guard is needed. Shown by default; hidden only when the SERVED\n // chart doc's theme sets hideBadge (the API forces that false for orgs\n // without the white-label entitlement, so the client can trust the flag).\n this.buildBadge(host);\n return this;\n }\n\n /**\n * Attribution badge pinned to the embed's bottom-right, linking to\n * seatlayer.io. Rendered as an absolutely-positioned overlay with\n * self-contained inline styles — the SDK embed ships no widget CSS, and an\n * overlay keeps it out of the layout flow so it never disturbs the SDK v0.22\n * fill-height resize contract. Mirrors the full widget's mark + wordmark and\n * reuses the `picker.poweredBy` i18n string.\n */\n private buildBadge(host: HTMLDivElement): void {\n if (this.controller.doc?.theme?.hideBadge) return;\n const badge = document.createElement('a');\n badge.href = 'https://seatlayer.io';\n badge.target = '_blank';\n badge.rel = 'noopener noreferrer';\n badge.setAttribute('aria-label', t('picker.poweredBy'));\n badge.style.cssText =\n 'position:absolute;bottom:10px;right:12px;z-index:5;' +\n 'display:inline-flex;align-items:center;gap:6px;padding:5px 9px;border-radius:999px;' +\n 'background:rgba(255,255,255,.92);color:#4a5163;text-decoration:none;' +\n 'font:600 11px/1 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;letter-spacing:.02em;' +\n 'box-shadow:0 2px 8px rgba(0,0,0,.12);';\n badge.innerHTML =\n '<span aria-hidden=\"true\" style=\"width:16px;height:16px;border-radius:4px;flex:none;' +\n 'display:flex;align-items:center;justify-content:center;background:#0c1220;color:#fcf7ee\">' +\n SEATLAYER_ATTRIBUTION_MARK_SVG + '</span>' +\n `<span>${t('picker.poweredBy')}</span>`;\n host.appendChild(badge);\n }\n\n private placeTooltip(): void {\n if (!this.tipEl || !this.hostEl) return;\n const hw = this.hostEl.clientWidth;\n const tw = this.tipEl.offsetWidth;\n const th = this.tipEl.offsetHeight;\n let x = this.tipPos.x + 14;\n let y = this.tipPos.y - th - 12;\n if (x + tw > hw - 8) x = this.tipPos.x - tw - 14;\n if (y < 8) y = this.tipPos.y + 18;\n this.tipEl.style.left = `${Math.max(8, x)}px`;\n this.tipEl.style.top = `${Math.max(8, y)}px`;\n }\n\n private updateTooltip(details: SeatHoverDetails | null): void {\n if (!this.tipEl) return;\n if (!details) {\n this.tipEl.style.display = 'none';\n return;\n }\n const money = (() => {\n try {\n return new Intl.NumberFormat(undefined, { style: 'currency', currency: details.currency }).format(details.price);\n } catch {\n return `${details.price} ${details.currency}`;\n }\n })();\n const statusLine =\n details.status === 'free'\n ? ''\n : `<div style=\"margin-top:5px;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;color:#fca5a5;font-weight:700\">${\n details.status === 'held' ? t('map.statusHeld') : t('map.statusTaken')\n }</div>`;\n this.tipEl.innerHTML =\n `<div style=\"font-weight:700;font-size:13px\">${details.label}</div>` +\n `<div style=\"display:flex;align-items:center;gap:6px;margin-top:4px;color:#c7cddc\">` +\n `<span style=\"width:9px;height:9px;border-radius:50%;flex:none;background:${details.categoryColor}\"></span>` +\n `<span>${details.categoryLabel}</span>` +\n `<span style=\"margin-left:auto;font-weight:700;color:#fff\">${money}</span></div>` +\n statusLine;\n this.tipEl.style.display = 'block';\n this.placeTooltip();\n }\n\n /**\n * Whether the SERVED event is a live or a test event (`sk_test_` keys create\n * test events, which never book real inventory). `null` before render()\n * resolves — the mode comes from the server with the chart, not from options.\n *\n * The widget already surfaces this visually with the test-mode ribbon; this\n * getter is for hosts that draw their own chrome — notably a native WebView\n * wrapper, which must be able to tell an integrator that the build they are\n * about to ship is pointed at a test event.\n */\n getMode(): 'live' | 'test' | null {\n return this.mode_;\n }\n\n /** Current selection with prices resolved from the chart categories. */\n getSelection(): SelectedSeat[] {\n return this.controller.getSelection();\n }\n\n /** Hold the current selection. Resolves the hold, or null on a 409 conflict. */\n async hold(options: { ttlMs?: number } = {}): Promise<HoldResult | null> {\n try {\n return await this.holdOrThrow(options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /**\n * @internal Like {@link hold} but RE-THROWS the structured API error (409\n * `reason`/`code` + `conflicts`) instead of swallowing it into `onError` +\n * `null`. The native WebView host adapter needs the throw so it can answer the\n * originating command with a correlated error carrying the SPECIFIC reason\n * (`sold_out` vs `not_enough_together`); the public method above keeps the\n * catch-and-onError contract that direct web consumers rely on. Not a stable\n * part of the embed API.\n */\n async holdOrThrow(options: { ttlMs?: number } = {}): Promise<HoldResult | null> {\n const h = await this.controller.hold(undefined, options.ttlMs);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /** Restore an active hold by its opaque id without extending its expiry. */\n async resumeHold(holdId: string): Promise<HoldResult | null> {\n try {\n return await this.resumeHoldOrThrow(holdId);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link resumeHold} for the native host adapter. See {@link holdOrThrow}. */\n async resumeHoldOrThrow(holdId: string): Promise<HoldResult | null> {\n const h = await this.controller.resumeHold(holdId);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /**\n * Push the OPEN hold's expiry out (\"need more time?\"). Resolves the refreshed\n * hold, or `null` when there is nothing held or the server refused (the hold\n * is gone, already expired, or at its renewal cap) — refusal is a normal\n * outcome, not an error, so the host decides the copy. The client-side expiry\n * timer is re-armed to match, so `onHoldExpired` won't fire early.\n */\n async extendHold(ttlMs?: number): Promise<HoldResult | null> {\n try {\n const h = await this.controller.extendHold(ttlMs);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** Current active hold known to this chart, if any. */\n getCurrentHold(): HoldResult | null {\n const h = this.controller.currentHold();\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n getGAAreas(): GAAreaAvailability[] {\n return this.controller.getGAAreas();\n }\n\n async holdGA(\n areaId: string,\n qty: number,\n options: { tierId?: string | null; ttlMs?: number } = {},\n ): Promise<HoldResult | null> {\n try {\n return await this.holdGAOrThrow(areaId, qty, options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link holdGA} for the native host adapter. See {@link holdOrThrow}. */\n async holdGAOrThrow(\n areaId: string,\n qty: number,\n options: { tierId?: string | null; ttlMs?: number } = {},\n ): Promise<HoldResult | null> {\n const h = await this.controller.holdGA(areaId, qty, options);\n return h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n\n /**\n * Ask the server for the `qty` best free seats and hold them atomically.\n * `options.ttlMs` sets the checkout window exactly like {@link hold}; omit it\n * and the server falls back to the event setting, then its own default.\n */\n async bestAvailable(\n qty: number,\n categoryKey?: string,\n options: { zoneId?: string; preferPremium?: boolean; ttlMs?: number } = {},\n ): Promise<BestAvailableResult | null> {\n try {\n return await this.bestAvailableOrThrow(qty, categoryKey, options);\n } catch (err) {\n this.opts.onError?.(err);\n return null;\n }\n }\n\n /** @internal Throwing variant of {@link bestAvailable} for the native host adapter. See {@link holdOrThrow}. */\n async bestAvailableOrThrow(\n qty: number,\n categoryKey?: string,\n options: { zoneId?: string; preferPremium?: boolean; ttlMs?: number } = {},\n ): Promise<BestAvailableResult | null> {\n const h = await this.controller.bestAvailable(qty, categoryKey, options);\n return h ? {\n holdId: h.holdId,\n expiresAt: h.expiresAt,\n labels: h.labels,\n seats: h.seats,\n items: h.items,\n ...(options.zoneId ? { zoneId: options.zoneId } : {}),\n } : null;\n }\n\n /**\n * Choose a ticket tier for a selected seat (e.g. Adult → Child). The seat's\n * available `tiers` are on each `SelectedSeat` from `getSelection()` /\n * `onSelectionChange`. Re-emits the selection with the new tier + price, and\n * the tier rides along in the next `hold()` / `onHold` per seat. `tierId=null`\n * reverts to the default tier.\n */\n setSeatTier(seatId: string, tierId: string | null): void {\n this.controller.setSeatTier(seatId, tierId);\n }\n\n /**\n * Floors of a multi-floor chart — `[{ id, name }]` (single-floor charts\n * return one entry; empty before render()). Pair with setFloor() to build a\n * host-side floor switcher.\n */\n getFloors(): { id: string; name: string }[] {\n return this.controller.getFloors();\n }\n\n /** Switch the shown floor (2D). Warns + no-ops on single-floor charts. */\n setFloor(floorId: string): void {\n if (this.controller.getFloors().length <= 1) {\n console.warn('seatmap: setFloor() ignored — this chart has a single floor');\n return;\n }\n this.controller.setFloor(floorId);\n }\n\n /** Toggle colorblind-safe rendering at runtime (see options.colorblindSafe). */\n setColorblindSafe(on: boolean): void {\n this.controller.setColorblindSafe(on);\n }\n\n /** Switch the 2D canvas projection.\n * @deprecated `'isometric'` and `'perspective'` are retired in favour of the\n * real 3D venue view (`setBuyerView('venue3d')`); accepted for source\n * compatibility until the next major. */\n setViewMode(mode: RendererViewMode): void {\n this.controller.setViewMode(mode);\n }\n\n /** Current canvas projection. */\n getViewMode(): RendererViewMode {\n return this.controller.getViewMode();\n }\n\n /** Zoom in one step (same increment as the wheel/pinch gesture). */\n zoomIn(): void {\n this.controller.zoomIn();\n }\n\n /** Zoom out one step. */\n zoomOut(): void {\n this.controller.zoomOut();\n }\n\n /** Reset the camera so the whole chart fits the container. */\n zoomToFit(): void {\n this.controller.zoomToFit();\n }\n\n /** Release the current hold (if any). No-op when nothing is held. */\n async release(): Promise<void> {\n await this.controller.release();\n }\n\n /** Release selected labels from the current hold while keeping the remainder. */\n async releaseLabels(labels: string[]): Promise<boolean> {\n return this.controller.releaseLabels(labels);\n }\n\n /** Tear everything down: close the socket, stop timers, drop the canvas. */\n /**\n * Realtime for an access-scoped chart.\n *\n * A tokenless chart never gets here: `access` is null, `PubApi.socketUrl()`\n * returns the URL it always has, and PickerController keeps its own socket\n * and its own legacy frames. Nothing about the public path changes.\n */\n private startRealtime(): void {\n if (!this.access?.configured || this.realtime) return;\n this.realtime = new BuyerRealtimeClient({\n url: this.api.subscribeUrl(this.opts.event),\n mintTicket: () => this.api.subscribeTicket(this.opts.event),\n onAccessUnavailable: (event) => this.opts.onAccessUnavailable?.(event),\n sink: createControllerSink(this.controller, {\n flashOnLiveChange: true,\n onSelectedObjectUnavailable: (labels, reason) =>\n this.opts.onSelectedObjectUnavailable?.({ labels, reason }),\n }),\n });\n this.realtime.start();\n }\n\n /**\n * Re-acquire the buyer access session — call after your app has re-authorized\n * the buyer (a revoked session cannot be recovered any other way). Resolves\n * true when a fresh bearer is held; the realtime feed restarts with it.\n */\n async refreshAccess(): Promise<boolean> {\n if (!this.access?.configured) return false;\n const ok = await this.access.refresh('manual');\n if (ok) {\n await this.controller.refresh();\n this.realtime?.restart();\n if (!this.realtime) this.startRealtime();\n }\n return ok;\n }\n\n /**\n * The visible failure state. Deliberately inline-styled and dependency-free:\n * this renders on a stranger's website, where our stylesheet may not have\n * loaded (the chart fetch just failed) and where inheriting the host's own\n * styles is likelier to produce something unreadable than something on-brand.\n */\n private showLoadFailure(host: HTMLDivElement): void {\n const box = document.createElement('div');\n box.setAttribute('role', 'status');\n box.style.cssText =\n 'display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;' +\n 'width:100%;height:100%;min-height:180px;box-sizing:border-box;padding:24px;text-align:center;' +\n 'font:500 14px/1.5 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;color:#3b4256;';\n\n const text = document.createElement('div');\n // No error detail: a buyer cannot act on it, and it can carry internals.\n text.textContent = 'The seat map didn’t load.';\n box.appendChild(text);\n\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.textContent = 'Try again';\n btn.style.cssText =\n 'appearance:none;border:1px solid #c9cede;background:#fff;color:#10162a;border-radius:8px;' +\n 'padding:8px 16px;font:600 13px/1 inherit;cursor:pointer;';\n btn.addEventListener('click', () => {\n // Full remount: the controller holds no partial state worth salvaging\n // after a failed render, and this is the same recovery SeatPicker uses.\n this.destroy();\n void this.render().catch((err) => this.opts.onError?.(err));\n });\n box.appendChild(btn);\n this.retryBtn = btn;\n host.appendChild(box);\n }\n\n destroy(): void {\n this.realtime?.stop();\n this.realtime = null;\n this.access?.clear();\n this.retryBtn = null;\n if (this.hostEl && this.onTipMove) this.hostEl.removeEventListener('mousemove', this.onTipMove);\n this.tipEl = null;\n this.onTipMove = null;\n this.controller.destroy();\n if (this.hostEl && this.hostEl.parentNode) this.hostEl.parentNode.removeChild(this.hostEl);\n this.hostEl = null;\n this.mount = null;\n this.rendered = false;\n this.mode_ = null;\n }\n}\n","/**\n * BuyerRealtimeClient — the client half of `docs/realtime-protocol-2026-08-01.md`.\n *\n * Why this exists as a separate socket rather than inside PickerController:\n * a private scope authenticates with a one-use **subscribe ticket** carried in\n * `Sec-WebSocket-Protocol`, and a browser can only set that at construction —\n * `new WebSocket(url, protocols)`. The controller's socket is built from a URL\n * alone (`PickerTransport.socketUrl`), and a bearer must never travel in a URL\n * because URLs are routinely logged. So an access-scoped picker asks the\n * transport for an empty `socketUrl()` (the controller then skips its own\n * connection entirely) and this client owns the wire instead.\n *\n * A tokenless public picker never reaches this file. It keeps the controller's\n * original socket, offers no subprotocol, and therefore receives byte-for-byte\n * the frames it received before this module existed (protocol doc §1).\n *\n * What it implements:\n * - protocol negotiation: offer `seatlayer.v1`, believe the 101 echo, and fall\n * back to legacy frame handling when the server (or a proxy) does not echo;\n * - the ticket exchange, one mint per connection attempt, ticket in the\n * subprotocol list and never in the URL;\n * - compact `{default, exceptions}` snapshot reconstruction;\n * - `sv.<n>` resume, handling BOTH outcomes (a `resumed` delta or a full\n * snapshot) on every reconnect;\n * - close code 4401 as a typed access-revoked state, never a reconnect loop;\n * - liveness by ping/pong only. Silence is normal and carries no information\n * (protocol doc §5) — a quiet socket is never treated as a dead one.\n */\nimport type { BuyerAccessUnavailableEvent } from './buyerAccess';\n\n/** The projected status of one unit, as the server words it on the wire. */\nexport type WireStatus = string;\n\n/** A scope's projection: one default plus the units that differ from it. */\nexport interface Projection {\n default: WireStatus;\n exceptions: Record<string, WireStatus>;\n}\n\nexport interface StatusChange {\n label: string;\n status: WireStatus;\n}\n\n/** Where reconstructed inventory goes. Implemented over PickerController. */\nexport interface RealtimeSink {\n /** Apply a batch of label→status changes. Implementations must paint this as\n * ONE pass, not one pass per label (motion system §4 rule 2). */\n applyStatuses(changes: StatusChange[]): void;\n /** Re-pull authoritative state over the scoped HTTP route. Used when a frame\n * cannot be diffed against what we hold (first snapshot, or the scope's\n * default itself changed, which redefines every unit we were never told\n * about). */\n resync(): void | Promise<void>;\n /** Section availability changed (channel-agnostic; identical for every scope). */\n onSections?(hidden: string[], closed: string[]): void;\n /** Scope-projected presence counters. */\n onPresence?(counts: { shoppingSessions: number; activeHolds: number }): void;\n}\n\nexport interface SubscribeTicket {\n ticket?: string;\n /** Exactly what to hand `new WebSocket(url, protocols)`, per protocol doc §3. */\n protocols?: string[];\n}\n\nexport interface BuyerRealtimeOptions {\n /** The subscribe URL. Must never carry a credential — asserted below. */\n url: string;\n sink: RealtimeSink;\n /** Mint a one-use ticket for THIS connection attempt. Returns null for the\n * anonymous public case (no ticket needed). Throwing stops the client. */\n mintTicket?: () => Promise<SubscribeTicket | null>;\n /** Typed access states. 4401 arrives here as `revoked`. */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /** Test seam. Defaults to the global WebSocket. */\n socketFactory?: (url: string, protocols: string[]) => WebSocket;\n /** Test seam for the keepalive/backoff timers. */\n now?: () => number;\n}\n\nexport const SEATLAYER_V1 = 'seatlayer.v1';\n/**\n * Join separator for the section-visibility dedupe keys. A NUL can never occur\n * in a section id, so two different arrays can never collide on one key. It is\n * written as an escape deliberately: a literal NUL byte in the source made the\n * whole file read as binary to grep, diff, and review tooling.\n */\nconst SEP = '\\u0000';\n\n/** Protocol doc §3: revocation closes the socket with this code. */\nexport const CLOSE_ACCESS_REVOKED = 4401;\n\nconst MAX_BACKOFF_MS = 15_000;\nconst PING_INTERVAL_MS = 25_000;\nconst PONG_GRACE_MS = 10_000;\n/** Only armed when we offered a resume; the server always answers a resume. */\nconst RESUME_ANSWER_GRACE_MS = 5_000;\n\n/**\n * Turn a snapshot frame into a projection. Handles both wire forms: the v1\n * compact frame states its `default` and lists only the exceptions; the legacy\n * verbose frame lists every non-free unit, which is the same thing with an\n * implicit default of `free`.\n */\nexport function projectionFromSnapshot(frame: {\n default?: unknown;\n seats?: unknown;\n}): Projection {\n const fallback = typeof frame.default === 'string' ? frame.default : 'free';\n const exceptions: Record<string, WireStatus> = {};\n if (frame.seats && typeof frame.seats === 'object') {\n for (const [label, status] of Object.entries(frame.seats as Record<string, unknown>)) {\n if (typeof status === 'string' && status !== fallback) exceptions[label] = status;\n }\n }\n return { default: fallback, exceptions };\n}\n\n/**\n * The changes needed to move a renderer from `prev` to `next`.\n *\n * Returns null when the two projections have different defaults: the default\n * describes every unit the frame does NOT name, and the client does not hold\n * that universe, so the move cannot be expressed as a bounded diff. The caller\n * resyncs over HTTP instead — correct, and rare (it means a channel pause or an\n * allocation change moved the whole scope).\n */\nexport function diffProjections(prev: Projection | null, next: Projection): StatusChange[] | null {\n if (!prev || prev.default !== next.default) return null;\n const changes: StatusChange[] = [];\n for (const [label, status] of Object.entries(next.exceptions)) {\n if (prev.exceptions[label] !== status) changes.push({ label, status });\n }\n for (const label of Object.keys(prev.exceptions)) {\n if (!(label in next.exceptions)) changes.push({ label, status: next.default });\n }\n return changes;\n}\n\n/** Fold a delta batch into a projection (an exception equal to the default\n * stops being an exception, so the model cannot grow without bound). */\nexport function applyChanges(projection: Projection, changes: StatusChange[]): void {\n for (const change of changes) {\n if (change.status === projection.default) delete projection.exceptions[change.label];\n else projection.exceptions[change.label] = change.status;\n }\n}\n\n/** Belt and braces for the \"no bearer in a URL\" rule — cheap, and it turns a\n * future refactor that reintroduces one into a thrown error, not a silent leak. */\nexport function assertCredentialFreeUrl(url: string): void {\n if (/(?:^|[?&#])(?:token|access_token|bearer|authorization|ticket|tkt|bse)=/i.test(url)) {\n throw new Error('seatlayer: refusing to open a socket with a credential in the URL');\n }\n if (/\\bbse_[A-Za-z0-9._-]+/.test(url)) {\n throw new Error('seatlayer: refusing to open a socket with a credential in the URL');\n }\n}\n\nexport class BuyerRealtimeClient {\n private readonly opts: BuyerRealtimeOptions;\n private ws: WebSocket | null = null;\n private stopped = true;\n private attempt = 0;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Our model of this scope's projection. Null until the first snapshot. */\n private projection: Projection | null = null;\n /** Last `snapshotVersion` seen on any frame that carried one — the resume point. */\n private version: number | null = null;\n /** True once the 101 echoed `seatlayer.v1`. */\n private v1 = false;\n /** Set when we offered v1 and the handshake came back without it — a proxy\n * most likely stripped the header, so the next attempt selects the v1 frame\n * format with the `?pv=1` marker instead (protocol doc §1). The marker\n * selects a format and can never carry a credential or widen a scope. */\n private useQueryMarker = false;\n private hidden: string | null = null;\n private closedSections: string | null = null;\n\n constructor(options: BuyerRealtimeOptions) {\n this.opts = options;\n assertCredentialFreeUrl(options.url);\n }\n\n /** Negotiated protocol, for tests and diagnostics. */\n get protocol(): 'v1' | 'legacy' | null {\n return this.ws ? (this.v1 ? 'v1' : 'legacy') : null;\n }\n\n get snapshotVersion(): number | null {\n return this.version;\n }\n\n start(): void {\n if (!this.stopped) return;\n this.stopped = false;\n void this.connect();\n }\n\n /** Stop for good (destroy, or a revocation). Safe to call twice. */\n stop(): void {\n this.stopped = true;\n this.clearTimers();\n const ws = this.ws;\n this.ws = null;\n if (ws) {\n ws.onopen = null;\n ws.onmessage = null;\n ws.onclose = null;\n ws.onerror = null;\n try {\n ws.close();\n } catch {\n /* already closing */\n }\n }\n }\n\n /** Restart after the host re-authorized a revoked buyer (`refreshAccess()`). */\n restart(): void {\n this.stop();\n this.projection = null;\n this.version = null;\n this.attempt = 0;\n this.start();\n }\n\n // ---- connection -----------------------------------------------------------\n\n private async connect(): Promise<void> {\n if (this.stopped) return;\n\n let protocols: string[] = [SEATLAYER_V1];\n if (this.opts.mintTicket) {\n let minted: SubscribeTicket | null;\n try {\n // One mint per connection attempt, including every reconnect. Tickets\n // are TTL ≤ 30s and single-redemption, so reusing one cannot work.\n minted = await this.opts.mintTicket();\n } catch (err) {\n // The mint is an ordinary scoped HTTP call: the transport has already\n // classified and reported any access failure. A transport-level failure\n // is transient, so back off rather than give up.\n this.reportIfAccessError(err);\n this.scheduleReconnect();\n return;\n }\n if (this.stopped) return;\n if (minted?.protocols?.length) {\n protocols = [...minted.protocols];\n if (!protocols.includes(SEATLAYER_V1)) protocols.unshift(SEATLAYER_V1);\n } else if (minted?.ticket) {\n protocols = [SEATLAYER_V1, `tkt.${minted.ticket}`];\n }\n }\n\n // Resume from the last version we actually saw. Both outcomes — a `resumed`\n // delta or a full snapshot — are handled in onmessage.\n const offeredResume = this.version !== null;\n if (offeredResume) protocols.push(`sv.${this.version}`);\n\n const url = this.useQueryMarker\n ? `${this.opts.url}${this.opts.url.includes('?') ? '&' : '?'}pv=1`\n : this.opts.url;\n assertCredentialFreeUrl(url);\n\n let ws: WebSocket;\n try {\n const make = this.opts.socketFactory ?? ((u: string, p: string[]) => new WebSocket(u, p));\n ws = make(url, protocols);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.attempt = 0;\n this.v1 = ws.protocol === SEATLAYER_V1;\n // We asked for v1 and the server did not echo it. Either it is a\n // pre-M5 server (legacy frames are correct and byte-compatible) or a\n // proxy ate the header — the next attempt tries the query marker.\n if (!this.v1) this.useQueryMarker = true;\n this.startKeepalive(ws);\n if (offeredResume) {\n // The server always answers a resume with a delta or a snapshot. If\n // neither lands, fall back to authoritative HTTP rather than sit on a\n // possibly stale map. This timer is NOT a liveness check — ordinary\n // silence on a live socket never triggers it.\n this.resumeTimer = setTimeout(() => {\n this.resumeTimer = null;\n void this.opts.sink.resync();\n }, RESUME_ANSWER_GRACE_MS);\n } else {\n // Parity with the controller's own socket: pull authoritative state on\n // every fresh connection.\n void this.opts.sink.resync();\n }\n };\n\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(typeof event.data === 'string' ? event.data : '');\n } catch {\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n this.handleFrame(parsed as Record<string, unknown>);\n };\n\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.ws = null;\n this.clearTimers();\n if (event?.code === CLOSE_ACCESS_REVOKED) {\n // Retrying with the same credential is guaranteed to fail, so this is\n // a typed terminal state, not a reconnect loop (protocol doc §3).\n this.stopped = true;\n this.opts.onAccessUnavailable?.({\n reason: 'revoked',\n code: 'access_revoked',\n retryable: false,\n });\n return;\n }\n this.scheduleReconnect();\n };\n\n ws.onerror = () => {\n try {\n ws.close();\n } catch {\n /* onclose drives the reconnect */\n }\n };\n }\n\n private handleFrame(frame: Record<string, unknown>): void {\n const type = typeof frame.type === 'string' ? frame.type : '';\n\n // A frame carrying `protocol: 1` proves v1 even when the 101 echo was\n // stripped in transit (the `?pv=1` path).\n if (frame.protocol === 1) this.v1 = true;\n\n if (typeof frame.snapshotVersion === 'number') this.version = frame.snapshotVersion;\n\n if (type === 'pong') {\n this.clearPongTimer();\n return;\n }\n\n // Section availability rides on `hidden`/`closed`, either on its own frame\n // or alongside a snapshot. Identical for every scope.\n if (Array.isArray(frame.hidden) || Array.isArray(frame.closed)) {\n const hidden = Array.isArray(frame.hidden) ? (frame.hidden as string[]) : [];\n const closed = Array.isArray(frame.closed) ? (frame.closed as string[]) : [];\n const hKey = hidden.join(SEP);\n const cKey = closed.join(SEP);\n if (hKey !== this.hidden || cKey !== this.closedSections) {\n this.hidden = hKey;\n this.closedSections = cKey;\n this.opts.sink.onSections?.(hidden, closed);\n }\n }\n if (type === 'hidden') return; // carries no inventory\n\n if (type === 'presence') {\n this.opts.sink.onPresence?.({\n shoppingSessions: Number(frame.shoppingSessions) || 0,\n activeHolds: Number(frame.activeHolds) || 0,\n });\n return;\n }\n\n if (type === 'allocation') {\n // Always followed by a fresh snapshot, which is authoritative. Nothing to\n // do here — and deliberately NO dedupe on allocationVersion: a pause or\n // unpause changes the projection without moving that number.\n return;\n }\n\n if (type === 'snapshot' || (!type && frame.seats)) {\n this.answered();\n const next = projectionFromSnapshot(frame);\n const changes = diffProjections(this.projection, next);\n this.projection = next;\n if (changes === null) void this.opts.sink.resync();\n else if (changes.length) this.opts.sink.applyStatuses(changes);\n return;\n }\n\n if (type === 'delta' && Array.isArray(frame.changes)) {\n this.answered();\n const changes = (frame.changes as Array<Record<string, unknown>>)\n .filter((c) => typeof c?.label === 'string' && typeof c?.status === 'string')\n .map((c) => ({ label: c.label as string, status: c.status as string }));\n if (!changes.length) return;\n if (this.projection) applyChanges(this.projection, changes);\n this.opts.sink.applyStatuses(changes);\n }\n }\n\n /** The server answered our resume; cancel the fallback resync. */\n private answered(): void {\n if (!this.resumeTimer) return;\n clearTimeout(this.resumeTimer);\n this.resumeTimer = null;\n }\n\n private reportIfAccessError(err: unknown): void {\n const reason = (err as { reason?: string } | null)?.reason;\n if ((err as { name?: string } | null)?.name !== 'BuyerAccessUnavailableError') return;\n this.stopped = true;\n this.opts.onAccessUnavailable?.({\n reason: (reason ?? 'invalid') as BuyerAccessUnavailableEvent['reason'],\n code: (err as { code?: string }).code,\n status: (err as { status?: number }).status,\n retryable: reason === 'paused',\n });\n }\n\n // ---- keepalive & backoff --------------------------------------------------\n\n /**\n * Liveness is ping/pong, and only ping/pong. A socket that receives nothing\n * for minutes is the normal, correct state for a narrowly-scoped buyer on a\n * busy event (protocol doc §5), so quiet time never triggers a reconnect.\n */\n private startKeepalive(ws: WebSocket): void {\n this.pingTimer = setInterval(() => {\n if (this.ws !== ws) return;\n try {\n ws.send(JSON.stringify({ type: 'ping' }));\n } catch {\n return;\n }\n this.clearPongTimer();\n this.pongTimer = setTimeout(() => {\n this.pongTimer = null;\n try {\n ws.close();\n } catch {\n /* onclose drives the reconnect */\n }\n }, PONG_GRACE_MS);\n }, PING_INTERVAL_MS);\n }\n\n /**\n * FULL jitter, not plain exponential backoff.\n *\n * A deterministic `2**attempt` schedule makes every browser that lost the same\n * socket — a worker redeploy, a DO eviction, a flaky edge PoP — come back in\n * the same millisecond, and an on-sale crowd reconnecting in lockstep is the\n * thing that turns one blip into a self-sustaining thundering herd. Full\n * jitter (`random() * ceiling`) spreads the same crowd across the whole\n * window; the ceiling still doubles, so a persistent outage still backs off.\n *\n * `Math.random` is correct here: this is client code choosing a delay, not a\n * Workflow step that has to replay deterministically.\n */\n private scheduleReconnect(): void {\n if (this.stopped || this.reconnectTimer) return;\n const attempt = Math.min(this.attempt++, 5);\n const ceiling = Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);\n const delay = Math.random() * ceiling;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n void this.connect();\n }, delay);\n }\n\n private clearPongTimer(): void {\n if (!this.pongTimer) return;\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n\n private clearTimers(): void {\n if (this.pingTimer) clearInterval(this.pingTimer);\n this.pingTimer = null;\n this.clearPongTimer();\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n if (this.resumeTimer) clearTimeout(this.resumeTimer);\n this.resumeTimer = null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Controller sink\n// ---------------------------------------------------------------------------\n\n/**\n * The slice of PickerController this module drives. Structural on purpose — it\n * keeps this file free of an `@seatlayer/core` import, and every member here is\n * public controller API, so nothing in the engine mirror has to change.\n */\nexport interface PickerControllerLike {\n idForLabel(label: string): string | undefined;\n tableSelection(seatIdOrLabel: string): { physicalSeatIds: string[] } | null;\n setStatus(ids: string[], status: 'free' | 'held' | 'booked' | 'not_for_sale'): void;\n getStatus(id: string): string | undefined;\n flashSeat(id: string, color?: string): void;\n currentHold(): { labels: string[] } | null;\n getSelection(): Array<{ id: string; label: string }>;\n deselect(ids: string[]): void;\n refresh(): Promise<void>;\n}\n\n/** Wire status → renderer status. `blocked` is the one neutral unavailable\n * value an out-of-scope unit reads as; the buyer must not be able to tell it\n * apart from ordinary off-sale inventory (protocol doc §5). */\nfunction rendererStatus(wire: string): 'free' | 'held' | 'booked' | 'not_for_sale' {\n if (wire === 'blocked') return 'not_for_sale';\n if (wire === 'held' || wire === 'booked' || wire === 'free' || wire === 'not_for_sale') return wire;\n return 'free';\n}\n\nexport interface ControllerSinkOptions {\n /** Pulse seats other buyers take, as the controller's own socket does. */\n flashOnLiveChange?: boolean;\n /** Selected-but-unheld units that stopped being selectable. */\n onSelectedObjectUnavailable?: (labels: string[], reason: 'ineligible' | 'taken') => void;\n /** Section availability changed and the chart itself needs rebuilding. */\n onSections?: (hidden: string[], closed: string[]) => void;\n onStatusChange?: () => void;\n}\n\nexport function createControllerSink(\n controller: PickerControllerLike,\n options: ControllerSinkOptions = {},\n): RealtimeSink {\n const idsForLabel = (label: string): string[] => {\n const table = controller.tableSelection(label);\n if (table) return table.physicalSeatIds;\n const id = controller.idForLabel(label);\n return id ? [id] : [];\n };\n\n return {\n applyStatuses(changes) {\n const held = controller.currentHold()?.labels ?? [];\n // Bucket the whole batch and paint one call per status: a 256-label\n // delta must animate as ONE canvas pass, never one per seat.\n const buckets: Record<string, string[]> = {\n free: [], held: [], booked: [], not_for_sale: [],\n };\n const flashes: Array<{ id: string; color: string }> = [];\n const lost: string[] = [];\n const selected = new Map(controller.getSelection().map((s) => [s.label, s.id]));\n\n for (const change of changes) {\n const ids = idsForLabel(change.label);\n if (!ids.length) continue;\n const next = rendererStatus(change.status);\n buckets[next].push(...ids);\n if (\n options.flashOnLiveChange &&\n next !== 'free' &&\n !held.includes(change.label) &&\n ids.some((id) => controller.getStatus(id) === 'free')\n ) {\n const color = next === 'held' ? '#f4b740' : '#f43f5e';\n for (const id of ids) flashes.push({ id, color });\n }\n if (next !== 'free' && !held.includes(change.label) && selected.has(change.label)) {\n lost.push(change.label);\n }\n }\n\n for (const status of ['free', 'held', 'booked', 'not_for_sale'] as const) {\n if (buckets[status].length) controller.setStatus(buckets[status], status);\n }\n for (const flash of flashes) controller.flashSeat(flash.id, flash.color);\n\n if (lost.length) {\n // One deselect call, so the map cross-fades in a single pass rather\n // than blinking seat by seat (motion system §3, buyer picker).\n const ids = lost.flatMap((label) => idsForLabel(label));\n if (ids.length) controller.deselect(ids);\n const ineligible = changes.some(\n (c) => c.status === 'blocked' && lost.includes(c.label),\n );\n options.onSelectedObjectUnavailable?.(lost, ineligible ? 'ineligible' : 'taken');\n }\n options.onStatusChange?.();\n },\n\n async resync() {\n await controller.refresh();\n },\n\n /**\n * Section availability moved. Statuses are re-pulled so the map repaints.\n *\n * Known limit: rebuilding the chart when a section is newly HIDDEN (its\n * seats are stripped, not greyed) lives inside PickerController's own\n * socket handler and has no public entry point, so an access-scoped picker\n * repaints statuses but does not restructure the chart until its next\n * mount. Closing/opening a section — the common mid-sale move — is a\n * status-level change and is handled here in full.\n */\n onSections(hidden, closed) {\n void controller.refresh();\n options.onSections?.(hidden, closed);\n },\n };\n}\n","/**\n * Minimal client for the public embed surface of workers/api (the `/pub/*`\n * routes). Deliberately self-contained — it does NOT reuse src/lib/api.ts,\n * which bakes in a build-time API base and dashboard session credentials. The\n * SDK runs cross-origin on a third-party ticketing page, so:\n * - apiBase is per-instance (constructor option), not a build constant;\n * - credentials are omitted (no cookie to send, avoids CORS-credential setup);\n * - no custom headers on mutating calls (keeps the CORS preflight trivial).\n */\nimport type { ChartDoc, PickerSeat as SelectedSeat } from '@seatlayer/core';\nimport type {\n BuyerAccessContext,\n SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, SEATLAYER_V1, type RealtimeSink } from './buyerRealtime';\n\nexport interface HoldConflict {\n label: string;\n status: string;\n}\n\nexport interface HoldLineItem {\n label: string; objectId: string; objectType: 'seat' | 'booth' | 'ga' | 'table'; categoryKey: string;\n tierId: string | null;\n /** Price in major currency units (for example 45 means $45.00). */\n unitPrice: number;\n currency: string;\n quantity?: number;\n}\n\nexport class ApiError extends Error {\n status: number;\n code?: string;\n /** Present when a hold 409s because seats were just taken/held. */\n conflicts?: HoldConflict[];\n /** Present when best-available 409s ('not_enough_together' | 'sold_out'). */\n reason?: string;\n /**\n * Seconds the server asked the caller to wait, off a 429's `Retry-After`.\n *\n * Present ONLY on a rate-limit error, and it is the server's number — never a\n * guess. A widget that catches this can say \"try again in N seconds\" instead\n * of rendering the blank map a swallowed 429 used to produce.\n */\n retryAfterS?: number;\n\n constructor(\n status: number,\n message: string,\n code?: string,\n conflicts?: HoldConflict[],\n reason?: string,\n retryAfterS?: number,\n ) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.conflicts = conflicts;\n this.reason = reason;\n this.retryAfterS = retryAfterS;\n }\n}\n\n/**\n * Longest advertised delay we will sit out inside a request.\n *\n * A rate limit the buyer can wait through invisibly is worth absorbing; one\n * that is 30 seconds long is not — sleeping that long inside `chart()` looks\n * like a hung widget, and the retry would very likely 429 again anyway. Past\n * the cap the error is thrown WITH `retryAfterS`, so the host decides.\n */\nconst MAX_RATE_LIMIT_WAIT_S = 10;\n/** What to assume when a 429 names no delay at all. */\nconst DEFAULT_RATE_LIMIT_WAIT_S = 1;\n\n/**\n * `Retry-After` in seconds. RFC 9110 allows either a delta-seconds integer or\n * an HTTP-date; the API sends the integer, and the date form is handled so a\n * proxy that rewrites it cannot turn a well-formed 429 into an untyped one.\n * Returns undefined when neither the header nor the body says anything.\n */\nexport function parseRetryAfter(header: string | null, bodyValue?: unknown): number | undefined {\n const raw = (header ?? '').trim();\n if (raw) {\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);\n const at = Date.parse(raw);\n if (Number.isFinite(at)) return Math.max(0, Math.ceil((at - Date.now()) / 1000));\n }\n if (typeof bodyValue === 'number' && Number.isFinite(bodyValue) && bodyValue >= 0) {\n return Math.ceil(bodyValue);\n }\n return undefined;\n}\n\nexport interface PubChartResult {\n event: { key: string; name: string; inventoryModelVersion?: 1 | 2 };\n doc: ChartDoc;\n}\n\nexport interface PubObjectsResult {\n /** Every non-free seat's status, keyed by seat label. */\n seats: Record<string, string>;\n /** Section/zone ids hidden from buyers this event (seats stripped from the map). */\n hidden?: string[];\n /** Section/zone ids in the `closed` state (Phase 2): rendered grey + not purchasable. */\n closed?: string[];\n updatedAt: number;\n}\n\nexport interface HoldResult {\n holdId: string;\n expiresAt: number;\n /** The held seats with the buyer's chosen ticket tier per seat (present on hold). */\n seats?: SelectedSeat[];\n items?: HoldLineItem[];\n}\n\n/** Browser-safe active-hold projection returned by the resume endpoint. */\nexport interface ResumedHoldResult extends HoldResult {\n items: HoldLineItem[];\n}\n\n/** Best-available response — the server-picked seats plus the hold they landed in. */\nexport interface BestAvailableResult {\n holdId: string;\n expiresAt: number;\n labels: string[];\n seats?: SelectedSeat[];\n items?: HoldResult['items'];\n zoneId?: string;\n}\n\n/** A gateway the organizer can be connected to. */\nexport type PaymentProviderName = 'stripe' | 'razorpay';\n\n/**\n * Why `payment-options` came back with an empty list.\n *\n * The three are NOT interchangeable and two of them give opposite advice:\n * `not_configured` means the organizer takes payment somewhere else,\n * `payments_off_for_event` means they deliberately do not sell THIS event\n * online, and `unavailable_for_event` means they switched it on and it is\n * broken. Collapsing them makes the widget blame a working integration for a\n * decision that was made on purpose.\n */\nexport type PaymentOptionsReason =\n | 'not_configured'\n | 'payments_off_for_event'\n | 'unavailable_for_event';\n\n/**\n * What this event can take money through. Since the per-event gateway column\n * landed, `providers` holds AT MOST ONE entry — the gateway the organizer\n * assigned — so no browser can choose which one charges.\n *\n * `reason` is optional on the wire: a widget pinned against an older worker\n * still parses, and its absence means what that worker meant by an empty list.\n */\nexport interface PaymentOptionsResult {\n providers: PaymentProviderName[];\n currency: string | null;\n reason?: PaymentOptionsReason | null;\n}\n\n/** A started payment. Exactly one of the two handoffs comes back. */\nexport interface CheckoutSessionResult {\n orderId: string;\n totalMinor: number;\n currency: string;\n expiresAt: number;\n /** Hosted gateway page — navigate to it. */\n redirectUrl?: string;\n /** In-page modal gateway — open it without leaving the page. */\n clientPayload?: Record<string, unknown>;\n}\n\n/** An order's state while its gateway webhook is in flight. */\nexport interface OrderStatusResult {\n orderId: string;\n status: string;\n totalMinor: number;\n currency: string;\n amountFormatted: string;\n seatCount: number;\n}\n\n/** Codes a 409 uses to say \"the unit you picked is no longer yours to pick\". */\nconst OBJECT_UNAVAILABLE_CODES: Record<string, SelectedObjectUnavailableEvent['reason']> = {\n seat_conflict: 'taken',\n conflict: 'taken',\n channel_assignment_conflict: 'ineligible',\n allocation_exhausted: 'exhausted',\n};\n\nexport interface PubApiOptions {\n /**\n * Buyer access session. When present, EVERY scoped operation on this client\n * carries `Authorization: Bearer bse_…` — chart, objects, hold, replace-hold,\n * best-available, resume, release, extend, resnapshot and the realtime\n * subscribe ticket. The binding is immutable for the client's lifetime: there\n * is no method that turns it off, so no operation can silently downgrade to\n * anonymous Public sale (guide §6, §7).\n */\n access?: BuyerAccessContext;\n /** A 409 named specific inventory the buyer can no longer have. */\n onObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n}\n\n/** Public-surface client bound to one apiBase (e.g. https://api.seatlayer.io). */\nexport class PubApi {\n private readonly viewerId = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `viewer_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n\n private readonly access?: BuyerAccessContext;\n private readonly onObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n\n constructor(private readonly base: string, options: PubApiOptions = {}) {\n this.access = options.access;\n this.onObjectUnavailable = options.onObjectUnavailable;\n }\n\n /** True when this client is bound to a buyer access session. */\n get accessScoped(): boolean {\n return !!this.access?.configured;\n }\n\n private async request<T>(\n path: string,\n init: { method?: 'GET' | 'POST'; body?: unknown; labels?: string[] } = {},\n retried: { auth?: boolean; rateLimit?: boolean } = {},\n ): Promise<T> {\n const method = init.method ?? 'GET';\n const headers: Record<string, string> = {};\n let body: string | undefined;\n if (init.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(init.body);\n }\n // Throws BuyerAccessUnavailableError rather than returning undefined when a\n // configured session cannot produce a bearer — the request must not go out\n // anonymous, because anonymous means Public sale.\n const authorization = await this.access?.authorization(retried.auth ? 'unauthorized' : 'initial');\n if (authorization) headers.Authorization = authorization;\n\n const res = await fetch(`${this.base}${path}`, { method, headers, body, credentials: 'omit' });\n\n const isJson = (res.headers.get('content-type') ?? '').includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : null;\n\n if (!res.ok) {\n const err = data as\n | {\n error?: string; code?: string; conflicts?: HoldConflict[]; reason?: string;\n retryAfterSeconds?: number;\n }\n | null;\n // The public API names its machine code in `error` (`conflict`, `event_closed`,\n // …); older/other routes may send `code`. Carry whichever into ApiError.code so\n // the code is populated (it was previously always undefined — nothing reads it\n // yet) and the bridge can pass it through. The specific 409 discriminator still\n // rides in `reason` (`sold_out` | `not_enough_together`) and wins downstream.\n const code = err?.code ?? err?.error;\n\n if (this.access?.configured && (res.status === 401 || res.status === 403 || res.status === 422)) {\n const refreshed = await this.access.handleFailure(res.status, code);\n // Exactly one retry, and only for an expiry the provider just renewed.\n // A refresh returns the same or a narrower scope; it never widens, and\n // a second failure is reported rather than looped.\n if (refreshed && !retried.auth) return this.request<T>(path, init, { ...retried, auth: true });\n }\n if (res.status === 409) {\n const reason = code ? OBJECT_UNAVAILABLE_CODES[code] : undefined;\n const labels = err?.conflicts?.map((c) => c.label) ?? init.labels ?? [];\n if (reason) this.onObjectUnavailable?.({ labels, reason, code });\n }\n\n let retryAfterS: number | undefined;\n if (res.status === 429) {\n retryAfterS = parseRetryAfter(res.headers.get('Retry-After'), err?.retryAfterSeconds)\n ?? DEFAULT_RATE_LIMIT_WAIT_S;\n // One automatic retry, and only for a READ.\n //\n // A rate-limited `chart()`/`objects()` is what turns an on-sale spike\n // into a blank widget, and re-reading is free of consequence — the same\n // GET twice is the same GET. A hold, a best-available, a checkout or an\n // extend is NOT: replaying one can take a second seat, start a second\n // payment, or burn an extend allowance, so a 429 on those is reported to\n // the caller with the server's delay attached and never replayed here.\n if (\n method === 'GET'\n && !retried.rateLimit\n && retryAfterS <= MAX_RATE_LIMIT_WAIT_S\n ) {\n await new Promise((resolve) => setTimeout(resolve, retryAfterS! * 1000));\n return this.request<T>(path, init, { ...retried, rateLimit: true });\n }\n }\n\n throw new ApiError(\n res.status,\n err?.error ?? `request_failed_${res.status}`,\n code,\n err?.conflicts,\n err?.reason,\n retryAfterS,\n );\n }\n return data as T;\n }\n\n chart(key: string): Promise<PubChartResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/chart`);\n }\n\n objects(key: string): Promise<PubObjectsResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/objects`);\n }\n\n hold(key: string, selections: Array<{ label: string; tierId?: string | null; quantity?: number }>, ttlMs?: number, replaceHoldId?: string): Promise<HoldResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/hold`, {\n method: 'POST',\n body: { selections, ...(ttlMs ? { ttlMs } : {}), ...(replaceHoldId ? { replaceHoldId } : {}) },\n labels: selections.map((s) => s.label),\n });\n }\n\n // `zoneId` scopes the pick to one zone and `ttlMs` carries the host's checkout\n // window — both are part of the route contract, and dropping either here made\n // the SDK quietly pick venue-wide and hold for the server default instead.\n bestAvailable(key: string, qty: number, categoryKey?: string, zoneId?: string, ttlMs?: number): Promise<BestAvailableResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/best-available`, {\n method: 'POST',\n body: { qty, ...(categoryKey ? { categoryKey } : {}), ...(zoneId ? { zoneId } : {}), ...(ttlMs ? { ttlMs } : {}) },\n });\n }\n\n resume(key: string, holdId: string): Promise<ResumedHoldResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/hold/resume`, {\n method: 'POST',\n body: { holdId },\n });\n }\n\n release(key: string, labels: string[], holdId: string): Promise<{ ok: true; released?: string[] }> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/release`, {\n method: 'POST',\n body: { labels, holdId },\n });\n }\n\n /** P4 \"need more time?\": push an active hold's expiry out. Throws ApiError 409\n * (reason: expired | extend_limit | not_found | not_active) if it can't. */\n extend(key: string, holdId: string, ttlMs?: number): Promise<{ holdId: string; expiresAt: number; extends: number }> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/extend`, {\n method: 'POST',\n body: { holdId, ...(ttlMs ? { ttlMs } : {}) },\n });\n }\n\n /**\n * Which gateways this event can actually take money through — the question\n * `checkout: 'hosted'` has to answer BEFORE it shows a buyer a Pay button, so\n * the answer is never discovered by failing a payment.\n *\n * Anonymous, and it discloses no account, key, mode or currency for a gateway\n * that did not match.\n */\n paymentOptions(key: string): Promise<PaymentOptionsResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/payment-options`);\n }\n\n /**\n * Turn a live hold into an order and start a payment.\n *\n * The amount is NOT sent: the server recomputes it from the hold's own items,\n * which is the only reason a browser cannot alter what it pays. Nor is the\n * PROVIDER — the event row decides which gateway charges, and a `provider` in\n * the body is checked rather than obeyed (409 `provider_mismatch`). Omitting\n * it is the shape that cannot disagree.\n */\n startCheckout(\n key: string,\n input: { holdId: string; buyerEmail: string; buyerName?: string; returnUrl?: string },\n ): Promise<CheckoutSessionResult> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/checkout`, {\n method: 'POST',\n body: input,\n });\n }\n\n /**\n * Poll an order while its gateway webhook lands. The order id is an\n * unguessable token the buyer already holds, so it acts as the capability —\n * which is also why a buyer returning from a gateway page can be told what\n * happened with nothing but the id in the return URL.\n */\n orderStatus(orderId: string): Promise<OrderStatusResult> {\n return this.request(`/pub/orders/${encodeURIComponent(orderId)}/status`);\n }\n\n /**\n * Mint a one-use subscribe ticket for the next socket attempt (protocol doc\n * §3). The bearer travels here, over ordinary HTTPS where CORS and Origin\n * already apply; the socket then carries only the short-lived ticket, in its\n * subprotocol list. TTL ≤ 30s, single redemption — mint one per attempt.\n */\n subscribeTicket(key: string): Promise<{ ticket?: string; protocols?: string[] } | null> {\n return this.request(`/pub/events/${encodeURIComponent(key)}/subscribe-tickets`, {\n method: 'POST',\n body: {},\n });\n }\n\n /**\n * The subscribe URL. Never carries a credential — not the bearer, not the\n * ticket. Query parameters are diagnostics only.\n */\n subscribeUrl(key: string): string {\n const wsBase = this.base.replace(/^http/, 'ws');\n const params = new URLSearchParams({ surface: 'picker', viewerId: this.viewerId });\n return `${wsBase}/pub/events/${encodeURIComponent(key)}/subscribe?${params}`;\n }\n\n /**\n * What PickerController opens its own socket with.\n *\n * Empty for an access-scoped client: a private scope authenticates with a\n * subprotocol ticket, which a URL-only constructor cannot carry, so the SDK's\n * BuyerRealtimeClient owns that socket instead and the controller skips its\n * own (an empty URL is its documented \"no live feed\" contract). A tokenless\n * public client returns exactly the URL it always has, so nothing about the\n * public picker's realtime path changes.\n */\n socketUrl(key: string): string {\n return this.accessScoped ? '' : this.subscribeUrl(key);\n }\n\n /**\n * The subprotocol list a PLAIN `new WebSocket(url, protocols)` must offer for\n * this transport — `PickerTransport.socketProtocols`, which PickerController\n * calls optionally and which nothing implemented until now.\n *\n * Offering `seatlayer.v1` is the whole point: without it the DO answers an\n * anonymous socket with the LEGACY verbose frame — every unit of a 10k-seat\n * event, on connect and on every reconnect — instead of the compact\n * `{default, exceptions}` form. Empty for an access-scoped client, which\n * authenticates with a one-use ticket a URL-only constructor cannot carry and\n * whose socket BuyerRealtimeClient owns instead (see `socketUrl`).\n *\n * `createRealtime` below is the preferred path and supersedes this for any\n * host that can use it; this stays the correct answer for a host that builds\n * the socket itself from the transport contract.\n */\n socketProtocols(key: string): string[] {\n void key; // same answer for every event; the parameter is the interface's\n return this.accessScoped ? [] : [SEATLAYER_V1];\n }\n\n /**\n * Hand PickerController the v1 realtime client instead of letting it open a\n * bare socket — `PickerTransport.createRealtime`.\n *\n * This is what puts an ANONYMOUS buyer (the on-sale case) on the same wire as\n * a private-channel one: compact snapshots, `sv.<n>` resume so a reconnect\n * inside the ring costs a delta rather than a full re-snapshot, ping/pong\n * liveness, and one jittered backoff implementation shared by both. The\n * anonymous case simply passes no `mintTicket` — the `/pub/events/:key/\n * subscribe` upgrade requires no ticket, and the DO resolves a ticketless\n * socket to the public scope.\n *\n * Null when access-scoped: that socket is owned by the widget's own\n * BuyerRealtimeClient (with the ticket exchange), and `socketUrl()` already\n * returns '' so the controller opens nothing.\n */\n createRealtime(key: string, sink: RealtimeSink): BuyerRealtimeClient | null {\n if (this.accessScoped) return null;\n return new BuyerRealtimeClient({ url: this.subscribeUrl(key), sink });\n }\n}\n","/**\n * Buyer access context — the browser half of the Sales Channels contract\n * (`docs/sales-channels-integration-guide-2026-08-01.md` §6, §9, §10).\n *\n * A promoter's own backend mints a short-lived, opaque buyer-access session\n * (`bse_…`) that grants exactly one event's private channel scope. That bearer\n * reaches the browser, and only the browser — this module is where it lives,\n * and the rules it enforces are the ones the guide states outright:\n *\n * - the token is held in memory on a private field. It is never written to\n * localStorage/sessionStorage/cookies, never appended to a URL, and never\n * placed in a log, an Error message, telemetry, or JSON. `toJSON()` and\n * `toString()` are overridden so an accidental `JSON.stringify(context)` or\n * template interpolation cannot leak it;\n * - refresh goes through the host's `buyerAccessTokenProvider`, which is\n * called with a `reason` so the host can distinguish a first acquisition\n * from an expiry from a 401;\n * - **a configured context never falls back to anonymous Public sale.** When\n * no bearer can be obtained the operation fails with a typed access error\n * instead of going out unauthenticated. Sending the request without the\n * bearer would silently widen the buyer's scope to Public — the exact\n * failure the feature exists to prevent (guide §7).\n *\n * Deliberately free of any `@seatlayer/core` import: it deals in tokens, HTTP\n * status codes and callbacks only, so it vendors into the app's widget copy\n * with no engine coupling.\n */\n\n/** Why the SDK is asking the host for a token. Passed to the provider. */\nexport type BuyerAccessRefreshReason =\n /** First acquisition, before the chart is fetched. */\n | 'initial'\n /** Proactive: the held token is inside the renewal skew. */\n | 'expiring'\n /** Reactive: the held token's own expiry has passed. */\n | 'expired'\n /** Reactive: the server answered 401 `buyer_access_expired`. */\n | 'unauthorized'\n /** A realtime reconnect needs a live bearer to mint a subscribe ticket. */\n | 'reconnect'\n /** The host called `refreshAccess()`. */\n | 'manual';\n\n/** What a `buyerAccessTokenProvider` resolves to — the response body of the\n * host's own mint endpoint, unchanged. */\nexport interface BuyerAccessToken {\n /** The opaque `bse_…` buyer-access session bearer. */\n token: string;\n /** Epoch ms. Optional — absent means \"trust the server\", and the SDK then\n * refreshes only reactively on a 401. */\n expiresAt?: number;\n}\n\nexport type BuyerAccessTokenProvider = (\n context: { reason: BuyerAccessRefreshReason },\n) => BuyerAccessToken | Promise<BuyerAccessToken>;\n\n/**\n * Why private inventory is not available. Never collapsed into a generic\n * network failure (guide §10) and never carrying channel identity — the buyer\n * is told the state, not which allocation they missed.\n */\nexport type BuyerAccessUnavailableReason =\n /** The session was revoked (HTTP 401 after refresh, or WS close 4401). */\n | 'revoked'\n /** The channel is paused — a legitimate, temporary organizer state. */\n | 'paused'\n /** 401 `buyer_access_invalid`: do not retry this bearer. */\n | 'invalid'\n /** 403 `buyer_access_origin_mismatch`. */\n | 'origin_mismatch'\n /** 403 `buyer_access_event_mismatch`. */\n | 'event_mismatch'\n /** 403 `buyer_access_mode_mismatch` (test bearer on a live event or v.v.). */\n | 'mode_mismatch'\n /** 403 `channel_access_denied`. */\n | 'channel_denied'\n /** 422 `invalid_channel_scope` — an integration configuration error. */\n | 'invalid_scope'\n /** The host's token provider threw or returned nothing usable. */\n | 'provider_failed'\n /** A one-shot `buyerAccessToken` lapsed and no provider was configured. */\n | 'no_token';\n\n/** The access session expired. Carries whether the refresh recovered it. */\nexport interface BuyerAccessExpiredEvent {\n reason: BuyerAccessRefreshReason;\n /** The server's machine code when the expiry was observed over HTTP. */\n code?: string;\n /** True when the provider handed back a fresh token and work continues. */\n refreshed: boolean;\n}\n\n/** Private inventory is unavailable, and refreshing will not fix it. */\nexport interface BuyerAccessUnavailableEvent {\n reason: BuyerAccessUnavailableReason;\n /** The server's machine code, when there was one. */\n code?: string;\n /** The HTTP status, when the state came from an HTTP response. */\n status?: number;\n /** True only for states a later retry could clear (`paused`). */\n retryable: boolean;\n}\n\n/** One or more selected-but-unheld units stopped being selectable. */\nexport interface SelectedObjectUnavailableEvent {\n /** Inventory labels (never channel identity). */\n labels: string[];\n reason:\n /** An allocation change moved it out of this buyer's scope (guide §9). */\n | 'ineligible'\n /** Someone else held or booked it. */\n | 'taken'\n /** 409 `allocation_exhausted` — this private allocation has none left. */\n | 'exhausted';\n code?: string;\n}\n\nexport interface BuyerAccessContextOptions {\n provider?: BuyerAccessTokenProvider;\n /** One-shot escape hatch for hosts that already own the token lifecycle. */\n token?: string | BuyerAccessToken;\n /** Renew this long before the stated expiry. Default 30s. */\n skewMs?: number;\n onExpired?: (event: BuyerAccessExpiredEvent) => void;\n onUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n}\n\n/**\n * Thrown instead of letting a scoped request go out unauthenticated. Carries no\n * bearer and no channel identity, so it is safe to log or hand to an error\n * reporter verbatim.\n */\nexport class BuyerAccessUnavailableError extends Error {\n readonly reason: BuyerAccessUnavailableReason;\n readonly code?: string;\n readonly status?: number;\n\n constructor(event: BuyerAccessUnavailableEvent) {\n super(`buyer_access_unavailable:${event.reason}`);\n this.name = 'BuyerAccessUnavailableError';\n this.reason = event.reason;\n this.code = event.code;\n this.status = event.status;\n }\n}\n\n/** Server error codes that mean \"this session lapsed; run the refresh flow\". */\nconst EXPIRED_CODES = new Set(['buyer_access_expired']);\n\n/**\n * Reasons that describe ONE request, not the session behind it. They report to\n * the host but never latch the context terminal and never discard the bearer.\n *\n * `channel_denied` is here on the guide's own reading: §10 answers a 403\n * `channel_access_denied` with \"return buyer to permitted inventory\" — the\n * buyer asked for a seat outside their allocation, which is a mis-click, not a\n * dead session. Latching it meant one wrong seat permanently killed a live\n * buyer's access, including their ability to RELEASE the hold they already\n * legitimately owned. Found against a live worker in the M9 pass.\n */\nconst RECOVERABLE = new Set<BuyerAccessUnavailableReason>([\n 'paused',\n 'provider_failed',\n 'channel_denied',\n]);\n\n/**\n * Guide §10 error table → an unavailable reason. Anything not in the table is\n * not an access failure and must stay an ordinary error, so this returns null.\n */\nexport function classifyAccessFailure(\n status: number,\n code: string | undefined,\n): BuyerAccessUnavailableReason | null {\n switch (code) {\n case 'buyer_access_invalid':\n return 'invalid';\n case 'buyer_access_revoked':\n return 'revoked';\n case 'buyer_access_origin_mismatch':\n return 'origin_mismatch';\n case 'buyer_access_event_mismatch':\n return 'event_mismatch';\n case 'buyer_access_mode_mismatch':\n return 'mode_mismatch';\n case 'channel_access_denied':\n return 'channel_denied';\n case 'channel_paused':\n return 'paused';\n case 'invalid_channel_scope':\n return 'invalid_scope';\n default:\n break;\n }\n // An unnamed 401 on a scoped request is still an access failure; treat it as\n // the non-retryable kind rather than falling through to Public sale.\n if (status === 401) return 'invalid';\n return null;\n}\n\n/** True when this HTTP failure means \"refresh the session and try again\". */\nexport function isAccessExpiry(status: number, code: string | undefined): boolean {\n return status === 401 && !!code && EXPIRED_CODES.has(code);\n}\n\nconst DEFAULT_SKEW_MS = 30_000;\n\nexport class BuyerAccessContext {\n /** Private field: not enumerable, not spreadable, not serializable. */\n #token: string | null = null;\n #expiresAt = 0;\n #provider?: BuyerAccessTokenProvider;\n #skewMs: number;\n #inflight: Promise<string | null> | null = null;\n #terminal: BuyerAccessUnavailableEvent | null = null;\n /** The most recent failure, terminal or not — so one cause reports once. */\n #lastFailure: BuyerAccessUnavailableEvent | null = null;\n #onExpired?: (event: BuyerAccessExpiredEvent) => void;\n #onUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /** Decided once, at construction. See the `configured` getter. */\n #configured = false;\n\n constructor(options: BuyerAccessContextOptions) {\n this.#provider = options.provider;\n this.#skewMs = options.skewMs ?? DEFAULT_SKEW_MS;\n this.#onExpired = options.onExpired;\n this.#onUnavailable = options.onUnavailable;\n if (options.token) {\n const seed = typeof options.token === 'string' ? { token: options.token } : options.token;\n this.#accept(seed);\n }\n this.#configured = !!this.#provider || !!this.#token;\n }\n\n /**\n * True when this picker is access-scoped at all. A false here is the\n * tokenless public picker, which must behave exactly as it always has.\n *\n * Answered from what the HOST asked for, never from live token state. It used\n * to be `!!#provider || !!#token`, which quietly inverted this file's central\n * rule for a one-shot `buyerAccessToken` host: `#fail()` clears `#token`, so\n * the first refusal turned a configured context into an \"unconfigured\" one,\n * `authorization()` then returned null instead of throwing, and the very next\n * call went out with no bearer — the anonymous Public sale fallback this\n * module exists to prevent. A provider host never saw it, because `#provider`\n * held `configured` true. Found against a live worker in the M9 pass.\n */\n get configured(): boolean {\n return this.#configured;\n }\n\n /** Set once a state arrives that refreshing cannot clear. */\n get unavailable(): BuyerAccessUnavailableEvent | null {\n return this.#terminal;\n }\n\n /** True while a usable bearer is held (ignores skew). */\n get hasToken(): boolean {\n return !!this.#token && (this.#expiresAt === 0 || this.#expiresAt > Date.now());\n }\n\n /** Epoch ms the current token expires, or 0 when the host didn't say. */\n get expiresAt(): number {\n return this.#expiresAt;\n }\n\n /**\n * The `Authorization` header value for a scoped operation.\n *\n * Returns null only when this context is not configured at all (the ordinary\n * anonymous public picker). A configured context either returns a bearer or\n * throws `BuyerAccessUnavailableError` — it never returns null, because a\n * null here would send the request as anonymous Public sale.\n */\n async authorization(reason: BuyerAccessRefreshReason = 'initial'): Promise<string | null> {\n if (!this.configured) return null;\n if (this.#terminal) throw new BuyerAccessUnavailableError(this.#terminal);\n\n const now = Date.now();\n const stale = !this.#token || (this.#expiresAt > 0 && this.#expiresAt - this.#skewMs <= now);\n if (stale) {\n const expired = !!this.#token && this.#expiresAt > 0 && this.#expiresAt <= now;\n const why: BuyerAccessRefreshReason = this.#token ? (expired ? 'expired' : 'expiring') : reason;\n const token = await this.#renew(why);\n if (!token) {\n // #renew already classified and reported the failure; reuse that event\n // rather than raising a second one for the same cause.\n throw new BuyerAccessUnavailableError(\n this.#terminal ?? this.#lastFailure ?? this.#fail('provider_failed'),\n );\n }\n return `Bearer ${token}`;\n }\n return `Bearer ${this.#token}`;\n }\n\n /**\n * Handle a 401/403 from a scoped call. Returns true when the caller should\n * retry the same request once with the refreshed bearer.\n */\n async handleFailure(status: number, code: string | undefined): Promise<boolean> {\n if (!this.configured) return false;\n\n if (isAccessExpiry(status, code)) {\n this.#token = null;\n this.#expiresAt = 0;\n const token = await this.#renew('unauthorized', code);\n this.#onExpired?.({ reason: 'unauthorized', code, refreshed: !!token });\n return !!token;\n }\n\n const reason = classifyAccessFailure(status, code);\n if (reason) {\n this.#fail(reason, code, status);\n return false;\n }\n return false;\n }\n\n /** Host-driven re-acquisition (after the buyer signs in again, say). */\n async refresh(reason: BuyerAccessRefreshReason = 'manual'): Promise<boolean> {\n this.#terminal = null;\n this.#lastFailure = null;\n this.#token = null;\n this.#expiresAt = 0;\n return !!(await this.#renew(reason));\n }\n\n /** Drop the bearer. Called on destroy so nothing outlives the widget. */\n clear(): void {\n this.#token = null;\n this.#expiresAt = 0;\n this.#inflight = null;\n }\n\n /** Redaction: the bearer must not survive a stringify or an interpolation. */\n toJSON(): { configured: boolean; hasToken: boolean } {\n return { configured: this.configured, hasToken: this.hasToken };\n }\n\n toString(): string {\n return '[BuyerAccessContext redacted]';\n }\n\n // ---- internals ------------------------------------------------------------\n\n #accept(next: BuyerAccessToken | null | undefined): string | null {\n if (!next || typeof next.token !== 'string' || !next.token) return null;\n this.#token = next.token;\n this.#expiresAt = typeof next.expiresAt === 'number' ? next.expiresAt : 0;\n return this.#token;\n }\n\n /**\n * One provider call at a time. Several operations racing an expiry (chart +\n * objects + a socket ticket) must not mint several sessions — the guide's\n * rotate-on-retry rule would revoke the ones they didn't observe.\n */\n #renew(reason: BuyerAccessRefreshReason, code?: string): Promise<string | null> {\n if (this.#inflight) return this.#inflight;\n const provider = this.#provider;\n if (!provider) {\n // A one-shot token with no provider cannot be renewed. That is a legal\n // host choice, so it is a typed state, not a crash.\n this.#fail('no_token', code);\n return Promise.resolve(null);\n }\n const run = (async (): Promise<string | null> => {\n try {\n const next = await provider({ reason });\n const token = this.#accept(next);\n if (!token) {\n this.#fail('provider_failed', code);\n return null;\n }\n return token;\n } catch {\n // The provider's own error text may contain host detail; it is not\n // rethrown and not logged. The host already saw its own failure.\n this.#fail('provider_failed', code);\n return null;\n } finally {\n this.#inflight = null;\n }\n })();\n this.#inflight = run;\n return run;\n }\n\n #fail(\n reason: BuyerAccessUnavailableReason,\n code?: string,\n status?: number,\n ): BuyerAccessUnavailableEvent {\n const event: BuyerAccessUnavailableEvent = {\n reason,\n code,\n status,\n // Unchanged: `retryable` means \"the SAME request may succeed later\".\n // `provider_failed` is recoverable but not retryable — the host must fix\n // its mint endpoint first — so the two sets are deliberately different.\n retryable: reason === 'paused' || reason === 'channel_denied',\n };\n this.#lastFailure = event;\n // A recoverable reason says nothing about the SESSION, so it must not latch\n // the context terminal and must not throw the bearer away.\n if (!RECOVERABLE.has(reason)) {\n this.#terminal = event;\n this.#token = null;\n this.#expiresAt = 0;\n }\n this.#onUnavailable?.(event);\n return event;\n }\n}\n\n/** Build a context from widget options, or null for the tokenless public path. */\nexport function createBuyerAccessContext(\n options: {\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n buyerAccessToken?: string | BuyerAccessToken;\n },\n hooks: Pick<BuyerAccessContextOptions, 'onExpired' | 'onUnavailable'> = {},\n): BuyerAccessContext | null {\n if (!options.buyerAccessTokenProvider && !options.buyerAccessToken) return null;\n return new BuyerAccessContext({\n provider: options.buyerAccessTokenProvider,\n token: options.buyerAccessToken,\n ...hooks,\n });\n}\n","/** Dependency-free canonical SeatLayer mark for distributed SDK attribution.\n *\n * Keep the geometry in sync with `SeatLayerMark` and\n * `scripts/generate-brand-assets.py`. The fixed dark-surface palette makes the\n * fragment safe inside the self-contained midnight attribution tile.\n */\nexport const SEATLAYER_ATTRIBUTION_MARK_SVG =\n '<svg viewBox=\"0 0 64 56\" width=\"12\" height=\"11\" fill=\"none\" aria-hidden=\"true\" focusable=\"false\" style=\"display:block\">' +\n '<path d=\"M4 13 Q16 6 29 7 L28.5 17 Q17 16.5 7 22 Z\" fill=\"#f4b740\"/>' +\n '<path d=\"M4 13 Q16 6 29 7 L28.5 17 Q17 16.5 7 22 Z\" fill=\"#f4b740\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '<path d=\"M8 28 Q18 22 28.6 23 L28.2 32 Q18 28.5 10 36 Z\" fill=\"#fcf7ee\"/>' +\n '<path d=\"M8 28 Q18 22 28.6 23 L28.2 32 Q18 28.5 10 36 Z\" fill=\"#fcf7ee\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '<path d=\"M11 41 Q19 35 28.2 36 L27.8 45 Q19.5 42 13.5 49 Z\" fill=\"#fcf7ee\"/>' +\n '<path d=\"M11 41 Q19 35 28.2 36 L27.8 45 Q19.5 42 13.5 49 Z\" fill=\"#fcf7ee\" transform=\"translate(64 0) scale(-1 1)\"/>' +\n '</svg>';\n","/**\n * A secure, framework-neutral host for the SeatLayer chart Designer.\n *\n * The Designer remains an iframe so a platform never gives its SeatLayer secret\n * key to a browser. This class owns the iframe lifecycle and accepts messages\n * only from that iframe's exact origin.\n */\nexport type EmbeddedDesignerEventType =\n | 'seatlayer.designer.ready'\n | 'seatlayer.designer.saved'\n | 'seatlayer.designer.published'\n | 'seatlayer.designer.close'\n | 'seatlayer.designer.error';\n\nexport interface EmbeddedDesignerMessage {\n type: EmbeddedDesignerEventType;\n chartId?: string;\n workspaceId?: string;\n expiresAt?: number;\n code?: string;\n message?: string;\n meta?: unknown;\n /**\n * Set by the Designer on an error it raised while the editor was already\n * running (a failed autosave, thumbnail upload, reload…). Such an error is\n * about ONE operation, not about the session, so the SDK reports it to the\n * host and leaves the live editor mounted instead of replacing it with the\n * dead-end card. Absent on older Designer builds — see\n * {@link EmbeddedDesigner} for the phase-based fallback.\n */\n fatal?: boolean;\n /** The operation that failed, when `fatal` is `false` (e.g. `'save'`). */\n action?: string;\n}\n\nexport interface EmbeddedDesignerOptions {\n /** The short-lived URL returned by your backend's Designer-session call. */\n designerUrl: string;\n /** CSS selector or element where the iframe is mounted. */\n container: string | HTMLElement;\n /** Verify the message belongs to the chart your backend opened. */\n expectedChartId?: string;\n /** Verify the message belongs to the workspace your backend opened. */\n expectedWorkspaceId?: string;\n title?: string;\n className?: string;\n style?: Partial<CSSStyleDeclaration>;\n allow?: string;\n referrerPolicy?: ReferrerPolicy;\n /**\n * Show the built-in branded loading skeleton and error/expiry card inside the\n * container while the Designer boots. Defaults to `true`. Set `false` when the\n * host renders its own loading and error chrome.\n */\n showLoadingState?: boolean;\n /**\n * If the Designer never posts `ready` within this many milliseconds, the host\n * transitions to the error card with a timeout message. Defaults to `20000`.\n * Only used when `showLoadingState` is enabled.\n */\n loadingTimeoutMs?: number;\n /**\n * How to size the iframe's height. The Designer is a full application (its\n * shell is `position:fixed; height:100dvh`), not flowing content, so it should\n * fill its box rather than be measured.\n *\n * - `'fill'` (default): container-aware. On mount the SDK probes whether the\n * host gave the container a DEFINITE (bounded) height:\n * - **Bounded container** (a fixed-height block, `height`/`max-height`,\n * `flex:1; min-h:0`, a resolved `%`, etc.) → the iframe fills 100% of\n * that block and tracks its size live via a `ResizeObserver`.\n * - **Content-sized container** (the block collapses to whatever the iframe\n * measures — typical full-page usage) → the iframe grows so its bottom\n * edge reaches the bottom of the viewport (`window.innerHeight -\n * iframe.top`), recomputed (rAF-throttled) on `resize` /\n * `orientationchange` / `scroll`.\n * Either way the result is clamped to `minHeight`. The verdict is cached but\n * re-probed on `resize`/`orientationchange` so a responsive host layout can\n * flip between the two. The legacy `seatlayer.designer.resize` message is\n * ignored in `'fill'` mode: it is circular, because the fixed-position shell\n * just echoes the iframe height.\n * - a number: a fixed pixel height. In this mode the legacy resize message is\n * still honoured (unless `autoResize` is `false`) so older hosts keep growing.\n *\n * All SDK-managed heights are written with `!important` priority so a host\n * theme's `iframe { height: … !important }` cannot override them.\n */\n height?: 'fill' | number;\n /** Minimum height (px) that `'fill'` mode clamps to. Defaults to `480`. */\n minHeight?: number;\n /**\n * Auto-grow the iframe to the height the Designer reports over the resize\n * protocol (`seatlayer.designer.resize`). Only applies when `height` is a fixed\n * number; ignored in `'fill'` mode. Defaults to `true`. Set `false` when the\n * host sizes a fixed-height iframe itself.\n */\n autoResize?: boolean;\n /**\n * Called when the user presses \"Try again\" on the error card. Use it to mint a\n * fresh Designer session and call `setDesignerUrl()` with the new URL, which\n * recreates the iframe and returns to the loading state. When omitted, \"Try\n * again\" reloads the current `designerUrl` in place.\n *\n * When supplied, it also powers automatic session renewal — see\n * {@link EmbeddedDesignerOptions.autoRenewSession}.\n */\n onRequestRelaunch?: () => void;\n /**\n * Keep long editing sessions alive without the user ever hitting the expiry\n * wall. Designer sessions are short-lived security tokens; when the host wires\n * `onRequestRelaunch` the SDK, with this enabled, will:\n *\n * - **Renew proactively.** From each `ready` message's `expiresAt` it schedules\n * a silent relaunch shortly before the session lapses (~3 min ahead; for a\n * TTL under 15 min it renews after 80% of the remaining life, and never\n * sooner than 30s after `ready`). The host mints a fresh session and swaps\n * `designerUrl`, so the editor keeps working with no error card.\n * - **Recover on expiry.** If an expiry error still slips through (a slept\n * laptop woke past the renewal window, say) it makes ONE automatic relaunch\n * attempt before showing the \"Try again\" card, and only falls back to the\n * card if that relaunch also fails.\n *\n * Defaults to `true` whenever `onRequestRelaunch` is provided; a no-op without\n * it. Set `false` to keep the fully manual \"Try again\" behavior.\n */\n autoRenewSession?: boolean;\n onReady?: (message: EmbeddedDesignerMessage) => void;\n onSaved?: (message: EmbeddedDesignerMessage) => void;\n onPublished?: (message: EmbeddedDesignerMessage) => void;\n onClose?: (message: EmbeddedDesignerMessage) => void;\n onError?: (message: EmbeddedDesignerMessage) => void;\n}\n\nconst TYPES = new Set<EmbeddedDesignerEventType>([\n 'seatlayer.designer.ready',\n 'seatlayer.designer.saved',\n 'seatlayer.designer.published',\n 'seatlayer.designer.close',\n 'seatlayer.designer.error',\n]);\n\nconst DEFAULT_LOADING_TIMEOUT_MS = 20000;\nconst DEFAULT_MIN_FILL_HEIGHT = 480;\n/**\n * Proactive session-renewal timing (see {@link EmbeddedDesigner.scheduleRenewal}).\n * We aim to relaunch a comfortable lead ahead of `expiresAt`; short-lived sessions\n * instead renew after a fraction of their life so the lead never overshoots the TTL.\n */\nconst RENEW_LEAD_MS = 3 * 60 * 1000; // standard lead: renew ~3 min before expiry\nconst RENEW_SHORT_TTL_MS = 15 * 60 * 1000; // below this TTL, use the fraction clamp\nconst RENEW_SHORT_TTL_FRACTION = 0.8; // short TTL: renew after 80% of remaining life\nconst RENEW_MIN_DELAY_MS = 30 * 1000; // never renew sooner than 30s after `ready`\n/**\n * Container-fill detection tunables. The probe drives the iframe to two extreme\n * heights within one synchronous task (no paint between reads, so no flash) and\n * watches whether the container tracks it.\n */\nconst FILL_PROBE_HEIGHT_PX = 100000; // \"huge\" iframe used to see if the box grows with it\nconst FILL_PROBE_TRACK_EPSILON_PX = 4; // container grew with the iframe ⇒ content-sized\nconst FILL_MIN_DEFINITE_HEIGHT_PX = 50; // a bounded box must keep at least this much height\n\n/** Internal reason the error card is being shown, used to pick human copy. */\ntype ErrorCause = 'expired' | 'mismatch' | 'timeout' | 'load';\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container !== 'string') return container;\n const element = document.querySelector<HTMLElement>(container);\n if (!element) throw new Error(`EmbeddedDesigner container not found: ${container}`);\n return element;\n}\n\n/** Map an error message's `code` onto one of the human-copy causes. */\nfunction causeFromCode(code: string | undefined): ErrorCause {\n const value = (code ?? '').toLowerCase();\n if (value.includes('expire') || value.includes('revoke') || value === '401') return 'expired';\n if (value.includes('mismatch')) return 'mismatch';\n if (value.includes('timeout')) return 'timeout';\n return 'load';\n}\n\nconst ERROR_COPY: Record<ErrorCause, { title: string; body: string }> = {\n expired: {\n title: 'This design session expired',\n body: 'For your security, editing sessions are short-lived. Start a fresh one to keep designing.',\n },\n mismatch: {\n title: \"This editor doesn't match this chart\",\n body: 'The session that loaded belongs to a different chart or workspace. Reopen the designer to continue.',\n },\n timeout: {\n title: 'The designer is taking too long',\n body: 'It did not finish loading in time. This is usually a slow connection — try again.',\n },\n load: {\n title: \"We couldn't load the designer\",\n body: 'Something went wrong while opening the editor. Please try again.',\n },\n};\n\n/** Mount, replace, and destroy a scoped Designer iframe safely. */\nexport class EmbeddedDesigner {\n private options: EmbeddedDesignerOptions;\n private frame: HTMLIFrameElement | null = null;\n private designerOrigin = '';\n private overlay: HTMLDivElement | null = null;\n private timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n /** Proactive session-renewal timer; armed from each `ready`, cleared on re-mount. */\n private renewTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * One automatic recovery relaunch is allowed per expiry. Reset ONLY when a fresh\n * `ready` arrives — deliberately not on re-mount — so a session that keeps failing\n * to load can't loop the host through endless silent relaunches.\n */\n private autoRecoverUsed = false;\n private phase: 'loading' | 'ready' | 'error' = 'loading';\n private restoreContainerPosition: string | null = null;\n // Host-side fullscreen pin: saved state we restore on `off`/Escape/destroy.\n private pinned = false;\n private frameStyleBeforeFs: string | null = null;\n private docOverflowBeforeFs: string | null = null;\n private bodyOverflowBeforeFs: string | null = null;\n private fsKeyHandler: ((event: KeyboardEvent) => void) | null = null;\n /** Latest height (px string) the Designer reported; re-applied after unpin. */\n private lastAutoHeight = '';\n // Fill sizing: pending rAF handles + whether window listeners are attached.\n private fillRaf: number | null = null;\n private reprobeRaf: number | null = null;\n private fillListening = false;\n /** Resolved container element (fill measurement + ResizeObserver target). */\n private containerEl: HTMLElement | null = null;\n /** Cached fill verdict: 'container' = bounded block, 'viewport' = full page. */\n private fillMode: 'viewport' | 'container' | null = null;\n /** Live block-size tracking in container-fill mode; disconnected on destroy. */\n private resizeObs: ResizeObserver | null = null;\n\n constructor(options: EmbeddedDesignerOptions) {\n this.options = options;\n }\n\n mount(): HTMLIFrameElement {\n this.destroy();\n const url = new URL(this.options.designerUrl, window.location.href);\n if (url.protocol !== 'https:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {\n throw new Error('EmbeddedDesigner requires an HTTPS designerUrl outside local development.');\n }\n this.designerOrigin = url.origin;\n\n const frame = document.createElement('iframe');\n frame.title = this.options.title ?? 'Venue chart Designer';\n frame.allow = this.options.allow ?? 'fullscreen; clipboard-write';\n frame.referrerPolicy = this.options.referrerPolicy ?? 'origin';\n frame.src = url.toString();\n // Width/height are written with `!important` priority so a host theme's\n // `iframe { height: … !important }` cannot beat the SDK's inline sizing.\n frame.style.setProperty('width', '100%', 'important');\n // `'fill'` (default) is (re)computed once the frame is in the DOM (see\n // startFill); a numeric height is a fixed pixel box.\n frame.style.setProperty(\n 'height',\n typeof this.options.height === 'number' ? `${this.options.height}px` : '100%',\n 'important',\n );\n frame.style.border = '0';\n Object.assign(frame.style, this.options.style);\n if (this.options.className) frame.className = this.options.className;\n\n const container = resolveContainer(this.options.container);\n this.containerEl = container;\n window.addEventListener('message', this.handleMessage);\n container.append(frame);\n this.frame = frame;\n\n // Fill mode owns the height from the viewport now the frame is measurable.\n if (this.fillEnabled()) this.startFill();\n\n this.phase = 'loading';\n if (this.loadingStateEnabled()) {\n this.ensureContainerPositioned(container);\n this.renderOverlay(container, 'loading');\n const timeout = this.options.loadingTimeoutMs ?? DEFAULT_LOADING_TIMEOUT_MS;\n if (timeout > 0 && Number.isFinite(timeout)) {\n this.timeoutTimer = setTimeout(() => {\n if (this.phase === 'loading') this.showError('timeout');\n }, timeout);\n }\n }\n return frame;\n }\n\n /** Replace the iframe instead of assigning a new fragment to an existing one. */\n setDesignerUrl(designerUrl: string): HTMLIFrameElement {\n this.options = { ...this.options, designerUrl };\n // mount() tears everything down and re-enters the loading state.\n return this.mount();\n }\n\n getIframe(): HTMLIFrameElement | null {\n return this.frame;\n }\n\n destroy(): void {\n window.removeEventListener('message', this.handleMessage);\n this.stopFill();\n this.unpinFullscreen();\n this.clearTimeoutTimer();\n this.clearRenewTimer();\n this.removeOverlay();\n this.restoreContainerStyle();\n this.frame?.remove();\n this.frame = null;\n this.containerEl = null;\n this.fillMode = null;\n this.designerOrigin = '';\n this.phase = 'loading';\n this.lastAutoHeight = '';\n }\n\n private loadingStateEnabled(): boolean {\n return this.options.showLoadingState !== false;\n }\n\n private autoResizeEnabled(): boolean {\n return this.options.autoResize !== false;\n }\n\n /** Fill mode is the default; a numeric `height` opts into a fixed pixel box. */\n private fillEnabled(): boolean {\n return typeof this.options.height !== 'number';\n }\n\n /** Write an SDK-managed height with `!important` so a host theme can't win. */\n private setFrameHeight(value: string): void {\n this.frame?.style.setProperty('height', value, 'important');\n }\n\n /**\n * Decide whether the host gave the container a DEFINITE (bounded) height — a\n * fixed block the embed should fill 100% of — versus a content-sized container\n * that collapses to whatever the iframe measures (full-page usage).\n *\n * We drive the iframe to two extreme heights within a single synchronous task\n * and watch whether the container follows: a bounded box barely moves, a\n * content-sized one grows with the iframe. Because we restore the height before\n * yielding, the browser only lays out — it never paints the extremes, so there\n * is no visible flash. Works for px, resolved `%`, and flex (`flex:1;min-h:0`)\n * heights, and leaves a mere `min-height` floor classified as content-sized so\n * full-page hosts keep the old viewport-fill behavior.\n */\n private detectFillMode(): 'viewport' | 'container' {\n const container = this.containerEl;\n const frame = this.frame;\n if (this.pinned || !container || !frame) return this.fillMode ?? 'viewport';\n const measure = (): number => container.getBoundingClientRect().height;\n const savedValue = frame.style.getPropertyValue('height');\n const savedPriority = frame.style.getPropertyPriority('height');\n\n frame.style.setProperty('height', '0px', 'important');\n const collapsed = measure();\n frame.style.setProperty('height', `${FILL_PROBE_HEIGHT_PX}px`, 'important');\n const expanded = measure();\n\n if (savedValue) frame.style.setProperty('height', savedValue, savedPriority);\n else frame.style.removeProperty('height');\n\n const tracksIframe = expanded - collapsed > FILL_PROBE_TRACK_EPSILON_PX;\n const bounded = !tracksIframe && collapsed >= FILL_MIN_DEFINITE_HEIGHT_PX;\n return bounded ? 'container' : 'viewport';\n }\n\n /**\n * Size the iframe for the current fill verdict, clamped to `minHeight`. In\n * container mode it fills 100% of the bounded block; in viewport mode its\n * bottom edge meets the bottom of the viewport (`window.innerHeight - top`).\n * No-op while pinned fullscreen (the pin fills the viewport itself).\n */\n private applyFill(): void {\n if (!this.frame || this.pinned) return;\n const min = this.options.minHeight ?? DEFAULT_MIN_FILL_HEIGHT;\n if (this.fillMode === 'container' && this.containerEl) {\n const target = Math.max(min, Math.round(this.containerEl.getBoundingClientRect().height));\n this.setFrameHeight(`${target}px`);\n return;\n }\n const top = this.frame.getBoundingClientRect().top;\n const target = Math.max(min, Math.round(window.innerHeight - top));\n this.setFrameHeight(`${target}px`);\n }\n\n /** rAF-throttled fill recompute, so a burst of scroll/RO ticks coalesces. */\n private scheduleFill = (): void => {\n if (this.fillRaf !== null) return;\n this.fillRaf = requestAnimationFrame(() => {\n this.fillRaf = null;\n this.applyFill();\n });\n };\n\n /**\n * rAF-throttled re-probe: a host layout change (responsive breakpoint, a block\n * gaining/losing a definite height) can flip the verdict, so `resize` /\n * `orientationchange` re-detect and swap the container observer accordingly.\n */\n private scheduleReprobe = (): void => {\n if (this.reprobeRaf !== null) return;\n this.reprobeRaf = requestAnimationFrame(() => {\n this.reprobeRaf = null;\n if (this.pinned) return;\n this.fillMode = this.detectFillMode();\n this.syncContainerObserver();\n this.applyFill();\n });\n };\n\n /** Attach/detach the container ResizeObserver to match the current verdict. */\n private syncContainerObserver(): void {\n const want =\n this.fillMode === 'container' && !!this.containerEl && typeof ResizeObserver !== 'undefined';\n if (want && !this.resizeObs) {\n this.resizeObs = new ResizeObserver(() => this.scheduleFill());\n this.resizeObs.observe(this.containerEl!);\n } else if (!want && this.resizeObs) {\n this.resizeObs.disconnect();\n this.resizeObs = null;\n }\n }\n\n private startFill(): void {\n this.fillMode = this.detectFillMode();\n this.syncContainerObserver();\n this.applyFill();\n if (this.fillListening) return;\n this.fillListening = true;\n // Layout-changing events re-probe (the verdict can flip); scroll only shifts\n // the viewport-fill top offset, so it just re-applies.\n window.addEventListener('resize', this.scheduleReprobe);\n window.addEventListener('orientationchange', this.scheduleReprobe);\n window.addEventListener('scroll', this.scheduleFill, { passive: true });\n }\n\n private stopFill(): void {\n if (this.fillRaf !== null) {\n cancelAnimationFrame(this.fillRaf);\n this.fillRaf = null;\n }\n if (this.reprobeRaf !== null) {\n cancelAnimationFrame(this.reprobeRaf);\n this.reprobeRaf = null;\n }\n if (this.resizeObs) {\n this.resizeObs.disconnect();\n this.resizeObs = null;\n }\n if (!this.fillListening) return;\n this.fillListening = false;\n window.removeEventListener('resize', this.scheduleReprobe);\n window.removeEventListener('orientationchange', this.scheduleReprobe);\n window.removeEventListener('scroll', this.scheduleFill);\n }\n\n /**\n * Pin the iframe over the host page as a viewport-filling overlay. We save the\n * iframe's inline style and the document scroll state so `unpinFullscreen`\n * restores everything exactly. Escape (host-side) also exits.\n */\n private pinFullscreen(): void {\n if (this.pinned || !this.frame) return;\n this.pinned = true;\n this.frameStyleBeforeFs = this.frame.getAttribute('style');\n // Every pin property is `!important` so a host theme's `iframe { … }` rules\n // (height/width/inset) can't unpin us. `inset` is written as its four longhands\n // for reliability across engines. Restored wholesale via the saved style attr.\n const pin: Record<string, string> = {\n position: 'fixed',\n top: '0',\n right: '0',\n bottom: '0',\n left: '0',\n width: '100vw',\n height: '100vh',\n margin: '0',\n border: '0',\n 'z-index': '2147483000',\n background: '#101625',\n };\n for (const [property, value] of Object.entries(pin)) {\n this.frame.style.setProperty(property, value, 'important');\n }\n\n const docEl = document.documentElement;\n this.docOverflowBeforeFs = docEl.style.overflow;\n docEl.style.overflow = 'hidden';\n if (document.body) {\n this.bodyOverflowBeforeFs = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n this.fsKeyHandler = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') this.unpinFullscreen();\n };\n window.addEventListener('keydown', this.fsKeyHandler);\n }\n\n /** Undo `pinFullscreen`: restore the iframe style + scroll lock. Idempotent. */\n private unpinFullscreen(): void {\n if (!this.pinned) return;\n this.pinned = false;\n if (this.frame) {\n if (this.frameStyleBeforeFs === null) this.frame.removeAttribute('style');\n else this.frame.setAttribute('style', this.frameStyleBeforeFs);\n // Restore the right height for the mode: recompute the fill, or re-apply\n // the last height the Designer reported (numeric mode). Both use\n // `!important` so a host theme can't win after we unpin.\n if (this.fillEnabled()) this.applyFill();\n else if (this.autoResizeEnabled() && this.lastAutoHeight) this.setFrameHeight(this.lastAutoHeight);\n }\n this.frameStyleBeforeFs = null;\n\n if (this.docOverflowBeforeFs !== null) {\n document.documentElement.style.overflow = this.docOverflowBeforeFs;\n this.docOverflowBeforeFs = null;\n }\n if (this.bodyOverflowBeforeFs !== null && document.body) {\n document.body.style.overflow = this.bodyOverflowBeforeFs;\n this.bodyOverflowBeforeFs = null;\n }\n if (this.fsKeyHandler) {\n window.removeEventListener('keydown', this.fsKeyHandler);\n this.fsKeyHandler = null;\n }\n }\n\n private clearTimeoutTimer(): void {\n if (this.timeoutTimer !== null) {\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = null;\n }\n }\n\n /**\n * Auto-renewal (proactive + one expiry recovery) is on when the host wired a\n * relaunch hook and did not opt out. Without the hook there is nothing to call,\n * so it is a no-op.\n */\n private autoRenewEnabled(): boolean {\n return !!this.options.onRequestRelaunch && this.options.autoRenewSession !== false;\n }\n\n private clearRenewTimer(): void {\n if (this.renewTimer !== null) {\n clearTimeout(this.renewTimer);\n this.renewTimer = null;\n }\n }\n\n /**\n * Arm the proactive renewal timer from a `ready` message's `expiresAt` (epoch\n * ms). We relaunch a comfortable lead before expiry so the host can mint a fresh\n * session and swap `designerUrl` without the user ever seeing the expiry card:\n *\n * - normal TTL (≥ 15 min): renew {@link RENEW_LEAD_MS} (~3 min) before expiry;\n * - short TTL (< 15 min): renew after {@link RENEW_SHORT_TTL_FRACTION} (80%) of\n * the remaining life, so the lead can't overshoot the whole session;\n * - either way, never sooner than {@link RENEW_MIN_DELAY_MS} (30s) after `ready`\n * so a burst of `ready` messages can't spin the host.\n *\n * Re-armed on every `ready`; cleared on destroy / setDesignerUrl (via re-mount).\n * A no-op when auto-renewal is off or `expiresAt` is missing/already past — the\n * expiry-error path recovers a session that has already lapsed.\n */\n private scheduleRenewal(expiresAt: number | undefined): void {\n this.clearRenewTimer();\n if (!this.autoRenewEnabled()) return;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return;\n const remaining = expiresAt - Date.now();\n if (remaining <= 0) return;\n const lead =\n remaining < RENEW_SHORT_TTL_MS\n ? remaining * RENEW_SHORT_TTL_FRACTION\n : remaining - RENEW_LEAD_MS;\n const delay = Math.max(RENEW_MIN_DELAY_MS, lead);\n this.renewTimer = setTimeout(() => {\n this.renewTimer = null;\n // Silent renewal: the host mints a fresh session and swaps designerUrl,\n // which re-mounts the iframe and re-arms us from the next `ready`.\n if (this.autoRenewEnabled()) this.options.onRequestRelaunch!();\n }, delay);\n }\n\n private ensureContainerPositioned(container: HTMLElement): void {\n // The overlay is absolutely positioned; the container must establish a\n // positioning context. Only touch a `static` container, and remember to\n // restore it on destroy.\n const position = getComputedStyle(container).position;\n if (position === 'static') {\n this.restoreContainerPosition = container.style.position;\n container.style.position = 'relative';\n }\n }\n\n private restoreContainerStyle(): void {\n if (this.restoreContainerPosition === null) return;\n try {\n resolveContainer(this.options.container).style.position = this.restoreContainerPosition;\n } catch {\n /* container already gone — nothing to restore */\n }\n this.restoreContainerPosition = null;\n }\n\n private removeOverlay(): void {\n this.overlay?.remove();\n this.overlay = null;\n }\n\n private showError(cause: ErrorCause): void {\n this.phase = 'error';\n this.clearTimeoutTimer();\n if (!this.loadingStateEnabled()) return;\n let container: HTMLElement;\n try {\n container = resolveContainer(this.options.container);\n } catch {\n return;\n }\n this.renderOverlay(container, 'error', cause);\n }\n\n private handleTryAgain(): void {\n if (this.options.onRequestRelaunch) {\n // Host mints a fresh session and calls setDesignerUrl(), which re-mounts\n // the iframe and returns to the loading state.\n this.options.onRequestRelaunch();\n return;\n }\n // No relaunch hook: reload the same session URL in place.\n this.mount();\n }\n\n /**\n * Build (or rebuild) the overlay for the given phase. A single overlay element\n * is reused so we never stack stale skeletons or cards.\n */\n private renderOverlay(container: HTMLElement, phase: 'loading' | 'error', cause?: ErrorCause): void {\n this.removeOverlay();\n const overlay = document.createElement('div');\n overlay.setAttribute('data-seatlayer-designer-overlay', phase);\n overlay.setAttribute('role', phase === 'error' ? 'alert' : 'status');\n overlay.setAttribute('aria-live', 'polite');\n Object.assign(overlay.style, {\n position: 'absolute',\n inset: '0',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#101625',\n color: '#e6ebf5',\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif',\n zIndex: '2',\n overflow: 'hidden',\n } satisfies Partial<CSSStyleDeclaration>);\n\n if (phase === 'loading') this.buildSkeleton(overlay);\n else this.buildErrorCard(overlay, cause ?? 'load');\n\n container.append(overlay);\n this.overlay = overlay;\n }\n\n private buildSkeleton(overlay: HTMLDivElement): void {\n // Scoped keyframes; the shimmer only runs when the user allows motion.\n // `@sl-css` opts it into build-time minification (cdn/minifyCssLiterals.ts).\n const style = document.createElement('style');\n style.textContent = /* @sl-css */ `\n@media (prefers-reduced-motion: no-preference) {\n @keyframes seatlayer-designer-shimmer {\n 0% { background-position: -320px 0; }\n 100% { background-position: 320px 0; }\n }\n [data-seatlayer-designer-overlay=\"loading\"] .sl-shimmer {\n animation: seatlayer-designer-shimmer 1.25s ease-in-out infinite;\n background-size: 640px 100%;\n }\n}`;\n overlay.append(style);\n\n const shimmer =\n 'linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.10) 37%, rgba(255,255,255,0.04) 63%)';\n\n const scaffold = document.createElement('div');\n Object.assign(scaffold.style, {\n position: 'absolute',\n inset: '0',\n display: 'flex',\n flexDirection: 'column',\n padding: '16px',\n gap: '14px',\n opacity: '0.9',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const bar = (styles: Partial<CSSStyleDeclaration>): HTMLDivElement => {\n const node = document.createElement('div');\n node.className = 'sl-shimmer';\n Object.assign(node.style, {\n background: shimmer,\n borderRadius: '8px',\n } satisfies Partial<CSSStyleDeclaration>);\n Object.assign(node.style, styles);\n return node;\n };\n\n // Top toolbar row.\n scaffold.append(bar({ height: '40px', width: '100%', flex: '0 0 auto' }));\n\n // Body: side panel + canvas.\n const body = document.createElement('div');\n Object.assign(body.style, {\n display: 'flex',\n gap: '14px',\n flex: '1 1 auto',\n minHeight: '0',\n } satisfies Partial<CSSStyleDeclaration>);\n body.append(bar({ width: '220px', height: '100%', flex: '0 0 auto' }));\n body.append(bar({ flex: '1 1 auto', height: '100%' }));\n scaffold.append(body);\n\n overlay.append(scaffold);\n\n // Centered caption above the scaffold.\n const caption = document.createElement('div');\n Object.assign(caption.style, {\n position: 'relative',\n zIndex: '1',\n display: 'flex',\n alignItems: 'center',\n gap: '10px',\n padding: '10px 16px',\n borderRadius: '999px',\n background: 'rgba(16, 22, 37, 0.72)',\n fontSize: '13px',\n fontWeight: '500',\n letterSpacing: '0.01em',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const dot = document.createElement('span');\n dot.className = 'sl-shimmer';\n Object.assign(dot.style, {\n width: '9px',\n height: '9px',\n borderRadius: '50%',\n background: shimmer,\n flex: '0 0 auto',\n } satisfies Partial<CSSStyleDeclaration>);\n caption.append(dot);\n caption.append(document.createTextNode('Loading designer…'));\n overlay.append(caption);\n }\n\n private buildErrorCard(overlay: HTMLDivElement, cause: ErrorCause): void {\n const copy = ERROR_COPY[cause];\n const card = document.createElement('div');\n Object.assign(card.style, {\n maxWidth: '420px',\n margin: '0 24px',\n padding: '28px',\n textAlign: 'center',\n background: 'rgba(255, 255, 255, 0.03)',\n border: '1px solid rgba(255, 255, 255, 0.08)',\n borderRadius: '16px',\n boxShadow: '0 12px 40px rgba(0, 0, 0, 0.35)',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const heading = document.createElement('h2');\n heading.textContent = copy.title;\n Object.assign(heading.style, {\n margin: '0 0 8px',\n fontSize: '17px',\n fontWeight: '600',\n color: '#f4f7ff',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const body = document.createElement('p');\n body.textContent = copy.body;\n Object.assign(body.style, {\n margin: '0 0 20px',\n fontSize: '13.5px',\n lineHeight: '1.5',\n color: '#aab4c8',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = 'Try again';\n Object.assign(button.style, {\n appearance: 'none',\n cursor: 'pointer',\n border: '0',\n borderRadius: '10px',\n padding: '10px 22px',\n fontSize: '14px',\n fontWeight: '600',\n color: '#101625',\n background: '#7aa2ff',\n } satisfies Partial<CSSStyleDeclaration>);\n button.addEventListener('click', () => this.handleTryAgain());\n\n card.append(heading, body, button);\n overlay.append(card);\n }\n\n private handleMessage = (event: MessageEvent<unknown>) => {\n if (!this.frame || event.origin !== this.designerOrigin || event.source !== this.frame.contentWindow) return;\n if (!event.data || typeof event.data !== 'object') return;\n const data = event.data as Record<string, unknown>;\n\n // Layout protocol — origin-locked like everything else, but handled here\n // rather than dispatched to the host callbacks.\n if (data.type === 'seatlayer.designer.resize') {\n // Fill mode owns the height from the viewport; the reported scrollHeight is\n // circular (the fixed-position shell echoes the iframe height), so ignore\n // it. Only a fixed numeric height honours the legacy auto-grow.\n if (!this.fillEnabled() && this.autoResizeEnabled()\n && typeof data.px === 'number' && Number.isFinite(data.px) && data.px > 0) {\n this.lastAutoHeight = `${Math.round(data.px)}px`;\n // While pinned fullscreen the iframe fills the viewport; apply the\n // reported height only when not pinned (it's re-applied on unpin).\n // `!important` so a host theme's `iframe { height … }` can't win.\n if (!this.pinned) this.setFrameHeight(this.lastAutoHeight);\n }\n return;\n }\n if (data.type === 'seatlayer.designer.fullscreen') {\n if (data.on === true) this.pinFullscreen();\n else if (data.on === false) this.unpinFullscreen();\n return;\n }\n\n if (typeof data.type !== 'string' || !TYPES.has(data.type as EmbeddedDesignerEventType)) return;\n\n const message: EmbeddedDesignerMessage = {\n type: data.type as EmbeddedDesignerEventType,\n chartId: typeof data.chartId === 'string' ? data.chartId : undefined,\n workspaceId: typeof data.workspaceId === 'string' ? data.workspaceId : undefined,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : undefined,\n code: typeof data.code === 'string' ? data.code : undefined,\n message: typeof data.message === 'string' ? data.message : undefined,\n meta: data.meta,\n };\n if (\n (this.options.expectedChartId && message.chartId && message.chartId !== this.options.expectedChartId) ||\n (this.options.expectedWorkspaceId && message.workspaceId && message.workspaceId !== this.options.expectedWorkspaceId)\n ) {\n // A message from our exact iframe carrying the wrong identity is a real\n // session mismatch, not spoofing. Surface it (loading state on) rather than\n // dispatching it to the host callbacks.\n this.showError('mismatch');\n return;\n }\n\n switch (message.type) {\n case 'seatlayer.designer.ready':\n this.phase = 'ready';\n this.clearTimeoutTimer();\n this.removeOverlay();\n // A fresh live session: clear the recovery guard and (re)arm proactive\n // renewal from this session's expiry.\n this.autoRecoverUsed = false;\n this.scheduleRenewal(message.expiresAt);\n this.options.onReady?.(message);\n break;\n case 'seatlayer.designer.saved': this.options.onSaved?.(message); break;\n case 'seatlayer.designer.published': this.options.onPublished?.(message); break;\n case 'seatlayer.designer.close': this.options.onClose?.(message); break;\n case 'seatlayer.designer.error': {\n const cause = causeFromCode(message.code);\n // Expiry is recoverable. If the host wired a relaunch hook, make ONE\n // silent auto-relaunch before ever showing the dead-end card — the user\n // never sees an overlay. Guarded (reset only on a fresh `ready`) so a\n // session that keeps failing to load falls through to the card instead of\n // looping the host.\n if (cause === 'expired' && this.autoRenewEnabled() && !this.autoRecoverUsed) {\n this.autoRecoverUsed = true;\n this.clearRenewTimer();\n this.options.onRequestRelaunch!();\n return;\n }\n // Only a dead session justifies tearing the editor down. An operation\n // that failed inside a running editor (autosave hitting a transient 5xx,\n // a thumbnail upload) leaves the session and the user's work intact, so\n // it is reported to the host and surfaced by the Designer's own in-editor\n // banner — replacing the canvas with \"We couldn't load the designer\"\n // would be both wrong and destructive. `fatal` is authoritative when the\n // Designer sends it; otherwise we fall back to the phase, which is the\n // same signal (we already had a `ready`).\n const fatal = typeof message.fatal === 'boolean'\n ? message.fatal\n : (cause !== 'load' || this.phase !== 'ready');\n if (fatal) this.showError(cause);\n this.options.onError?.(message);\n break;\n }\n }\n };\n}\n","/**\n * SeatPicker — the full buyer experience as a widget.\n *\n * Where `SeatingChart` is canvas-only, SeatPicker owns the complete chrome\n * from the canonical UX contract: branded header,\n * live price panel, selection tray with GA steppers, hold countdown, snipe\n * toasts and expiry recovery — all on top of the shared PickerController, so\n * every host gets the whole experience with one mount.\n *\n * Render contexts (owner requirement): the SAME widget adapts to a full-screen\n * takeover, an inline <div> in a content page, or a popup — breakpoints key\n * off the CONTAINER via ResizeObserver, never the viewport. `SeatPicker.open()`\n * mounts a document-level modal (scrim, ESC, focus restore) in one call.\n *\n * Theming (owner requirement): org account customization flows automatically —\n * the chart payload's ChartTheme (accent, accentInk, logoUrl, brand name,\n * fontFamily, …) seeds the look; the host `theme` option overrides any subset;\n * and every value lands as a `--sl-*` CSS custom property on the widget root\n * so plain host CSS can restyle too.\n */\nimport {\n PickerController,\n ACCESSIBILITY_TYPES,\n expandChart,\n // generateSeatPanorama is deliberately NOT here — see loadPanorama().\n generateSeatThumb,\n loadLocale,\n setStringOverrides,\n t,\n tCount,\n type AccessibilityType,\n type ChartTheme,\n type ExpandedSeat,\n type LodRung,\n type PanoramaResult,\n type PickerSeat,\n type PickerTransport,\n type RendererViewMode,\n type SeatCommercialAttributes,\n type SeatHoverDetails,\n type SectionSummary,\n type TableSelectionDetails,\n} from '@seatlayer/core';\nimport type { Venue3DHandle, SeatView as View3DSeatView } from '@seatlayer/core/view3d';\nimport {\n PubApi,\n type HoldLineItem,\n type HoldResult,\n type OrderStatusResult,\n type PaymentOptionsReason,\n type PaymentOptionsResult,\n} from './api';\n// mountCheckout is deliberately NOT imported here — see loadHostedCheckout().\nimport type { CheckoutHandle, CheckoutState } from './hostedCheckout';\nimport {\n createBuyerAccessContext,\n type BuyerAccessContext,\n type BuyerAccessExpiredEvent,\n type BuyerAccessToken,\n type BuyerAccessTokenProvider,\n type BuyerAccessUnavailableEvent,\n type BuyerAccessUnavailableReason,\n type SelectedObjectUnavailableEvent,\n} from './buyerAccess';\nimport { BuyerRealtimeClient, createControllerSink } from './buyerRealtime';\nimport { SEATLAYER_ATTRIBUTION_MARK_SVG } from './seatLayerBrand';\n\nconst DEFAULT_API_BASE = 'https://api.seatlayer.io';\nconst DEFAULT_MAX_SELECTION = 10;\n/** Show the \"Need more time?\" prompt when the hold has this long (ms) left. */\nconst EXTEND_PROMPT_MS = 60_000;\n/** Default seat ceiling for offering 3D — see the `max3DSeats` option. */\nconst MAX_3D_SEATS_DEFAULT = 15_000;\n/** Most section pills the 3D navigation rail will offer before it stays quiet. */\nconst MAX_3D_SECTION_PILLS = 12;\n\n/** Minimal shape of a section object read off the ChartDoc for the minimap. */\ninterface SectionLike {\n type: string;\n id: string;\n outline?: { x: number; y: number }[];\n color?: string;\n zone?: string;\n}\n\n/** Even-odd point-in-polygon test in world units (minimap click → section). */\nfunction pointInPolygon(x: number, y: number, poly: { x: number; y: number }[]): boolean {\n let inside = false;\n for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n const xi = poly[i].x, yi = poly[i].y, xj = poly[j].x, yj = poly[j].y;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n return inside;\n}\n\n/** One price band in the F4 filter — a set of category keys within a price range. */\ninterface PriceBand {\n id: string;\n label: string;\n keys: string[];\n min: number;\n max: number;\n}\n\n/**\n * Stable checkout-handoff contract (P4). Passed as the THIRD argument to\n * `onCheckout(hold, seats, handoff)` — additive, so the legacy `(hold, seats)`\n * shape used by DesiPass web-v2 (SDK 0.7.3+) is untouched. This is the object to\n * build your order against: it is self-contained (holdId, expiry, currency, and\n * per-line tier + price) and never changes shape across minor releases.\n */\nexport interface CheckoutLineItem {\n /** Seat label (or GA synthetic-unit label) — the stable booking identity. */\n label: string;\n /**\n * Buyer-facing name (the designer's `displayLabel` override), when set.\n * Show this in YOUR order summary; `label` stays the booking identity you\n * pass to the book call. Absent = no override, fall back to `label`.\n */\n displayLabel?: string;\n /**\n * Buyer-facing type word override (seats.io \"Displayed type\", e.g. \"Table\",\n * \"Bench\", \"Box\"), when the designer set one. Absent = the default word.\n */\n displayType?: string;\n /** Chart object id (row/booth/GA area) the unit belongs to. */\n objectId: string;\n objectType: 'seat' | 'booth' | 'ga' | 'table';\n categoryKey: string;\n /** Chosen ticket tier id (Adult/Child/…), or null when the category has no tiers. */\n tierId: string | null;\n /** Unit price in MAJOR currency units (e.g. 45 = 45.00). Server-authoritative. */\n unitPrice: number;\n /** ISO-4217, resolved server-side (per-event override → org → USD). */\n currency: string;\n quantity: number;\n}\n\nexport interface CheckoutHandoff {\n /** Server hold id — pass this to YOUR book call. */\n holdId: string;\n /** Epoch ms the hold expires (after any extensions). */\n expiresAt: number;\n /** ISO-4217 currency for the whole order. */\n currency: string;\n /** Priced line items (tier + unit price + currency), server-authoritative. */\n lineItems: CheckoutLineItem[];\n /** Convenience total in major units (Σ unitPrice × quantity). */\n total: number;\n}\n\n/** Host-authoritative pricing — see {@link SeatPickerOptions.pricing}. */\nexport interface SeatPickerPricing {\n /** Unit prices by category key: a flat number, or `{ base, tiers: { tierId: price } }`. */\n prices?: Record<string, number | { base?: number; tiers?: Record<string, number> }>;\n /** Custom money renderer (e.g. `(n) => n + '€'`). Defaults to Intl currency formatting. */\n formatter?: (amount: number, currency: string) => string;\n}\n\n/** Host theme overrides — any subset; unset keys fall back to the org's chart theme, then defaults. */\nexport interface SeatPickerTheme {\n /** Brand accent (CTA, active chips, hold pill). */\n accent?: string;\n /** Ink on the accent (button labels). */\n accentInk?: string;\n /** Widget background. */\n background?: string;\n /** Panel/card surface color. */\n surface?: string;\n /** Primary text color. */\n text?: string;\n /** Secondary text color. */\n muted?: string;\n /** Hairline/border color. */\n line?: string;\n /** Font stack for all widget chrome. */\n fontFamily?: string;\n /** Corner radius base (px). */\n radius?: number;\n /** Header logo URL (falls back to the org logo from the chart theme, then a monogram). */\n logoUrl?: string;\n /** Brand/event fallback name for the monogram. */\n brandName?: string;\n}\n\nexport interface SeatPickerOptions {\n /** CSS selector or element to mount into. Omit when using SeatPicker.open(). */\n container?: string | HTMLElement;\n /** Event key, e.g. `ev_xxx`. */\n event: string;\n /** API origin. Defaults to https://api.seatlayer.io. */\n apiBase?: string;\n /**\n * Custom data transport. Defaults to the CORS-trivial PubApi against\n * `apiBase`. Inject to run the widget against another backend adapter (the\n * SeatLayer dashboard's own transport) or a fully local mock (demos).\n */\n transport?: PickerTransport;\n /** Reserved for future authenticated rendering. NOT the channel-access\n * credential — a buyer access session is a different thing with different\n * authority, and uses the two options below. */\n publicKey?: string;\n /**\n * Buyer access session provider — the recommended way to show private channel\n * inventory (Sales Channels guide §6).\n *\n * Called with a `reason` whenever the widget needs a bearer: first\n * acquisition, a near/actual expiry, a 401 `buyer_access_expired`, a realtime\n * reconnect, or `refreshAccess()`. It should POST to YOUR backend, which\n * mints the session with your secret key and returns `{ token, expiresAt }`.\n *\n * The token lives in memory for the widget's lifetime and nowhere else: never\n * in storage, never in a URL, never in a log or an error message. Refresh\n * returns the same or a narrower scope; the widget never widens to Public\n * sale on its own, and a failed refresh stops the scoped operation rather\n * than retrying it anonymously. Any held seats stay held — a hold is\n * relinquished by its own opaque capability, not by channel access, so\n * losing access never strands inventory (guide §9).\n *\n * Ignored when a custom `transport` is supplied: that host owns its own\n * credentials.\n */\n buyerAccessTokenProvider?: BuyerAccessTokenProvider;\n /**\n * One-shot escape hatch for hosts that already own the session lifecycle.\n * Cannot be renewed — when it lapses the widget reports `onAccessExpired`\n * and then `onAccessUnavailable`. Prefer `buyerAccessTokenProvider`.\n */\n buyerAccessToken?: string | BuyerAccessToken;\n /** Max seats selectable at once (default 10). */\n maxSelection?: number;\n /** BCP 47 language for the widget UI. Built-in: en, es, de, fr. */\n locale?: string;\n /** Per-key string overrides layered over the active locale. */\n messages?: Record<string, string>;\n /** ISO 4217 currency fallback (the org/event currency on the chart wins). */\n currency?: string;\n /** Colorblind-safe rendering (Okabe-Ito palette, hollow booked seats). */\n colorblindSafe?: boolean;\n /** Initial map projection. Buyers now toggle **Map (flat 2D) + 3D** only; the\n * legacy `perspective` (2.5D) value is still ACCEPTED for source compatibility\n * but is deprecated — it is coerced to `flat` with a one-time console warning.\n * The 3D venue view is entered from the Map/3D control, not this option. */\n initialView?: RendererViewMode;\n /**\n * Offer the interactive 3D venue view (Map | 3D toggle + a \"See it in 3D\"\n * action on the seat-confirm card). Default true. The 3D button is shown only\n * when this is not false AND the browser exposes WebGL2; there are ZERO GL\n * bytes on the wire until the buyer actually opens 3D (the OGL chunk is\n * dynamically imported on first use). Set false for embed hosts that must\n * stay strictly 2D. */\n enable3D?: boolean;\n /**\n * Seat-count ceiling above which 3D is not offered. Default: the measured-good\n * ceiling of 15,000 seats (14,142 renders at 58 fps), halved to 7,500 on a\n * device that reports itself as small/low-core.\n *\n * The 3D scene holds EVERY seat resident — there is no streaming rung yet — so\n * a 53,000-seat chart builds its scene in ~780 ms on a desktop and much worse\n * on a phone. Offering 3D there is offering a stall. A host that knows its\n * audience can raise this; the ceiling goes away when seat streaming lands. */\n max3DSeats?: number;\n /**\n * Optional analytics sink for the widget's own journey events. Currently emits\n * the 3D venue-view journey (`3d_opened`, `3d_orbit_engaged`, `3d_seat_picked`,\n * `3d_cinematic_played`/`_skipped`/`_cancelled`, `3d_panorama_opened`/`_closed`)\n * with `{ surface: 'buyer' }` merged into the props. A throwing sink never\n * breaks the widget. Route it to your product analytics (e.g. PostHog). */\n onAnalytics?: (event: string, props: Record<string, unknown>) => void;\n /**\n * Hide the \"Powered by SeatLayer\" attribution badge in the side panel foot.\n * The chart theme's own `hideBadge` flag (paid orgs) also hides it — the badge\n * is shown only when BOTH this option and the theme flag are unset/false.\n */\n hideBadge?: boolean;\n /** Host theme overrides — see SeatPickerTheme. */\n theme?: SeatPickerTheme;\n /**\n * Host-authoritative pricing. When your shop charges different prices than\n * the chart's stored category prices, pass them here so the buyer sees the\n * price they will actually pay — on the map tooltip, confirm popover, price\n * panel, tray, totals, and in the checkout handoff's line items. Keyed by\n * category key; per-tier overrides nest under `tiers`. Unlisted categories\n * fall back to the chart price.\n */\n pricing?: SeatPickerPricing;\n /** Hold TTL in ms passed to hold(); server clamps to its own limits. */\n holdTtlMs?: number;\n /**\n * An opaque hold id supplied by the host to restore after navigation. It is\n * verified against the event and active server state before anything renders\n * as owned by this buyer.\n */\n initialHoldId?: string;\n /**\n * Automatically remember the active hold id in sessionStorage and restore it\n * when this event's picker mounts again. Default true. Set false when the host\n * owns hold persistence and supplies initialHoldId itself.\n */\n restoreHold?: boolean;\n /**\n * Confirm mode: tapping a seat shows a confirmation card with section, row,\n * seat, category, price and Select/Cancel before it enters the tray. Default\n * true for the full buyer picker; set false only when the host supplies its\n * own equivalent confirmation UI.\n */\n confirmSelection?: boolean;\n /**\n * Offer a \"View from seat\" 360° preview (confirm popover + tray chips). The\n * panorama is generated from the chart geometry, or the organizer's uploaded\n * photo when a seat carries one. Default true; set false to hide the affordance.\n */\n seatView?: boolean;\n /**\n * WHERE the buyer goes once their seats are held. Default `'handoff'`.\n *\n * 'handoff' (default, and every integration that has ever existed) the\n * widget fires {@link onCheckout} with a holdId and priced line\n * items, and YOUR server takes the money. Nothing about this path\n * changes, and no payment code is even downloaded.\n * 'hosted' the widget takes the money through the gateway the ORGANIZER\n * connected, on their account — the \"sell tickets with no\n * backend\" path. Requires the org to be on hosted checkout and\n * the event to have a gateway assigned; when it does not, this\n * falls back to `'handoff'` for that buyer rather than dead-ending\n * them, and reports why through {@link onCheckoutUnavailable}.\n *\n * Named for the destination rather than as a boolean flag because there is a\n * real third answer coming and `hostedCheckout: true` would have no room for\n * it; spelling the default out also makes a host's intent legible in their own\n * source instead of hiding it in an absent option.\n *\n * TWO THINGS ARE WORTH KNOWING BEFORE YOU SWITCH THIS ON:\n *\n * 1. It needs the widget's own transport. A host-supplied `transport` owns its\n * credentials and its backend, so hosted checkout stays off there (with one\n * console warning) rather than reaching past it to api.seatlayer.io.\n * 2. WHERE A HOSTED GATEWAY RETURNS THE BUYER is settled by {@link returnUrl}\n * and by the organizer. Without one — or from an origin the organizer has\n * not declared — the buyer comes back to SeatLayer's own buyer page and is\n * confirmed THERE, not in this widget. Declare the embedding site under\n * Embed domains in the dashboard and pass `returnUrl`, and the buyer\n * returns to your page instead. In-page gateways never navigate away at\n * all, so they are unaffected either way.\n */\n checkout?: 'handoff' | 'hosted';\n /**\n * Where a redirecting gateway should send the buyer back to, for\n * `checkout: 'hosted'`.\n *\n * The server keeps this URL verbatim — path and query included — and only\n * stamps `?order=…&status=success|cancelled` onto it, so point it at\n * whichever of YOUR pages should confirm the purchase (often just\n * `window.location.href`). Mount a picker on that page and it resumes in\n * place from those parameters.\n *\n * It is validated, not trusted: the organizer declares their embed origins\n * in the dashboard, and an undeclared origin is ignored rather than\n * refused — the sale still completes, the buyer just finishes on\n * SeatLayer's page. Supplying a URL therefore cannot authorize it, which is\n * what stops a copied snippet from redirecting a paid buyer anywhere it\n * likes.\n */\n returnUrl?: string;\n /**\n * Buyer pressed the CTA and the hold succeeded — hand off to YOUR checkout.\n * `hold` and `seats` are the legacy args (unchanged since 0.6). `handoff` (P4)\n * is the stable, self-contained {@link CheckoutHandoff} to build your order\n * against — holdId, expiry, currency and priced line items. Prefer it.\n *\n * Under `checkout: 'hosted'` this fires ONLY when hosted checkout cannot run\n * for this event, so a host can keep one code path for both. It never fires\n * alongside a payment the widget is taking itself.\n */\n onCheckout?: (hold: HoldResult, seats: PickerSeat[], handoff: CheckoutHandoff) => void;\n /**\n * `checkout: 'hosted'` was asked for and this event cannot take money.\n * The seats ARE held — the buyer is mid-journey — so this is a routing\n * decision, not an error, and it is never collapsed into {@link onError}.\n *\n * `reason` carries the server's three-way answer verbatim, because two of the\n * three give opposite advice: `payments_off_for_event` means the organizer\n * deliberately does not sell this event online (nothing is wrong), while\n * `unavailable_for_event` means they switched it on and it is broken. Anything\n * unreadable — a failed lookup, an older worker — reads as `not_configured`,\n * which asserts the least about them.\n *\n * `onCheckout` fires immediately after this with the same hold. Supply either\n * (or both) and you own the next screen; supply NEITHER and the widget shows\n * the buyer an honest card of its own rather than swallowing the press.\n */\n onCheckoutUnavailable?: (event: {\n reason: PaymentOptionsReason;\n handoff: CheckoutHandoff;\n }) => void;\n /**\n * `checkout: 'hosted'` only — the gateway's webhook landed and the order is\n * PAID. The one signal a host with no backend actually needs, and the only\n * place a receipt can come from on a page that has no server of its own.\n *\n * Distinct from {@link onBooked}, which reports the same sale seen from the\n * seat map over the realtime channel and cannot fire at all for a buyer whose\n * widget was torn down by a redirect to the gateway.\n */\n onOrderConfirmed?: (order: OrderStatusResult) => void;\n /**\n * The held seats were BOOKED (P4) — your server completed payment and the\n * booking landed over the realtime channel while the widget was still open.\n * The widget shows a success state; use this to advance your own UI (receipt,\n * redirect). Fires once per hold.\n */\n onBooked?: (handoff: CheckoutHandoff) => void;\n /** Selection changed (tap or best-available). */\n onSelectionChange?: (seats: PickerSeat[]) => void;\n /**\n * Active hold changed because it was created, restored, extended, partially\n * released, or fully released. Hosts should persist this state for route\n * navigation and clear their checkout cart when `hold` becomes null.\n */\n onHoldChange?: (hold: HoldResult | null, seats: PickerSeat[], handoff: CheckoutHandoff | null) => void;\n /** The open hold expired server-side (widget already reset itself). */\n onHoldExpired?: () => void;\n /** A prior active hold was verified and restored into the tray. */\n onHoldRestored?: (hold: HoldResult, seats: PickerSeat[], handoff: CheckoutHandoff) => void;\n /** Modal only: the buyer closed the picker (ESC / scrim / ✕). */\n onClose?: () => void;\n /**\n * The buyer access session lapsed. `refreshed` says whether the provider\n * already recovered it — false means private inventory is now unavailable and\n * `onAccessUnavailable` follows. Never collapsed into `onError`: an expiry is\n * a recoverable, buyer-explainable state, not a network failure (guide §10).\n */\n onAccessExpired?: (event: BuyerAccessExpiredEvent) => void;\n /**\n * Private inventory is unavailable and refreshing will not fix it — revoked,\n * paused, wrong origin/event/mode, or the provider failed. Carries a reason,\n * never a channel name, id, colour or count. The widget shows its own\n * explanatory panel; return nothing to keep it, or handle the state yourself.\n */\n onAccessUnavailable?: (event: BuyerAccessUnavailableEvent) => void;\n /**\n * Selected-but-unheld units stopped being selectable — someone else took\n * them, or an allocation change moved them out of this buyer's scope. The\n * widget has already dropped them from the tray.\n */\n onSelectedObjectUnavailable?: (event: SelectedObjectUnavailableEvent) => void;\n onError?: (err: unknown) => void;\n}\n\nfunction resolveContainer(container: string | HTMLElement): HTMLElement {\n if (typeof container === 'string') {\n const el = document.querySelector(container);\n if (!el) throw new Error(`seatmap: container \"${container}\" not found`);\n return el as HTMLElement;\n }\n if (!(container instanceof HTMLElement)) {\n throw new Error('seatmap: container must be a CSS selector or an HTMLElement');\n }\n return container;\n}\n\nfunction escapeOption(value: unknown): string {\n return String(value ?? '').replace(/[&<>\"']/g, (character) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''',\n })[character]!);\n}\n\n// ---- 3D venue view: lazy loader + capability probe -------------------------\n\n/** The full module type for the lazy OGL venue-view chunk (`@seatlayer/core/view3d`). */\ntype Venue3DModule = typeof import('@seatlayer/core/view3d');\n\n/**\n * Injected `true` only in the CDN/IIFE build (see cdn/vite.config.ts `define`).\n * Undefined in the npm/tsup build and the vendored app copy, so the runtime-URL\n * branch below is never taken there and esbuild dead-code-eliminates it in the\n * CDN build once the constant folds to `true`.\n */\ndeclare const __SEATLAYER_CDN__: boolean | undefined;\n\n/**\n * This bundle's own URL, used only in the CDN build to locate its sibling lazy\n * chunks (`./seatlayer-view3d.mjs`, `./seatlayer-panorama.mjs`).\n * `import.meta.url` resolves to the module URL in\n * the ESM CDN output (`…/seatlayer.mjs`), and Rollup auto-shims it to a\n * `document.currentScript.src` expression in the IIFE output (`…/seatlayer.js`),\n * so both CDN formats find the chunk next to them. Guarded so no environment\n * that lacks `import.meta` throws at module init.\n */\nconst SEATLAYER_MODULE_URL: string | undefined = (() => {\n // IIFE/classic-script (CDN seatlayer.js): the tag sets document.currentScript\n // synchronously while this module's top level runs. Resolve from it first —\n // the IIFE build folds `import.meta` to `{}`, so import.meta.url is unusable\n // there anyway.\n if (typeof document !== 'undefined'\n && document.currentScript instanceof HTMLScriptElement\n && document.currentScript.src) {\n return document.currentScript.src;\n }\n // ESM (CDN seatlayer.mjs / bundlers): import.meta.url is the module URL.\n try {\n const u = import.meta.url;\n if (typeof u === 'string' && u) return u;\n } catch {\n /* no import.meta in this environment */\n }\n return undefined;\n})();\n\nlet _webgl2Cache: boolean | null = null;\n/** Whether the browser exposes WebGL2 (cached). Gates the 3D affordances. */\nfunction hasWebGL2(): boolean {\n if (_webgl2Cache !== null) return _webgl2Cache;\n try {\n if (typeof document === 'undefined') return (_webgl2Cache = false);\n const canvas = document.createElement('canvas');\n _webgl2Cache = !!canvas.getContext('webgl2');\n } catch {\n _webgl2Cache = false;\n }\n return _webgl2Cache;\n}\n\n/** Absolute URL of a sibling lazy chunk in this bundle's pinned CDN directory. */\nfunction cdnChunkUrl(fileName: string): string {\n const base = SEATLAYER_MODULE_URL ?? (typeof location !== 'undefined' ? location.href : undefined);\n if (!base) throw new Error(`seatlayer: cannot resolve the ${fileName} chunk URL`);\n return new URL(`./${fileName}`, base).href;\n}\n\n/**\n * Dynamically load the view3d module. Two build targets, one source:\n * - CDN/IIFE (cannot code-split): load the sibling ESM asset by absolute URL\n * derived from this script's own src.\n * - npm/ESM and the vendored app copy (rewritten to `../../view3d`): a bare\n * dynamic import the consumer's bundler chunk-splits automatically.\n * Either way, ZERO GL bytes are fetched until this actually runs.\n */\nasync function loadVenue3d(): Promise<Venue3DModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-view3d.mjs')) as Promise<Venue3DModule>;\n }\n return import('@seatlayer/core/view3d');\n}\n\n/** Just the generator, so the type does not drag the rest of the engine in. */\ntype PanoramaModule = Pick<typeof import('@seatlayer/core'), 'generateSeatPanorama'>;\n\n/**\n * Dynamically load the view-from-seat panorama generator, on exactly the same\n * pattern as {@link loadVenue3d}. It is ~25 KB of drawing code that runs only\n * when a buyer asks to see the view from a seat, so it stays out of the bytes\n * every buyer downloads to look at a seat map.\n *\n * Its own chunk rather than a fold into the 3D one: the 2D \"View from here\"\n * button does not enter 3D, so folding would make that tap pull the whole OGL\n * scene — 74 KB gzipped, unrunnable without WebGL2 — to draw a 2D canvas.\n *\n * On npm and in the vendored app copy this is a dynamic import of a module the\n * widget ALREADY imports statically, so every bundler resolves it out of the\n * chunk that is loaded anyway: same bytes, same behaviour, no extra request.\n */\nasync function loadPanorama(): Promise<PanoramaModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-panorama.mjs')) as Promise<PanoramaModule>;\n }\n return import('@seatlayer/core');\n}\n\n/** Just the mount function, so the type does not drag the module's DOM in. */\ntype HostedCheckoutModule = Pick<typeof import('./hostedCheckout'), 'mountCheckout'>;\n\n/**\n * Dynamically load the hosted-checkout card, on the same pattern as\n * {@link loadVenue3d} and {@link loadPanorama}, and for a stronger reason than\n * either: this is payment UI, and the overwhelming majority of buyers who load\n * a seat map never reach it. Most integrations never enable it at all —\n * `checkout` defaults to `'handoff'`, where these bytes are unreachable code.\n *\n * So there are ZERO payment bytes on the wire until a buyer presses the CTA in\n * a picker whose host opted into `checkout: 'hosted'`. Unlike the panorama\n * chunk, `./hostedCheckout` is NOT imported statically anywhere, so on npm this\n * is a genuine code split rather than a free reference into a module that was\n * loading anyway — which is exactly what we want here.\n */\nasync function loadHostedCheckout(): Promise<HostedCheckoutModule> {\n if (typeof __SEATLAYER_CDN__ !== 'undefined' && __SEATLAYER_CDN__) {\n return import(/* @vite-ignore */ cdnChunkUrl('seatlayer-checkout.mjs')) as Promise<HostedCheckoutModule>;\n }\n return import('./hostedCheckout');\n}\n\n/**\n * Read the wire's reason, failing to the least-accusing one.\n *\n * Anything unrecognised — a failed read, an older worker that sent nothing, a\n * newer one naming a reason this build has never heard of — becomes\n * `not_configured`, which asserts the least about the organizer. A story\n * invented from a missing field is worse than the coarse truth.\n */\nexport function paymentsOffReason(reason: string | null | undefined): PaymentOptionsReason {\n return reason === 'unavailable_for_event' || reason === 'payments_off_for_event'\n ? reason\n : 'not_configured';\n}\n\n/**\n * Widget stylesheet — injected once per document. Every color/font/radius is a\n * --sl-* token.\n *\n * The `@sl-css` marker opts this literal into build-time CSS minification (see\n * cdn/minifyCssLiterals.ts). Keep writing it long-hand and commented: the CDN\n * build strips the comments and the indentation, the source keeps them.\n */\nconst STYLE_ID = 'seatlayer-picker-style';\nconst CSS = /* @sl-css */ `\n.sl-picker{position:relative;display:flex;flex-direction:column;width:100%;height:100%;min-height:420px;overflow:hidden;\n background:var(--sl-bg);color:var(--sl-text);font-family:var(--sl-font);border-radius:var(--sl-radius);\n --sl-r-sm:calc(var(--sl-radius) * .55);\n /* Motion tokens, defined ON the widget root so an embed is self-contained and\n never inherits (or fights) the host page's own timing. Values mirror\n docs/motion-system-2026-08-01.md §2. */\n --slm-mo-instant:80ms;--slm-mo-quick:140ms;--slm-mo-base:200ms;--slm-mo-slow:320ms;\n --slm-mo-out:cubic-bezier(0.2,0.8,0.2,1);--slm-mo-exit:cubic-bezier(0.4,0,1,1)}\n.sl-picker *{box-sizing:border-box;margin:0;padding:0}\n.sl-picker button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}\n\n/* header */\n.sl-head{display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--sl-line);flex:none}\n.sl-logo{width:34px;height:34px;border-radius:9px;flex:none;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink);font-weight:800;font-size:15px;overflow:hidden}\n.sl-logo img{width:100%;height:100%;object-fit:cover;display:block}\n.sl-head-info{min-width:0;flex:1}\n.sl-head-name{font-weight:700;font-size:15px;line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-head-meta{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--sl-muted);margin-top:3px;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600}\n.sl-hold-pill{display:none;align-items:center;gap:6px;padding:6px 12px;border-radius:999px;flex:none;\n background:var(--sl-accent);color:var(--sl-accent-ink);font-weight:700;font-size:12px;font-variant-numeric:tabular-nums;\n transform-origin:right center}\n.sl-hold-pill.on{display:inline-flex;animation:slPillIn .34s cubic-bezier(.2,.8,.2,1) both}\n.sl-hold-dot{width:7px;height:7px;border-radius:50%;background:currentColor;opacity:.78;box-shadow:0 0 0 0 currentColor}\n.sl-hold-pill.is-expiring .sl-hold-dot{animation:slHoldPulse 1.4s ease-out infinite}\n.sl-hold-time{min-width:3.35em;text-align:left}\n.sl-close{width:32px;height:32px;border-radius:999px;flex:none;display:none;align-items:center;justify-content:center;\n border:1px solid var(--sl-line);color:var(--sl-muted);transition:color .15s,border-color .15s}\n.sl-close:hover{color:var(--sl-text);border-color:var(--sl-muted)}\n.sl-close.on{display:inline-flex}\n.sl-close svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round}\n\n/* body */\n.sl-body{display:flex;flex:1;min-height:0}\n.sl-map{position:relative;flex:1;min-width:0}\n.sl-map-host{position:absolute;inset:0}\n.sl-side{width:300px;flex:none;border-left:1px solid var(--sl-line);display:flex;flex-direction:column;min-height:0;overflow:hidden}\n\n/* narrow (container < 640px): map-first — the map claims ~80-85% of the\n container and the side panel becomes a PEEKING bottom sheet (AXS/Ticketmaster\n mobile pattern). data-sheet on the root: \"peek\" (default: grab handle + one\n summary line) / \"open\" (room for rows + checkout, swipe up to open).\n Swipe handling lives on the sheet head ONLY — never the map host, so the\n map's raw-pointer gesture pipeline is untouched. */\n.sl-picker[data-layout=\"narrow\"] .sl-body{flex-direction:column}\n.sl-picker[data-layout=\"narrow\"] .sl-map{min-height:0;flex:1}\n.sl-picker[data-layout=\"narrow\"] .sl-side{width:100%;border-left:0;border-top:1px solid var(--sl-line);\n flex:none;height:min(72%,480px);overflow:hidden;transition:height .3s cubic-bezier(.2,.8,.2,1);overscroll-behavior:contain}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"][data-has-selection=\"false\"] .sl-side{height:min(252px,52%)}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"peek\"] .sl-side{height:86px;overflow:hidden}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"peek\"] .sl-side > :not(.sl-sheet-head){display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-tray{flex:1;min-height:0;overflow-y:auto;overscroll-behavior:contain}\n.sl-picker[data-layout=\"narrow\"] .sl-foot{position:static;background:var(--sl-bg)}\n.sl-picker[data-layout=\"narrow\"] .sl-foot.empty{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-sheet-head{order:0}\n.sl-picker[data-layout=\"narrow\"] .sl-seats-sec{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-tray{order:2}\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec{order:3}\n.sl-picker[data-layout=\"narrow\"] .sl-filters{order:4}\n.sl-picker[data-layout=\"narrow\"] .sl-prices-sec{order:5}\n.sl-picker[data-layout=\"narrow\"] .sl-pricef{order:6}\n.sl-picker[data-layout=\"narrow\"] .sl-prices{order:7}\n.sl-picker[data-layout=\"narrow\"] .sl-foot{order:8}\n.sl-picker[data-layout=\"narrow\"] .sl-tray-hint,\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec,\n.sl-picker[data-layout=\"narrow\"] .sl-filters,\n.sl-picker[data-layout=\"narrow\"] .sl-prices-sec,\n.sl-picker[data-layout=\"narrow\"] .sl-prices{display:none!important}\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filtersec,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filters,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-prices-sec{display:none}\n/* Reclaim the bottom sheet once the cart has anything: the \"Find best seats\"\n panel collapses too. EXCEPT the confirm (\"Replace your current choices?\") and\n in-flight busy states, which legitimately show with a non-empty cart — those\n set data-ba-active=\"true\" (see setAttribute alongside data-has-selection). */\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"]:not([data-ba-active=\"true\"]) .sl-ba{display:none}\n/* touch chrome: pinch-zoom exists — hide +/− on the sheet layout (keep fit) */\n.sl-picker[data-layout=\"narrow\"] .sl-zoom [data-ref=\"zin\"],\n.sl-picker[data-layout=\"narrow\"] .sl-zoom [data-ref=\"zout\"]{display:none}\n\n/* bottom-sheet head: grab handle + one-line summary (narrow only). The WHOLE\n head is the tap/swipe toggle target (min 44px), so it reads as one control. */\n.sl-sheet-head{display:none;flex-direction:column;justify-content:center;padding:6px 12px 8px;min-height:56px;\n cursor:pointer;touch-action:none;user-select:none;-webkit-user-select:none;flex:none}\n.sl-picker[data-layout=\"narrow\"] .sl-sheet-head{display:flex}\n.sl-sheet-grab{width:36px;height:4px;border-radius:999px;background:var(--sl-muted);opacity:.55;margin:2px auto 7px}\n.sl-sheet-bar{display:flex;align-items:center;gap:10px;min-height:26px}\n.sl-sheet-peek{display:flex;align-items:center;gap:7px;flex:1;min-width:0;font-size:13px;font-weight:700;color:var(--sl-text);\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-sheet-peek .sub{color:var(--sl-muted);font-weight:600}\n/* collapsed-peek \"Continue\" affordance: a real accent pill, not plain text */\n.sl-sheet-peek .go{margin-left:auto;flex:none;display:inline-flex;align-items:center;min-height:30px;\n padding:6px 13px;border-radius:999px;background:var(--sl-accent);color:var(--sl-accent-ink);\n font-weight:800;font-size:12.5px}\n/* state chevron: points UP while peeking, rotates to point DOWN when open.\n Base keeps an explicit rotate(0) — transitioning to/from a bare 'none' leaves\n the value stuck in some engines, so both endpoints must be real transforms. */\n.sl-sheet-toggle{width:44px;height:44px;margin:-8px -8px -8px 0;border-radius:999px;flex:none;display:flex;\n align-items:center;justify-content:center;color:var(--sl-muted);transition:color .15s,background .15s}\n.sl-sheet-toggle:hover,.sl-sheet-toggle:focus-visible{color:var(--sl-text);background:color-mix(in srgb,var(--sl-line) 44%,transparent)}\n.sl-sheet-toggle svg{width:21px;height:21px;stroke:currentColor;stroke-width:2.4;fill:none;\n stroke-linecap:round;stroke-linejoin:round}\n.sl-sheet-toggle svg{transform:rotate(0deg);transition:transform .24s cubic-bezier(.2,.8,.2,1)}\n.sl-picker[data-sheet=\"open\"] .sl-sheet-toggle svg{transform:rotate(180deg)}\n\n/* consolidated Filters row inside the sheet (a11y chips + colorblind toggle\n dock here on narrow; they live on the map / zoom column on wide) */\n.sl-filtersec{display:none}\n.sl-filters{display:none;gap:6px;flex-wrap:wrap;align-items:center;padding:2px 16px 10px}\n.sl-picker[data-layout=\"narrow\"] .sl-filtersec.has,\n.sl-picker[data-layout=\"narrow\"] .sl-filters.has{display:none}\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filtersec.has,\n.sl-picker[data-layout=\"narrow\"][data-has-selection=\"true\"] .sl-filters.has{display:none}\n/* Accessibility and colour-safety controls must remain reachable on phones.\n Keep them out of the 86px peek, then reveal their consolidated row whenever\n the buyer explicitly opens the ticket panel. */\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"] .sl-filtersec.has{display:block!important}\n.sl-picker[data-layout=\"narrow\"][data-sheet=\"open\"] .sl-filters.has{display:flex!important}\n.sl-cbbtn{width:32px;height:32px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-cbbtn:hover{border-color:var(--sl-muted)}\n.sl-cbbtn svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* price panel — one compact filter control replaces the wrapping price-chip row. */\n.sl-sec{padding:14px 14px 4px;font-size:9.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--sl-muted);font-weight:700}\n.sl-prices-sec{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:13px}\n.sl-price-select{min-height:32px;max-width:130px;padding:5px 28px 5px 9px;border:1px solid var(--sl-line);border-radius:9px;\n background:var(--sl-surface);color:var(--sl-text);font:inherit;font-size:11px;font-weight:750;letter-spacing:0;text-transform:none}\n.sl-prices{display:flex;flex-direction:column;padding:4px 14px 8px;border-bottom:1px solid var(--sl-line)}\n.sl-prices-sec,.sl-prices,.sl-seats-sec{flex:none}\n.sl-price-row{display:flex;align-items:center;gap:7px;min-height:28px;font-size:12px;\n padding:0 6px;margin:0 -6px;border-radius:8px;cursor:pointer;transition:background .15s}\n.sl-price-row:hover,.sl-price-row:focus-visible{background:color-mix(in srgb,var(--sl-line) 40%,transparent)}\n.sl-price-row.sl-active{background:color-mix(in srgb,var(--sl-accent) 9%,transparent)}\n.sl-price-row.sl-active .sl-price-label{color:var(--sl-accent)}\n.sl-dot{width:9px;height:9px;border-radius:50%;flex:none}\n.sl-price-label{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600}\n.sl-price-left{font-size:11px;color:var(--sl-muted);font-variant-numeric:tabular-nums}\n.sl-price-amt{font-weight:800;font-variant-numeric:tabular-nums}\n/* long category lists: capped by default, scroll once expanded */\n.sl-prices.sl-expanded{max-height:196px;overflow-y:auto;overscroll-behavior:contain;scrollbar-gutter:stable}\n.sl-price-more{display:flex;align-items:center;min-height:26px;padding:0;\n color:var(--sl-muted);font-size:11px;font-weight:750;transition:color .15s}\n.sl-price-more:hover,.sl-price-more:focus-visible{color:var(--sl-text)}\n/* held/sold key — one quiet caption line; the map itself teaches these states */\n.sl-status-key{display:flex;gap:11px;flex-wrap:wrap;padding:5px 0 0;margin-top:4px;border-top:1px solid var(--sl-line);color:var(--sl-muted);font-size:10px}\n.sl-status-item{display:inline-flex;align-items:center;gap:5px}\n.sl-status-icon{width:13px;height:13px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;\n color:#fff;background:#6b7280;line-height:1}\n.sl-status-icon svg{width:8px;height:8px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-status-icon.sold{background:#8b93a0}\n.sl-status-icon.sold svg{width:9px;height:9px;stroke-width:2.4}\n\n/* tray */\n.sl-seats-sec{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:13px}\n.sl-seat-summary{font-size:10px;letter-spacing:0;text-transform:none;white-space:nowrap}\n.sl-tray{flex:1;padding:10px 14px 14px;display:flex;flex-direction:column;gap:7px;min-height:0;overflow-y:auto;\n overscroll-behavior:contain;scrollbar-gutter:stable}\n.sl-tray-hint{font-size:12.5px;color:var(--sl-muted);line-height:1.5}\n.sl-chip{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 34px;align-items:stretch;\n flex:none;min-height:53px;border:1px solid var(--sl-line);border-radius:var(--sl-r-sm);overflow:hidden;\n background:var(--sl-surface);font-size:13px;transform-origin:center;transition:border-color .15s,background .15s}\n.sl-chip:hover{border-color:color-mix(in srgb,var(--sl-accent) 38%,var(--sl-line))}\n.sl-chip.sl-enter{animation:slChipIn .38s cubic-bezier(.2,.8,.2,1) both}\n.sl-chip.sl-leave{pointer-events:none;animation:slChipOut .16s ease-in both}\n.sl-chip.sl-held{border-color:var(--sl-line);background:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-surface));\n box-shadow:inset 3px 0 0 color-mix(in srgb,var(--sl-accent) 72%,transparent)}\n.sl-ticket-state{width:17px;height:17px;border-radius:999px;flex:none;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-ticket-state.held{background:color-mix(in srgb,var(--sl-accent) 18%,var(--sl-surface));color:var(--sl-accent)}\n.sl-ticket-state svg{width:10px;height:10px;stroke:currentColor;stroke-width:2.6;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-chip-main{min-width:0;padding:8px 10px 8px 11px;display:flex;flex-direction:column;justify-content:center;gap:5px}\n.sl-chip-id{display:flex;gap:12px;min-width:0}\n.sl-chip-id .fld{min-width:0}\n.sl-chip-id .fld.sec{flex:1}\n.sl-chip-id .fld.mid{flex:none;text-align:center}\n.sl-chip-eb{display:block;font-size:8px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);margin-bottom:1px}\n.sl-chip-id .val{display:block;font-weight:600;font-size:13px;line-height:1.25;white-space:nowrap}\n.sl-chip-id .fld.sec .val{overflow:hidden;text-overflow:ellipsis}\n.sl-chip-sub{display:flex;align-items:center;gap:6px;min-width:0}\n.sl-chip .cat{color:var(--sl-muted);font-size:10.5px;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-chip .amt{font-weight:700;font-variant-numeric:tabular-nums;flex:none;white-space:nowrap}\n.sl-chip-rail{display:flex;flex-direction:column;border-left:1px solid var(--sl-line)}\n.sl-chip .rm,.sl-chip .view{flex:1;min-height:26px;border-radius:0;display:flex;align-items:center;justify-content:center;\n color:var(--sl-muted);transition:color .15s,background .15s}\n.sl-chip .view{border-top:1px solid var(--sl-line)}\n.sl-chip .rm:hover,.sl-chip .rm:focus-visible{color:#e5484d;background:color-mix(in srgb,#e5484d 9%,transparent)}\n.sl-chip .view:hover,.sl-chip .view:focus-visible{color:var(--sl-text);background:color-mix(in srgb,var(--sl-accent) 10%,transparent)}\n.sl-chip .rm svg{width:11px;height:11px;stroke:currentColor;stroke-width:2.4;fill:none;stroke-linecap:round}\n.sl-chip .view svg{width:13px;height:13px;stroke:currentColor;stroke-width:1.8;fill:none}\n/* live-activity strip — narrates WS availability deltas (social proof + urgency).\n Hidden until a delta actually happens: a static \"seats update in real time\"\n banner is dead vertical space, a \"2 seats just taken\" flash is a signal. */\n.sl-live{display:none;align-items:center;gap:7px;margin:10px 14px 0;padding:7px 9px;flex:none;\n border:1px solid var(--sl-line);border-radius:8px;background:color-mix(in srgb,var(--sl-accent) 4%,var(--sl-surface));\n font-size:11px;color:var(--sl-muted)}\n.sl-live .dot{width:6px;height:6px;border-radius:999px;background:#22a06b;box-shadow:0 0 6px rgba(34,160,107,.75);flex:none}\n.sl-live span:last-child{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-live.on{display:flex;animation:slNoticeIn .38s cubic-bezier(.2,.8,.2,1) both}\n\n/* GA rows */\n.sl-ga{display:flex;align-items:center;gap:10px;padding:9px 11px;border:1px dashed var(--sl-line);border-radius:var(--sl-r-sm)}\n.sl-ga-info{flex:1;min-width:0}\n.sl-ga-name{font-weight:700;font-size:13px}\n.sl-ga-sub{font-size:11px;color:var(--sl-muted);margin-top:2px}\n.sl-ga-qty{display:flex;align-items:center;gap:8px}\n.sl-ga-qty button{width:26px;height:26px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n font-size:15px;font-weight:700;display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-ga-qty button:hover{border-color:var(--sl-muted)}\n.sl-ga-qty span{min-width:16px;text-align:center;font-weight:800;font-variant-numeric:tabular-nums}\n\n/* footer */\n.sl-foot{position:relative;z-index:2;padding:12px 16px 14px;border-top:1px solid var(--sl-line);flex:none;\n background:var(--sl-bg);box-shadow:0 -10px 24px -22px rgba(0,0,0,.72)}\n.sl-hold-note{display:none;align-items:center;gap:7px;margin-bottom:8px;padding:7px 8px;border-radius:var(--sl-r-sm);\n border:1px solid var(--sl-line);background:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-surface));\n box-shadow:inset 3px 0 0 color-mix(in srgb,var(--sl-accent) 72%,transparent);\n font-size:11.5px;line-height:1.35;color:var(--sl-muted)}\n.sl-hold-note.on{display:flex;animation:slNoticeIn .38s cubic-bezier(.2,.8,.2,1) both}\n.sl-hold-note svg{width:16px;height:16px;flex:none;stroke:var(--sl-accent);stroke-width:2.4;fill:none;\n stroke-linecap:round;stroke-linejoin:round}\n.sl-hold-note b{display:block;color:var(--sl-text);font-size:11.5px;white-space:nowrap}\n.sl-hold-copy{display:block;white-space:nowrap;font-size:10.5px}\n.sl-hold-note>span{flex:1;min-width:0}\n.sl-hold-change{flex:none;min-height:30px;padding:5px 8px;border-radius:8px;border:1px solid var(--sl-line);\n color:var(--sl-text);font-size:10.5px;font-weight:750;white-space:nowrap}\n.sl-hold-change:hover,.sl-hold-change:focus-visible{border-color:var(--sl-accent);color:var(--sl-accent)}\n.sl-hold-change:disabled{opacity:.58;cursor:wait}\n.sl-total{display:flex;justify-content:space-between;align-items:center;font-size:13px;margin-bottom:10px}\n.sl-total b{font-size:17px;font-variant-numeric:tabular-nums}\n.sl-value-pop{animation:slValuePop .32s cubic-bezier(.2,.8,.2,1)}\n/* Primary checkout CTA. Scoped under .sl-picker so it OUTWEIGHS the\n '.sl-picker button' reset (0,1,1) — an unscoped '.sl-cta' (0,1,0) loses to it\n and the button renders as plain text with no accent fill. */\n.sl-picker .sl-cta{display:flex;align-items:center;justify-content:center;width:100%;min-height:44px;\n padding:12px 16px;border-radius:var(--sl-r-sm);font-weight:800;font-size:14px;line-height:1.1;\n background:var(--sl-accent);color:var(--sl-accent-ink);\n transition:filter .15s,background .22s,color .22s,transform .12s,box-shadow .22s;gap:8px}\n.sl-picker .sl-cta:hover{filter:brightness(1.08)}\n.sl-picker .sl-cta:active{transform:translateY(1px);filter:brightness(.94)}\n.sl-picker .sl-cta.sl-ready{animation:slCtaReady .42s cubic-bezier(.2,.8,.2,1)}\n.sl-cta-spin,.sl-ba-spin{width:14px;height:14px;border-radius:50%;border:2px solid currentColor;border-right-color:transparent;\n animation:slspin .7s linear infinite;flex:none}\n/* Disabled (\"Select seats\"): quieter, but still a full-width button shape. */\n.sl-picker .sl-cta:disabled{background:var(--sl-surface);color:var(--sl-muted);opacity:1;\n cursor:not-allowed;filter:none;transform:none}\n\n/* Chrome anchor regions (Feature 6) — every persistent map overlay is APPENDED\n INTO one of these positioned flex containers and flows/stacks within it, so no\n two pieces of chrome free-float on top of each other. Regions never overlap:\n the top strip splits into left/center/right; rails + corners own their edge. */\n.sl-anchor{position:absolute;z-index:5;display:flex;gap:8px;pointer-events:none}\n.sl-anchor > *{pointer-events:auto}\n.sl-anchor[data-region=\"top-left\"]{top:12px;left:12px;flex-wrap:wrap;max-width:38%}\n.sl-anchor[data-region=\"top-center\"]{top:12px;left:50%;transform:translateX(-50%);flex-direction:column;\n align-items:center;max-width:44%}\n.sl-anchor[data-region=\"top-right\"]{top:12px;right:12px;justify-content:flex-end;flex-wrap:wrap;max-width:38%}\n.sl-anchor[data-region=\"left-rail\"]{top:50%;left:12px;transform:translateY(-50%);flex-direction:column;max-width:42%;gap:6px}\n.sl-anchor[data-region=\"bottom-left\"]{left:12px;bottom:12px;flex-direction:column;align-items:flex-start}\n.sl-anchor[data-region=\"bottom-center\"]{left:50%;bottom:14px;transform:translateX(-50%);z-index:9;\n flex-direction:column;align-items:center;gap:8px;max-width:92%}\n.sl-anchor[data-region=\"bottom-right\"]{right:12px;bottom:12px;flex-direction:column;align-items:flex-end;gap:6px}\n/* narrow: tighten the top strip so left/center can't crowd each other */\n.sl-picker[data-layout=\"narrow\"] .sl-anchor[data-region=\"top-left\"]{max-width:30%}\n.sl-picker[data-layout=\"narrow\"] .sl-anchor[data-region=\"top-center\"]{max-width:44%}\n\n/* TEST MODE badge — a small pill in the top-right region (shrinks on narrow) */\n.sl-testbadge{padding:5px 11px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.1em;\n text-transform:uppercase;white-space:nowrap;background:var(--sl-accent);color:var(--sl-accent-ink);\n box-shadow:0 2px 8px rgba(0,0,0,.25)}\n.sl-picker[data-layout=\"narrow\"] .sl-testbadge{padding:3px 8px;font-size:8.5px;letter-spacing:.06em}\n\n/* zoom column (flows within the bottom-right region) */\n.sl-zoom{display:flex;flex-direction:column;gap:6px}\n/* CSS-fallback full screen (iOS Safari has no element fullscreen API) */\n.sl-picker.sl-fs{position:fixed;inset:0;z-index:2147483000;width:auto;height:auto;max-height:none;border-radius:0}\n.sl-zoom button{width:36px;height:36px;border-radius:999px;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);font-size:17px;font-weight:700;display:flex;align-items:center;justify-content:center;transition:border-color .15s}\n.sl-zoom button:hover{border-color:var(--sl-muted)}\n.sl-zoom svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* toast + boot states (toast flows in the bottom-center region) */\n.sl-toast{transform:translateY(6px) scale(.98);max-width:100%;\n background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-text);border-radius:999px;padding:9px 16px;\n font-size:12.5px;font-weight:600;opacity:0;pointer-events:none;transition:opacity .22s,transform .22s;white-space:nowrap;\n overflow:hidden;text-overflow:ellipsis}\n.sl-toast.on{opacity:1;transform:translateY(0) scale(1)}\n.sl-toast.has-action{pointer-events:auto;display:flex;align-items:center;gap:12px;padding-right:8px}\n.sl-toast-action{min-height:30px;padding:5px 10px;border-radius:999px;background:var(--sl-accent);color:var(--sl-accent-ink);\n font:inherit;font-weight:800}\n.sl-toast[data-tone=\"error\"]{border-color:#ef4444}\n.sl-toast[data-tone=\"warning\"]{border-color:var(--sl-accent)}\n.sl-toast[data-tone=\"success\"]{border-color:#22c55e}\n.sl-toast.on[data-tone=\"error\"]{animation:slToastNudge .32s ease-out}\n.sl-boot{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;align-items:center;justify-content:center;\n gap:10px;background:var(--sl-bg);font-size:13px;font-weight:600;color:var(--sl-muted)}\n.sl-boot-spin{width:24px;height:24px;border-radius:50%;border:3px solid var(--sl-line);border-top-color:var(--sl-accent);\n animation:slspin .8s linear infinite}\n@keyframes slspin{to{transform:rotate(360deg)}}\n.sl-boot-title{font-weight:800;font-size:15px;color:var(--sl-text)}\n.sl-boot-retry{margin-top:4px;padding:9px 20px;border-radius:var(--sl-r-sm);background:var(--sl-accent);\n color:var(--sl-accent-ink);font-weight:700;font-size:13px}\n\n/* \"Need more time?\" extend prompt (flows in the bottom-center region, above the toast) */\n.sl-extend{transform:translateY(6px);\n display:none;align-items:center;gap:12px;max-width:100%;background:var(--sl-surface);border:1px solid var(--sl-line);\n color:var(--sl-text);border-radius:14px;padding:10px 12px 10px 16px;box-shadow:0 18px 50px -18px rgba(0,0,0,.6);\n opacity:0;transition:opacity .2s,transform .2s}\n.sl-extend.on{display:flex;opacity:1;transform:translateY(0)}\n.sl-extend-txt{font-size:12.5px;font-weight:600;line-height:1.35}\n.sl-extend-txt b{font-variant-numeric:tabular-nums}\n.sl-extend-btn{flex:none;padding:8px 14px;border-radius:999px;font-weight:800;font-size:12.5px;\n background:var(--sl-accent);color:var(--sl-accent-ink);transition:filter .15s,opacity .15s}\n.sl-extend-btn:hover{filter:brightness(1.08)}\n.sl-extend-btn:disabled{opacity:.5;cursor:not-allowed}\n\n/* booked confirmation overlay (covers the widget once the held seats are sold) */\n.sl-booked{position:absolute;inset:0;z-index:11;display:flex;flex-direction:column;align-items:center;\n justify-content:center;gap:12px;text-align:center;padding:28px;background:var(--sl-bg);opacity:0;visibility:hidden;\n pointer-events:none;transition:opacity .34s ease,visibility 0s linear .34s}\n.sl-booked.on{opacity:1;visibility:visible;pointer-events:auto;transition:opacity .34s ease,visibility 0s}\n.sl-booked-badge{width:60px;height:60px;border-radius:999px;display:flex;align-items:center;justify-content:center;\n background:var(--sl-accent);color:var(--sl-accent-ink);transform:scale(.72)}\n.sl-booked.on .sl-booked-badge{animation:slSuccessPop .58s cubic-bezier(.2,1.25,.3,1) .08s both}\n.sl-booked-badge svg{width:30px;height:30px;stroke:currentColor;stroke-width:2.6;fill:none;stroke-linecap:round;stroke-linejoin:round;\n stroke-dasharray:30;stroke-dashoffset:30}\n.sl-booked.on .sl-booked-badge svg{animation:slCheckDraw .42s ease-out .32s forwards}\n.sl-booked-title{font-weight:800;font-size:19px;color:var(--sl-text)}\n.sl-booked-sub{font-size:13px;color:var(--sl-muted);line-height:1.5;max-width:320px}\n.sl-booked-seats{font-weight:700;color:var(--sl-text)}\n.sl-booked.on .sl-booked-title,.sl-booked.on .sl-booked-sub{animation:slCopyRise .42s ease-out both}\n.sl-booked.on .sl-booked-title{animation-delay:.22s}\n.sl-booked.on .sl-booked-sub{animation-delay:.3s}\n\n/* sold-out overlay — every SEATED category's live availability is 0. Centered\n over the map; a stub (disabled) \"Join waitlist\" button, exactly like the page.\n Suppressed when GA areas exist (GA capacity isn't seat-counted). Clears live\n the moment WS frees a seat up. */\n.sl-soldout{position:absolute;inset:0;z-index:10;display:none;flex-direction:column;align-items:center;\n justify-content:center;text-align:center;gap:8px;padding:24px;\n background:color-mix(in srgb,var(--sl-bg) 82%,transparent);backdrop-filter:blur(4px)}\n.sl-soldout.on{display:flex}\n.sl-soldout-eyebrow{font-size:10px;letter-spacing:.2em;text-transform:uppercase;color:var(--sl-accent);font-weight:800}\n.sl-soldout-title{font-size:32px;font-weight:800;color:var(--sl-text);line-height:1.05}\n.sl-soldout-copy{max-width:360px;font-size:13px;color:var(--sl-muted);line-height:1.5}\n.sl-picker .sl-soldout-btn{margin-top:10px;min-height:40px;padding:10px 18px;border-radius:var(--sl-r-sm);\n background:var(--sl-surface);color:var(--sl-muted);border:1px solid var(--sl-line);font-weight:800;font-size:13px;\n cursor:not-allowed;opacity:.85}\n\n/* sales-closed pill (header) — persistent read-only state when the event's sales\n window is closed at load or closes live mid-session. Neutral (not accent) so it\n reads as \"unavailable\", distinct from the accent hold pill next to it. */\n.sl-closed-pill{display:none;align-items:center;gap:6px;padding:6px 12px;border-radius:999px;flex:none;\n background:color-mix(in srgb,var(--sl-text) 12%,var(--sl-surface));color:var(--sl-text);\n font-weight:700;font-size:12px;white-space:nowrap}\n.sl-closed-pill.on{display:inline-flex}\n.sl-closed-pill svg{width:13px;height:13px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* \"Powered by SeatLayer\" attribution badge (side-panel foot) — the canonical\n Layered Rows mark + wordmark. Hidden when the host opts out or the org's paid\n theme sets hideBadge. */\n.sl-powered{display:flex;align-items:center;justify-content:center;gap:6px;margin-top:10px;\n font-size:11px;letter-spacing:.03em;color:var(--sl-muted)}\n.sl-powered-mark{width:16px;height:16px;border-radius:4px;flex:none;display:flex;align-items:center;justify-content:center;\n background:#0c1220;color:#fcf7ee}\n.sl-powered-mark svg{width:12px;height:11px}\n\n/* a11y filter chips (flow within the top-left region) */\n.sl-chips{display:flex;gap:6px;flex-wrap:wrap}\n.sl-chip-f{display:inline-flex;align-items:center;gap:6px;padding:7px 12px;border-radius:999px;font-size:12px;font-weight:700;\n background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted);transition:color .15s,border-color .15s}\n.sl-chip-f:hover{color:var(--sl-text)}\n.sl-chip-f.on{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n\n/* confirm card: a candidate is not in the tray until Select. Map gestures and\n floating chrome pause while the card owns focus, keeping the camera stable. */\n.sl-picker[data-confirming=\"true\"] .sl-map-host>:not(.sl-confirm){pointer-events:none}\n.sl-picker[data-confirming=\"true\"] .sl-anchor{pointer-events:none;opacity:.28;transition:opacity .16s}\n.sl-picker[data-confirming=\"true\"] .sl-side{pointer-events:none;opacity:.58;transition:opacity .16s}\n.sl-confirm{position:absolute;z-index:10;width:276px;max-width:calc(100% - 24px);overflow:hidden;pointer-events:auto;\n background:var(--sl-surface);border:1px solid color-mix(in srgb,var(--sl-line) 70%,var(--sl-text));\n border-radius:15px;box-shadow:0 24px 64px -18px rgba(0,0,0,.72);transform:translate(-50%,calc(-100% - 16px));\n animation:slConfirmIn .24s cubic-bezier(.2,.8,.2,1) both}\n.sl-confirm[data-placement=\"below\"]{transform:translate(-50%,16px);animation:slConfirmBelowIn .24s cubic-bezier(.2,.8,.2,1) both}\n.sl-confirm-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(52px,auto) minmax(52px,auto);border-bottom:1px solid var(--sl-line)}\n.sl-confirm-field{min-width:0;padding:12px 11px 10px;border-right:1px solid var(--sl-line)}\n.sl-confirm-field:last-child{border-right:0;text-align:center}\n.sl-confirm-field:nth-child(2){text-align:center}\n.sl-confirm-key{display:block;font-size:8.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-confirm-value{display:block;margin-top:4px;color:var(--sl-text);font-size:17px;line-height:1.1;font-weight:850;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n/* Long venue section names must read in full: smaller type + up to two lines\n beats an ellipsis at identity-confirmation time. Row/seat stay big — they're\n short and they're what the buyer double-checks against the map. */\n.sl-confirm-field:first-child .sl-confirm-value{font-size:13.5px;line-height:1.25;white-space:normal;\n display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}\n.sl-confirm-cat{display:flex;align-items:center;gap:8px;padding:10px 12px;background:color-mix(in srgb,var(--sl-cat) 76%,var(--sl-surface))}\n.sl-confirm-cat .sl-dot{border:2px solid rgba(255,255,255,.78);width:11px;height:11px}\n.sl-confirm-cat-name{font-size:13.5px;font-weight:800;color:#fff;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-confirm-price{font-size:17px;font-weight:850;color:#fff;font-variant-numeric:tabular-nums}\n.sl-confirm-body{padding:11px 12px 12px}\n.sl-confirm-row{display:flex;gap:8px;margin-top:10px}\n.sl-confirm-row button{flex:1;min-height:44px;padding:9px 12px;border-radius:9px;font-weight:800;font-size:13px}\n.sl-confirm-add{background:var(--sl-accent)!important;color:var(--sl-accent-ink)!important;display:flex;align-items:center;justify-content:center;gap:7px}\n.sl-confirm-add svg{width:16px;height:16px;stroke:currentColor;stroke-width:2.8;fill:none;stroke-linecap:round;stroke-linejoin:round}\n.sl-confirm-cancel{background:color-mix(in srgb,var(--sl-line) 44%,transparent)!important;border:1px solid var(--sl-line)!important;color:var(--sl-muted)!important}\n.sl-confirm-cancel:hover{color:var(--sl-text)}\n.sl-picker[data-layout=\"narrow\"] .sl-confirm{left:50%!important;top:auto!important;bottom:14px;width:min(342px,calc(100% - 24px));\n transform:translateX(-50%);animation:slConfirmMobileIn .24s cubic-bezier(.2,.8,.2,1) both}\n\n/* Atomic whole/variable-table chooser. Lives inside the widget so the same\n accessible dialog works in inline, modal, desktop and 390px mobile hosts. */\n.sl-table-scrim{position:absolute;inset:0;z-index:45;display:flex;align-items:center;justify-content:center;padding:18px;\n background:color-mix(in srgb,var(--sl-bg) 66%,transparent);backdrop-filter:blur(3px)}\n.sl-table-dialog{width:min(408px,100%);max-height:calc(100% - 24px);overflow:auto;border:1px solid var(--sl-line);\n border-radius:calc(var(--sl-radius) * 1.15);background:var(--sl-surface);box-shadow:0 28px 70px rgba(0,0,0,.42)}\n.sl-table-head{padding:18px 18px 14px;border-bottom:1px solid var(--sl-line)}\n.sl-table-eyebrow{font-size:10px;letter-spacing:.12em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-table-title{margin-top:5px;font-size:22px;line-height:1.15;font-weight:850}\n.sl-table-copy{margin-top:7px;color:var(--sl-muted);font-size:13px;line-height:1.45}\n.sl-table-body{padding:16px 18px 18px}\n.sl-table-summary{display:grid;grid-template-columns:1fr auto;gap:8px 16px;padding:12px;border:1px solid var(--sl-line);\n border-radius:var(--sl-r-sm);background:color-mix(in srgb,var(--sl-line) 22%,transparent);font-size:13px}\n.sl-table-summary b{font-size:15px}.sl-table-summary .muted{color:var(--sl-muted)}\n.sl-table-qtylabel{display:block;margin:16px 0 8px;font-size:12px;font-weight:800}\n.sl-table-stepper{display:grid;grid-template-columns:48px 1fr 48px;align-items:center;border:1px solid var(--sl-line);\n border-radius:12px;overflow:hidden;background:var(--sl-bg)}\n.sl-table-stepper button{height:48px;font-size:24px;font-weight:700;background:color-mix(in srgb,var(--sl-line) 34%,transparent)!important}\n.sl-table-stepper button:disabled{opacity:.38;cursor:not-allowed}\n.sl-table-stepper output{text-align:center;font-size:19px;font-weight:850;font-variant-numeric:tabular-nums}\n.sl-table-range{margin-top:7px;color:var(--sl-muted);font-size:11px;text-align:center}\n.sl-table-actions{display:flex;gap:9px;margin-top:17px}.sl-table-actions button{flex:1;min-height:46px;border-radius:10px;font-weight:800}\n.sl-table-cancel{border:1px solid var(--sl-line)!important;color:var(--sl-muted)!important}\n.sl-table-confirm{background:var(--sl-accent)!important;color:var(--sl-accent-ink)!important}\n.sl-table-confirm:disabled{opacity:.62;cursor:wait}\n.sl-table-edit{margin-left:4px;padding:2px 7px!important;border:1px solid var(--sl-line)!important;border-radius:999px!important;\n color:var(--sl-muted)!important;font-size:10px!important;font-weight:800!important}\n.sl-picker[data-layout=\"narrow\"] .sl-table-scrim{align-items:flex-end;padding:0;background:rgba(5,7,12,.58)}\n.sl-picker[data-layout=\"narrow\"] .sl-table-dialog{width:100%;max-height:min(78%,620px);border-radius:18px 18px 0 0;border-width:1px 0 0}\n.sl-picker[data-layout=\"narrow\"] .sl-table-head{padding-top:22px}.sl-picker[data-layout=\"narrow\"] .sl-table-body{padding-bottom:max(20px,env(safe-area-inset-bottom))}\n\n/* hover preview — a COMPACT echo of the confirm card (deliberately smaller: it's\n a passing preview on hover, not the click/select action surface). Reuses the\n Section·Row·Seat identity grid so hover, confirm and the cart chip all share\n one visual language, just at three sizes. */\n.sl-tip{position:absolute;z-index:7;pointer-events:none;display:none;width:190px;overflow:hidden;\n background:var(--sl-surface);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:11px;\n box-shadow:0 12px 30px -14px rgba(0,0,0,.6)}\n.sl-tip-grid{display:grid;grid-template-columns:1.3fr .85fr .85fr;border-bottom:1px solid var(--sl-line)}\n.sl-tip-grid.one{grid-template-columns:1fr}\n.sl-tip-field{min-width:0;padding:6px 9px;border-right:1px solid var(--sl-line)}\n.sl-tip-field:last-child{border-right:0;text-align:center}\n.sl-tip-grid:not(.one) .sl-tip-field:nth-child(2){text-align:center}\n.sl-tip-key{display:block;font-size:7.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--sl-muted);font-weight:800}\n.sl-tip-val{display:block;margin-top:2px;color:var(--sl-text);font-size:13px;line-height:1.1;font-weight:750;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-tip-cat{display:flex;align-items:center;gap:7px;padding:6px 10px;font-size:11px;\n background:color-mix(in srgb,var(--sl-cat) 12%,var(--sl-surface))}\n.sl-tip-dot{width:8px;height:8px;border-radius:50%;flex:none}\n.sl-tip-name{color:var(--sl-muted);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-tip-amt{margin-left:auto;font-weight:800;color:var(--sl-text);font-variant-numeric:tabular-nums;font-size:12px}\n.sl-tip-status{padding:5px 10px 7px;font-size:8.5px;letter-spacing:.09em;text-transform:uppercase;font-weight:700;color:var(--sl-muted)}\n\n/* Best available is a first-class shortcut, not an anonymous utility row. */\n.sl-ba{position:relative;flex:none;overflow:hidden;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:7px;\n padding:13px;border:1px solid color-mix(in srgb,var(--sl-accent) 34%,var(--sl-line));border-radius:13px;\n background:linear-gradient(135deg,color-mix(in srgb,var(--sl-accent) 5%,var(--sl-surface)),color-mix(in srgb,var(--sl-accent) 11%,var(--sl-surface)))}\n.sl-ba::after{content:'✦';position:absolute;right:10px;top:3px;color:color-mix(in srgb,var(--sl-accent) 20%,transparent);font-size:42px;line-height:1}\n.sl-ba-title,.sl-ba-copy,.sl-ba select,.sl-ba-qty,.sl-ba-go{position:relative;z-index:1}\n.sl-ba-title{grid-column:1/-1;display:flex;align-items:center;gap:7px;font-size:13px;font-weight:850}\n.sl-ba-title .spark{color:var(--sl-accent);font-size:16px}\n.sl-ba-copy{grid-column:1/-1;margin:-4px 0 2px 23px;color:var(--sl-muted);font-size:10.5px;line-height:1.35}\n.sl-ba-copy .narrow{display:none}\n/* \"★ Best seats\" premium quick-pick — gold accent echoing the ★ Premium pill on\n the confirm popover; deliberately distinct from the accent-toned qty/go. */\n.sl-ba-premium{position:relative;z-index:1;grid-column:1/-1;justify-self:start;display:inline-flex;align-items:center;gap:6px;\n padding:6px 12px;border-radius:999px;font-size:11px;font-weight:800;letter-spacing:.02em;cursor:pointer;\n color:#c9a24b;background:color-mix(in srgb,#e8c15a 10%,var(--sl-surface));\n border:1px solid color-mix(in srgb,#e8c15a 34%,var(--sl-line));transition:filter .15s,background .15s,color .15s}\n.sl-ba-premium .star{font-size:12px;line-height:1;color:#e8c15a}\n.sl-ba-premium:hover{filter:brightness(1.05)}\n.sl-ba-premium.on{color:#1c1608;background:linear-gradient(135deg,#f0cf6b,#e0b23f);border-color:transparent;\n box-shadow:0 6px 16px color-mix(in srgb,#e8c15a 26%,transparent)}\n.sl-ba-premium.on .star{color:#5a4410}\n.sl-ba select{background:var(--sl-surface);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:8px;\n font:inherit;font-size:11px;padding:7px 8px;min-width:0;width:100%;max-width:none}\n.sl-ba-qty{display:flex;align-items:center;gap:7px;padding:3px;border:1px solid var(--sl-line);border-radius:9px;background:var(--sl-surface)}\n.sl-ba-qty button{width:25px;height:25px;border-radius:7px;background:color-mix(in srgb,var(--sl-line) 35%,transparent);border:0;\n font-size:14px;font-weight:800;display:flex;align-items:center;justify-content:center}\n.sl-ba-qty span{min-width:14px;text-align:center;font-weight:800}\n.sl-picker .sl-ba-go{grid-column:1/-1;width:100%;min-height:37px;padding:7px 12px;border-radius:9px;background:var(--sl-accent);\n color:var(--sl-accent-ink);font-weight:800;font-size:12px;transition:filter .15s,opacity .15s;display:flex;align-items:center;justify-content:center;gap:6px;\n box-shadow:0 8px 18px color-mix(in srgb,var(--sl-accent) 18%,transparent)}\n.sl-picker .sl-ba-go:hover{filter:brightness(1.06)}\n.sl-picker .sl-ba-go:disabled{opacity:.62;cursor:wait}\n.sl-ba-replace{grid-column:1/-1;padding:3px 0 1px}\n.sl-ba-replace b{display:block;font-size:12.5px}\n.sl-ba-replace span{display:block;margin-top:3px;color:var(--sl-muted);font-size:10.5px;line-height:1.35}\n.sl-ba-actions{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;gap:7px}\n.sl-ba-actions button{min-height:36px;border-radius:9px;border:1px solid var(--sl-line);font-size:11.5px;font-weight:800}\n.sl-ba-actions .replace{border-color:var(--sl-accent);background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-picker[data-layout=\"narrow\"] .sl-ba{padding:11px}\n.sl-picker[data-layout=\"narrow\"] .sl-ba-copy .wide{display:none}\n.sl-picker[data-layout=\"narrow\"] .sl-ba-copy .narrow{display:inline}\n.sl-picker[data-layout=\"narrow\"] .sl-ba select{min-height:44px}\n\n/* screen-reader live region */\n.sl-sr{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n\n/* per-seat ticket-tier select + view-from-seat button in tray chips */\n.sl-chip .tier{background:var(--sl-bg);color:var(--sl-text);border:1px solid var(--sl-line);border-radius:6px;\n font:inherit;font-size:10px;padding:2px 4px;min-width:0;max-width:100%;cursor:pointer}\n\n/* arena: LOD rung pills (flow within the top-center region) */\n.sl-rungs{display:none;background:var(--sl-surface);border:1px solid var(--sl-line);border-radius:999px;padding:3px}\n.sl-rungs.on{display:inline-flex;gap:2px}\n.sl-rungs button{padding:6px 13px;border-radius:999px;font-size:10.5px;font-weight:800;letter-spacing:.07em;\n color:var(--sl-muted);white-space:nowrap;transition:color .15s}\n.sl-rungs button:hover{color:var(--sl-text)}\n.sl-rungs button.on{background:var(--sl-accent);color:var(--sl-accent-ink)}\n/* narrow: shrink the rung pills so the centered row can't reach the corner regions */\n.sl-picker[data-layout=\"narrow\"] .sl-rungs button{padding:5px 9px;font-size:9px;letter-spacing:.03em}\n\n/* Projection is deliberately a separate control from zoom/LOD. Perspective\n changes geometry; the two choices stay explicit and keyboard-native. */\n.sl-projection{display:inline-flex;align-items:center;gap:2px;padding:3px;border-radius:999px;\n background:var(--sl-surface);border:1px solid var(--sl-line);box-shadow:0 8px 24px -16px rgba(0,0,0,.65)}\n.sl-projection button{min-width:42px;min-height:30px;padding:5px 10px;border-radius:999px;color:var(--sl-muted);\n font-size:10px;font-weight:800;letter-spacing:.04em;white-space:nowrap}\n.sl-projection button:hover,.sl-projection button:focus-visible{color:var(--sl-text)}\n.sl-projection button.on{background:var(--sl-accent);color:var(--sl-accent-ink)}\n.sl-picker[data-layout=\"narrow\"] .sl-projection button{min-width:38px;min-height:32px;padding:5px 8px;font-size:9.5px}\n\n/* 3D venue overlay — mounts over the (paused) Konva stage inside the map host.\n Carries its own gradient so it paints instantly before the scene builds, and\n cross-fades on enter/exit via a compositor-only opacity transition. Sits below\n the anchored chrome (z-index:5) and the confirm card (z-index:10) so the\n Map|3D toggle and the seat confirm both stay usable over it. */\n.sl-view3d{position:absolute;inset:0;z-index:4;opacity:0;touch-action:none;\n transition:opacity .3s ease;background:radial-gradient(120% 120% at 50% 0%,#191f28 0%,#0d1014 70%)}\n.sl-view3d canvas{display:block;width:100%;height:100%}\n[data-view3d=on] .sl-chips,[data-view3d=on] .sl-rungs{display:none}\n.sl-view3d-back{position:absolute;top:12px;left:12px;z-index:2;display:inline-flex;align-items:center;gap:6px;\n padding:7px 13px 7px 9px;border-radius:999px;font-size:11px;font-weight:800;letter-spacing:.03em;\n color:#e6edf3;background:rgba(10,14,20,.62);border:1px solid rgba(255,255,255,.22);backdrop-filter:blur(6px)}\n.sl-view3d-back:hover,.sl-view3d-back:focus-visible{background:rgba(16,22,30,.82);border-color:rgba(255,255,255,.4)}\n.sl-view3d-back svg{width:15px;height:15px;stroke:currentColor;stroke-width:2.4;fill:none;stroke-linecap:round;stroke-linejoin:round}\n/* Venue navigation inside 3D: levels (isolate a floor) and areas (fly to a zone).\n Bottom-LEFT, clear of the module's own chips (Overview bottom-right, 360\n bottom-centre) and of the bottom-sheeted confirm card. Horizontally scrollable\n so a venue with many zones never pushes the rail off a phone screen. */\n.sl-view3d-nav{position:absolute;left:12px;bottom:16px;z-index:3;display:flex;flex-direction:column;gap:6px;\n max-width:calc(100% - 24px);pointer-events:none}\n.sl-view3d-nav > div{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;pointer-events:auto;\n padding:1px;-webkit-overflow-scrolling:touch}\n.sl-view3d-nav > div::-webkit-scrollbar{display:none}\n.sl-view3d-nav button{flex:0 0 auto;min-height:32px;padding:7px 12px;border-radius:999px;white-space:nowrap;\n font-size:11.5px;font-weight:700;color:#c9d4ea;background:rgba(12,18,32,.72);\n border:1px solid rgba(150,165,205,.35);backdrop-filter:blur(6px);cursor:pointer}\n.sl-view3d-nav button:hover,.sl-view3d-nav button:focus-visible{color:#eef1f8;border-color:rgba(190,205,240,.6)}\n.sl-view3d-nav button[aria-pressed=\"true\"]{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n/* While immersed, the 2D-only chrome is meaningless — hide it, keep Map|3D. */\n.sl-picker[data-view3d=\"on\"] .sl-rungs,\n.sl-picker[data-view3d=\"on\"] .sl-floors,\n.sl-picker[data-view3d=\"on\"] .sl-zoom,\n.sl-picker[data-view3d=\"on\"] .sl-seccard,\n.sl-picker[data-view3d=\"on\"] .sl-minimap{display:none!important}\n/* The confirm card bottom-sheets over 3D (no 2D screen anchor to track). */\n.sl-picker[data-view3d=\"on\"] .sl-confirm{left:50%!important;top:auto!important;bottom:16px;\n transform:translateX(-50%);width:min(342px,calc(100% - 24px))}\n.sl-picker[data-view3d=\"on\"] .sl-confirm[data-placement]{transform:translateX(-50%)}\n\n/* Plain \"View from here\" action shown when no real photo exists (the synthetic\n thumb is suppressed at card size — full-screen is where it earns its keep). */\n.sl-confirm-viewbtn{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n display:flex;align-items:center;justify-content:center;gap:7px;font-size:12px;font-weight:800;\n color:var(--sl-text);background:transparent;transition:border-color .15s,background .15s}\n.sl-confirm-viewbtn:hover,.sl-confirm-viewbtn:focus-visible{border-color:var(--sl-accent);background:color-mix(in srgb,var(--sl-accent) 10%,transparent)}\n/* confirm-card \"See it in 3D\" / \"View from this seat\" action — the purchase-\n moment bridge into the cinematic. Styled like the view-from-seat button. */\n.sl-confirm-3d{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n display:flex;align-items:center;justify-content:center;gap:7px;font-size:12px;font-weight:800;\n color:var(--sl-text);background:color-mix(in srgb,var(--sl-accent) 12%,transparent);transition:border-color .15s,background .15s}\n.sl-confirm-3d:hover,.sl-confirm-3d:focus-visible{border-color:var(--sl-accent);background:color-mix(in srgb,var(--sl-accent) 20%,transparent)}\n.sl-confirm-3d svg{width:15px;height:15px;stroke:currentColor;stroke-width:1.9;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* multi-floor switcher (flows within the left-rail region) */\n.sl-floors{display:none;flex-direction:column;gap:6px;max-width:100%}\n.sl-floors.on{display:flex}\n.sl-floors button{padding:7px 13px;border-radius:999px;font-size:12px;font-weight:700;background:var(--sl-surface);\n border:1px solid var(--sl-line);color:var(--sl-muted);white-space:nowrap;max-width:100%;overflow:hidden;\n text-overflow:ellipsis;transition:color .15s,border-color .15s}\n.sl-floors button:hover{color:var(--sl-text)}\n.sl-floors button.on{background:var(--sl-accent);color:var(--sl-accent-ink);border-color:transparent}\n\n/* tapped-section summary card — docks INSIDE the top-center anchor region on\n wide (flows below the rung pills, never over them, never floating over the\n seats at the tap point). Auto-collapses to a slim pill once seat-picking\n begins (first seat select, or a pan/zoom after the focus glide); tapping the\n pill re-expands; ✕ closes in both states. On narrow it renders as a compact\n strip inside the bottom sheet's peek head — never over the canvas. */\n.sl-seccard{width:250px;max-width:100%;background:var(--sl-surface);border:1px solid var(--sl-line);border-radius:12px;\n padding:12px 14px;box-shadow:0 18px 50px -18px rgba(0,0,0,.6);display:none}\n.sl-seccard.on{display:block}\n/* collapsed pill (wide) */\n.sl-seccard.mini{width:auto;padding:5px 7px 5px 12px;border-radius:999px;cursor:pointer}\n.sl-seccard.mini.on{display:inline-flex;align-items:center;gap:7px}\n.sl-seccard.mini .sl-seccard-name{font-size:12px;flex:none;max-width:120px}\n.sl-seccard.mini .sl-seccard-left{font-size:11px}\n/* narrow: compact strip inside the sheet head (peek area) */\n.sl-seccard.strip{width:100%;padding:7px 0 0;border:0;border-radius:0;box-shadow:none;background:none;cursor:default}\n.sl-seccard.strip.on{display:flex;align-items:center;gap:7px;font-size:12.5px}\n.sl-seccard.strip .sl-seccard-name{font-size:12.5px}\n.sl-seccard.strip .sl-seccard-price{margin-left:auto}\n.sl-seccard-head{display:flex;align-items:center;gap:8px}\n.sl-seccard-dot{width:10px;height:10px;border-radius:50%;flex:none}\n.sl-seccard-name{font-weight:800;font-size:14px;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.sl-seccard-price{font-weight:800;font-size:12.5px;font-variant-numeric:tabular-nums}\n.sl-seccard-x{width:22px;height:22px;border-radius:999px;flex:none;display:flex;align-items:center;justify-content:center;\n color:var(--sl-muted);font-size:12px}\n.sl-seccard-x:hover{color:var(--sl-text)}\n.sl-seccard-zone{font-size:11.5px;color:var(--sl-muted);margin-top:6px}\n.sl-seccard-left{color:var(--sl-text);font-weight:700}\n.sl-seccard-mix{display:flex;flex-wrap:wrap;gap:6px 10px;margin-top:8px}\n.sl-seccard-mix-item{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;color:var(--sl-muted)}\n.sl-seccard-mix-dot{width:8px;height:8px;border-radius:50%;flex:none}\n.sl-seccard-mix-price{font-weight:700;color:var(--sl-text)}\n.sl-seccard-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:10px}\n.sl-seccard-overview{font-size:12px;font-weight:800;color:var(--sl-accent)}\n.sl-seccard-hint{font-size:10.5px;color:var(--sl-muted)}\n\n/* view-from-seat button on the confirm popover */\n/* Eager sightline preview inside the confirm card */\n.sl-confirm-thumbwrap{position:relative;display:block;width:100%;height:74px;margin:0 0 8px;padding:0!important;\n border-radius:9px;overflow:hidden;border:1px solid var(--sl-line);cursor:pointer}\n.sl-confirm-thumb{display:block;width:100%;height:100%;object-fit:cover}\n.sl-confirm-thumb-badge{position:absolute;right:7px;top:7px;display:inline-flex;align-items:center;gap:5px;\n font-size:10px;font-weight:700;color:#fff;background:rgba(10,14,22,0.72);border-radius:12px;padding:4px 9px;backdrop-filter:blur(3px)}\n.sl-confirm-sight{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--sl-muted);margin-bottom:2px}\n.sl-confirm-sight span{color:#22a06b;font-weight:800}\n.sl-confirm-view{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid var(--sl-line);\n color:var(--sl-text);font-weight:700;font-size:12px;display:flex;align-items:center;justify-content:center;gap:7px}\n.sl-confirm-view:hover{border-color:var(--sl-muted)}\n.sl-confirm-view svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round;stroke-linejoin:round}\n\n/* commercial seat flags — limited-view caution + premium tag. Amber tone,\n deliberately distinct from the red taken/held state; shown on the confirm\n card, echoed as a small ◐ marker on cart chips and the hover tip. */\n.sl-cx{display:flex;flex-direction:column;gap:6px;margin-bottom:10px}\n.sl-cx-warn{display:flex;align-items:flex-start;gap:7px;padding:8px 10px;border-radius:9px;\n background:color-mix(in srgb,#f4b740 13%,var(--sl-surface));border:1px solid color-mix(in srgb,#f4b740 40%,var(--sl-line));\n animation:slNoticeIn .28s ease both}\n.sl-cx-glyph{flex:none;font-size:14px;line-height:1.2;color:#f4b740}\n.sl-cx-txt{min-width:0;display:flex;flex-direction:column;gap:2px}\n.sl-cx-txt b{font-size:12px;font-weight:800;color:var(--sl-text)}\n.sl-cx-note{font-size:11px;line-height:1.4;color:var(--sl-muted)}\n.sl-cx-premium{display:inline-flex;align-items:center;gap:6px;align-self:flex-start;padding:4px 10px;border-radius:999px;\n font-size:11px;font-weight:800;letter-spacing:.02em;color:#c9a24b;\n background:color-mix(in srgb,#e8c15a 13%,var(--sl-surface));border:1px solid color-mix(in srgb,#e8c15a 38%,var(--sl-line))}\n.sl-cx-star{font-size:12px;line-height:1;color:#e8c15a}\n.sl-cx-mark{flex:none;font-size:12px;line-height:1;color:#f4b740;cursor:help}\n.sl-tip-cx{display:flex;align-items:center;gap:6px;padding:5px 10px 7px;font-size:10.5px;font-weight:700;color:#e8b24a}\n.sl-tip-cx .g{font-size:12px}\n\n/* 360° seat-view modal (fills the widget; drag-to-look-around equirectangular) */\n.sl-view{position:absolute;inset:0;z-index:12;display:flex;flex-direction:column;background:var(--sl-bg)}\n.sl-view-head{display:flex;align-items:center;gap:8px;padding:12px 16px;border-bottom:1px solid var(--sl-line);flex:none}\n.sl-view-title{font-weight:800;font-size:15px}\n.sl-view-cap{font-size:11px;color:var(--sl-muted)}\n.sl-view-x{margin-left:auto;width:32px;height:32px;border-radius:999px;border:1px solid var(--sl-line);color:var(--sl-muted);\n flex:none;display:flex;align-items:center;justify-content:center;transition:color .15s,border-color .15s}\n.sl-view-x:hover{color:var(--sl-text);border-color:var(--sl-muted)}\n.sl-view-x svg{width:14px;height:14px;stroke:currentColor;stroke-width:2;fill:none;stroke-linecap:round}\n.sl-view-pano{position:relative;flex:1;min-height:0;overflow:hidden;cursor:grab;background-color:#05070c;\n background-repeat:repeat-x;touch-action:none;user-select:none}\n.sl-view-pano.drag{cursor:grabbing}\n.sl-view-badge{position:absolute;top:12px;left:12px;padding:5px 11px;border-radius:999px;font-size:10px;font-weight:800;\n letter-spacing:.08em;background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted)}\n.sl-view-hint{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);padding:6px 14px;border-radius:999px;\n font-size:11.5px;font-weight:600;background:var(--sl-surface);border:1px solid var(--sl-line);color:var(--sl-muted);\n white-space:nowrap;pointer-events:none;max-width:90%;overflow:hidden;text-overflow:ellipsis}\n\n/* F3 minimap — venue overview + live viewport rect (flows in the bottom-left region) */\n.sl-minimap{border:1px solid var(--sl-line);border-radius:9px;\n overflow:hidden;background:var(--sl-surface);box-shadow:0 12px 34px -14px rgba(0,0,0,.55);line-height:0;cursor:pointer}\n.sl-minimap canvas{display:block}\n.sl-picker[data-layout=\"narrow\"] .sl-minimap{display:none}\n\n/* F4 legend reflection: rows + counts for out-of-band categories read muted */\n.sl-price-row.sl-dim{opacity:.4}\n.sl-seccard-mix-item.sl-dim{opacity:.4}\n\n/* Buyer-journey motion: every animation explains a state transition (selected,\n held, checkout handoff, conflict or booked). No decorative infinite motion\n except the expiring-hold pulse and active progress spinners. */\n@keyframes slPillIn{from{opacity:0;transform:translateX(7px) scale(.9)}to{opacity:1;transform:translateX(0) scale(1)}}\n@keyframes slHoldPulse{0%{box-shadow:0 0 0 0 currentColor;opacity:.9}75%,100%{box-shadow:0 0 0 7px transparent;opacity:.55}}\n@keyframes slChipIn{from{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}\n@keyframes slChipOut{to{opacity:0;transform:translateX(10px) scale(.98)}}\n@keyframes slNoticeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}\n@keyframes slValuePop{0%{opacity:.6;transform:translateY(3px)}55%{transform:translateY(-1px) scale(1.05)}100%{opacity:1;transform:none}}\n@keyframes slCtaReady{0%{transform:scale(.98);box-shadow:0 0 0 0 transparent}55%{transform:scale(1.01);box-shadow:0 0 0 5px color-mix(in srgb,var(--sl-accent) 18%,transparent)}100%{transform:none;box-shadow:none}}\n@keyframes slToastNudge{0%,100%{margin-left:0}30%{margin-left:-4px}60%{margin-left:3px}}\n@keyframes slSuccessPop{0%{opacity:0;transform:scale(.72)}65%{opacity:1;transform:scale(1.08)}100%{opacity:1;transform:scale(1)}}\n@keyframes slCheckDraw{to{stroke-dashoffset:0}}\n@keyframes slCopyRise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\n@keyframes slConfirmIn{from{opacity:0;transform:translate(-50%,calc(-100% - 8px)) scale(.96)}to{opacity:1;transform:translate(-50%,calc(-100% - 14px)) scale(1)}}\n@keyframes slConfirmBelowIn{from{opacity:0;transform:translate(-50%,8px) scale(.96)}to{opacity:1;transform:translate(-50%,16px) scale(1)}}\n@keyframes slConfirmMobileIn{from{opacity:0;transform:translate(-50%,10px) scale(.97)}to{opacity:1;transform:translate(-50%,0) scale(1)}}\n\n/* Access state (channels): the panel fades AND rises at --slm-mo-base. It never\n covers the map — inventory is cross-faded to neutral by the canvas in one\n batched pass, so nothing blinks away underneath it. */\n.sl-access{position:absolute;left:50%;bottom:18px;z-index:9;transform:translateX(-50%);\n max-width:min(420px,calc(100% - 24px));display:flex;gap:12px;align-items:flex-start;\n padding:12px 14px;border-radius:var(--sl-r-sm);background:var(--sl-panel,#151b2c);color:var(--sl-text);\n border:1px solid var(--sl-line);box-shadow:0 18px 44px -18px rgba(0,0,0,.6);\n animation:slAccessIn var(--slm-mo-base) var(--slm-mo-out) both}\n.sl-access-title{font-weight:700;font-size:13px}\n.sl-access-body{font-size:12px;line-height:1.5;opacity:.82;margin-top:2px}\n.sl-access-act{margin-top:8px;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:700;\n background:var(--sl-accent);color:var(--sl-accent-ink)}\n@keyframes slAccessIn{from{opacity:0;transform:translate(-50%,10px)}to{opacity:1;transform:translate(-50%,0)}}\n\n@media(prefers-reduced-motion:reduce){\n .sl-picker *,.sl-modal-scrim *{animation-duration:.001ms!important;animation-iteration-count:1!important;\n transition-duration:.001ms!important;scroll-behavior:auto!important}\n .sl-access{animation:none;opacity:1;transform:translate(-50%,0)}\n}\n.sl-ba [data-ba-zone]{grid-column:1/-1;width:100%}\n\n/* modal host */\n.sl-modal-scrim{position:fixed;inset:0;z-index:2147483000;background:rgba(5,7,12,.66);display:flex;align-items:center;justify-content:center;padding:18px}\n.sl-modal-frame{width:min(1200px,100%);height:min(820px,100%);border-radius:16px;overflow:hidden;box-shadow:0 40px 120px -30px rgba(0,0,0,.8)}\n@media(max-width:640px){.sl-modal-scrim{padding:0}.sl-modal-frame{width:100%;height:100%;border-radius:0}}\n`;\n\nfunction ensureStyle(): void {\n if (document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = CSS;\n document.head.appendChild(el);\n}\n\n/** Merge order: defaults ← org chart theme ← host overrides. */\nfunction resolveTokens(chart: ChartTheme | undefined, host: SeatPickerTheme | undefined): Record<string, string> {\n const accent = host?.accent ?? chart?.accent ?? '#f4b740';\n const accentInk = host?.accentInk ?? chart?.accentInk ?? '#1a1200';\n return {\n '--sl-accent': accent,\n '--sl-accent-ink': accentInk,\n '--sl-bg': host?.background ?? chart?.background ?? '#0f1522',\n '--sl-surface': host?.surface ?? '#1a2234',\n '--sl-text': host?.text ?? chart?.textColor ?? '#eef1f8',\n '--sl-muted': host?.muted ?? '#8b93a7',\n '--sl-line': host?.line ?? 'rgba(139,147,167,.22)',\n '--sl-font': host?.fontFamily ?? chart?.fontFamily ?? \"-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif\",\n '--sl-radius': `${host?.radius ?? 14}px`,\n };\n}\n\n/**\n * Colorblind-safe preference is a SHARED buyer preference across every SeatLayer\n * surface (the bespoke public page persists it too), so the widget reads/writes\n * the SAME localStorage key. All access is guarded — private-mode/SSR safe.\n */\nconst CB_STORAGE_KEY = 'seatmap.a11y.cb';\nfunction readStoredColorblind(): boolean | null {\n try {\n if (typeof window === 'undefined') return null;\n const raw = window.localStorage.getItem(CB_STORAGE_KEY);\n return raw == null ? null : raw === '1';\n } catch {\n return null;\n }\n}\nfunction writeStoredColorblind(on: boolean): void {\n try {\n window.localStorage.setItem(CB_STORAGE_KEY, on ? '1' : '0');\n } catch {\n /* private mode / storage disabled — preference is best-effort */\n }\n}\n\nexport class SeatPicker {\n private readonly opts: SeatPickerOptions;\n private readonly api: PickerTransport;\n /** Our own public client, or null when the host injected a transport. */\n private readonly pubApi: PubApi | null;\n /** Null for the ordinary public picker — the tokenless path is untouched. */\n private readonly access: BuyerAccessContext | null;\n private realtime: BuyerRealtimeClient | null = null;\n private accessEl: HTMLDivElement | null = null;\n private readonly apiBase: string;\n private readonly controller: PickerController;\n private readonly maxTickets: number;\n\n private root: HTMLDivElement | null = null;\n private mapHost: HTMLDivElement | null = null;\n private rendered = false;\n private destroyed = false;\n\n // chrome refs\n private els: Record<string, HTMLElement> = {};\n /** Feature 6 anchor regions — positioned flex containers over the map. */\n private regions: Record<string, HTMLElement> = {};\n private ro: ResizeObserver | null = null;\n private holdTimer: ReturnType<typeof setInterval> | null = null;\n private toastTimer: ReturnType<typeof setTimeout> | null = null;\n /** Short-lived UI motion timers; all are cancelled on destroy. */\n private motionTimers = new Set<ReturnType<typeof setTimeout>>();\n\n // state\n private currency = 'USD';\n private hold: HoldResult | null = null;\n /** Latest server expiry for the open hold (moves on extend). */\n private holdExpiresAt = 0;\n /** True once we handed off to checkout — arms booked-confirmation detection. */\n private handedOff = false;\n /** Guards single onBooked + single success overlay per hold. */\n private bookedShown = false;\n /**\n * `'hosted'` only when the host asked for it AND the widget owns its own\n * transport. Resolved once in the constructor so every later read is a field\n * comparison rather than a re-derivation that could drift.\n */\n private readonly checkoutMode: 'handoff' | 'hosted';\n /**\n * In-flight or settled `payment-options` for this event, started at render in\n * hosted mode. One request, kicked off while the buyer is still choosing, so\n * pressing Pay does not wait on a lookup whose answer never changes mid-session.\n */\n private paymentOptions: Promise<PaymentOptionsResult> | null = null;\n /** The mounted payment card, while one is up. */\n private checkoutPanel: CheckoutHandle | null = null;\n private extendEl: HTMLDivElement | null = null;\n private bookedEl: HTMLDivElement | null = null;\n private gaQty = new Map<string, number>();\n private tipEl: HTMLDivElement | null = null;\n private tipPos = { x: 0, y: 0 };\n private confirmEl: HTMLDivElement | null = null;\n private confirmSeat: ExpandedSeat | null = null;\n private tableDialogEl: HTMLDivElement | null = null;\n private tableDialog: TableSelectionDetails | null = null;\n private tableDialogHeld = false;\n private tableDialogReturnFocus: HTMLElement | null = null;\n private srEl: HTMLDivElement | null = null;\n private baQty = 2;\n private baCat = '';\n /** Optional navigation-zone scope for buyer best-available. */\n private baZone = '';\n /** \"★ Best seats\" premium quick-pick toggle — biases best-available to premium seats. */\n private baPremium = false;\n private bestAvailableConfirm = false;\n private releasingHold = false;\n /** Event sales window is closed (read-only load state / live close). */\n private salesClosed = false;\n /** Every seated category's live availability is 0 (sold-out overlay is up). */\n private soldOut = false;\n private soldoutEl: HTMLDivElement | null = null;\n /** Resolved colorblind-safe state — stored preference wins over the option. */\n private cbSafe = false;\n\n // arena / multi-floor / seat-view chrome\n private rungsEl: HTMLDivElement | null = null;\n private projectionEl: HTMLDivElement | null = null;\n // --- 3D venue view (Map | 3D) ---\n private buyerView: 'map' | 'venue3d' = 'map';\n private view3dEl: HTMLDivElement | null = null;\n private view3dHandle: Venue3DHandle | null = null;\n /** Monotonic token so a stale async mount (buyer left before OGL finished\n * loading) never installs its handle over a newer state. */\n private view3dGen = 0;\n /** Seat whose 2D confirm card launched \"See it in 3D\"; re-shown on return. */\n private view3dReturnSeat: ExpandedSeat | null = null;\n private floorsEl: HTMLDivElement | null = null;\n private secCardEl: HTMLDivElement | null = null;\n private viewEl: HTMLDivElement | null = null;\n private viewCleanup: (() => void) | null = null;\n private allSeatsCache: ExpandedSeat[] | null = null;\n\n // F3 minimap\n private miniCanvas: HTMLCanvasElement | null = null;\n private miniBase: HTMLCanvasElement | null = null;\n private miniTf: { scale: number; offX: number; offY: number; dpr: number } | null = null;\n\n // F4 price-band filter — active band's category keys (null = all prices)\n private priceBandKeys: Set<string> | null = null;\n private focusedCatKey: string | null = null;\n /** \"Hide limited-view seats\" — mirrored into 3D by `seatState3dFor`. */\n private limitedViewFilter = false;\n private pricesExpanded = false;\n /** Last surfaced section summary (re-rendered when the price band changes). */\n private lastSection: SectionSummary | null = null;\n /** Section card collapsed to its slim pill (seat-picking has begun). */\n private secCardCollapsed = false;\n /** When the card was (re)shown — the focus glide's own view change must not collapse it. */\n private secCardShownAt = 0;\n /** Previous tray ticket count — first 0→n transition auto-expands the mobile sheet. */\n private lastTrayCount = 0;\n /** Previous computed total — drives a single explanatory value bump. */\n private lastTrayTotal = 0;\n /** Stable item keys prevent tray chips re-animating on unrelated realtime syncs. */\n private lastTrayKeys = new Set<string>();\n private bestAvailableBusy = false;\n private releasingLabels = new Set<string>();\n /** Selected labels awaiting the hold response; their own realtime echo can arrive first. */\n private holdingLabels = new Set<string>();\n private ctaPhase: 'idle' | 'holding' | 'checkout' = 'idle';\n // narrow-layout chrome that docks into the sheet's Filters row on mobile\n private a11yChipsEl: HTMLDivElement | null = null;\n private fsFallback = false;\n private fsChangeHandler: (() => void) | null = null;\n private fsEscHandler: ((e: KeyboardEvent) => void) | null = null;\n /** True once we've asked the host page to pin us fullscreen (framed, no native). */\n private framedFs = false;\n /** Last height (px) posted to a host frame; dedupes redundant reports. */\n private lastPostedHeight = 0;\n\n /** True when the chart carries a real performance anchor — a stage-kind shape.\n * Every chart has a `focalPoint` (a bare look-at coordinate), so its presence\n * alone never justifies a \"to stage\" claim; only an actual stage does. */\n private chartHasStage(): boolean {\n const doc = this.controller.doc;\n if (!doc) return false;\n const objectSets = doc.floors?.length ? doc.floors.map((f) => f.objects ?? []) : [doc.objects ?? []];\n for (const objects of objectSets) {\n for (const obj of objects) {\n if (obj.type === 'shape' && (obj.role === 'stage' || obj.stageKind)) return true;\n }\n }\n return false;\n }\n\n /**\n * Eager sightline preview for the confirm card: the organizer's real view\n * photo, or — only when the chart has an actual stage to look at — a generated\n * forward view plus an \"≈ Nm to stage · clear sightline\" line. On a stageless\n * chart both the distance/sightline claim and the generic stage silhouette are\n * invented promises, so we suppress them; a real attached photo always shows.\n * (OV-52)\n */\n private confirmThumbHtml(seat: ExpandedSeat): string {\n const doc = this.controller.doc;\n if (!doc) return '';\n const realPhoto = seat.viewUrl ?? '';\n const hasStage = this.chartHasStage();\n // No organizer photo AND no stage to measure against → nothing honest to show.\n if (!realPhoto && !hasStage) return '';\n let distance: number | null = null;\n if (!realPhoto) {\n try {\n // Rendered only for its distance figure — the synthetic image itself is\n // deliberately NOT shown at card size, where it reads as a cheap fake\n // photo (owner call 2026-07-24). Full-screen is where generated views\n // earn their keep; the card keeps a plain \"View from here\" button.\n const thumb = generateSeatThumb(seat, seat.focalPoint ?? doc.focalPoint);\n distance = thumb.distanceM ?? null;\n } catch {\n return '';\n }\n }\n // The distance/sightline line is only truthful when a stage anchors it.\n const sightHtml = hasStage\n ? `<div class=\"sl-confirm-sight\"><span aria-hidden=\"true\">✓</span>${distance != null\n ? t('picker.sightline', { m: distance })\n : this.tf('picker.sightlineClear', 'Clear sightline')}</div>`\n : '';\n const viewBtn = realPhoto\n ? `<button type=\"button\" class=\"sl-confirm-view sl-confirm-thumbwrap\" aria-label=\"${t('picker.viewFromSeat', { label: seat.label })}\">` +\n `<img class=\"sl-confirm-thumb\" src=\"${realPhoto}\" alt=\"\" />` +\n `<span class=\"sl-confirm-thumb-badge\">🔭 ${this.tf('picker.viewFromHere', 'View from here')}</span>` +\n `</button>`\n : `<button type=\"button\" class=\"sl-confirm-view sl-confirm-viewbtn\" aria-label=\"${t('picker.viewFromSeat', { label: seat.label })}\">` +\n `<span aria-hidden=\"true\">🔭</span><span>${this.tf('picker.viewFromHere', 'View from here')}</span>` +\n `</button>`;\n return viewBtn + sightHtml;\n }\n\n /** \"See it in 3D\" (2D) / \"View from this seat\" (already in 3D) action for the\n * confirm card. Only when 3D is available — the purchase-moment bridge into\n * the cinematic that reaches buyers who never press the Map | 3D toggle. */\n private see3dConfirmHtml(): string {\n if (!this.canOffer3d()) return '';\n const label = this.buyerView === 'venue3d'\n ? this.tf('picker.viewFromThisSeat', 'View from this seat')\n : this.tf('picker.seeItIn3d', 'See it in 3D');\n return (\n `<button type=\"button\" class=\"sl-confirm-3d\" aria-label=\"${label}\">`\n + '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2l9 5v10l-9 5-9-5V7z\"/><path d=\"M12 12l9-5M12 12v10M12 12L3 7\"/></svg>'\n + `<span>${label}</span></button>`\n );\n }\n\n /** Minimal HTML/attribute escaper for buyer-authored commercial text (notes). */\n private escCx(value: unknown): string {\n return String(value ?? '').replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!));\n }\n\n /** Localized \"Restricted view\" / \"Obstructed view\" label for a seat's flags,\n * or '' when neither is set. Restricted takes precedence when both are on. */\n private limitedViewLabel(c: SeatCommercialAttributes | undefined): string {\n if (c?.restrictedView) return this.tf('picker.restrictedView', 'Restricted view');\n if (c?.obstructedView) return this.tf('picker.obstructedView', 'Obstructed view');\n return '';\n }\n\n /**\n * Commercial flags block for the confirm/detail surface: a subtle ★ Premium\n * tag plus an amber ◐ limited-view caution (with the organizer's note when\n * present). '' when the seat carries no surfaced commercial flag.\n */\n private commercialConfirmHtml(c: SeatCommercialAttributes | undefined): string {\n if (!c) return '';\n const rows: string[] = [];\n if (c.premium) {\n rows.push(\n `<div class=\"sl-cx-premium\"><span class=\"sl-cx-star\" aria-hidden=\"true\">★</span>${this.tf('picker.premiumSeat', 'Premium seat')}</div>`,\n );\n }\n const limited = this.limitedViewLabel(c);\n if (limited) {\n rows.push(\n `<div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">◐</span>` +\n `<span class=\"sl-cx-txt\"><b>${limited}</b>${c.note ? `<span class=\"sl-cx-note\">${this.escCx(c.note)}</span>` : ''}</span></div>`,\n );\n } else if (c.note) {\n // A note with no view flag (e.g. seller info) still deserves a calm line.\n rows.push(\n `<div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">ℹ</span>` +\n `<span class=\"sl-cx-txt\"><span class=\"sl-cx-note\">${this.escCx(c.note)}</span></span></div>`,\n );\n }\n return rows.length ? `<div class=\"sl-cx\">${rows.join('')}</div>` : '';\n }\n\n /** Small ◐ limited-view marker for a cart chip; title/aria uses the seat's\n * note when present, else the generic view label. '' for a clear-view seat. */\n private commercialChipMarker(c: SeatCommercialAttributes | undefined): string {\n const limited = this.limitedViewLabel(c);\n if (!limited) return '';\n const title = this.escCx(c?.note ? c.note : limited);\n return `<span class=\"sl-cx-mark\" role=\"img\" aria-label=\"${title}\" title=\"${title}\">◐</span>`;\n }\n\n private wheelchairProvisionLabel(type: 'seat-present' | 'no-seat' | undefined): string {\n if (type === 'no-seat') return 'Empty wheelchair space';\n if (type === 'seat-present') return 'Accessible physical seat';\n return '';\n }\n\n private wheelchairConfirmHtml(type: 'seat-present' | 'no-seat' | undefined): string {\n const label = this.wheelchairProvisionLabel(type);\n return label\n ? `<div class=\"sl-cx\"><div class=\"sl-cx-warn\"><span class=\"sl-cx-glyph\" aria-hidden=\"true\">♿</span><span class=\"sl-cx-txt\"><b>${label}</b></span></div></div>`\n : '';\n }\n\n private wheelchairChipMarker(type: 'seat-present' | 'no-seat' | undefined): string {\n const label = this.wheelchairProvisionLabel(type);\n return label\n ? `<span class=\"sl-cx-mark\" role=\"img\" aria-label=\"${label}\" title=\"${label}\">♿</span>`\n : '';\n }\n\n /** True when the picker is rendered inside an iframe (snippet embed at /e/:key). */\n private isFramed(): boolean {\n return typeof window !== 'undefined' && window.parent !== window;\n }\n\n /**\n * Post a widget→host message when framed. targetOrigin is '*' because the\n * payload carries nothing sensitive (a height number / a fullscreen flag);\n * hosts verify `event.origin` on their side (see `attachPickerFrame`).\n */\n private postToHost(message: { type: string; [key: string]: unknown }): void {\n if (!this.isFramed()) return;\n try {\n window.parent.postMessage(message, '*');\n } catch {\n /* a hostile/cross-origin parent may reject postMessage — nothing to do */\n }\n }\n\n /**\n * Height (px) to advertise to a host frame.\n *\n * The picker fills whatever box it's given: `.sl-picker` is `height:100%;\n * overflow:hidden`, and the /e/:key shell mounts it `position:fixed; inset:0`.\n * So it has no intrinsic *document* height to read — `scrollHeight` just\n * collapses to the current viewport, which for a framed embed would echo the\n * host's own iframe height straight back (a circular value). We therefore\n * report a width-driven *desired* height: a pleasant landscape box on desktop,\n * taller on narrow widths where the bottom sheet needs room, clamped to the\n * widget's `min-height` of 420. Width is host-controlled and never moves in\n * response to the height we report, so this cannot feedback-loop.\n */\n private measureFramedHeight(): number {\n const root = this.root;\n if (!root) return 0;\n const width = root.clientWidth || (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;\n if (width <= 0) return 0;\n const ratio = width < 640 ? 1.2 : 0.62;\n return Math.max(420, Math.round(width * ratio));\n }\n\n /** Post `seatlayer:height` to the host when framed and the value changed. */\n private reportFramedHeight(): void {\n if (!this.isFramed()) return;\n const px = this.measureFramedHeight();\n if (px <= 0 || px === this.lastPostedHeight) return;\n this.lastPostedHeight = px;\n this.postToHost({ type: 'seatlayer:height', px });\n }\n\n /** Full screen via the native API, falling back to a fixed-position overlay (iOS Safari). */\n private toggleFullscreen(): void {\n const root = this.root;\n if (!root) return;\n const active = !!document.fullscreenElement || this.fsFallback || this.framedFs;\n if (!active) {\n if (root.requestFullscreen) {\n root.requestFullscreen().catch(() => this.enterFsFallback());\n } else {\n this.enterFsFallback();\n }\n } else if (document.fullscreenElement) {\n void document.exitFullscreen().catch(() => {});\n } else if (this.framedFs) {\n this.setFramedFs(false);\n } else {\n this.setFsFallback(false);\n }\n }\n\n /**\n * Native element-fullscreen was unavailable or rejected. When framed, a CSS\n * `.sl-fs` overlay can't escape the iframe, so we ask the host page to pin us\n * (`seatlayer:fullscreen`). Otherwise (iOS Safari, same document) fall back to\n * the `.sl-fs` overlay as before.\n */\n private enterFsFallback(): void {\n if (this.isFramed()) this.setFramedFs(true);\n else this.setFsFallback(true);\n }\n\n /** Toggle host-driven (framed) fullscreen: post the flag + own the Esc key. */\n private setFramedFs(on: boolean): void {\n if (this.framedFs === on) return;\n this.framedFs = on;\n this.els.zfs?.setAttribute('aria-pressed', String(on || !!document.fullscreenElement));\n this.postToHost({ type: 'seatlayer:fullscreen', on });\n if (on && !this.fsEscHandler) {\n this.fsEscHandler = (e: KeyboardEvent): void => {\n if (e.key === 'Escape' && !document.fullscreenElement) this.setFramedFs(false);\n };\n window.addEventListener('keydown', this.fsEscHandler);\n } else if (!on && this.fsEscHandler) {\n window.removeEventListener('keydown', this.fsEscHandler);\n this.fsEscHandler = null;\n }\n requestAnimationFrame(() => this.controller.zoomToFit());\n }\n\n private setFsFallback(on: boolean): void {\n if (this.fsFallback === on) return;\n this.fsFallback = on;\n this.root?.classList.toggle('sl-fs', on);\n this.els.zfs?.setAttribute('aria-pressed', String(on || !!document.fullscreenElement));\n if (on && !this.fsEscHandler) {\n this.fsEscHandler = (e: KeyboardEvent): void => {\n if (e.key === 'Escape' && !document.fullscreenElement) this.setFsFallback(false);\n };\n window.addEventListener('keydown', this.fsEscHandler);\n } else if (!on && this.fsEscHandler) {\n window.removeEventListener('keydown', this.fsEscHandler);\n this.fsEscHandler = null;\n }\n requestAnimationFrame(() => this.controller.zoomToFit());\n }\n private cbEl: HTMLButtonElement | null = null;\n\n // modal plumbing (set by open())\n private modalScrim: HTMLElement | null = null;\n private prevFocus: Element | null = null;\n private escHandler: ((e: KeyboardEvent) => void) | null = null;\n\n /** Set by open(): closes the modal (scroll restore + destroy + onClose). */\n private closeModal: (() => void) | null = null;\n\n /**\n * Close the picker. In modal mode (SeatPicker.open()) this dismisses the\n * modal exactly like ESC/scrim/✕ — restores page scroll and fires onClose.\n * For inline mounts it simply destroys the widget.\n */\n close(): void {\n if (this.closeModal) this.closeModal();\n else this.destroy();\n }\n\n /** Mount the full picker as a document-level modal. Resolves after render. */\n static async open(options: Omit<SeatPickerOptions, 'container'>): Promise<SeatPicker> {\n ensureStyle();\n const scrim = document.createElement('div');\n scrim.className = 'sl-modal-scrim';\n const frame = document.createElement('div');\n frame.className = 'sl-modal-frame';\n scrim.appendChild(frame);\n document.body.appendChild(scrim);\n const prevOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n const picker = new SeatPicker({ ...options, container: frame });\n picker.modalScrim = scrim;\n picker.prevFocus = document.activeElement;\n let closing = false;\n const close = (): void => {\n if (closing) return;\n closing = true;\n document.body.style.overflow = prevOverflow;\n // Visually dismiss immediately, but let an abandoned auto-hold finish its\n // release request before tearing down the transport. This keeps closing a\n // modal from stranding inventory until the normal hold expiry.\n scrim.style.opacity = '0';\n scrim.style.pointerEvents = 'none';\n const finish = (): void => {\n picker.destroy();\n options.onClose?.();\n };\n if (picker.hold && !picker.handedOff) void picker.release().finally(finish);\n else finish();\n };\n picker.closeModal = close;\n scrim.addEventListener('mousedown', (e) => {\n if (e.target === scrim) close();\n });\n picker.escHandler = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (picker.tableDialog) {\n e.preventDefault();\n picker.cancelTableDialog();\n } else if (picker.confirmSeat) {\n e.preventDefault();\n picker.cancelConfirm();\n } else if (picker.bestAvailableConfirm) {\n e.preventDefault();\n picker.bestAvailableConfirm = false;\n picker.syncTray();\n } else {\n close();\n }\n };\n document.addEventListener('keydown', picker.escHandler);\n await picker.render();\n picker.els.close?.classList.add('on');\n picker.els.close?.addEventListener('click', close);\n return picker;\n }\n\n constructor(options: SeatPickerOptions) {\n if (!options || typeof options !== 'object') throw new Error('seatmap: options object is required');\n if (!options.event || typeof options.event !== 'string') throw new Error('seatmap: `event` key is required');\n if (!options.container) throw new Error('seatmap: `container` is required (or use SeatPicker.open())');\n this.opts = { ...options, confirmSelection: options.confirmSelection ?? true };\n this.apiBase = (options.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '');\n // A host-supplied transport owns its own credentials, so the access context\n // is only built for our own PubApi.\n this.access = options.transport\n ? null\n : createBuyerAccessContext(options, {\n onExpired: (event) => {\n this.opts.onAccessExpired?.(event);\n if (!event.refreshed) this.showAccessPanel({ reason: 'no_token', retryable: false });\n },\n onUnavailable: (event) => {\n this.opts.onAccessUnavailable?.(event);\n this.showAccessPanel(event);\n },\n });\n this.pubApi = options.transport\n ? null\n : new PubApi(this.apiBase, {\n access: this.access ?? undefined,\n onObjectUnavailable: (event) => this.opts.onSelectedObjectUnavailable?.(event),\n });\n this.api = options.transport ?? this.pubApi!;\n // Hosted checkout talks to OUR /pub routes with OUR client. A host that\n // injected a transport owns its backend and its credentials, and quietly\n // reaching past it to api.seatlayer.io would be the widget deciding where a\n // buyer's money goes. Refuse out loud, once, and stay on the default.\n if (options.checkout === 'hosted' && !this.pubApi) {\n console.warn(\n 'seatlayer: checkout: \"hosted\" needs the widget\\'s own transport — a custom `transport` '\n + 'owns its backend, so the picker is staying on onCheckout for this mount.',\n );\n }\n this.checkoutMode = options.checkout === 'hosted' && this.pubApi ? 'hosted' : 'handoff';\n this.maxTickets = Math.max(1, Math.floor(options.maxSelection ?? DEFAULT_MAX_SELECTION));\n // Colorblind preference: the stored (cross-surface) value wins over the\n // option; the option is only the initial default when nothing is stored.\n this.cbSafe = readStoredColorblind() ?? !!options.colorblindSafe;\n this.controller = new PickerController({\n transport: this.api,\n eventKey: options.event,\n maxSelection: this.maxTickets,\n currency: options.currency,\n flashOnLiveChange: true,\n colorblindSafe: this.cbSafe,\n onSelectionChange: () => {\n this.syncTray();\n // Seat-picking has begun — collapse the section card out of the way.\n if (this.committedSelection().length) this.collapseSectionCard();\n // Keep the 3D overlay's selection highlight in lockstep (both directions).\n this.syncSelectionTo3d();\n },\n onStatusChange: () => {\n this.syncPrices();\n this.evictTakenSelections();\n this.detectBooked();\n // Live open/close of a section repaints the minimap's static overview.\n this.refreshMinimap();\n // Mirror every live availability delta into the 3D view while it's open.\n this.pushAvailabilityTo3d();\n },\n onHoldExpired: () => {\n this.hold = null;\n this.forgetHold();\n this.handedOff = false;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.stopHoldTimer();\n this.gaQty.clear();\n this.toast(t('picker.holdExpired', undefined) || 'Your hold expired — seats released. Pick again.', 'warning');\n this.syncTray();\n this.emitHoldChange();\n this.opts.onHoldExpired?.();\n },\n confirmSelection: this.opts.confirmSelection,\n onSelect: (seat) => {\n // Sales-closed is a read-only state — refuse the pick (the controller\n // doesn't gate tapping; server would 409 the eventual hold anyway).\n if (this.salesClosed) {\n this.controller.deselect([seat.id]);\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n return;\n }\n // Grouped tables own a dedicated whole/guest-count dialog. The raw\n // chair callback is retained for compatibility, but must not open the\n // ordinary one-seat confirm card in this full buyer widget.\n if (this.controller.tableSelection(seat.id)) return;\n this.flashPickedSeat(seat.id);\n if (this.opts.confirmSelection) this.showConfirm(seat);\n },\n onTableSelectionRequest: (table) => {\n if (this.salesClosed) {\n this.controller.deselect(table.physicalSeatIds);\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n return;\n }\n this.showTableDialog(table, false);\n },\n onDeselect: (seat) => {\n if (this.confirmSeat?.id === seat.id) this.dismissConfirm();\n if (this.tableDialog?.physicalSeatIds.includes(seat.id)) this.dismissTableDialog();\n },\n onSelectionLimit: () => {\n this.toast(`You can select up to ${this.maxTickets} tickets for this order.`, 'warning');\n },\n onViewChange: () => {\n this.reanchorConfirm();\n this.syncRung();\n this.syncProjection();\n this.drawMinimapRect();\n this.sectionCardOnView();\n },\n // Tapped-section glide-in → surface (or clear) the section-summary card.\n onSectionFocus: (summary) => this.showSectionCard(summary),\n onFocusSeat: (seat) => this.announceSeat(seat),\n onSeatHover: (d) => this.updateTooltip(d),\n onHint: (m) => {\n if (m) this.toast(m);\n },\n // Server declared the event closed mid-session (409 event_closed) — keep\n // the toast (raised by handleCta), and add the persistent read-only state.\n onSalesClosed: () => this.setSalesClosed(true),\n onError: (err) => this.opts.onError?.(err),\n });\n }\n\n async render(): Promise<this> {\n if (this.rendered) return this;\n this.rendered = true;\n ensureStyle();\n await loadLocale(this.opts.locale);\n if (this.opts.messages) setStringOverrides(this.opts.messages);\n\n // Hosted checkout asks the server what this event can charge through while\n // the buyer is still looking at the map. The answer cannot change mid-\n // session, and asking now means pressing Pay is not gated on a round trip.\n // A rejection is caught at the point of use, not here — a widget must not\n // die because a payment lookup failed.\n if (this.checkoutMode === 'hosted') this.paymentOptions = this.pubApi!.paymentOptions(this.opts.event);\n\n const mount = resolveContainer(this.opts.container!);\n const root = document.createElement('div');\n root.className = 'sl-picker';\n root.tabIndex = -1;\n this.root = root;\n mount.appendChild(root);\n root.addEventListener('keydown', (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (this.tableDialog) {\n e.preventDefault();\n e.stopPropagation();\n this.cancelTableDialog();\n } else if (this.confirmSeat) {\n e.preventDefault();\n e.stopPropagation();\n this.cancelConfirm();\n } else if (this.bestAvailableConfirm) {\n e.preventDefault();\n e.stopPropagation();\n this.bestAvailableConfirm = false;\n this.syncTray();\n }\n });\n\n // skeleton first — tokens get re-applied once the chart theme arrives\n Object.entries(resolveTokens(undefined, this.opts.theme)).forEach(([k, v]) => root.style.setProperty(k, v));\n root.innerHTML = `\n <div class=\"sl-head\">\n <div class=\"sl-logo\" data-ref=\"logo\"></div>\n <div class=\"sl-head-info\">\n <div class=\"sl-head-name\" data-ref=\"name\"></div>\n <div class=\"sl-head-meta\" data-ref=\"meta\"></div>\n </div>\n <span class=\"sl-hold-pill\" data-ref=\"hold\"></span>\n <span class=\"sl-closed-pill\" data-ref=\"closedPill\" role=\"status\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"5\" y=\"11\" width=\"14\" height=\"9\" rx=\"2\"/><path d=\"M8 11V7a4 4 0 0 1 8 0v4\"/></svg>\n <span data-ref=\"closedPillText\"></span>\n </span>\n <button type=\"button\" class=\"sl-close\" data-ref=\"close\" aria-label=\"Close\">\n <svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg>\n </button>\n </div>\n <div class=\"sl-body\">\n <div class=\"sl-map\">\n <div class=\"sl-map-host\" data-ref=\"map\"></div>\n <div class=\"sl-zoom\" data-ref=\"zoom\">\n <button type=\"button\" aria-label=\"Zoom in\" data-ref=\"zin\">+</button>\n <button type=\"button\" aria-label=\"Zoom out\" data-ref=\"zout\">−</button>\n <button type=\"button\" aria-label=\"Fit to screen\" data-ref=\"zfit\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3\"/></svg>\n </button>\n <button type=\"button\" aria-label=\"Full screen\" aria-pressed=\"false\" data-ref=\"zfs\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7\"/></svg>\n </button>\n </div>\n <div class=\"sl-boot\" data-ref=\"boot\"><span class=\"sl-boot-spin\"></span>Loading seat map…</div>\n <div class=\"sl-toast\" data-ref=\"toast\" role=\"status\" aria-live=\"polite\"></div>\n </div>\n <div class=\"sl-side\" data-ref=\"side\">\n <div class=\"sl-sheet-head\" data-ref=\"sheetHead\">\n <div class=\"sl-sheet-grab\"></div>\n <div class=\"sl-sheet-bar\">\n <div class=\"sl-sheet-peek\" data-ref=\"peek\"></div>\n <button type=\"button\" class=\"sl-sheet-toggle\" data-ref=\"sheetToggle\" aria-label=\"Open ticket panel\" aria-expanded=\"false\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M6 15l6-6 6 6\"/></svg>\n </button>\n </div>\n </div>\n <div class=\"sl-sec sl-filtersec\" data-ref=\"filtersSec\">Filters</div>\n <div class=\"sl-filters\" data-ref=\"filters\"></div>\n <div class=\"sl-sec sl-prices-sec\" data-ref=\"pricesSec\"><span>Ticket prices</span></div>\n <div class=\"sl-prices\" data-ref=\"prices\"></div>\n <div class=\"sl-live\" data-ref=\"live\" role=\"status\" aria-live=\"polite\"><span class=\"dot\" aria-hidden=\"true\"></span><span data-ref=\"liveText\">Live availability — seats update in real time</span></div>\n <div class=\"sl-sec sl-seats-sec\"><span>Your seats</span><span class=\"sl-seat-summary\" data-ref=\"seatSummary\"></span></div>\n <div class=\"sl-tray\" data-ref=\"tray\"></div>\n <div class=\"sl-foot\" data-ref=\"foot\">\n <div class=\"sl-hold-note\" data-ref=\"holdNote\" role=\"status\" aria-live=\"polite\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M20 6L9 17l-5-5\"/></svg>\n <span><b data-ref=\"holdTitle\">Seats secured</b><span class=\"sl-hold-copy\" data-ref=\"holdCopy\">Checkout timer is running.</span></span>\n <button type=\"button\" class=\"sl-hold-change\" data-ref=\"holdChange\" aria-label=\"Release held tickets and choose different seats\">Change</button>\n </div>\n <div class=\"sl-total\"><span data-ref=\"count\"></span><b data-ref=\"total\"></b></div>\n <button type=\"button\" class=\"sl-cta\" data-ref=\"cta\" disabled></button>\n </div>\n </div>\n </div>`;\n root.querySelectorAll<HTMLElement>('[data-ref]').forEach((el) => {\n this.els[el.dataset.ref!] = el;\n });\n this.mapHost = this.els.map as HTMLDivElement;\n\n // container-adaptive layout (breakpoint keys off the CONTAINER, not the viewport)\n const applyLayout = (): void => {\n const w = root.clientWidth;\n if (w <= 0) return;\n // Report our desired height to a host frame on every size change (deduped),\n // not just when the layout breakpoint flips below.\n this.reportFramedHeight();\n const next = w < 640 ? 'narrow' : 'wide';\n if (root.dataset.layout === next) return;\n root.dataset.layout = next;\n // Entering the mobile sheet layout: start in the peek state (map-first).\n if (next === 'narrow' && !root.dataset.sheet) root.dataset.sheet = 'peek';\n this.dockLayoutChrome();\n };\n this.ro = new ResizeObserver(applyLayout);\n this.ro.observe(root);\n // Some environments defer the ResizeObserver's initial callback (backgrounded\n // tabs throttle delivery). Seed the layout synchronously + next frame so a\n // container that mounts already-wide gets data-layout=\"wide\" immediately,\n // instead of waiting on a resize that may never arrive.\n applyLayout();\n requestAnimationFrame(applyLayout);\n\n // zoom + tooltip wiring\n this.els.zin.addEventListener('click', () => this.controller.zoomIn());\n this.els.zout.addEventListener('click', () => this.controller.zoomOut());\n this.els.zfit.addEventListener('click', () => this.controller.zoomToFit());\n // Full screen: native API with a CSS-fallback overlay for iOS Safari\n // (which has no element fullscreen). Esc exits both paths; the renderer's\n // ResizeObserver re-fits, plus an explicit zoomToFit for a crisp frame.\n this.els.zfs.addEventListener('click', () => this.toggleFullscreen());\n this.fsChangeHandler = (): void => {\n if (!document.fullscreenElement) this.setFsFallback(false);\n this.els.zfs?.setAttribute('aria-pressed', String(!!document.fullscreenElement || this.fsFallback || this.framedFs));\n requestAnimationFrame(() => this.controller.zoomToFit());\n };\n document.addEventListener('fullscreenchange', this.fsChangeHandler);\n\n // Mobile bottom sheet: swipe/tap on the sheet HEAD only (never the map host,\n // so the map's raw-pointer gesture pipeline is untouched). Swipe up → open\n // (≤50%); swipe down → peek; a plain tap toggles. The section-card strip's\n // ✕ lives inside the head — taps on the card must not toggle the sheet.\n const head = this.els.sheetHead;\n if (head) {\n const toggle = this.els.sheetToggle as HTMLButtonElement | undefined;\n const setSheet = (open: boolean): void => {\n root.dataset.sheet = open ? 'open' : 'peek';\n toggle?.setAttribute('aria-expanded', String(open));\n toggle?.setAttribute('aria-label', open ? 'Collapse ticket panel' : 'Open ticket panel');\n };\n setSheet(root.dataset.sheet === 'open');\n toggle?.addEventListener('click', (e) => {\n e.stopPropagation();\n setSheet(root.dataset.sheet !== 'open');\n });\n let startY = 0;\n let swiped = false;\n let tracking = false;\n head.addEventListener('pointerdown', (e: PointerEvent) => {\n tracking = true;\n swiped = false;\n startY = e.clientY;\n head.setPointerCapture?.(e.pointerId);\n });\n head.addEventListener('pointermove', (e: PointerEvent) => {\n if (!tracking || swiped) return;\n const dy = e.clientY - startY;\n if (dy < -18) {\n setSheet(true);\n swiped = true;\n } else if (dy > 18) {\n setSheet(false);\n swiped = true;\n }\n });\n head.addEventListener('pointerup', (e: PointerEvent) => {\n if (tracking && !swiped && Math.abs(e.clientY - startY) < 6) {\n if (!(e.target as HTMLElement).closest('.sl-seccard,.sl-sheet-toggle')) setSheet(root.dataset.sheet !== 'open');\n }\n tracking = false;\n head.releasePointerCapture?.(e.pointerId);\n });\n }\n this.tipEl = document.createElement('div');\n this.tipEl.setAttribute('role', 'tooltip');\n this.tipEl.className = 'sl-tip';\n this.els.map.appendChild(this.tipEl);\n this.els.map.addEventListener('mousemove', (e: MouseEvent) => {\n const r = this.els.map.getBoundingClientRect();\n this.tipPos = { x: e.clientX - r.left, y: e.clientY - r.top };\n if (this.tipEl && this.tipEl.style.display !== 'none') this.placeTooltip();\n });\n\n this.els.cta.addEventListener('click', () => void this.handleCta());\n this.els.holdChange?.addEventListener('click', () => void this.handleChangeSeats());\n\n const canvasHost = document.createElement('div');\n canvasHost.style.cssText = 'position:absolute;inset:0';\n this.mapHost.appendChild(canvasHost);\n const info = await this.controller.render(canvasHost);\n if (this.destroyed) return this;\n if (!info) {\n this.els.boot.innerHTML =\n '<div class=\"sl-boot-title\">The seat map didn’t load</div>' +\n '<div>Check your connection and try again.</div>' +\n '<button type=\"button\" class=\"sl-boot-retry\">Try again</button>';\n this.els.boot.querySelector('button')!.addEventListener('click', () => {\n // full remount: cheapest reliable recovery\n const container = this.opts.container!;\n const opts = this.opts;\n this.destroy();\n void new SeatPicker({ ...opts, container }).render();\n });\n return this;\n }\n this.els.boot.remove();\n this.startRealtime();\n // Read-only load state: the chart() payload carries salesClosed.\n this.salesClosed = !!info.salesClosed;\n this.controller.setViewMode(this.normalizeInitialView(this.opts.initialView));\n\n // Feature 6: anchor regions for all persistent map chrome, then move the\n // pre-built zoom column + toast into their regions (both were in the skeleton).\n this.buildRegions();\n this.regions['bottom-right'].appendChild(this.els.zoom);\n this.regions['bottom-center'].appendChild(this.els.toast);\n\n if (info.mode === 'test') {\n // TEST MODE reads as a small badge in the top-right region (was a corner\n // ribbon that collided with the top-right control cluster on narrow widths).\n const badge = document.createElement('div');\n badge.className = 'sl-testbadge';\n badge.textContent = t('picker.testMode');\n badge.setAttribute('aria-label', t('picker.testMode'));\n this.regions['top-right'].appendChild(badge);\n }\n\n // theme: defaults ← org chart theme ← host overrides\n const chartTheme = this.controller.doc?.theme;\n Object.entries(resolveTokens(chartTheme, this.opts.theme)).forEach(([k, v]) => root.style.setProperty(k, v));\n this.currency = info.currency ?? this.opts.currency ?? 'USD';\n\n // header\n const logoUrl = this.opts.theme?.logoUrl ?? chartTheme?.logoUrl;\n if (logoUrl) this.els.logo.innerHTML = `<img src=\"${logoUrl}\" alt=\"\">`;\n else this.els.logo.textContent = (this.opts.theme?.brandName ?? chartTheme?.brandName ?? info.eventName ?? '?').slice(0, 1).toUpperCase();\n this.els.name.textContent = info.eventName ?? '';\n const when = info.startsAt\n ? new Date(info.startsAt).toLocaleString(this.opts.locale, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })\n : '';\n this.els.meta.textContent = [info.venue, when].filter(Boolean).join(' · ');\n\n // \"Powered by SeatLayer\" attribution badge — hidden when the host opts out\n // OR the org's paid chart theme sets hideBadge (either being true hides it).\n this.buildBadge(chartTheme);\n\n // Accessibility filter chips — only for types actually present in the chart.\n // Same sweep also detects whether ANY seat carries a limited-view (restricted\n // or obstructed) commercial flag, which gates the \"Hide limited-view seats\"\n // toggle that shares this chip row.\n const present = new Set<AccessibilityType>();\n let hasLimitedView = false;\n if (this.controller.doc) {\n for (const seat of expandChart(this.controller.doc)) {\n for (const type of seat.accessibility ?? []) present.add(type);\n if (seat.accessible && !seat.accessibility?.length) present.add('wheelchair');\n if (seat.commercial?.restrictedView || seat.commercial?.obstructedView) hasLimitedView = true;\n }\n }\n // Jump to the seats rung when a dimming filter turns on — the dimming only\n // renders at seat detail; applying it zoomed out would silently dim seats\n // the buyer can't see. Shared by the a11y chips and the limited-view toggle.\n const focusSeatsForFilter = (): void => {\n if (this.rungsEl && this.controller.getRung() !== 'seats') {\n this.controller.setRung('seats');\n this.collapseSectionCard();\n this.syncRung();\n }\n };\n if (present.size || hasLimitedView) {\n const chips = document.createElement('div');\n chips.className = 'sl-chips';\n this.regions['top-left'].appendChild(chips);\n this.a11yChipsEl = chips;\n\n if (present.size) {\n const mk = (key: AccessibilityType | 'all', label: string): string =>\n `<button type=\"button\" class=\"sl-chip-f${key === 'all' ? ' on' : ''}\" data-a11y=\"1\" data-f=\"${key}\">${label}</button>`;\n chips.insertAdjacentHTML('beforeend',\n mk('all', 'All seats') +\n ACCESSIBILITY_TYPES\n .filter(({ key }) => present.has(key))\n .map(({ key, short, icon }) => mk(key, `${icon} ${short}`))\n .join(''));\n // Multi-select OR semantics (parity with the buyer page): each type chip\n // toggles independently; the active filter is the union; \"All seats\"\n // clears. A buyer needing wheelchair AND companion seats combines both.\n const active = new Set<AccessibilityType>();\n const syncChips = (): void => {\n chips.querySelectorAll<HTMLButtonElement>('button[data-a11y]').forEach((b) => {\n const f = b.dataset.f as AccessibilityType | 'all';\n const on = f === 'all' ? active.size === 0 : active.has(f);\n b.classList.toggle('on', on);\n b.setAttribute('aria-pressed', String(on));\n });\n const filter = active.size ? [...active] : null;\n this.controller.setAccessibilityFilter(filter);\n if (filter) focusSeatsForFilter();\n };\n chips.querySelectorAll<HTMLButtonElement>('button[data-a11y]').forEach((btn) => {\n btn.addEventListener('click', () => {\n const f = btn.dataset.f as AccessibilityType | 'all';\n if (f === 'all') active.clear();\n else if (active.has(f)) active.delete(f);\n else active.add(f);\n syncChips();\n });\n });\n }\n\n // \"Hide limited-view seats\" toggle — one independent on/off chip that dims\n // free seats flagged restricted/obstructed view (same chip pattern, sits\n // beside the a11y chips). Isolated from the a11y OR-union above.\n if (hasLimitedView) {\n const limited = document.createElement('button');\n limited.type = 'button';\n limited.className = 'sl-chip-f';\n limited.setAttribute('aria-pressed', 'false');\n limited.innerHTML = `◐ ${this.tf('picker.hideLimitedView', 'Hide limited-view seats')}`;\n chips.appendChild(limited);\n limited.addEventListener('click', () => {\n const limitedOn = !this.limitedViewFilter;\n this.limitedViewFilter = limitedOn;\n limited.classList.toggle('on', limitedOn);\n limited.setAttribute('aria-pressed', String(limitedOn));\n this.controller.setCommercialLimitedFilter(limitedOn);\n // Keep 3D in step — the filter must survive the switch between views.\n this.pushAvailabilityTo3d();\n if (limitedOn) focusSeatsForFilter();\n });\n }\n }\n\n // Colorblind-safe toggle rides in the zoom column (wide) or the sheet's\n // Filters row (narrow) — dockLayoutChrome moves it between the two.\n const cb = document.createElement('button');\n cb.type = 'button';\n cb.className = 'sl-cbbtn';\n this.cbEl = cb;\n cb.setAttribute('aria-label', 'Toggle colorblind-friendly colors');\n // Rehydrated from the shared preference (constructor read stored → this.cbSafe).\n cb.setAttribute('aria-pressed', String(this.cbSafe));\n cb.innerHTML = '<svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg>';\n this.els.zfit.parentElement!.appendChild(cb);\n // Route through the single source of truth so host chrome (e.g. the Designer\n // preview chip) and this in-widget button always agree.\n cb.addEventListener('click', () => { this.setColorblindSafe(!this.cbSafe); });\n\n // Screen-reader announcements for keyboard seat focus.\n this.srEl = document.createElement('div');\n this.srEl.className = 'sl-sr';\n this.srEl.setAttribute('aria-live', 'polite');\n root.appendChild(this.srEl);\n\n // Big-venue chrome: LOD rung pills, multi-floor switcher, section card.\n // Appended AFTER controller.render() — render() wipes the map host's children.\n this.buildArenaChrome();\n\n // F3 minimap (venue overview + viewport rect) and F4 price-band filter.\n // Same post-render append (the map host was wiped by controller.render()).\n this.buildMinimap();\n this.buildPriceFilter();\n\n // \"Need more time?\" prompt (over the map) + booked-confirmation overlay (over\n // the whole widget). Both appended post-render for the same wipe reason.\n this.buildExtendPrompt();\n this.buildBookedOverlay();\n this.buildSoldoutOverlay();\n\n // Dock layout-dependent chrome (a11y chips + colorblind toggle) for the\n // CURRENT layout — the initial applyLayout ran before these were built.\n this.dockLayoutChrome();\n\n await this.restoreRememberedHold();\n if (this.destroyed) return this;\n\n // Reflect the read-only load state (pill + disabled CTA/controls) with no\n // toast — a fresh mount into a closed event is not a live \"just closed\" event.\n if (this.salesClosed) this.applySalesClosed();\n this.syncPrices();\n this.syncTray();\n // Last, so a buyer coming back from a gateway sees a finished map behind the\n // confirmation rather than a skeleton.\n this.resumeHostedOrder();\n return this;\n }\n\n /**\n * A hosted gateway returned this buyer to a page that runs the widget, with\n * `?order=…&status=…` in the URL. Pick the order up and finish the story.\n *\n * Only `success` resumes. `cancelled` means the buyer backed out at the\n * gateway and their seats are still held — the map they are looking at IS the\n * right screen, and opening a card to say \"you cancelled\" would be noise.\n *\n * The two parameters are then stripped with `replaceState`, because they are a\n * one-shot instruction: leaving them in place would re-open the confirmation\n * on every later navigation, and would carry an order id into browser history\n * and any Referer this page later sends. `status` is only ever removed\n * alongside an `order` we actually consumed, so a host page that uses a\n * `status` parameter of its own keeps it.\n */\n private resumeHostedOrder(): void {\n if (this.checkoutMode !== 'hosted' || typeof location === 'undefined') return;\n const params = new URLSearchParams(location.search);\n const orderId = params.get('order');\n if (!orderId) return;\n const status = params.get('status');\n params.delete('order');\n params.delete('status');\n try {\n const query = params.toString();\n history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);\n } catch {\n // A sandboxed frame can refuse replaceState. Losing the tidy-up is not a\n // reason to lose the confirmation.\n }\n if (status !== 'success') return;\n void this.openCheckoutPanel({ kind: 'resume', orderId });\n }\n\n /**\n * Move layout-dependent chrome between its wide dock (map regions / zoom\n * column) and its narrow dock (the sheet's consolidated Filters row), and\n * re-render the section card in the form the layout wants (docked card/pill\n * on wide, sheet strip on narrow). Runs on every layout flip + once post-render.\n */\n private dockLayoutChrome(): void {\n const narrow = this.root?.dataset.layout === 'narrow';\n const filters = this.els.filters;\n if (filters) {\n if (narrow) {\n if (this.a11yChipsEl) filters.appendChild(this.a11yChipsEl);\n if (this.cbEl) filters.appendChild(this.cbEl);\n } else {\n if (this.a11yChipsEl) this.regions['top-left']?.appendChild(this.a11yChipsEl);\n if (this.cbEl) this.els.zoom?.appendChild(this.cbEl);\n }\n const has = narrow && filters.children.length > 0;\n filters.classList.toggle('has', has);\n this.els.filtersSec?.classList.toggle('has', has);\n }\n if (this.lastSection) this.renderSectionCard(this.lastSection);\n }\n\n /** The \"Need more time?\" prompt shown in the hold's final EXTEND_PROMPT_MS. */\n private buildExtendPrompt(): void {\n const el = document.createElement('div');\n el.className = 'sl-extend';\n el.setAttribute('role', 'status');\n el.innerHTML =\n `<span class=\"sl-extend-txt\" data-ref=\"extendTxt\"></span>` +\n `<button type=\"button\" class=\"sl-extend-btn\" data-ref=\"extendBtn\"></button>`;\n (this.regions['bottom-center'] ?? this.els.map).appendChild(el);\n this.extendEl = el;\n this.els.extendTxt = el.querySelector('[data-ref=\"extendTxt\"]') as HTMLElement;\n this.els.extendBtn = el.querySelector('[data-ref=\"extendBtn\"]') as HTMLElement;\n this.els.extendBtn.textContent = 'Add time';\n this.els.extendBtn.addEventListener('click', () => void this.handleExtend());\n }\n\n /** Success overlay + onBooked fire when the held seats settle to booked. */\n private buildBookedOverlay(): void {\n const el = document.createElement('div');\n el.className = 'sl-booked';\n el.setAttribute('role', 'status');\n el.setAttribute('aria-live', 'polite');\n el.innerHTML =\n `<div class=\"sl-booked-badge\"><svg viewBox=\"0 0 24 24\"><path d=\"M20 6L9 17l-5-5\"/></svg></div>` +\n `<div class=\"sl-booked-title\">You're all set</div>` +\n `<div class=\"sl-booked-sub\" data-ref=\"bookedSub\"></div>`;\n this.root!.appendChild(el);\n this.bookedEl = el;\n this.els.bookedSub = el.querySelector('[data-ref=\"bookedSub\"]') as HTMLElement;\n }\n\n /**\n * Localized string with a literal fallback. `t()` returns the key itself for\n * unknown keys, so this collapses that to `fallback` — while still honoring a\n * host `messages` override (which makes `t()` return the override, not the key).\n */\n private tf(key: string, fallback: string): string {\n const v = t(key);\n return v === key ? fallback : v;\n }\n\n /** Sold-out overlay — centered over the map, disabled waitlist stub (Gap 2). */\n private buildSoldoutOverlay(): void {\n if (!this.els.map) return;\n const el = document.createElement('div');\n el.className = 'sl-soldout';\n el.setAttribute('role', 'status');\n const name = (this.controller.doc?.theme?.brandName ?? this.opts.theme?.brandName ?? this.els.name?.textContent ?? this.tf('picker.soldOutEyebrow', 'This event')).toUpperCase();\n el.innerHTML =\n `<div class=\"sl-soldout-eyebrow\">${name}</div>` +\n `<div class=\"sl-soldout-title\">${this.tf('picker.soldOutTitle', 'Sold out')}</div>` +\n `<p class=\"sl-soldout-copy\">${this.tf('picker.soldOutCopy', \"Every seat is gone. Join the waitlist and we’ll email you if seats are released.\")}</p>` +\n `<button type=\"button\" class=\"sl-soldout-btn\" disabled>${this.tf('picker.waitlist', 'Join waitlist')}</button>`;\n this.els.map.appendChild(el);\n this.soldoutEl = el;\n }\n\n /**\n * Recompute the sold-out state on every price/availability sync. Sold-out ⇔\n * every SEATED category's live free count is 0. Suppressed when the chart has\n * GA areas (GA capacity isn't per-seat, so seated counts would read 0 and\n * falsely block standing room) — mirrors the public page. Clears live when WS\n * frees a seat up.\n */\n private syncSoldout(categories: Array<{ key: string }>, left: Record<string, number>): void {\n const hasGA = this.controller.getGAAreas().length > 0;\n const soldOut = this.isSoldOut(categories, left, hasGA);\n if (soldOut === this.soldOut) return;\n this.soldOut = soldOut;\n this.soldoutEl?.classList.toggle('on', soldOut);\n }\n\n /**\n * Pure sold-out predicate: every SEATED category's free count is 0, there is at\n * least one seated category, and there are no GA areas (GA capacity isn't\n * per-seat, so seated counts read 0 and would falsely block standing room).\n * `left` is seeded implicitly — a missing key means a fully-booked tier (0 free).\n */\n private isSoldOut(categories: Array<{ key: string }>, left: Record<string, number>, hasGA: boolean): boolean {\n return !hasGA && categories.length > 0 && categories.every((c) => (left[c.key] ?? 0) === 0);\n }\n\n /**\n * Sales-closed read-only state (Gap 3): persistent header pill, disabled CTA\n * with a closed label, and frozen best-available / GA controls. `setSalesClosed`\n * is the reactive entry (live 409 event_closed); `applySalesClosed` is the\n * idempotent DOM apply used at load and on transition.\n */\n private setSalesClosed(closed: boolean): void {\n if (this.salesClosed === closed) return;\n this.salesClosed = closed;\n this.applySalesClosed();\n }\n\n private applySalesClosed(): void {\n if (this.salesClosed && this.tableDialog && !this.tableDialogHeld) this.cancelTableDialog();\n const pill = this.els.closedPill;\n if (pill) {\n pill.classList.toggle('on', this.salesClosed);\n const text = this.els.closedPillText ?? pill;\n text.textContent = this.tf('picker.salesClosedPill', 'Sales are closed');\n }\n this.root?.setAttribute('data-sales-closed', String(this.salesClosed));\n this.syncCta();\n this.syncTray();\n }\n\n /** The badge is hidden when the host opts out OR the org's theme sets hideBadge. */\n private badgeHidden(chartTheme?: ChartTheme): boolean {\n return !!(this.opts.hideBadge || chartTheme?.hideBadge);\n }\n\n /** Attribution badge in the side-panel foot (Gap 7). Hidden per host/theme. */\n private buildBadge(chartTheme: ChartTheme | undefined): void {\n if (this.badgeHidden(chartTheme)) return;\n const foot = this.els.foot;\n if (!foot) return;\n const el = document.createElement('div');\n el.className = 'sl-powered';\n el.innerHTML =\n `<span class=\"sl-powered-mark\" aria-hidden=\"true\">` +\n SEATLAYER_ATTRIBUTION_MARK_SVG +\n `</span><span>${this.tf('picker.poweredBy', 'Powered by SeatLayer')}</span>`;\n foot.appendChild(el);\n }\n\n // ---- Feature 6: chrome anchor regions -------------------------------------\n\n /**\n * Create the positioned flex containers that own every persistent map overlay.\n * Appended once after controller.render(); each chrome piece is then appended\n * INTO its region and flows within it, so nothing free-floats over anything\n * else. Regions carve the map into non-overlapping zones (top strip split into\n * left/center/right, left rail, and the three used corners).\n */\n private buildRegions(): void {\n if (!this.els.map) return;\n const REGIONS = ['top-left', 'top-center', 'top-right', 'left-rail', 'bottom-left', 'bottom-center', 'bottom-right'];\n for (const region of REGIONS) {\n const el = document.createElement('div');\n el.className = 'sl-anchor';\n el.dataset.region = region;\n this.els.map.appendChild(el);\n this.regions[region] = el;\n }\n }\n\n // ---- F3 minimap -----------------------------------------------------------\n\n /** Read a resolved --sl-* token value (canvas needs a real color, not var()). */\n private cssVar(name: string): string {\n return this.root ? getComputedStyle(this.root).getPropertyValue(name).trim() : '';\n }\n\n /** Motion is progressive enhancement; all state remains legible when reduced. */\n private reducedMotion(): boolean {\n return typeof window !== 'undefined' &&\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n }\n\n private scheduleMotion(fn: () => void, delay: number): void {\n const timer = setTimeout(() => {\n this.motionTimers.delete(timer);\n if (!this.destroyed) fn();\n }, delay);\n this.motionTimers.add(timer);\n }\n\n /** Restart one finite CSS animation without leaving a permanent state class. */\n private animateOnce(el: HTMLElement | undefined, className: string, duration = 600): void {\n if (!el || this.reducedMotion()) return;\n el.classList.remove(className);\n void el.offsetWidth;\n el.classList.add(className);\n this.scheduleMotion(() => el.classList.remove(className), duration);\n }\n\n /** Selection feedback belongs on the selected seat, not across the whole map. */\n private flashPickedSeat(id: string): void {\n if (this.reducedMotion()) return;\n this.controller.flashSeat(id, this.cssVar('--sl-accent') || '#f4b740');\n }\n\n /** A completed hold gets one short map ripple per concrete seat. */\n private flashHeldSeats(hold: HoldResult): void {\n if (this.reducedMotion()) return;\n const labels = (hold.items ?? []).filter((item) => item.objectType !== 'ga').map((item) => item.label);\n labels.slice(0, 10).forEach((label, index) => {\n const seat = this.controller.seatByLabel(label);\n if (!seat) return;\n this.scheduleMotion(\n () => this.controller.flashSeat(seat.id, this.cssVar('--sl-accent') || '#f4b740'),\n index * 55,\n );\n });\n }\n\n /** Update only the action affordance; selection callbacks must not refire. */\n private committedSelection(): PickerSeat[] {\n const candidateId = this.confirmSeat?.id;\n const pendingTableId = this.tableDialog && !this.tableDialogHeld ? this.tableDialog.id : null;\n return this.controller.getSelection().filter((seat) => seat.id !== candidateId && seat.id !== pendingTableId);\n }\n\n private pendingSelectionCount(): number {\n const heldItems = this.hold?.items ?? [];\n const heldLabels = new Set(heldItems.map((item) => item.label));\n const pendingSeats = this.committedSelection()\n .filter((seat) => !heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n return pendingSeats + this.pendingGACount();\n }\n\n private heldGACounts(): Map<string, number> {\n const heldGA = new Map<string, number>();\n for (const item of (this.hold?.items ?? []).filter((candidate) => candidate.objectType === 'ga')) {\n heldGA.set(item.objectId, (heldGA.get(item.objectId) ?? 0) + (item.quantity ?? 1));\n }\n return heldGA;\n }\n\n private pendingGACount(): number {\n const heldGA = this.heldGACounts();\n return [...this.gaQty.entries()].reduce(\n (sum, [areaId, qty]) => sum + Math.max(0, qty - (heldGA.get(areaId) ?? 0)),\n 0,\n );\n }\n\n private heldTicketCount(): number {\n return (this.hold?.items ?? []).reduce((sum, item) => sum + (item.quantity ?? 1), 0);\n }\n\n private totalTicketCount(): number {\n const heldLabels = new Set((this.hold?.items ?? []).map((item) => item.label));\n const freshSeats = this.committedSelection()\n .filter((seat) => !heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n return this.heldTicketCount() + freshSeats + this.pendingGACount();\n }\n\n /** Held tickets and standing quantities consume the same order-wide cap. */\n private updateSelectionCapacity(): void {\n const heldLabels = new Set((this.hold?.items ?? []).map((item) => item.label));\n const selectedHeld = this.committedSelection()\n .filter((seat) => heldLabels.has(seat.label))\n .reduce((sum, seat) => sum + (seat.quantity ?? 1), 0);\n const remaining = Math.max(0, this.maxTickets - this.heldTicketCount() - this.pendingGACount());\n this.controller.setMaxSelection(selectedHeld + remaining);\n }\n\n private canAddTicket(): boolean {\n if (this.totalTicketCount() < this.maxTickets) return true;\n this.toast(`You can select up to ${this.maxTickets} tickets for this order.`, 'warning');\n return false;\n }\n\n private pendingGATotal(gaAreas: ReturnType<PickerController['getGAAreas']>): number {\n const heldGA = new Map<string, number>();\n for (const item of (this.hold?.items ?? []).filter((candidate) => candidate.objectType === 'ga')) {\n heldGA.set(item.objectId, (heldGA.get(item.objectId) ?? 0) + (item.quantity ?? 1));\n }\n return gaAreas.reduce(\n (sum, area) => sum + this.paidPrice(area.categoryKey, null, area.price) * Math.max(0, (this.gaQty.get(area.id) ?? 0) - (heldGA.get(area.id) ?? 0)),\n 0,\n );\n }\n\n private syncCta(count = this.lastTrayCount, pending = this.pendingSelectionCount()): void {\n const cta = this.els.cta as HTMLButtonElement | undefined;\n if (!cta) return;\n if (this.salesClosed) {\n cta.disabled = true;\n cta.textContent = this.tf('picker.salesClosedCta', 'Sales closed');\n return;\n }\n if (this.confirmSeat || (this.tableDialog && !this.tableDialogHeld)) {\n cta.disabled = true;\n cta.textContent = this.tableDialog ? 'Confirm your table' : 'Confirm or cancel this seat';\n return;\n }\n if (this.ctaPhase === 'holding') {\n cta.disabled = true;\n cta.innerHTML = '<span class=\"sl-cta-spin\" aria-hidden=\"true\"></span>Securing seats…';\n return;\n }\n if (this.ctaPhase === 'checkout') {\n cta.disabled = true;\n cta.innerHTML = '<span class=\"sl-cta-spin\" aria-hidden=\"true\"></span>Opening checkout…';\n return;\n }\n cta.disabled = count === 0;\n cta.textContent = this.hold\n ? pending\n ? `Secure ${pending} more & checkout`\n : 'Continue to checkout'\n : count\n ? 'Hold seats & checkout'\n : 'Select seats';\n }\n\n private setCtaPhase(phase: 'idle' | 'holding' | 'checkout'): void {\n this.ctaPhase = phase;\n this.syncCta();\n if (phase === 'checkout') {\n this.scheduleMotion(() => {\n if (this.ctaPhase !== 'checkout') return;\n this.ctaPhase = 'idle';\n this.syncCta();\n }, 1100);\n }\n }\n\n /** Session-scoped capability key: isolated by API origin and event. */\n private holdStorageKey(): string {\n return `@seatlayer/hold/v1/${encodeURIComponent(this.apiBase)}/${encodeURIComponent(this.opts.event)}`;\n }\n\n private rememberedHoldId(): string | null {\n if (this.opts.initialHoldId) return this.opts.initialHoldId;\n if (this.opts.restoreHold === false || typeof window === 'undefined') return null;\n try {\n return window.sessionStorage.getItem(this.holdStorageKey());\n } catch {\n return null;\n }\n }\n\n private rememberHold(hold: HoldResult): void {\n if (this.opts.restoreHold === false || typeof window === 'undefined') return;\n try {\n // Persist only the opaque capability. Labels, prices and expiry are\n // always reloaded from the authoritative server projection.\n window.sessionStorage.setItem(this.holdStorageKey(), hold.holdId);\n } catch {\n // Storage can be unavailable in privacy/sandboxed embeds; the live picker\n // remains fully functional for the current mount.\n }\n }\n\n private forgetHold(): void {\n if (typeof window === 'undefined') return;\n try {\n window.sessionStorage.removeItem(this.holdStorageKey());\n } catch {\n // Best-effort cleanup only.\n }\n }\n\n private async resumeHoldFromServer(holdId: string, automatic: boolean): Promise<HoldResult | null> {\n try {\n const h = await this.controller.resumeHold(holdId);\n if (!h) return null;\n const restored: HoldResult = {\n holdId: h.holdId,\n expiresAt: h.expiresAt,\n seats: h.seats,\n items: h.items,\n };\n this.hold = restored;\n // A resumed capability came from an earlier checkout handoff. Keep it\n // alive if this picker mount is refreshed or torn down before the buyer\n // explicitly removes/releases it.\n this.handedOff = true;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.startHoldTimer(restored.expiresAt);\n this.rememberHold(restored);\n this.syncTray();\n this.emitHoldChange();\n this.opts.onHoldRestored?.(restored, restored.seats ?? [], this.buildHandoff(restored));\n if (automatic) this.toast('Your held tickets have been restored.', 'success');\n return restored;\n } catch (error) {\n const status = (error as { status?: number })?.status;\n if (status === 404 || status === 409) {\n // A stale/foreign/settled capability is expected recovery state, not a\n // picker failure. Drop it and let the buyer choose again.\n this.forgetHold();\n } else {\n this.opts.onError?.(error);\n }\n return null;\n }\n }\n\n private async restoreRememberedHold(): Promise<void> {\n const holdId = this.rememberedHoldId();\n if (holdId) await this.resumeHoldFromServer(holdId, true);\n }\n\n /** Section-bearing objects on the active floor (single-floor → doc.objects). */\n private activeFloorObjects(): SectionLike[] {\n const doc = this.controller.doc;\n if (!doc) return [];\n const floors = doc.floors;\n if (floors?.length) {\n const id = this.controller.getActiveFloorId();\n return ((floors.find((f) => f.id === id) ?? floors[0]).objects as unknown as SectionLike[]) ?? [];\n }\n return (doc.objects as unknown as SectionLike[]) ?? [];\n }\n\n /**\n * Build the overview minimap: a static venue thumbnail (section outlines, or\n * seat dots when the chart has no sections) with the live viewport rectangle\n * drawn on top. The rect tracks pan/zoom via the constructor's onViewChange.\n */\n private buildMinimap(): void {\n const vp = this.controller.getViewport();\n if (!vp || !this.els.map) return;\n const b = vp.bounds;\n if (!(b.width > 0 && b.height > 0)) return;\n\n const MAXW = 158;\n const MAXH = 118;\n const PAD = 6;\n const aspect = b.width / Math.max(1, b.height);\n let w = MAXW;\n let h = Math.round(MAXW / aspect);\n if (h > MAXH) {\n h = MAXH;\n w = Math.round(MAXH * aspect);\n }\n w = Math.max(64, w);\n h = Math.max(48, h);\n const dpr = Math.min(2, window.devicePixelRatio || 1);\n\n const wrap = document.createElement('div');\n wrap.className = 'sl-minimap';\n wrap.setAttribute('aria-hidden', 'true'); // decorative; the map itself is the keyboard surface\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(w * dpr);\n canvas.height = Math.round(h * dpr);\n canvas.style.width = `${w}px`;\n canvas.style.height = `${h}px`;\n wrap.appendChild(canvas);\n (this.regions['bottom-left'] ?? this.els.map).appendChild(wrap);\n this.miniCanvas = canvas;\n\n // world → minimap (device px), contain + centre — matches thumb.ts.\n const scale = Math.min((w - PAD * 2) / Math.max(1, b.width), (h - PAD * 2) / Math.max(1, b.height)) * dpr;\n const offX = (w * dpr - b.width * scale) / 2 - b.x * scale;\n const offY = (h * dpr - b.height * scale) / 2 - b.y * scale;\n this.miniTf = { scale, offX, offY, dpr };\n\n const base = document.createElement('canvas');\n base.width = canvas.width;\n base.height = canvas.height;\n this.miniBase = base;\n\n // Click a section on the minimap → glide the camera into it (existing API).\n wrap.addEventListener('click', (e) => this.minimapJump(e));\n\n this.drawMinimapStatic();\n this.drawMinimapRect();\n }\n\n /** Repaint the static overview + rect (floor switch, live open/close). */\n private refreshMinimap(): void {\n if (!this.miniBase) return;\n this.drawMinimapStatic();\n this.drawMinimapRect();\n }\n\n /** Paint the venue overview into the offscreen base canvas. */\n private drawMinimapStatic(): void {\n const base = this.miniBase;\n const tf = this.miniTf;\n const doc = this.controller.doc;\n if (!base || !tf || !doc) return;\n const ctx = base.getContext('2d');\n if (!ctx) return;\n ctx.clearRect(0, 0, base.width, base.height);\n const fx = (x: number): number => x * tf.scale + tf.offX;\n const fy = (y: number): number => y * tf.scale + tf.offY;\n const line = this.cssVar('--sl-line') || 'rgba(139,147,167,.5)';\n const muted = this.cssVar('--sl-muted') || '#8b93a7';\n const accent = this.cssVar('--sl-accent') || '#6e7bff';\n const zoneColor = new Map((doc.zones ?? []).map((z) => [z.id, z.color] as const));\n\n let drewSection = false;\n for (const o of this.activeFloorObjects()) {\n if (o.type !== 'section' || !o.outline || o.outline.length < 3) continue;\n drewSection = true;\n const closed = this.controller.isSectionClosed(o.id);\n const fill = closed ? muted : o.color ?? (o.zone && zoneColor.get(o.zone)) ?? accent;\n ctx.beginPath();\n o.outline.forEach((p, i) => (i === 0 ? ctx.moveTo(fx(p.x), fy(p.y)) : ctx.lineTo(fx(p.x), fy(p.y))));\n ctx.closePath();\n ctx.globalAlpha = closed ? 0.26 : 0.42;\n ctx.fillStyle = fill;\n ctx.fill();\n ctx.globalAlpha = 0.85;\n ctx.lineWidth = Math.max(1, tf.dpr);\n ctx.strokeStyle = line;\n ctx.stroke();\n }\n ctx.globalAlpha = 1;\n\n // Section-less charts: fall back to faint category-colored seat dots.\n if (!drewSection) {\n const r = Math.max(1, tf.dpr);\n for (const seat of expandChart(doc)) {\n const cat = doc.categories.find((c) => c.key === seat.categoryKey);\n ctx.fillStyle = cat?.color ?? accent;\n ctx.beginPath();\n ctx.arc(fx(seat.x), fy(seat.y), r, 0, Math.PI * 2);\n ctx.fill();\n }\n }\n }\n\n /** Blit the base overview, then stroke the current viewport rectangle on top. */\n private drawMinimapRect(): void {\n const canvas = this.miniCanvas;\n const base = this.miniBase;\n const tf = this.miniTf;\n if (!canvas || !base || !tf) return;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(base, 0, 0);\n const vp = this.controller.getViewport();\n if (!vp) return;\n const v = vp.visible;\n const x = v.x * tf.scale + tf.offX;\n const y = v.y * tf.scale + tf.offY;\n const w = v.width * tf.scale;\n const h = v.height * tf.scale;\n const accent = this.cssVar('--sl-accent') || '#f4b740';\n ctx.save();\n ctx.globalAlpha = 0.14;\n ctx.fillStyle = accent;\n ctx.fillRect(x, y, w, h);\n ctx.globalAlpha = 1;\n ctx.lineWidth = Math.max(1.5, tf.dpr * 1.5);\n ctx.strokeStyle = accent;\n ctx.strokeRect(x, y, w, h);\n ctx.restore();\n }\n\n /** Minimap click → focus the section under the point (or overview on a miss). */\n private minimapJump(e: MouseEvent): void {\n const canvas = this.miniCanvas;\n const tf = this.miniTf;\n if (!canvas || !tf) return;\n const r = canvas.getBoundingClientRect();\n const px = (e.clientX - r.left) * (canvas.width / r.width);\n const py = (e.clientY - r.top) * (canvas.height / r.height);\n const wx = (px - tf.offX) / tf.scale;\n const wy = (py - tf.offY) / tf.scale;\n for (const o of this.activeFloorObjects()) {\n if (o.type !== 'section' || !o.outline || o.outline.length < 3) continue;\n if (this.controller.isSectionClosed(o.id)) continue;\n if (pointInPolygon(wx, wy, o.outline)) {\n this.controller.focusSection(o.id);\n return;\n }\n }\n this.controller.overview();\n }\n\n // ---- F4 price-band filter -------------------------------------------------\n\n /** Effective display price of a category: host pricing override → first tier → base. */\n private catPrice(c: { key?: string; price?: number; tiers?: { id?: string; price: number }[] }): number | undefined {\n const chart = c.tiers?.length ? c.tiers[0].price : c.price;\n if (chart === undefined || !c.key) return chart;\n return this.paidPrice(c.key, c.tiers?.[0]?.id ?? null, chart);\n }\n\n /** Derive price bands: one chip per distinct price (≤5), else quantile ranges. */\n private priceBands(): PriceBand[] {\n const doc = this.controller.doc;\n if (!doc) return [];\n const priced = doc.categories\n .map((c) => ({ key: c.key, price: this.catPrice(c) }))\n .filter((x): x is { key: string; price: number } => x.price != null);\n if (!priced.length) return [];\n const distinct = [...new Set(priced.map((p) => p.price))].sort((a, b) => a - b);\n if (distinct.length <= 5) {\n return distinct.map((price) => ({\n id: `p${price}`,\n label: this.money(price),\n keys: priced.filter((p) => p.price === price).map((p) => p.key),\n min: price,\n max: price,\n }));\n }\n // Many distinct prices → ~4 contiguous quantile bands (ranges).\n const chunk = Math.ceil(distinct.length / 4);\n const bands: PriceBand[] = [];\n for (let i = 0; i < distinct.length; i += chunk) {\n const slice = distinct.slice(i, i + chunk);\n const lo = slice[0];\n const hi = slice[slice.length - 1];\n bands.push({\n id: `b${i}`,\n label: lo === hi ? this.money(lo) : `${this.money(lo)}–${this.money(hi)}`,\n keys: priced.filter((p) => p.price >= lo && p.price <= hi).map((p) => p.key),\n min: lo,\n max: hi,\n });\n }\n return bands;\n }\n\n /** Build the compact price selector in the panel header. Choosing a band both\n * filters availability and smoothly frames the matching seats on the map. */\n private buildPriceFilter(): void {\n if (!this.els.prices || !this.els.pricesSec) return;\n const bands = this.priceBands();\n if (bands.length < 2) return;\n const select = document.createElement('select');\n select.className = 'sl-price-select';\n select.setAttribute('aria-label', 'Filter and focus seats by price');\n select.innerHTML = `<option value=\"all\">All prices</option>` + bands\n .map((band) => `<option value=\"${band.id}\">${band.label}</option>`)\n .join('');\n this.els.pricesSec.appendChild(select);\n select.addEventListener('change', () => {\n const band = bands.find((candidate) => candidate.id === select.value);\n const keys = band?.keys ?? null;\n this.focusedCatKey = null; // band filter supersedes any pinned row focus\n this.priceBandKeys = keys ? new Set(keys) : null;\n this.controller.setCategoryFilter(keys);\n this.controller.focusCategoryFilter(keys);\n // The band has to survive a switch into 3D, which paints from its own\n // state snapshot rather than from Konva opacity.\n this.pushAvailabilityTo3d();\n // A band whose seats live on another deck switches floors — mirror it.\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n // Reflect the band in the legend rows + any open section card.\n this.syncPrices();\n if (this.lastSection) this.showSectionCard(this.lastSection);\n });\n }\n\n // ---- arena / multi-floor chrome -------------------------------------------\n\n /** Build projection, rung and floor controls for arena-scale charts. */\n private buildArenaChrome(): void {\n const doc = this.controller.doc;\n if (!doc || !this.els.map) return;\n const hasSections = doc.objects.some((o) => o.type === 'section')\n || (doc.floors ?? []).some((f) => f.objects.some((o) => o.type === 'section'));\n\n // Buyer view toggle: **Map | 3D** (2.5D/perspective is retired from the buyer\n // surface). The 3D button is offered only when 3D is enabled AND the browser\n // exposes WebGL2 — otherwise the picker stays a plain flat map with no toggle\n // at all. Available for ANY chart with a real 3D relief source, not just\n // sectioned venues.\n if (this.canOffer3d()) {\n const projection = document.createElement('div');\n projection.className = 'sl-projection';\n projection.setAttribute('role', 'group');\n projection.setAttribute('aria-label', 'Venue view');\n projection.innerHTML =\n '<button type=\"button\" data-view=\"map\" aria-pressed=\"true\" title=\"Flat 2D map\">Map</button>' +\n '<button type=\"button\" data-view=\"venue3d\" aria-pressed=\"false\" title=\"Interactive 3D venue view\">3D</button>';\n projection.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {\n button.addEventListener('click', () => {\n this.setBuyerView(button.dataset.view as 'map' | 'venue3d');\n });\n });\n this.regions['top-right'].appendChild(projection);\n this.projectionEl = projection;\n this.syncProjection();\n }\n\n // LOD rung pills — jump straight between zones / sections / seats.\n if (hasSections) {\n const RUNGS: LodRung[] = ['zones', 'sections', 'seats'];\n const pills = document.createElement('div');\n pills.className = 'sl-rungs on';\n pills.setAttribute('role', 'group');\n pills.setAttribute('aria-label', t('picker.zoomLevel'));\n const LABEL: Record<LodRung, string> = {\n zones: t('picker.rungLabel.zones'),\n sections: t('picker.rungLabel.sections'),\n seats: t('picker.rungLabel.seats'),\n };\n const TIP: Record<LodRung, string> = {\n zones: t('picker.rungTip.zones'),\n sections: t('picker.rungTip.sections'),\n seats: t('picker.rungTip.seats'),\n };\n pills.innerHTML = RUNGS.map(\n (r) => `<button type=\"button\" data-rung=\"${r}\" title=\"${TIP[r]}\" aria-pressed=\"false\">${LABEL[r]}</button>`,\n ).join('');\n pills.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.addEventListener('click', () => {\n const rung = btn.dataset.rung as LodRung;\n this.controller.setRung(rung);\n if (rung === 'seats') this.collapseSectionCard();\n });\n });\n this.regions['top-center'].appendChild(pills);\n this.rungsEl = pills;\n this.syncRung();\n }\n\n // Multi-floor switcher — only when the chart truly has >1 floor.\n if (this.controller.isMultiFloor()) {\n const floors = this.controller.getFloors();\n const rail = document.createElement('div');\n rail.className = 'sl-floors on';\n rail.setAttribute('role', 'group');\n rail.setAttribute('aria-label', t('picker.floor'));\n rail.innerHTML = floors\n .map((f) => `<button type=\"button\" data-floor=\"${f.id}\">${f.name}</button>`)\n .join('');\n rail.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.addEventListener('click', () => {\n this.controller.setFloor(btn.dataset.floor!);\n this.showSectionCard(null);\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n });\n });\n this.regions['left-rail'].appendChild(rail);\n this.floorsEl = rail;\n this.syncFloors();\n }\n }\n\n /** Reflect the engine's current LOD rung onto the pill group. */\n private syncRung(): void {\n if (!this.rungsEl) return;\n const active = this.controller.getRung();\n this.rungsEl.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n const on = btn.dataset.rung === active;\n btn.classList.toggle('on', on);\n btn.setAttribute('aria-pressed', String(on));\n });\n }\n\n private syncProjection(): void {\n if (!this.projectionEl) return;\n this.projectionEl.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {\n const on = button.dataset.view === this.buyerView;\n button.classList.toggle('on', on);\n button.setAttribute('aria-pressed', String(on));\n });\n }\n\n /** Can this picker offer the 3D venue view? Requires the option (default on),\n * WebGL2, a chart to render, and a chart small enough to render WELL. */\n private canOffer3d(): boolean {\n if (this.opts.enable3D === false || !this.controller.doc || !hasWebGL2()) return false;\n return this.allSeats().length <= this.max3dSeats();\n }\n\n /**\n * The seat ceiling for offering 3D. See `max3DSeats` — an explicit host value\n * always wins; otherwise a small/low-core device gets half the desktop budget,\n * because it is the device that turns \"slow\" into \"stalled\".\n */\n private max3dSeats(): number {\n const authored = this.opts.max3DSeats;\n if (typeof authored === 'number' && authored > 0) return authored;\n const nav = globalThis.navigator as (Navigator & { deviceMemory?: number }) | undefined;\n const small = (nav?.hardwareConcurrency ?? 8) <= 4\n || (nav?.deviceMemory ?? 8) <= 4\n || (globalThis.matchMedia?.('(pointer: coarse)').matches ?? false);\n return small ? MAX_3D_SEATS_DEFAULT / 2 : MAX_3D_SEATS_DEFAULT;\n }\n\n /** Reflect the active floor onto the switcher rail. */\n private syncFloors(): void {\n if (!this.floorsEl) return;\n const active = this.controller.getActiveFloorId();\n this.floorsEl.querySelectorAll<HTMLButtonElement>('button').forEach((btn) => {\n btn.classList.toggle('on', btn.dataset.floor === active);\n });\n }\n\n /** Show (or clear, on null) the tapped-section summary card. */\n private showSectionCard(summary: SectionSummary | null): void {\n this.lastSection = summary;\n this.secCardEl?.remove();\n this.secCardEl = null;\n if (!summary) return;\n // At seat level the summary is context, not a blocking decision surface.\n // Keep it as the compact pill from the first seat-level paint.\n this.secCardCollapsed = this.controller.getRung() === 'seats';\n this.secCardShownAt = Date.now();\n this.renderSectionCard(summary);\n }\n\n /**\n * Render the section card in the form the layout + state want: expanded card\n * or slim pill in the top-center anchor region (wide), or a compact strip in\n * the sheet head (narrow). Never floats over the seats at the tap point.\n */\n private renderSectionCard(summary: SectionSummary): void {\n if (!this.els.map) return;\n this.secCardEl?.remove();\n // min/max over the section's categories at the price the buyer will PAY\n // (host pricing override aware) — not the chart's stored range.\n const paid = summary.categories.length\n ? summary.categories.map((c) => this.paidPrice(c.key, null, c.price))\n : [summary.priceMin, summary.priceMax];\n const paidMin = Math.min(...paid);\n const paidMax = Math.max(...paid);\n const priceLabel =\n paidMin === paidMax\n ? this.money(paidMin)\n : `${this.money(paidMin)}–${this.money(paidMax)}`;\n const leftLabel = tCount('picker.seatsLeftInSection', summary.seatsLeft);\n const xBtn = `<button type=\"button\" class=\"sl-seccard-x\" aria-label=\"${t('picker.closeSectionSummary')}\">✕</button>`;\n const card = document.createElement('div');\n const narrow = this.root?.dataset.layout === 'narrow';\n\n if (narrow) {\n // Compact strip inside the bottom sheet's peek head — never over the map.\n card.className = 'sl-seccard strip on';\n card.setAttribute('role', 'status');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n card.innerHTML =\n `<span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span>` +\n (summary.categories.length ? `<span class=\"sl-seccard-price\">${priceLabel}</span>` : '') +\n xBtn;\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n (this.els.sheetHead ?? this.els.side ?? this.els.map).appendChild(card);\n } else if (this.secCardCollapsed) {\n // Slim pill — seat-picking has begun. Tap to re-expand; ✕ still closes.\n card.className = 'sl-seccard mini on';\n card.setAttribute('role', 'button');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n card.innerHTML =\n `<span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span>` +\n xBtn;\n card.addEventListener('click', (e) => {\n if ((e.target as HTMLElement).closest('.sl-seccard-x')) return;\n this.secCardCollapsed = false;\n this.secCardShownAt = Date.now();\n this.renderSectionCard(summary);\n });\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n (this.regions['top-center'] ?? this.els.map).appendChild(card);\n } else {\n card.className = 'sl-seccard on';\n card.setAttribute('role', 'dialog');\n card.setAttribute('aria-label', t('picker.sectionSummaryAria', { label: summary.label }));\n const mix = summary.categories\n .map((c) => {\n const dim = this.priceBandKeys != null && !this.priceBandKeys.has(c.key);\n return (\n `<span class=\"sl-seccard-mix-item${dim ? ' sl-dim' : ''}\"><span class=\"sl-seccard-mix-dot\" style=\"background:${c.color}\"></span>` +\n `${c.label} <span class=\"sl-seccard-mix-price\">${this.money(this.paidPrice(c.key, null, c.price))}</span></span>`\n );\n })\n .join('');\n card.innerHTML =\n `<div class=\"sl-seccard-head\"><span class=\"sl-seccard-dot\" style=\"background:${summary.color}\"></span>` +\n `<span class=\"sl-seccard-name\">${summary.label}</span>` +\n (summary.categories.length ? `<span class=\"sl-seccard-price\">${priceLabel}</span>` : '') +\n xBtn + `</div>` +\n `<div class=\"sl-seccard-zone\">${summary.zoneLabel ? `${summary.zoneLabel} · ` : ''}` +\n `<span class=\"sl-seccard-left\">${leftLabel}</span></div>` +\n (summary.entrance\n ? `<div class=\"sl-seccard-entrance\">${t('picker.entrance')} ${String(summary.entrance).replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!))}</div>`\n : '') +\n (mix ? `<div class=\"sl-seccard-mix\">${mix}</div>` : '') +\n `<div class=\"sl-seccard-foot\">` +\n `<button type=\"button\" class=\"sl-seccard-overview\">← ${t('picker.overview')}</button>` +\n `<span class=\"sl-seccard-hint\">${t('picker.tapSeatHint')}</span></div>`;\n card.querySelector('.sl-seccard-x')!.addEventListener('click', () => this.controller.overview());\n card.querySelector('.sl-seccard-overview')!.addEventListener('click', () => this.controller.overview());\n (this.regions['top-center'] ?? this.els.map).appendChild(card);\n }\n this.secCardEl = card;\n }\n\n /** Collapse the expanded card to its slim pill (seat-picking started). */\n private collapseSectionCard(): void {\n if (!this.secCardEl || this.secCardCollapsed || !this.lastSection) return;\n if (this.root?.dataset.layout === 'narrow') return; // strip is already compact\n this.secCardCollapsed = true;\n this.renderSectionCard(this.lastSection);\n }\n\n /**\n * onViewChange hook for the card. The focus glide's own settle (within the\n * grace window) enforces the ~25% coverage rule with the FINAL viewport; any\n * later pan/zoom means seat-picking has begun → collapse to the pill.\n */\n private sectionCardOnView(): void {\n if (!this.secCardEl || this.secCardCollapsed || !this.lastSection) return;\n if (this.root?.dataset.layout === 'narrow') return;\n if (this.controller.getRung() === 'seats') {\n this.collapseSectionCard();\n return;\n }\n if (Date.now() - this.secCardShownAt < 1400) {\n if (this.sectionCardCoverage() > 0.25) this.collapseSectionCard();\n return;\n }\n this.collapseSectionCard();\n }\n\n /** Fraction of the focused section's on-screen bbox covered by the card. */\n private sectionCardCoverage(): number {\n const card = this.secCardEl;\n const sec = this.lastSection;\n if (!card || !sec || !this.els.map) return 0;\n const outline = this.activeFloorObjects().find((o) => o.type === 'section' && o.id === sec.id)?.outline;\n if (!outline || outline.length < 3) return 0;\n const pts = outline.map((p) => this.controller.worldToScreen(p));\n const xs = pts.map((p) => p.x);\n const ys = pts.map((p) => p.y);\n const bx = Math.min(...xs);\n const by = Math.min(...ys);\n const bw = Math.max(...xs) - bx;\n const bh = Math.max(...ys) - by;\n if (bw <= 0 || bh <= 0) return 0;\n const mapR = this.els.map.getBoundingClientRect();\n const cr = card.getBoundingClientRect();\n const cx = cr.left - mapR.left;\n const cy = cr.top - mapR.top;\n const ox = Math.max(0, Math.min(cx + cr.width, bx + bw) - Math.max(cx, bx));\n const oy = Math.max(0, Math.min(cy + cr.height, by + bh) - Math.max(cy, by));\n return (ox * oy) / (bw * bh);\n }\n\n /** aria-live readout when keyboard focus lands on a seat. */\n private announceSeat(seat: ExpandedSeat | null): void {\n if (!this.srEl) return;\n if (!seat) {\n this.srEl.textContent = '';\n return;\n }\n const cat = this.controller.doc?.categories.find((c) => c.key === seat.categoryKey);\n const status = this.controller.getStatus(seat.id) ?? 'free';\n const statusText = status === 'free' ? 'available' : status === 'held' ? 'on hold' : 'taken';\n const price = cat ? this.catPrice(cat) : undefined;\n const table = this.controller.tableSelection(seat.id);\n const details = table ?? this.controller.seatDetails(seat.id);\n const typeWord = this.rowTypeWord(details);\n const buyerName = details?.rowLabel ?? details?.displayLabel ?? seat.displayLabel ?? seat.label;\n const identity = table\n ? `${typeWord} ${buyerName}, ${table.bookingMode === 'variable' ? `${table.minOccupancy} to ${table.maxOccupancy} guests` : `${table.capacity} guests`}`\n : details?.objectType === 'booth'\n ? `${typeWord} ${buyerName}`\n : details?.objectType === 'table'\n ? `${typeWord} ${buyerName}, seat ${details.seatNumber ?? seat.label}`\n : `Seat ${details?.displayLabel ?? seat.displayLabel ?? seat.label}`;\n this.srEl.textContent = `${identity}, ${cat?.label ?? seat.categoryKey}${\n price != null ? `, ${this.money(price)}` : ''\n }, ${statusText}`;\n }\n\n // ---- atomic table confirmation / guest quantity ---------------------------\n\n private showTableDialog(\n table: TableSelectionDetails,\n held: boolean,\n returnFocus?: HTMLElement | null,\n ): void {\n this.dismissTableDialog(false);\n this.tableDialog = { ...table };\n this.tableDialogHeld = held;\n this.tableDialogReturnFocus = returnFocus ?? (document.activeElement as HTMLElement | null);\n const esc = (value: unknown): string => String(value ?? '').replace(/[&<>\"']/g, (ch) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''',\n })[ch]!);\n const cat = this.controller.doc?.categories.find((candidate) => candidate.key === table.categoryKey);\n const variable = table.bookingMode === 'variable';\n const typeWord = this.rowTypeWord(table);\n const el = document.createElement('div');\n el.className = 'sl-table-scrim';\n el.innerHTML =\n `<section class=\"sl-table-dialog\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"sl-table-title\" aria-describedby=\"sl-table-copy\">` +\n `<div class=\"sl-table-head\"><div class=\"sl-table-eyebrow\">${esc(variable ? `Flexible party · ${typeWord}` : `Whole ${typeWord}`)}</div>` +\n `<h2 class=\"sl-table-title\" id=\"sl-table-title\">${esc(table.displayLabel ?? table.label)}</h2>` +\n `<p class=\"sl-table-copy\" id=\"sl-table-copy\">${variable\n ? `Choose how many guests will sit together. This table is held exclusively for your party.`\n : `All ${table.capacity} places are booked together as one exclusive table.`}</p></div>` +\n `<div class=\"sl-table-body\">` +\n `<div class=\"sl-table-summary\"><span>${esc(cat?.label ?? table.categoryKey)}</span><b data-table-unit>${this.money(this.paidPrice(table.categoryKey, table.tierId ?? null, table.price))} per guest</b>` +\n `<span class=\"muted\">Table capacity</span><span>${table.capacity} guests</span>` +\n `<span class=\"muted\">Total</span><b data-table-total></b></div>` +\n (variable\n ? `<label class=\"sl-table-qtylabel\" id=\"sl-table-qty-label\">Number of guests</label>` +\n `<div class=\"sl-table-stepper\" role=\"group\" aria-labelledby=\"sl-table-qty-label\">` +\n `<button type=\"button\" data-table-step=\"-1\" aria-label=\"Fewer guests\">−</button>` +\n `<output aria-live=\"polite\" data-table-qty>${table.quantity}</output>` +\n `<button type=\"button\" data-table-step=\"1\" aria-label=\"More guests\">+</button></div>` +\n `<div class=\"sl-table-range\">Choose ${table.minOccupancy}–${table.maxOccupancy} guests</div>`\n : `<input type=\"hidden\" data-table-qty value=\"${table.capacity}\">`) +\n `<div class=\"sl-table-actions\"><button type=\"button\" class=\"sl-table-cancel\">Cancel</button>` +\n `<button type=\"button\" class=\"sl-table-confirm\">${held ? 'Update table' : variable ? 'Select table' : 'Select whole table'}</button></div>` +\n `</div></section>`;\n this.root!.appendChild(el);\n this.tableDialogEl = el;\n this.renderTableDialogState();\n\n el.querySelectorAll<HTMLButtonElement>('[data-table-step]').forEach((button) => {\n button.addEventListener('click', () => {\n if (!this.tableDialog) return;\n const next = Math.max(\n this.tableDialog.minOccupancy,\n Math.min(this.tableDialog.maxOccupancy, this.tableDialog.quantity + Number(button.dataset.tableStep)),\n );\n this.tableDialog = { ...this.tableDialog, quantity: next };\n this.renderTableDialogState();\n });\n });\n el.querySelector<HTMLButtonElement>('.sl-table-cancel')!.addEventListener('click', () => this.cancelTableDialog());\n el.querySelector<HTMLButtonElement>('.sl-table-confirm')!.addEventListener('click', () => void this.confirmTableDialog());\n el.addEventListener('mousedown', (event) => {\n if (event.target === el) this.cancelTableDialog();\n });\n el.addEventListener('keydown', (event) => {\n if (event.key !== 'Tab') return;\n const focusable = [...el.querySelectorAll<HTMLElement>('button:not(:disabled),[tabindex]:not([tabindex=\"-1\"])')];\n if (!focusable.length) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n });\n requestAnimationFrame(() => (\n el.querySelector<HTMLButtonElement>(variable ? '[data-table-step=\"-1\"]' : '.sl-table-confirm')?.focus()\n ));\n }\n\n private renderTableDialogState(): void {\n const table = this.tableDialog;\n const el = this.tableDialogEl;\n if (!table || !el) return;\n const output = el.querySelector<HTMLOutputElement>('output[data-table-qty]');\n if (output) output.value = String(table.quantity);\n const hidden = el.querySelector<HTMLInputElement>('input[data-table-qty]');\n if (hidden) hidden.value = String(table.quantity);\n el.querySelectorAll<HTMLButtonElement>('[data-table-step]').forEach((button) => {\n const delta = Number(button.dataset.tableStep);\n button.disabled = delta < 0\n ? table.quantity <= table.minOccupancy\n : table.quantity >= table.maxOccupancy;\n });\n const unit = this.paidPrice(table.categoryKey, table.tierId ?? null, table.price);\n const total = el.querySelector<HTMLElement>('[data-table-total]');\n if (total) total.textContent = this.money(unit * table.quantity);\n }\n\n private async confirmTableDialog(): Promise<void> {\n const table = this.tableDialog;\n const held = this.tableDialogHeld;\n if (!table) return;\n const button = this.tableDialogEl?.querySelector<HTMLButtonElement>('.sl-table-confirm');\n if (button) {\n button.disabled = true;\n button.textContent = held ? 'Updating…' : 'Selecting…';\n }\n if (held) {\n try {\n const updated = await this.controller.replaceTableQuantity(table.label, table.quantity, this.opts.holdTtlMs);\n if (!updated) {\n this.toast('That guest count could not be secured. Your current table hold is unchanged.', 'warning');\n this.renderTableDialogState();\n if (button) {\n button.disabled = false;\n button.textContent = 'Update table';\n }\n return;\n }\n this.hold = {\n holdId: updated.holdId,\n expiresAt: updated.expiresAt,\n seats: updated.seats,\n items: updated.items,\n };\n this.startHoldTimer(updated.expiresAt);\n this.dismissTableDialog();\n this.syncTray();\n this.emitHoldChange();\n this.toast(`${table.label} updated for ${table.quantity} guests.`, 'success');\n } catch (error) {\n this.opts.onError?.(error);\n this.toast('That guest count is no longer available. Your current hold is unchanged.', 'error');\n if (button) {\n button.disabled = false;\n button.textContent = 'Update table';\n }\n }\n return;\n }\n\n if (!this.controller.setTableQuantity(table.label, table.quantity)) {\n if (button) {\n button.disabled = false;\n button.textContent = table.bookingMode === 'variable' ? 'Select table' : 'Select whole table';\n }\n return;\n }\n this.dismissTableDialog();\n this.collapseSectionCard();\n this.syncTray();\n }\n\n private cancelTableDialog(): void {\n const table = this.tableDialog;\n const held = this.tableDialogHeld;\n this.dismissTableDialog();\n if (table && !held) this.controller.deselect(table.physicalSeatIds);\n }\n\n private dismissTableDialog(restoreFocus = true): void {\n const focus = this.tableDialogReturnFocus;\n this.tableDialogEl?.remove();\n this.tableDialogEl = null;\n this.tableDialog = null;\n this.tableDialogHeld = false;\n this.tableDialogReturnFocus = null;\n if (restoreFocus) requestAnimationFrame(() => (focus?.isConnected ? focus : this.root)?.focus());\n }\n\n // ---- seat candidate confirmation ------------------------------------------\n\n private showConfirm(seat: ExpandedSeat): void {\n const previousId = this.confirmSeat?.id;\n this.confirmEl?.remove();\n this.confirmEl = null;\n this.confirmSeat = seat;\n this.root?.setAttribute('data-confirming', 'true');\n this.controller.setSelectionFocus(seat.id);\n if (previousId && previousId !== seat.id) this.controller.deselect([previousId]);\n if (this.tipEl) this.tipEl.style.display = 'none';\n const details = this.controller.seatDetails(seat.id);\n const cat = this.controller.doc?.categories.find((c) => c.key === seat.categoryKey);\n const chartPrice = details?.price ?? (cat?.tiers?.length ? cat.tiers[0].price : cat?.price);\n const price = chartPrice != null\n ? this.paidPrice(seat.categoryKey, details?.tierId ?? cat?.tiers?.[0]?.id ?? null, chartPrice)\n : undefined;\n const safe = (value: unknown): string => String(value ?? '—').replace(/[&<>\"]/g, (char) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"',\n })[char]!);\n const identityFields = [\n details?.sectionLabel\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">Section</span><span class=\"sl-confirm-value\">${safe(details.sectionLabel)}</span></div>`\n : '',\n details?.rowLabel || details?.objectType === 'booth'\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">${safe(this.rowTypeWord(details))}</span><span class=\"sl-confirm-value\">${safe(this.rowShort(details) ?? details?.displayLabel ?? seat.displayLabel ?? seat.label)}</span></div>`\n : '',\n details?.objectType !== 'booth'\n ? `<div class=\"sl-confirm-field\"><span class=\"sl-confirm-key\">Seat</span><span class=\"sl-confirm-value\">${safe(details?.seatNumber ?? details?.displayLabel ?? seat.displayLabel ?? seat.label)}</span></div>`\n : '',\n ].filter(Boolean).join('');\n const el = document.createElement('div');\n el.className = 'sl-confirm';\n el.setAttribute('role', 'dialog');\n el.setAttribute('aria-modal', 'true');\n el.setAttribute('aria-label', `Confirm seat ${seat.label}`);\n el.style.setProperty('--sl-cat', cat?.color ?? '#6e7bff');\n el.innerHTML =\n `<div class=\"sl-confirm-grid\">` +\n identityFields +\n `</div>` +\n `<div class=\"sl-confirm-cat\"><span class=\"sl-dot\" style=\"background:${cat?.color ?? '#6e7bff'}\"></span>` +\n `<span class=\"sl-confirm-cat-name\">${safe(details?.categoryLabel ?? cat?.label ?? seat.categoryKey)}</span>` +\n (price != null ? `<span class=\"sl-confirm-price\">${this.money(price)}</span>` : '') + `</div>` +\n `<div class=\"sl-confirm-body\">` +\n this.wheelchairConfirmHtml(details?.wheelchairSpaceType) +\n this.commercialConfirmHtml(seat.commercial) +\n (this.seatViewEnabled() ? this.confirmThumbHtml(seat) : '') +\n this.see3dConfirmHtml() +\n `<div class=\"sl-confirm-row\">` +\n `<button type=\"button\" class=\"sl-confirm-cancel\">Cancel</button>` +\n `<button type=\"button\" class=\"sl-confirm-add\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M5 12.5l4 4L19 7\"/></svg>Select</button></div></div>`;\n this.els.map.appendChild(el);\n this.confirmEl = el;\n this.reanchorConfirm();\n el.querySelector('.sl-confirm-view')?.addEventListener('click', () => void this.openSeatView(seat));\n el.querySelector('.sl-confirm-3d')?.addEventListener('click', () => {\n if (this.buyerView === 'venue3d') {\n // Already immersed — just fly the cinematic to this seat.\n void this.view3dHandle?.flyToSeat(seat.id);\n } else {\n // Enter 3D flying straight to the seat; re-show this card on return.\n this.view3dReturnSeat = seat;\n this.dismissConfirm();\n void this.enter3d(seat.id);\n }\n });\n el.querySelector('.sl-confirm-add')!.addEventListener('click', () => this.commitConfirm());\n el.querySelector('.sl-confirm-cancel')!.addEventListener('click', () => this.cancelConfirm());\n requestAnimationFrame(() => el.querySelector<HTMLButtonElement>('.sl-confirm-add')?.focus());\n }\n\n private reanchorConfirm(): void {\n if (!this.confirmEl || !this.confirmSeat) return;\n // In 3D the seat has no stable 2D screen anchor, so CSS bottom-sheets the\n // card (same treatment as the narrow layout). Nothing to position here.\n if (this.root?.dataset.view3d === 'on') return;\n const p = this.controller.worldToScreen({ x: this.confirmSeat.x, y: this.confirmSeat.y });\n if (this.root?.dataset.layout === 'narrow') return;\n const mapWidth = this.els.map.clientWidth;\n const mapHeight = this.els.map.clientHeight;\n const cardWidth = this.confirmEl.offsetWidth || 276;\n const cardHeight = this.confirmEl.offsetHeight || 230;\n const half = cardWidth / 2 + 12;\n const x = Math.max(half, Math.min(mapWidth - half, p.x));\n const belowFits = p.y + cardHeight + 24 <= mapHeight;\n const placeBelow = p.y < cardHeight + 24 && belowFits;\n this.confirmEl.dataset.placement = placeBelow ? 'below' : 'above';\n this.confirmEl.style.left = `${x}px`;\n this.confirmEl.style.top = `${Math.max(8, Math.min(mapHeight - 8, p.y))}px`;\n }\n\n private dismissConfirm(): void {\n this.confirmEl?.remove();\n this.confirmEl = null;\n this.confirmSeat = null;\n this.root?.removeAttribute('data-confirming');\n this.controller.setSelectionFocus(null);\n }\n\n private commitConfirm(): void {\n if (!this.confirmSeat) return;\n this.dismissConfirm();\n this.collapseSectionCard();\n this.syncTray();\n }\n\n private cancelConfirm(): void {\n const seat = this.confirmSeat;\n if (!seat) return;\n this.controller.deselect([seat.id]);\n if (this.confirmSeat) this.dismissConfirm();\n this.root?.focus({ preventScroll: true });\n }\n\n private closeConfirm(): void {\n this.dismissConfirm();\n }\n\n // ---- 360° view-from-seat modal --------------------------------------------\n\n private seatViewEnabled(): boolean {\n return this.opts.seatView !== false;\n }\n\n /** Every bookable seat (cached) — neighbor heads for the generated panorama. */\n private allSeats(): ExpandedSeat[] {\n if (!this.allSeatsCache) {\n const doc = this.controller.doc;\n this.allSeatsCache = doc ? expandChart(doc) : [];\n }\n return this.allSeatsCache;\n }\n\n /**\n * Open the drag-to-look-around 360° preview for a seat. Uses the organizer's\n * uploaded photo (seat.viewUrl) when present, else a panorama generated from\n * the chart geometry — the stage placed at this seat's true bearing + size.\n * Zero extra dependencies: an equirectangular image panned with `repeat-x`.\n *\n * Async only because the generator is a lazy chunk (see `loadPanorama`); an\n * organizer photo needs no generator and never waits on it. The two callers\n * are click handlers, so nothing observes the promise.\n */\n private async openSeatView(seat: ExpandedSeat): Promise<void> {\n if (!this.root || !this.seatViewEnabled()) return;\n\n const doc = this.controller.doc;\n const activeId = this.controller.getActiveFloorId();\n const focal = seat.focalPoint\n ?? doc?.floors?.find((f) => f.id === activeId)?.focalPoint\n ?? doc?.focalPoint\n ?? { x: 0, y: 0 };\n let panoUrl: string;\n let caption: string;\n let real = false;\n if (seat.viewUrl) {\n panoUrl = seat.viewUrl;\n caption = t('picker.panorama360');\n real = true;\n } else {\n let pano: PanoramaResult;\n try {\n const { generateSeatPanorama } = await loadPanorama();\n pano = generateSeatPanorama(seat, focal, this.allSeats());\n } catch (err) {\n // The chunk failed to fetch, or the draw threw. Report it and leave the\n // buyer on the map rather than opening an empty viewer.\n this.opts.onError?.(err);\n return;\n }\n // Torn down (or another view opened) while the chunk loaded.\n if (!this.root || !this.seatViewEnabled()) return;\n panoUrl = pano.url;\n caption = t('picker.illustrationCaption', { m: pano.distanceM });\n }\n\n // Retire any open view HERE, not before the await: two quick taps would\n // otherwise each close nothing and then leave the first viewer orphaned in\n // the DOM. It also means the current view stays up while the chunk loads.\n this.closeSeatView();\n\n const el = document.createElement('div');\n el.className = 'sl-view';\n el.setAttribute('role', 'dialog');\n el.setAttribute('aria-label', t('picker.viewFromSeat', { label: seat.label }));\n el.innerHTML =\n `<div class=\"sl-view-head\">` +\n `<span class=\"sl-view-title\">${t('picker.viewFromSeat', { label: seat.label })}</span>` +\n `<span class=\"sl-view-cap\">${caption}</span>` +\n `<button type=\"button\" class=\"sl-view-x\" aria-label=\"Close\">` +\n `<svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button></div>` +\n `<div class=\"sl-view-pano\">` +\n `<span class=\"sl-view-badge\">${real ? t('picker.real360') : t('picker.preview')}</span>` +\n `<span class=\"sl-view-hint\">Drag to look around · scroll to zoom</span>` +\n `</div>`;\n this.root.appendChild(el);\n this.viewEl = el;\n\n const pano = el.querySelector<HTMLDivElement>('.sl-view-pano')!;\n pano.style.backgroundImage = `url(\"${panoUrl}\")`;\n\n // Equirectangular pan: repeat-x gives seamless 360° horizontal wrap. The\n // source is a full 180° sphere; showing it raw wastes ~⅔ of the frame on\n // dead sky + black floor. So we WINDOW a ~70° vertical slice (horizon-centred)\n // to fill the viewport height, and clamp the vertical drag to ±35° so the\n // buyer looks around a real seat's field of view, never past the image edge.\n // `zoom` narrows the FOV further (scroll to zoom in); it never widens past 70°.\n const VFOV_DEG = 70;\n const MAX_PITCH_DEG = 35;\n let zoom = 1;\n // The generator draws the STAGE at the image's horizontal centre (yaw 0 =\n // stage). Open with that centre in the middle of the viewport — a view\n // that opens facing away from the stage is disorienting (seat 11G-21\n // owner report). Same default is right for uploaded 360s until Case-1\n // calibration exists. bgW = 2·bgH (2:1 equirect), zoom 1 at open.\n const vh0 = pano.clientHeight || 1;\n const vw0 = pano.clientWidth || 1;\n let posX = -(vh0 * (180 / VFOV_DEG) * 2 / 2 - vw0 / 2);\n let posY = 0;\n const apply = (): void => {\n const h = pano.clientHeight || 1;\n const bgH = h * (180 / VFOV_DEG) * zoom;\n const overV = Math.max(0, bgH - h);\n // Clamp pitch to ±35° of image travel (bgH px map the full 180°), and never\n // past the image edge (overV/2).\n const pitchLimit = Math.min(overV / 2, (MAX_PITCH_DEG / 180) * bgH);\n posY = Math.min(pitchLimit, Math.max(-pitchLimit, posY));\n pano.style.backgroundSize = `auto ${bgH}px`;\n // Horizon-centred: -overV/2 places the image's vertical centre at the\n // viewport centre; `posY` (drag, clamped ±35°) tilts up/down from there.\n pano.style.backgroundPosition = `${posX}px ${posY - overV / 2}px`;\n };\n apply();\n\n let dragging = false;\n let lastX = 0;\n let lastY = 0;\n const onDown = (e: PointerEvent): void => {\n dragging = true;\n lastX = e.clientX;\n lastY = e.clientY;\n pano.classList.add('drag');\n pano.setPointerCapture?.(e.pointerId);\n };\n const onMove = (e: PointerEvent): void => {\n if (!dragging) return;\n posX += e.clientX - lastX;\n posY += e.clientY - lastY;\n lastX = e.clientX;\n lastY = e.clientY;\n apply();\n };\n const onUp = (e: PointerEvent): void => {\n dragging = false;\n pano.classList.remove('drag');\n pano.releasePointerCapture?.(e.pointerId);\n };\n const onWheel = (e: WheelEvent): void => {\n e.preventDefault();\n zoom = Math.min(2.4, Math.max(1, zoom + (e.deltaY < 0 ? 0.12 : -0.12)));\n apply();\n };\n pano.addEventListener('pointerdown', onDown);\n pano.addEventListener('pointermove', onMove);\n pano.addEventListener('pointerup', onUp);\n pano.addEventListener('pointercancel', onUp);\n pano.addEventListener('wheel', onWheel, { passive: false });\n\n const closeBtn = el.querySelector<HTMLButtonElement>('.sl-view-x')!;\n closeBtn.addEventListener('click', () => this.closeSeatView());\n const onKey = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') {\n e.stopPropagation();\n this.closeSeatView();\n }\n };\n el.addEventListener('keydown', onKey);\n closeBtn.focus();\n\n this.viewCleanup = () => {\n pano.removeEventListener('pointerdown', onDown);\n pano.removeEventListener('pointermove', onMove);\n pano.removeEventListener('pointerup', onUp);\n pano.removeEventListener('pointercancel', onUp);\n pano.removeEventListener('wheel', onWheel);\n el.removeEventListener('keydown', onKey);\n };\n }\n\n private closeSeatView(): void {\n this.viewCleanup?.();\n this.viewCleanup = null;\n this.viewEl?.remove();\n this.viewEl = null;\n }\n\n // ---- chrome sync ----------------------------------------------------------\n\n private money(n: number): string {\n const formatter = this.opts.pricing?.formatter;\n if (formatter) return formatter(n, this.currency);\n try {\n return new Intl.NumberFormat(this.opts.locale, { style: 'currency', currency: this.currency }).format(n);\n } catch {\n return `${n} ${this.currency}`;\n }\n }\n\n /**\n * The price the buyer will actually pay for a category (+tier): the host's\n * `pricing` override when present, else the chart's stored price. Every\n * price the widget DISPLAYS or hands off must flow through here — a map\n * that shows one price while checkout charges another destroys trust.\n */\n private paidPrice(categoryKey: string | undefined, tierId: string | null | undefined, fallback: number): number {\n const entry = categoryKey ? this.opts.pricing?.prices?.[categoryKey] : undefined;\n if (entry === undefined) return fallback;\n if (typeof entry === 'number') return entry;\n if (tierId && entry.tiers?.[tierId] !== undefined) return entry.tiers[tierId];\n return entry.base ?? fallback;\n }\n\n private syncPrices(): void {\n const doc = this.controller.doc;\n if (!doc || !this.els.prices) return;\n const left = this.controller.categoryAvailability();\n this.narrateAvailability(doc.categories, left);\n this.syncSoldout(doc.categories, left);\n // Big events ship 10–20 ticket types; an uncapped list shoves \"Your seats\"\n // and the CTA below the fold. Cap the closed list and expand on demand\n // (never hide a single row behind a toggle — that costs more than it saves).\n const PRICE_LIMIT = 5;\n const overflow = doc.categories.length - PRICE_LIMIT;\n const collapsed = overflow > 1 && !this.pricesExpanded;\n const shown = collapsed ? doc.categories.slice(0, PRICE_LIMIT) : doc.categories;\n this.els.prices.classList.toggle('sl-expanded', overflow > 1 && this.pricesExpanded);\n this.els.prices.innerHTML = shown\n .map((c) => {\n const price = this.catPrice(c);\n const active = this.focusedCatKey === c.key;\n const dim = this.priceBandKeys != null && !this.priceBandKeys.has(c.key);\n return (\n `<div class=\"sl-price-row${dim ? ' sl-dim' : ''}${active ? ' sl-active' : ''}\" data-cat=\"${c.key}\"` +\n ` role=\"button\" tabindex=\"0\" aria-pressed=\"${active}\"` +\n ` title=\"${active ? 'Show all seats' : `Show ${c.label} seats on the map`}\">` +\n `<span class=\"sl-dot\" style=\"background:${c.color}\"></span>` +\n `<span class=\"sl-price-label\">${c.label}</span>` +\n `<span class=\"sl-price-left\">${left[c.key] ?? 0} left</span>` +\n (price != null ? `<span class=\"sl-price-amt\">${this.money(price)}</span>` : '') +\n `</div>`\n );\n })\n .join('') +\n (overflow > 1\n ? `<button type=\"button\" class=\"sl-price-more\" aria-expanded=\"${!collapsed}\">` +\n (collapsed ? `Show all ${doc.categories.length} ticket types` : 'Show fewer') +\n `</button>`\n : '') +\n `<div class=\"sl-status-key\" aria-label=\"Seat status legend\">` +\n `<span class=\"sl-status-item\"><i class=\"sl-status-icon\" aria-hidden=\"true\">` +\n `<svg viewBox=\"0 0 24 24\"><rect x=\"5\" y=\"10\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/></svg>` +\n `</i>Temporarily held</span>` +\n `<span class=\"sl-status-item\"><i class=\"sl-status-icon sold\" aria-hidden=\"true\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M7 17L17 7\"/></svg>` +\n `</i>Sold</span>` +\n `</div>`;\n // Legend-hover highlight: dim other categories on the map while hovering a row.\n // Click (or Enter/Space) pins that focus — filter + frame the category on\n // the map; a second click clears it.\n this.els.prices.querySelectorAll<HTMLElement>('.sl-price-row').forEach((row) => {\n row.addEventListener('mouseenter', () => this.controller.getRenderer()?.setCategoryHighlight?.(row.dataset.cat ?? null));\n row.addEventListener('mouseleave', () => this.controller.getRenderer()?.setCategoryHighlight?.(null));\n const toggle = () => this.focusCategory(row.dataset.cat ?? '');\n row.addEventListener('click', toggle);\n row.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n toggle();\n }\n });\n });\n this.els.prices.querySelector<HTMLButtonElement>('.sl-price-more')?.addEventListener('click', () => {\n this.pricesExpanded = !this.pricesExpanded;\n this.syncPrices();\n });\n }\n\n /** Tap a price row → filter + frame that category on the map; tap again to\n * clear. Shares `priceBandKeys` with the band selector so the row-dim state\n * has one source of truth (and each control resets the other). */\n private focusCategory(key: string): void {\n if (!key) return;\n const next = this.focusedCatKey === key ? null : key;\n this.focusedCatKey = next;\n this.priceBandKeys = next ? new Set([next]) : null;\n const select = this.els.pricesSec?.querySelector<HTMLSelectElement>('.sl-price-select');\n if (select) select.value = 'all';\n this.controller.setCategoryFilter(next ? [next] : null);\n this.controller.focusCategoryFilter(next ? [next] : null);\n this.pushAvailabilityTo3d();\n // Focusing a category on another deck switches floors — mirror that onto\n // the floor pills / rung pills / minimap, same as a manual deck switch.\n this.syncFloors();\n this.syncRung();\n this.refreshMinimap();\n this.syncPrices();\n if (this.lastSection) this.showSectionCard(this.lastSection);\n }\n\n /**\n * Live-activity strip: turn WS availability deltas into one quiet line of\n * social proof (\"2 seats just taken in VIP · 118 left\"). Diffs per-category\n * counts on every status change — no per-seat payload needed. Skips the very\n * first computation (initial load is not \"activity\").\n */\n private narrateAvailability(\n categories: Array<{ key: string; label: string }>,\n left: Record<string, number>,\n ): void {\n const textEl = this.els.liveText;\n const prev = this.lastCatAvail;\n this.lastCatAvail = { ...left };\n // A floor switch re-baselines availability (counts are per-rendered-floor,\n // and the post-switch status snapshot lands asynchronously a beat later).\n // Narrating across that window produces a phantom \"N seats just taken\", so\n // stay quiet until the new floor settles — only genuine WS deltas after\n // that are news.\n const floorId = this.controller.getActiveFloorId();\n if (floorId !== this.lastAvailFloorId) {\n this.lastAvailFloorId = floorId;\n this.availQuietUntil = performance.now() + 2000;\n }\n if (!textEl || !prev || performance.now() < this.availQuietUntil) return;\n for (const cat of categories) {\n const before = prev[cat.key];\n const now = left[cat.key] ?? 0;\n if (before === undefined || now >= before) continue;\n const taken = before - now;\n textEl.textContent = `${taken} seat${taken === 1 ? '' : 's'} just taken in ${cat.label} · ${now} left`;\n // Surface the strip only while it carries news, then give the space back.\n this.els.live?.classList.remove('on');\n // Reflow between remove/add restarts the entrance animation on repeats.\n void (this.els.live as HTMLElement | undefined)?.offsetWidth;\n this.els.live?.classList.add('on');\n if (this.liveTimer) clearTimeout(this.liveTimer);\n this.liveTimer = setTimeout(() => this.els.live?.classList.remove('on'), 8000);\n return;\n }\n }\n private lastCatAvail: Record<string, number> | null = null;\n private lastAvailFloorId = '';\n private availQuietUntil = 0;\n private liveTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** A live delta took one of OUR selected (not yet held) seats — evict + tell the buyer. */\n private evictTakenSelections(): void {\n // Our own hold's WS echo paints our seats 'held' — never treat those as sniped.\n const ownLabels = new Set<string>([\n ...(this.controller.currentHold()?.labels ?? []),\n ...this.holdingLabels,\n ]);\n const gone = this.controller\n .getSelection()\n .filter((s) => !ownLabels.has(s.label) && (this.controller.getStatus(s.id) ?? 'free') !== 'free');\n if (!gone.length) return;\n this.controller.deselect(gone.map((s) => s.id));\n this.toast(`Seat ${gone[0].label} was just taken by another buyer.`, 'error');\n }\n\n private syncTray(): void {\n if (!this.els.tray) return;\n this.updateSelectionCapacity();\n const seats = this.committedSelection();\n const gaAreas = this.controller.getGAAreas();\n const heldItems = this.hold?.items ?? [];\n const parts: string[] = [];\n const nextTrayKeys = new Set<string>();\n\n if (!seats.length && !heldItems.length && !gaAreas.length) {\n parts.push(`<div class=\"sl-tray-hint\">Tap a seat on the map, or let us pick the best available for you.</div>`);\n } else if (!seats.length && !heldItems.length) {\n parts.push(`<div class=\"sl-tray-hint\">Tap a seat on the map — or grab standing tickets below.</div>`);\n }\n\n // Best available is the fastest path for buyers who haven't picked yet —\n // but the moment a seat lands in the tray, the ticket cards own this space.\n // (Busy/confirm states stay visible so an in-flight search isn't cut off.)\n const noPicks = !seats.length && !heldItems.length && !this.pendingGACount();\n if (!this.hold && (noPicks || this.bestAvailableBusy || this.bestAvailableConfirm)) {\n const cats = this.controller.doc?.categories ?? [];\n const zones = this.controller.getBestAvailableZones();\n if (this.baZone && !zones.some((zone) => zone.id === this.baZone)) this.baZone = '';\n parts.push(this.bestAvailableConfirm\n ? `<div class=\"sl-ba\" role=\"alert\">` +\n `<div class=\"sl-ba-title\"><span class=\"spark\" aria-hidden=\"true\">✦</span>Replace your current choices?</div>` +\n `<div class=\"sl-ba-replace\"><b>We’ll find ${this.baQty} seats together.</b>` +\n `<span>Your manually selected tickets will be removed only after a new group is secured.</span></div>` +\n `<div class=\"sl-ba-actions\"><button type=\"button\" data-ba-cancel>Keep mine</button>` +\n `<button type=\"button\" class=\"replace\" data-ba-replace>Find new seats</button></div></div>`\n : `<div class=\"sl-ba\">` +\n `<div class=\"sl-ba-title\"><span class=\"spark\" aria-hidden=\"true\">✦</span>Find the best seats together</div>` +\n `<div class=\"sl-ba-copy\"><span class=\"wide\">We’ll choose the closest available group for you.</span>` +\n `<span class=\"narrow\">Closest available group, chosen instantly.</span></div>` +\n // Premium quick-pick — present only when the chart actually has premium\n // seats (same present-only philosophy as the a11y filter chips).\n (this.controller.hasPremiumSeats()\n ? `<button type=\"button\" class=\"sl-ba-premium${this.baPremium ? ' on' : ''}\" data-ba-premium aria-pressed=\"${this.baPremium ? 'true' : 'false'}\">` +\n `<span class=\"star\" aria-hidden=\"true\">★</span>${this.tf('picker.bestSeatsPremium', 'Best seats')}</button>`\n : '') +\n (cats.length > 1\n ? `<select aria-label=\"Preferred ticket type\" data-ba-cat>` +\n `<option value=\"\">Any ticket type</option>` +\n cats.map((c) => `<option value=\"${c.key}\"${this.baCat === c.key ? ' selected' : ''}>${c.label}</option>`).join('') +\n `</select>`\n : `<span aria-hidden=\"true\"></span>`) +\n (zones.length\n ? `<select aria-label=\"Preferred venue zone\" data-ba-zone>` +\n `<option value=\"\">Any venue zone</option>` +\n zones.map((zone) => `<option value=\"${escapeOption(zone.id)}\"${this.baZone === zone.id ? ' selected' : ''}>${escapeOption(zone.label)}</option>`).join('') +\n `</select>`\n : '') +\n `<div class=\"sl-ba-qty\">` +\n `<button type=\"button\" data-ba=\"-1\" aria-label=\"Fewer seats\">−</button><span>${this.baQty}</span>` +\n `<button type=\"button\" data-ba=\"1\" aria-label=\"More seats\">+</button></div>` +\n `<button type=\"button\" class=\"sl-ba-go\"${this.bestAvailableBusy ? ' disabled' : ''}>` +\n (this.bestAvailableBusy\n ? `<span class=\"sl-ba-spin\" aria-hidden=\"true\"></span>Finding the best seats…`\n : `Find ${this.baQty} best ${this.baQty === 1 ? 'seat' : 'seats'}`) +\n `</button></div>`);\n }\n\n // Held line items (best-available, completed, or restored). Tier is\n // server-committed, but each item can be released without discarding the\n // rest of the hold.\n // Ticket-card identity grid: SECTION | ROW | SEAT, echoing the confirm\n // popover so the buyer meets the same identity pattern at confirm and in\n // the cart. Falls back to the raw label when spatial context is missing\n // (GA lines, legacy labels).\n const idGrid = (\n seatId: string | null,\n label: string,\n objectType?: HoldLineItem['objectType'] | PickerSeat['objectType'],\n quantity = 1,\n objectId?: string,\n identity?: Partial<PickerSeat>,\n ): string => {\n const esc = (value: unknown): string => String(value ?? '—').replace(/[&<>\"]/g, (char) => ({\n '&': '&', '<': '<', '>': '>', '\"': '"',\n })[char]!);\n const d = seatId ? this.controller.seatDetails(seatId) : null;\n const area = objectType === 'ga' ? gaAreas.find((candidate) => candidate.id === objectId) : undefined;\n const effectiveType = objectType === 'ga' ? 'ga' : d?.objectType ?? objectType;\n const typeWord = identity?.displayType?.trim()\n || d?.displayType?.trim()\n || area?.displayType?.trim()\n || (effectiveType === 'table' ? 'Table' : effectiveType === 'booth' ? 'Booth' : effectiveType === 'ga' ? 'General admission' : 'Row');\n const buyerName = identity?.rowLabel\n ?? identity?.displayLabel\n ?? d?.rowLabel\n ?? d?.displayLabel\n ?? area?.displayLabel\n ?? area?.label\n ?? label;\n if (effectiveType === 'table' && identity?.bookingMode) {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span>` +\n `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Guests</span><span class=\"val\">${quantity}</span></span></div>`;\n }\n if (effectiveType === 'ga') {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span>` +\n (quantity > 1 ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Tickets</span><span class=\"val\">${quantity}</span></span>` : '') + `</div>`;\n }\n if (effectiveType === 'booth') {\n return `<div class=\"sl-chip-id\">` +\n (d?.sectionLabel ? `<span class=\"fld sec\"><span class=\"sl-chip-eb\">Section</span><span class=\"val\">${esc(d.sectionLabel)}</span></span>` : '') +\n `<span class=\"fld mid\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(buyerName)}</span></span></div>`;\n }\n if (!d?.sectionLabel && !d?.rowLabel && !d?.seatNumber) {\n return `<div class=\"sl-chip-id\"><span class=\"fld sec\"><span class=\"sl-chip-eb\">Seat</span><span class=\"val\">${esc(buyerName)}</span></span></div>`;\n }\n return (\n `<div class=\"sl-chip-id\">` +\n (d.sectionLabel ? `<span class=\"fld sec\"><span class=\"sl-chip-eb\">Section</span><span class=\"val\">${esc(d.sectionLabel)}</span></span>` : '') +\n (d.rowLabel ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">${esc(typeWord)}</span><span class=\"val\">${esc(this.rowShort(d))}</span></span>` : '') +\n (d.seatNumber ? `<span class=\"fld mid\"><span class=\"sl-chip-eb\">Seat</span><span class=\"val\">${esc(d.seatNumber)}</span></span>` : '') +\n `</div>`\n );\n };\n // Right icon rail per the canonical mock: remove on top, seat view below.\n const iconRail = (rmAria: string, viewLabel: string | null): string =>\n `<div class=\"sl-chip-rail\">` +\n `<button type=\"button\" class=\"rm\" aria-label=\"${rmAria}\">` +\n `<svg viewBox=\"0 0 24 24\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"/><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"/></svg></button>` +\n (viewLabel\n ? `<button type=\"button\" class=\"view\" data-view-label=\"${viewLabel}\" aria-label=\"${t('picker.viewFromSeat', { label: viewLabel })}\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg></button>`\n : '') +\n `</div>`;\n\n for (const item of heldItems) {\n const itemKey = `held:${item.label}`;\n nextTrayKeys.add(itemKey);\n const cat = this.controller.doc?.categories.find((c) => c.key === item.categoryKey);\n const tierName = item.tierId ? cat?.tiers?.find((ti) => ti.id === item.tierId)?.name : undefined;\n const heldSeat = item.objectType !== 'ga' ? this.controller.seatByLabel(item.label) : null;\n const table = item.objectType === 'table' ? this.controller.tableSelection(item.label) : null;\n const canView = this.seatViewEnabled() && !!heldSeat && item.objectType !== 'table';\n parts.push(\n `<div class=\"sl-chip sl-held${this.lastTrayKeys.has(itemKey) ? '' : ' sl-enter'}\" data-key=\"${itemKey}\" data-held=\"${encodeURIComponent(item.label)}\"${heldSeat ? ` data-locate=\"${heldSeat.id}\"` : ''}>` +\n `<div class=\"sl-chip-main\">` +\n idGrid(heldSeat?.id ?? null, item.label, item.objectType, item.quantity ?? 1, item.objectId, table ?? undefined) +\n `<div class=\"sl-chip-sub\">` +\n `<span class=\"sl-ticket-state held\" aria-label=\"Held for you\" title=\"Held for you\">` +\n `<svg viewBox=\"0 0 24 24\"><rect x=\"5\" y=\"10\" width=\"14\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/></svg></span>` +\n `<span class=\"cat\">${cat?.label ?? item.categoryKey}${tierName ? ` · ${tierName}` : ''}</span>` +\n (table?.bookingMode === 'variable'\n ? `<button type=\"button\" class=\"sl-table-edit\" data-table-edit=\"${encodeURIComponent(item.label)}\">${item.quantity ?? 1} guests · Edit</button>`\n : '') +\n this.wheelchairChipMarker(heldSeat?.wheelchairSpaceType) +\n this.commercialChipMarker(heldSeat?.commercial) +\n `<span class=\"amt\">${this.money(this.paidPrice(item.categoryKey, item.tierId, item.unitPrice) * (item.quantity ?? 1))}</span>` +\n `</div></div>` +\n iconRail(`Remove held ticket ${item.label}`, canView ? item.label : null) +\n `</div>`,\n );\n }\n\n const heldLabels = new Set(heldItems.map((item) => item.label));\n const canView = this.seatViewEnabled();\n for (const s of seats.filter((seat) => !heldLabels.has(seat.label))) {\n const itemKey = `seat:${s.id}`;\n nextTrayKeys.add(itemKey);\n const cat = this.controller.doc?.categories.find((c) => c.key === s.categoryKey);\n const tierSelect =\n s.tiers && s.tiers.length\n ? `<select class=\"tier\" data-tier=\"${s.id}\" aria-label=\"${t('picker.ticketTierFor', { label: s.label })}\">` +\n s.tiers\n .map((ti) => `<option value=\"${ti.id}\"${ti.id === s.tierId ? ' selected' : ''}>${ti.name} · ${this.money(this.paidPrice(s.categoryKey, ti.id, ti.price))}</option>`)\n .join('') +\n `</select>`\n : '';\n parts.push(\n `<div class=\"sl-chip${this.lastTrayKeys.has(itemKey) ? '' : ' sl-enter'}\" data-key=\"${itemKey}\" data-seat=\"${s.id}\" data-locate=\"${s.id}\">` +\n `<div class=\"sl-chip-main\">` +\n idGrid(s.id, s.label, s.objectType, s.quantity ?? 1, s.objectId, s) +\n `<div class=\"sl-chip-sub\">` +\n `<span class=\"sl-ticket-state\" aria-label=\"Selected\" title=\"Selected\">` +\n `<svg viewBox=\"0 0 24 24\"><path d=\"M5 12l4 4L19 6\"/></svg></span>` +\n `<span class=\"cat\">${cat?.label ?? s.categoryKey}</span>` +\n (s.objectType === 'table' && s.bookingMode === 'variable'\n ? `<button type=\"button\" class=\"sl-table-edit\" data-table-edit=\"${encodeURIComponent(s.label)}\">${s.quantity ?? 1} guests · Edit</button>`\n : '') +\n `${this.wheelchairChipMarker(s.wheelchairSpaceType)}${this.commercialChipMarker(s.commercial)}${tierSelect}` +\n `<span class=\"amt\">${this.money(this.paidPrice(s.categoryKey, s.tierId ?? null, s.price) * (s.quantity ?? 1))}</span>` +\n `</div></div>` +\n iconRail(`Remove ${s.label}`, canView && s.objectType !== 'table' ? s.label : null) +\n `</div>`,\n );\n }\n\n for (const area of gaAreas) {\n const qty = this.gaQty.get(area.id) ?? 0;\n parts.push(\n `<div class=\"sl-ga\" data-ga=\"${area.id}\"><div class=\"sl-ga-info\">` +\n `<div class=\"sl-ga-name\">${area.displayLabel ?? area.label}</div>` +\n `<div class=\"sl-ga-sub\">${area.displayType ?? 'General admission'} · ${this.money(this.paidPrice(area.categoryKey, null, area.price))} · ${area.available} left</div></div>` +\n `<div class=\"sl-ga-qty\">` +\n `<button type=\"button\" data-d=\"-1\" aria-label=\"Fewer\">−</button><span>${qty}</span>` +\n `<button type=\"button\" data-d=\"1\" aria-label=\"More\">+</button></div></div>`,\n );\n }\n\n this.els.tray.innerHTML = parts.join('');\n this.lastTrayKeys = nextTrayKeys;\n this.els.tray.querySelectorAll<HTMLButtonElement>('[data-ba]').forEach((btn) => {\n btn.addEventListener('click', () => {\n this.baQty = Math.max(1, Math.min(this.maxTickets, this.baQty + Number(btn.dataset.ba)));\n this.syncTray();\n });\n });\n this.els.tray.querySelector<HTMLSelectElement>('[data-ba-cat]')?.addEventListener('change', (e) => {\n this.baCat = (e.target as HTMLSelectElement).value;\n });\n this.els.tray.querySelector<HTMLSelectElement>('[data-ba-zone]')?.addEventListener('change', (e) => {\n this.baZone = (e.target as HTMLSelectElement).value;\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-premium]')?.addEventListener('click', () => {\n this.baPremium = !this.baPremium;\n this.syncTray();\n });\n this.els.tray.querySelector<HTMLButtonElement>('.sl-ba-go')?.addEventListener('click', () => {\n if (this.pendingSelectionCount() > 0) {\n this.bestAvailableConfirm = true;\n this.syncTray();\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-replace]')?.focus();\n return;\n }\n void this.bestAvailable(this.baQty, this.baCat || undefined, { preferPremium: this.baPremium, zoneId: this.baZone || undefined });\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-cancel]')?.addEventListener('click', () => {\n this.bestAvailableConfirm = false;\n this.syncTray();\n this.els.tray.querySelector<HTMLButtonElement>('.sl-ba-go')?.focus();\n });\n this.els.tray.querySelector<HTMLButtonElement>('[data-ba-replace]')?.addEventListener('click', () => {\n this.bestAvailableConfirm = false;\n void this.bestAvailable(this.baQty, this.baCat || undefined, { preferPremium: this.baPremium, zoneId: this.baZone || undefined });\n });\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip .rm').forEach((btn) => {\n btn.addEventListener('click', () => {\n const chip = btn.closest('.sl-chip') as HTMLElement;\n if (chip.dataset.held) {\n void this.removeHeldLabel(decodeURIComponent(chip.dataset.held), chip);\n return;\n }\n const id = chip.dataset.seat!;\n const label = this.controller.getSelection().find((sel) => sel.id === id)?.label ?? 'Seat';\n const remove = (): void => {\n this.controller.deselect([id]);\n this.toast(`${label} removed.`, 'neutral', {\n label: 'Undo',\n onClick: () => {\n const restored = this.controller.select([id]);\n this.toast(\n restored.length ? `${label} restored.` : `${label} is no longer available.`,\n restored.length ? 'success' : 'warning',\n );\n },\n });\n };\n if (this.reducedMotion()) {\n remove();\n return;\n }\n chip.classList.add('sl-leave');\n this.scheduleMotion(remove, 150);\n });\n });\n this.els.tray.querySelectorAll<HTMLButtonElement>('[data-table-edit]').forEach((button) => {\n button.addEventListener('click', (event) => {\n event.stopPropagation();\n const label = decodeURIComponent(button.dataset.tableEdit ?? '');\n const details = this.controller.tableSelection(label);\n if (!details) return;\n const heldItem = heldItems.find((item) => item.label === label && item.objectType === 'table');\n this.showTableDialog(\n { ...details, quantity: heldItem?.quantity ?? details.quantity },\n !!heldItem,\n button,\n );\n });\n });\n // Per-seat ticket-tier pick (Adult/Child/…) — updates price via onSelectionChange.\n this.els.tray.querySelectorAll<HTMLSelectElement>('.sl-chip .tier').forEach((sel) => {\n sel.addEventListener('change', () => this.controller.setSeatTier(sel.dataset.tier!, sel.value || null));\n });\n // View-from-seat button (data-view-label = seat label) on fresh + held chips.\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip .view[data-view-label]').forEach((btn) => {\n btn.addEventListener('click', () => {\n const seat = this.controller.seatByLabel(btn.dataset.viewLabel!);\n if (seat) void this.openSeatView(seat);\n });\n });\n // Card ↔ map linkage: hovering (or keyboard-focusing) a ticket card pulses\n // its seat on the map so the buyer can locate what they picked.\n this.els.tray.querySelectorAll<HTMLElement>('.sl-chip[data-locate]').forEach((chip) => {\n const locate = (): void => this.controller.flashSeat(chip.dataset.locate!, this.cssVar('--sl-accent') || '#f4b740');\n chip.addEventListener('mouseenter', locate);\n chip.addEventListener('focusin', locate);\n });\n this.els.tray.querySelectorAll<HTMLElement>('.sl-ga button').forEach((btn) => {\n btn.addEventListener('click', () => {\n const areaEl = btn.closest('.sl-ga') as HTMLElement;\n const id = areaEl.dataset.ga!;\n const area = gaAreas.find((a) => a.id === id);\n const delta = Number(btn.dataset.d);\n if (delta > 0 && !this.canAddTicket()) return;\n const next = Math.max(0, Math.min(area?.available ?? 0, (this.gaQty.get(id) ?? 0) + delta));\n this.gaQty.set(id, next);\n this.syncTray();\n });\n });\n\n // Sales closed: freeze the best-available + GA controls (read-only state).\n if (this.salesClosed) {\n this.els.tray\n .querySelectorAll<HTMLButtonElement | HTMLSelectElement>('.sl-ba-go,[data-ba],[data-ba-cat],[data-ba-zone],[data-ba-replace],.sl-ga button')\n .forEach((el) => {\n el.disabled = true;\n });\n }\n\n // totals + CTA (held lines + fresh selections + GA)\n const gaTotal = this.pendingGATotal(gaAreas);\n const gaCount = this.pendingGACount();\n const heldTotal = heldItems.reduce((sum, item) => sum + this.paidPrice(item.categoryKey, item.tierId, item.unitPrice) * (item.quantity ?? 1), 0);\n const heldCount = heldItems.reduce((sum, item) => sum + (item.quantity ?? 1), 0);\n const freshSeats = seats.filter((seat) => !heldLabels.has(seat.label));\n const total = freshSeats.reduce(\n (sum, s) => sum + this.paidPrice(s.categoryKey, s.tierId ?? null, s.price) * (s.quantity ?? 1),\n 0,\n ) + gaTotal + heldTotal;\n const count = freshSeats.reduce((sum, seat) => sum + (seat.quantity ?? 1), 0) + gaCount + heldCount;\n const pendingCount = this.pendingSelectionCount();\n const previousCount = this.lastTrayCount;\n const previousTotal = this.lastTrayTotal;\n this.els.count.textContent = count\n ? `${count} ${count === 1 ? 'ticket' : 'tickets'}`\n : 'No seats selected';\n this.els.total.textContent = count ? this.money(total) : '';\n this.root?.setAttribute('data-has-selection', String(count > 0));\n // The best-available panel's confirm (\"Replace your current choices?\") and\n // in-flight busy states must survive the narrow-layout collapse that hides\n // .sl-ba once the cart is non-empty. Mark them so the CSS keeps them shown.\n this.root?.setAttribute(\n 'data-ba-active',\n String(this.bestAvailableConfirm || this.bestAvailableBusy),\n );\n this.els.foot?.classList.toggle('empty', count === 0);\n if (this.els.seatSummary) {\n this.els.seatSummary.textContent = count ? `${count} selected` : '';\n }\n this.syncCta(count, pendingCount);\n if (this.hold) {\n const securedCount = heldCount || this.hold.seats?.length || 0;\n if (this.els.holdTitle) {\n this.els.holdTitle.textContent = `${securedCount} secured`;\n }\n if (this.els.holdCopy) {\n this.els.holdCopy.textContent = pendingCount\n ? `${pendingCount} more selected`\n : 'Checkout timer running';\n }\n const change = this.els.holdChange as HTMLButtonElement | undefined;\n if (change) {\n change.disabled = this.releasingHold;\n change.textContent = this.releasingHold ? 'Releasing…' : 'Change';\n }\n }\n if (count !== previousCount) this.animateOnce(this.els.count, 'sl-value-pop', 380);\n if (total !== previousTotal) this.animateOnce(this.els.total, 'sl-value-pop', 380);\n if (previousCount === 0 && count > 0) this.animateOnce(this.els.cta, 'sl-ready', 520);\n\n // Mobile sheet: one-line peek summary. Selected → \"N tickets · $X · Continue\";\n // empty → \"From $min · Best available\". Tap (sheet head) expands the sheet.\n if (this.els.peek) {\n if (count) {\n // Sheet state is shown by the persistent chevron in the head; the pill is\n // the action affordance (\"Continue\"/\"Review\") — no inline text arrow.\n this.els.peek.innerHTML =\n `<span>${count} ${count === 1 ? 'ticket' : 'tickets'} · ${this.money(total)}</span>` +\n `<span class=\"go\">${this.hold ? (pendingCount ? 'Secure more' : 'Continue') : 'Review'}</span>`;\n } else {\n const prices = (this.controller.doc?.categories ?? [])\n .map((c) => this.catPrice(c))\n .filter((p): p is number => p != null);\n this.els.peek.innerHTML =\n (prices.length ? `<span>From ${this.money(Math.min(...prices))}</span>` : '<span>Pick your seats</span>') +\n `<span class=\"go\">✦ Best seats</span>`;\n }\n }\n // Keep the mobile map stable after selection. The persistent Review pill\n // exposes the updated count/total without covering the seat the buyer just\n // confirmed; opening the sheet remains an explicit tap or swipe.\n this.lastTrayCount = count;\n this.lastTrayTotal = total;\n\n this.opts.onSelectionChange?.(seats);\n }\n\n private async removeHeldLabel(label: string, chip?: HTMLElement): Promise<boolean> {\n if (!label || this.releasingLabels.has(label)) return false;\n this.releasingLabels.add(label);\n chip?.setAttribute('aria-busy', 'true');\n const button = chip?.querySelector<HTMLButtonElement>('.rm');\n if (button) button.disabled = true;\n try {\n const preserveAcrossNavigation = this.handedOff;\n const released = await this.controller.releaseLabels([label]);\n if (!released) {\n this.toast(`Couldn't remove ${label}. Your hold is unchanged.`, 'error');\n return false;\n }\n const remaining = this.controller.currentHold();\n this.hold = remaining\n ? { holdId: remaining.holdId, expiresAt: remaining.expiresAt, seats: remaining.seats, items: remaining.items }\n : null;\n this.handedOff = !!this.hold && preserveAcrossNavigation;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n if (this.hold) {\n this.startHoldTimer(this.hold.expiresAt);\n } else {\n this.stopHoldTimer();\n this.forgetHold();\n }\n this.syncTray();\n this.emitHoldChange();\n this.toast(`${label} removed from your hold.`, 'success');\n return true;\n } finally {\n this.releasingLabels.delete(label);\n chip?.removeAttribute('aria-busy');\n if (button?.isConnected) button.disabled = false;\n }\n }\n\n private async handleChangeSeats(): Promise<void> {\n if (!this.hold || this.releasingHold) return;\n this.releasingHold = true;\n const button = this.els.holdChange as HTMLButtonElement | undefined;\n if (button) {\n button.disabled = true;\n button.textContent = 'Releasing…';\n }\n try {\n await this.release();\n if (!this.hold) this.toast('Held tickets released. Choose your new seats.', 'success');\n } finally {\n this.releasingHold = false;\n if (button?.isConnected) {\n button.disabled = false;\n button.textContent = 'Change';\n }\n }\n }\n\n private async handleCta(): Promise<void> {\n if (this.salesClosed) return;\n if (this.totalTicketCount() > this.maxTickets) {\n this.toast(`Remove tickets until your order has ${this.maxTickets} or fewer.`, 'warning');\n return;\n }\n // Best-available (or a prior CTA press) already holds the seats — hand off.\n // Held seats are NOT in the client selection (the server holds them), so\n // pass the hold's own seat list to the host.\n const committed = this.committedSelection();\n if (this.hold && !committed.some((s) => !(this.hold!.items ?? []).some((i) => i.label === s.label))) {\n const seats = this.hold.seats ?? committed;\n this.handedOff = true;\n this.setCtaPhase('checkout');\n this.checkoutHandoff(this.hold, seats);\n return;\n }\n this.holdingLabels = new Set(committed.map((seat) => seat.label));\n this.setCtaPhase('holding');\n try {\n // seats first (controller.hold covers selected seats); GA quantities ride along\n let hold: HoldResult | null = null;\n const gaEntries = [...this.gaQty.entries()].filter(([, q]) => q > 0);\n // Snapshot before hold — the hold's own WS echo repaints these seats.\n const chosenSeats = this.committedSelection();\n if (chosenSeats.length) {\n const h = await this.controller.hold(undefined, this.opts.holdTtlMs);\n hold = h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : null;\n }\n for (const [areaId, qty] of gaEntries) {\n const h = await this.controller.holdGA(areaId, qty, { ttlMs: this.opts.holdTtlMs });\n hold = h ? { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items } : hold;\n }\n if (!hold) {\n this.toast('One or more seats were just taken. Please pick again.', 'error');\n this.setCtaPhase('idle');\n this.syncTray();\n return;\n }\n this.hold = hold;\n this.handedOff = true;\n this.startHoldTimer(hold.expiresAt);\n this.flashHeldSeats(hold);\n this.setCtaPhase('checkout');\n this.emitHoldChange();\n // The replacement hold can combine an earlier best-available set with\n // newly selected seats. Hand the host the complete held seat set; the\n // server-priced line items remain authoritative for GA and totals.\n this.checkoutHandoff(hold, hold.seats ?? chosenSeats);\n } catch (err) {\n this.opts.onError?.(err);\n const problem = err as { reason?: string; conflicts?: Array<{ label?: string }> };\n const labels = (problem.conflicts ?? []).map((conflict) => conflict.label).filter(Boolean).slice(0, 3);\n // The CTA's controller.hold() path doesn't surface onSalesClosed — apply the\n // persistent read-only state here (the toast below stays). book/bestAvailable\n // paths reach it via the onSalesClosed callback.\n if (problem.reason === 'event_closed') this.setSalesClosed(true);\n const message = problem.reason === 'event_closed'\n ? 'Seat sales have closed for this event.'\n : labels.length\n ? `${labels.join(', ')} ${labels.length === 1 ? 'is' : 'are'} no longer available. Choose another ${labels.length === 1 ? 'seat' : 'group'}.`\n : 'One or more seats were just taken. Please pick again.';\n this.toast(message, 'error');\n this.setCtaPhase('idle');\n } finally {\n this.holdingLabels.clear();\n if (this.ctaPhase === 'holding') this.ctaPhase = 'idle';\n this.syncTray();\n }\n }\n\n private startHoldTimer(expiresAt: number): void {\n this.stopHoldTimer();\n this.holdExpiresAt = expiresAt;\n if (this.hold) this.rememberHold(this.hold);\n const pill = this.els.hold;\n pill.innerHTML =\n '<span class=\"sl-hold-dot\" aria-hidden=\"true\"></span><span>Held</span><span class=\"sl-hold-time\" data-ref=\"holdTime\"></span>';\n const time = pill.querySelector<HTMLElement>('[data-ref=\"holdTime\"]');\n this.els.holdNote?.classList.add('on');\n const tick = (): void => {\n const ms = Math.max(0, this.holdExpiresAt - Date.now());\n const m = Math.floor(ms / 60000);\n const s = String(Math.floor((ms % 60000) / 1000)).padStart(2, '0');\n if (time) time.textContent = `${m}:${s}`;\n pill.classList.add('on');\n pill.classList.toggle('is-expiring', ms > 0 && ms <= EXTEND_PROMPT_MS);\n // Offer an extension in the final stretch (but not once it's booked/expired).\n this.setExtendPrompt(ms > 0 && ms <= EXTEND_PROMPT_MS, ms);\n if (ms <= 0) this.stopHoldTimer();\n };\n tick();\n this.holdTimer = setInterval(tick, 500);\n }\n\n private stopHoldTimer(): void {\n if (this.holdTimer) clearInterval(this.holdTimer);\n this.holdTimer = null;\n this.els.hold?.classList.remove('on', 'is-expiring');\n this.els.holdNote?.classList.remove('on');\n this.setExtendPrompt(false, 0);\n }\n\n /** Show/refresh (or hide) the \"Need more time?\" prompt with the live seconds left. */\n private setExtendPrompt(show: boolean, ms: number): void {\n if (!this.extendEl) return;\n if (show && this.controller.currentHold() && !this.bookedShown) {\n const secs = Math.ceil(ms / 1000);\n this.els.extendTxt.innerHTML = `Your seats are held for <b>0:${String(secs).padStart(2, '0')}</b>. Need more time?`;\n this.extendEl.classList.add('on');\n } else {\n this.extendEl.classList.remove('on');\n }\n }\n\n private async handleExtend(): Promise<void> {\n const btn = this.els.extendBtn as HTMLButtonElement;\n btn.disabled = true;\n const prev = btn.textContent;\n btn.textContent = 'Adding…';\n try {\n const h = await this.controller.extendHold(this.opts.holdTtlMs);\n if (h) {\n // The controller re-armed its own expiry; sync ours + the pill, hide prompt.\n this.hold = { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items };\n this.holdExpiresAt = h.expiresAt;\n this.extendEl?.classList.remove('on');\n this.rememberHold(this.hold);\n this.emitHoldChange();\n this.toast('More time added — your seats are still held.', 'success');\n } else {\n this.toast(\"Couldn't add more time — please head to checkout now.\", 'warning');\n }\n } catch (err) {\n this.opts.onError?.(err);\n this.toast(\"Couldn't add more time — please head to checkout now.\", 'warning');\n } finally {\n btn.disabled = false;\n btn.textContent = prev;\n }\n }\n\n /**\n * Fire the booked-confirmation state once the buyer's held seats settle to\n * booked. The controller clears its own hold the moment every held label reads\n * 'booked' over the realtime channel (clearBookedHoldIfSettled), and this runs\n * on the same onStatusChange — so `currentHold() === null` while we still hold\n * a checkout handoff means \"sold\", not expired (expiry clears via onHoldExpired\n * on a different path, which nulls this.hold first).\n */\n private detectBooked(): void {\n if (this.bookedShown || !this.handedOff || !this.hold) return;\n if (this.controller.currentHold() !== null) return; // hold still open\n this.showBooked();\n }\n\n private showBooked(): void {\n if (this.bookedShown || !this.hold) return;\n this.bookedShown = true;\n const handoff = this.buildHandoff(this.hold);\n this.stopHoldTimer();\n this.forgetHold();\n const n = handoff.lineItems.reduce((sum, i) => sum + i.quantity, 0);\n if (this.els.bookedSub) {\n this.els.bookedSub.innerHTML =\n `<span class=\"sl-booked-seats\">${n} ${n === 1 ? 'ticket' : 'tickets'}</span> confirmed. ` +\n `A confirmation is on its way.`;\n }\n this.bookedEl?.classList.add('on');\n this.opts.onBooked?.(handoff);\n }\n\n /**\n * The seats are held. Send the buyer wherever this picker's `checkout` option\n * says they go.\n *\n * The default branch is the literal call that stood here before hosted\n * checkout existed, unchanged, so nothing about an existing integration moves.\n */\n private checkoutHandoff(hold: HoldResult, seats: PickerSeat[]): void {\n if (this.checkoutMode === 'hosted') {\n void this.startHostedCheckout(hold, seats);\n return;\n }\n this.opts.onCheckout?.(hold, seats, this.buildHandoff(hold));\n }\n\n /**\n * Take the money ourselves, through the organizer's own gateway.\n *\n * Order of operations matters: ASK FIRST, load second. `payment-options` is\n * already in flight from render, and its answer decides whether any payment\n * code is fetched at all — an event that cannot charge never downloads the\n * card that would have charged it.\n *\n * An empty list is not a failure and never dead-ends the buyer. It routes them\n * to whatever the host has: `onCheckoutUnavailable` (with the server's reason,\n * so the host can say the right one of three very different sentences), then\n * `onCheckout` with the ordinary handoff. A host that supplied neither gets\n * the widget's own honest card instead of a press that did nothing.\n */\n private async startHostedCheckout(hold: HoldResult, seats: PickerSeat[]): Promise<void> {\n const handoff = this.buildHandoff(hold);\n let options: PaymentOptionsResult | null = null;\n try {\n options = await (this.paymentOptions ??= this.pubApi!.paymentOptions(this.opts.event));\n } catch (err) {\n // A failed lookup is not evidence about the organizer's setup, so it falls\n // through to the reason that asserts the least about them.\n this.opts.onError?.(err);\n }\n if (this.destroyed) return;\n\n const provider = options?.providers?.[0];\n if (!provider) {\n const reason = paymentsOffReason(options?.reason);\n const handled = !!this.opts.onCheckoutUnavailable || !!this.opts.onCheckout;\n this.opts.onCheckoutUnavailable?.({ reason, handoff });\n this.opts.onCheckout?.(hold, seats, handoff);\n if (!handled) {\n void this.openCheckoutPanel({\n kind: 'unavailable',\n reason,\n seatCount: handoff.lineItems.reduce((sum, item) => sum + item.quantity, 0),\n });\n }\n return;\n }\n\n await this.openCheckoutPanel({\n kind: 'pay',\n provider,\n order: {\n holdId: handoff.holdId,\n expiresAt: handoff.expiresAt,\n currency: handoff.currency,\n total: handoff.total,\n labels: handoff.lineItems.map((item) => item.displayLabel ?? item.label),\n },\n });\n }\n\n /**\n * Fetch the checkout chunk and put its card over the map.\n *\n * Every failure here lands the buyer back on a map with their seats still\n * held, which is a place they can act from — a blocked chunk request must not\n * leave them staring at a CTA that no longer does anything.\n */\n private async openCheckoutPanel(state: CheckoutState): Promise<void> {\n let mountCheckout: HostedCheckoutModule['mountCheckout'];\n try {\n ({ mountCheckout } = await loadHostedCheckout());\n } catch (err) {\n this.opts.onError?.(err);\n this.toast('Checkout could not be opened. Your seats are still held — please try again.', 'error');\n this.setCtaPhase('idle');\n return;\n }\n if (this.destroyed || !this.root) return;\n this.closeCheckoutPanel();\n this.checkoutPanel = mountCheckout({\n root: this.root,\n state,\n // `returnUrl` rides along so a redirecting gateway can come back to the\n // HOST's page. The server validates its origin against the organizer's\n // declared embed domains and silently falls back to our own buyer page\n // when it does not match, so passing one can never redirect a paid buyer\n // somewhere the organizer did not sanction.\n startSession: (input) => this.pubApi!.startCheckout(this.opts.event, {\n ...input,\n ...(this.opts.returnUrl ? { returnUrl: this.opts.returnUrl } : {}),\n }),\n orderStatus: (orderId) => this.pubApi!.orderStatus(orderId),\n onCancel: () => {\n this.checkoutPanel = null;\n // The hold is untouched by cancelling — the buyer goes back to a map\n // that still has their seats, and the CTA still says checkout.\n if (!this.hold) this.setCtaPhase('idle');\n },\n onConfirmed: (order) => {\n this.opts.onOrderConfirmed?.(order);\n // The seats are sold. Re-read the map so they repaint as booked for this\n // buyer immediately rather than whenever the next realtime frame lands.\n void this.controller.refresh();\n },\n onError: (err) => this.opts.onError?.(err),\n });\n }\n\n private closeCheckoutPanel(): void {\n this.checkoutPanel?.destroy();\n this.checkoutPanel = null;\n }\n\n /** Assemble the stable {@link CheckoutHandoff} from a hold's server line items. */\n private buildHandoff(hold: HoldResult): CheckoutHandoff {\n const items = hold.items ?? [];\n // Host `pricing` overrides win in the handoff too — the host gets back the\n // prices it will actually charge, so map display and order total agree.\n const lineItems: CheckoutLineItem[] = items.map((it: HoldLineItem) => {\n const display = this.controller.lineItemDisplay(it);\n return {\n label: it.label,\n ...(display.displayLabel ? { displayLabel: display.displayLabel } : {}),\n ...(display.displayType ? { displayType: display.displayType } : {}),\n objectId: it.objectId,\n objectType: it.objectType,\n categoryKey: it.categoryKey,\n tierId: it.tierId,\n unitPrice: this.paidPrice(it.categoryKey, it.tierId, it.unitPrice),\n currency: it.currency ?? this.currency,\n quantity: it.quantity ?? 1,\n };\n });\n const currency = lineItems[0]?.currency ?? this.currency;\n const total = lineItems.reduce((sum, i) => sum + i.unitPrice * i.quantity, 0);\n return { holdId: hold.holdId, expiresAt: hold.expiresAt, currency, lineItems, total };\n }\n\n private emitHoldChange(): void {\n const hold = this.hold;\n this.opts.onHoldChange?.(\n hold,\n hold?.seats ?? [],\n hold ? this.buildHandoff(hold) : null,\n );\n }\n\n private toast(\n msg: string,\n tone: 'neutral' | 'success' | 'warning' | 'error' = 'neutral',\n action?: { label: string; onClick: () => void },\n ): void {\n const el = this.els.toast;\n if (!el) return;\n el.replaceChildren();\n const copy = document.createElement('span');\n copy.textContent = msg;\n el.appendChild(copy);\n el.classList.toggle('has-action', !!action);\n if (action) {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'sl-toast-action';\n button.textContent = action.label;\n button.addEventListener('click', action.onClick, { once: true });\n el.appendChild(button);\n }\n el.dataset.tone = tone;\n el.classList.add('on');\n if (this.toastTimer) clearTimeout(this.toastTimer);\n this.toastTimer = setTimeout(() => {\n el.classList.remove('on');\n el.classList.remove('has-action');\n el.dataset.tone = 'neutral';\n }, 4200);\n }\n\n private placeTooltip(): void {\n if (!this.tipEl) return;\n const hw = this.els.map.clientWidth;\n const tw = this.tipEl.offsetWidth;\n const th = this.tipEl.offsetHeight;\n let x = this.tipPos.x + 14;\n let y = this.tipPos.y - th - 12;\n if (x + tw > hw - 8) x = this.tipPos.x - tw - 14;\n if (y < 8) y = this.tipPos.y + 18;\n this.tipEl.style.left = `${Math.max(8, x)}px`;\n this.tipEl.style.top = `${Math.max(8, y)}px`;\n }\n\n /**\n * Row label without the redundant section prefix. Charts commonly name row\n * objects \"104-A\" while the Section column already shows \"104\" — so the Row\n * cell repeats the section and, in the compact hover card, truncates to\n * \"10…\". Strip a leading \"<section><sep>\" so Row reads a clean \"A\". Only when\n * the prefix is exact (won't touch \"1040-A\" under section \"104\"); otherwise\n * the label is shown verbatim.\n */\n /** Buyer-facing type word for the row/table key label — the designer's\n * per-object \"Displayed type\" override, or the default \"Row\". */\n private rowTypeWord(details: { displayType?: string; rowType?: string; objectType?: PickerSeat['objectType'] } | null | undefined): string {\n const authored = details?.displayType?.trim() || details?.rowType?.trim();\n if (authored) return authored;\n if (details?.objectType === 'table') return 'Table';\n if (details?.objectType === 'booth') return 'Booth';\n return 'Row';\n }\n\n private rowShort(details: { sectionLabel?: string; rowLabel?: string } | null | undefined): string | undefined {\n const row = details?.rowLabel;\n const sec = details?.sectionLabel;\n if (!row || !sec) return row;\n for (const sep of ['-', ' ', '·', '/', '_']) {\n const prefix = `${sec}${sep}`;\n if (row.startsWith(prefix) && row.length > prefix.length) return row.slice(prefix.length);\n }\n return row;\n }\n\n private updateTooltip(details: SeatHoverDetails | null): void {\n if (!this.tipEl) return;\n if (!details) {\n this.tipEl.style.display = 'none';\n return;\n }\n const esc = (v: unknown): string =>\n String(v ?? '—').replace(/[&<>\"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' }[ch]!));\n const price = this.money(this.paidPrice(details.categoryKey, details.tierId ?? null, details.price));\n // Identity grid — the same Section·Row·Seat card the buyer meets on confirm\n // and in the cart, just smaller. Falls back to a single field for a bare\n // label (GA / legacy seats with no spatial context).\n const isGroupedTable = details.objectType === 'table' && !!details.bookingMode;\n const isBooth = details.objectType === 'booth';\n const hasLoc = details.sectionLabel || details.rowLabel || details.seatNumber;\n const grid = isGroupedTable\n ? `<div class=\"sl-tip-grid\">` +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(details.rowLabel ?? details.displayLabel ?? details.label)}</span></div>` +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Guests</span><span class=\"sl-tip-val\">${details.bookingMode === 'variable' ? `${details.minOccupancy}–${details.maxOccupancy}` : details.capacity}</span></div>` +\n `</div>`\n : isBooth\n ? `<div class=\"sl-tip-grid\">` +\n (details.sectionLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Section</span><span class=\"sl-tip-val\">${esc(details.sectionLabel)}</span></div>` : '') +\n `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(details.rowLabel ?? details.displayLabel ?? details.label)}</span></div>` +\n `</div>`\n : hasLoc\n ? `<div class=\"sl-tip-grid\">` +\n (details.sectionLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Section</span><span class=\"sl-tip-val\">${esc(details.sectionLabel)}</span></div>` : '') +\n (details.rowLabel ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">${esc(this.rowTypeWord(details))}</span><span class=\"sl-tip-val\">${esc(this.rowShort(details))}</span></div>` : '') +\n (details.seatNumber ? `<div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Seat</span><span class=\"sl-tip-val\">${esc(details.seatNumber)}</span></div>` : '') +\n `</div>`\n : `<div class=\"sl-tip-grid one\"><div class=\"sl-tip-field\"><span class=\"sl-tip-key\">Seat</span><span class=\"sl-tip-val\">${esc(details.displayLabel ?? details.label)}</span></div></div>`;\n const statusLine =\n details.status === 'free'\n ? ''\n : `<div class=\"sl-tip-status\">${details.status === 'held' ? t('map.statusHeld') : t('map.statusTaken')}</div>`;\n const limited = this.limitedViewLabel(details.commercial);\n const cxLine = limited\n ? `<div class=\"sl-tip-cx\"><span class=\"g\" aria-hidden=\"true\">◐</span>${esc(limited)}</div>`\n : '';\n const wheelchair = this.wheelchairProvisionLabel(details.wheelchairSpaceType);\n const wheelchairLine = wheelchair\n ? `<div class=\"sl-tip-cx\"><span class=\"g\" aria-hidden=\"true\">♿</span>${esc(wheelchair)}</div>`\n : '';\n this.tipEl.style.setProperty('--sl-cat', details.categoryColor);\n this.tipEl.innerHTML =\n grid +\n `<div class=\"sl-tip-cat\"><span class=\"sl-tip-dot\" style=\"background:${details.categoryColor}\"></span>` +\n `<span class=\"sl-tip-name\">${esc(details.categoryLabel)}</span>` +\n `<span class=\"sl-tip-amt\">${price}</span></div>` +\n wheelchairLine +\n cxLine +\n statusLine;\n this.tipEl.style.display = 'block';\n this.placeTooltip();\n }\n\n // ---- public conveniences ----------------------------------------------------\n\n getSelection(): PickerSeat[] {\n return this.committedSelection();\n }\n\n /** Current colorblind-safe render state, resolved from the stored buyer\n * preference at mount. Host chrome (e.g. the Designer preview) reads this to\n * surface the state rather than rendering colorblind colors silently. */\n isColorblindSafe(): boolean {\n return this.cbSafe;\n }\n\n /** Single source of truth for the colorblind-safe toggle — used by both the\n * in-widget button and host chrome. Updates the renderer, the persisted\n * cross-surface preference, and the in-widget button's pressed state together\n * so the two controls never diverge. */\n setColorblindSafe(on: boolean): void {\n if (on === this.cbSafe) return;\n this.cbSafe = on;\n this.cbEl?.setAttribute('aria-pressed', String(on));\n this.controller.setColorblindSafe(on);\n // Persist under the SAME key the public page uses (cross-surface preference).\n writeStoredColorblind(on);\n }\n\n /** Switch the underlying 2D renderer projection (flat / isometric). The buyer\n * UI no longer exposes `perspective`; it is coerced to `flat`. */\n setViewMode(mode: RendererViewMode): void {\n this.controller.setViewMode(this.normalizeInitialView(mode));\n this.syncProjection();\n this.dismissConfirm();\n }\n\n /** Current buyer canvas projection. */\n getViewMode(): RendererViewMode {\n return this.controller.getViewMode();\n }\n\n /** `perspective` (2.5D) is retired from the buyer surface — accept it for\n * source compatibility but coerce to `flat` with a one-time deprecation warn. */\n private perspectiveWarned = false;\n private normalizeInitialView(mode: RendererViewMode | undefined): RendererViewMode {\n if (mode === 'perspective') {\n if (!this.perspectiveWarned) {\n this.perspectiveWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[seatlayer] initialView:'perspective' (2.5D) is deprecated for the buyer picker and \"\n + \"was coerced to 'flat'. Use the Map | 3D control for the immersive view.\",\n );\n }\n return 'flat';\n }\n return mode ?? 'flat';\n }\n\n // ---- 3D venue view ---------------------------------------------------------\n\n /** Current buyer view: the flat map, or the interactive 3D venue. */\n getBuyerView(): 'map' | 'venue3d' {\n return this.buyerView;\n }\n\n /**\n * Switch between the flat seat **Map** and the interactive **3D venue** view —\n * the same control the buyer's on-widget `Map | 3D` toggle drives.\n *\n * Entering `'venue3d'` with `opts.flyToSeatId` runs the cinematic tour: the\n * camera flies to the seat and holds in the live scene (a chip offers the\n * 360° view-from-seat) —\n * the widget enters 3D and auto-flies the camera to that seat, dissolving into\n * its view-from-seat panorama (the same chain as tapping \"See the view from\n * here\" on a seat's confirm card). When the widget is **already** in the 3D\n * view, the camera simply flies to the requested seat — the GL scene is not\n * torn down or rebuilt, so there is no flash or re-entry.\n *\n * No-op when the view is unchanged and no `flyToSeatId` is given, or when 3D is\n * unavailable for this chart.\n *\n * @param view `'map'` for the flat picker, `'venue3d'` for the 3D venue.\n * @param opts.flyToSeatId When entering (or already in) `'venue3d'`, the seat\n * id to fly the camera to — cinematic → panorama.\n * Ignored when `view` is `'map'`.\n *\n * @example\n * // Public 3D tour entry — enter 3D and fly straight to the buyer's seat:\n * picker.setBuyerView('venue3d', { flyToSeatId: 'A-12' });\n */\n setBuyerView(view: 'map' | 'venue3d', opts?: { flyToSeatId?: string }): void {\n if (view === 'map') {\n this.exit3d();\n return;\n }\n const flyToSeatId = opts?.flyToSeatId;\n if (this.buyerView === 'venue3d') {\n // Already immersed — just fly the cinematic to the requested seat (if any),\n // without a jarring teardown/rebuild of the GL scene.\n if (flyToSeatId) void this.view3dHandle?.flyToSeat(flyToSeatId);\n return;\n }\n // Enter 3D; when a seat is given, the cinematic flies straight to it.\n void this.enter3d(flyToSeatId);\n }\n\n /** SeatStatus → the view3d palette state. Selection is layered separately. */\n private seatState3dFor(seat: ExpandedSeat): 'available' | 'held' | 'sold' | 'dimmed' {\n switch (this.controller.getStatus(seat.id)) {\n case 'held': return 'held';\n case 'booked': return 'sold';\n case 'not_for_sale': return 'dimmed';\n default: break;\n }\n // A filter that dims a seat on the map has to dim it in 3D too. 2D applies\n // these as Konva opacity, which the GL view never saw — so a buyer who\n // filtered to one price band and then switched to 3D got the unfiltered\n // venue back with no indication the filter was still on. The 'dimmed' state\n // already exists for held-back inventory and is exactly this treatment.\n if (this.priceBandKeys != null && !this.priceBandKeys.has(seat.categoryKey)) return 'dimmed';\n if (this.limitedViewFilter && (seat.commercial?.restrictedView || seat.commercial?.obstructedView)) {\n return 'dimmed';\n }\n return 'available';\n }\n\n /** Push the full live availability snapshot into the 3D handle (selection is\n * preserved inside the module). Cheap enough per status delta. */\n private pushAvailabilityTo3d(): void {\n if (!this.view3dHandle) return;\n const updates = this.allSeats().map((s) => ({ seatId: s.id, state: this.seatState3dFor(s) }));\n this.view3dHandle.setAvailability(updates);\n }\n\n /** Mirror the authoritative widget selection into the 3D handle. */\n private syncSelectionTo3d(): void {\n if (!this.view3dHandle) return;\n this.view3dHandle.setSelection(this.controller.getSelection().map((s) => s.id));\n }\n\n /** Build the view-from-seat panorama the cinematic dissolves into — reuses the\n * exact input path as the 2D `openSeatView` (organizer photo, else generated). */\n private async seatViewFor3d(seatId: string): Promise<View3DSeatView | null> {\n const seat = this.allSeats().find((s) => s.id === seatId);\n if (!seat) return null;\n if (seat.viewUrl) return { url: seat.viewUrl };\n const doc = this.controller.doc;\n if (!doc) return null;\n const activeId = this.controller.getActiveFloorId();\n const focal = seat.focalPoint\n ?? doc.floors?.find((f) => f.id === activeId)?.focalPoint\n ?? doc.focalPoint\n ?? { x: 0, y: 0 };\n try {\n // Async only for the lazy generator chunk; by the time a cinematic asks\n // for a view the buyer has already been in 3D for a second or more.\n const { generateSeatPanorama } = await loadPanorama();\n return { url: generateSeatPanorama(seat, focal, this.allSeats()).url };\n } catch {\n return null;\n }\n }\n\n /** Route the module's decoupled analytics into the host callback, tagged buyer. */\n private emit3dAnalytics(event: string, props?: Record<string, unknown>): void {\n try {\n this.opts.onAnalytics?.(event, { ...props, surface: 'buyer' });\n } catch {\n /* a throwing host sink never breaks the widget */\n }\n }\n\n /** A 3D seat tap runs the SAME selection path as a 2D tap: toggle through the\n * controller, then raise the shared confirm card (bottom-sheeted in 3D). */\n private onView3dSeatPick(seatId: string): void {\n if (this.salesClosed) {\n this.toast(this.tf('picker.salesClosedToast', 'Sales are closed for this event.'), 'warning');\n this.syncSelectionTo3d();\n return;\n }\n const seat = this.allSeats().find((s) => s.id === seatId);\n if (!seat) return;\n // Tapping an already-committed seat clears it (mirrors the 2D toggle).\n const already = this.committedSelection().some((s) => s.id === seatId);\n if (already) {\n this.controller.deselect([seatId]);\n this.dismissConfirm();\n return;\n }\n this.flashPickedSeat(seatId);\n this.controller.select([seatId]); // programmatic select is silent → confirm ourselves\n if (this.opts.confirmSelection !== false) this.showConfirm(seat);\n else this.syncTray();\n }\n\n /**\n * The venue-navigation rail inside 3D: levels and areas.\n *\n * In 2D a buyer moves through the venue by floor switcher and by the LOD\n * rungs. Both are hidden while immersed, and the 3D module's own chips only\n * cover \"go home\" and \"see the 360\" — so on a multi-floor or multi-zone chart\n * the buyer entered 3D and LOST the ability to reach the level or area they\n * were booking. The camera moves for both already exist on the handle\n * (`focusFloor` / `focusZone`); this is the surface that offers them.\n *\n * Levels are a TOGGLE (a floor stays isolated until you pick another), areas\n * are an ACTION (the camera flies there and you are then free to orbit), which\n * is why only the level pills carry a pressed state.\n */\n private buildView3dNav(overlay: HTMLElement, handle: Venue3DHandle): void {\n const floors = handle.floors();\n // An empty zone has nothing to frame and `focusZone` refuses it — offering\n // a pill that cannot move the camera is worse than offering nothing.\n const zones = handle.zones().filter((z) => z.seatCount > 0);\n // Zones are optional; sections are not. A chart that authors no zones (or\n // one) still needs a way to move around the venue, so the rail falls back to\n // the rung below. Capped, because a 51-section arena is a list, not a rail —\n // past that the buyer is better served by the 2D map's section navigation.\n const sections = zones.length > 1\n ? []\n : handle.sections().filter((s) => s.seatCount > 0).slice(0, MAX_3D_SECTION_PILLS);\n // One of anything is not a choice — a single-floor, single-zone venue gets\n // no rail rather than a rail that does nothing.\n const wantFloors = floors.length > 1;\n const wantZones = zones.length > 1;\n const wantSections = sections.length > 1;\n if (!wantFloors && !wantZones && !wantSections) return;\n\n const nav = document.createElement('div');\n nav.className = 'sl-view3d-nav';\n\n if (wantFloors) {\n const row = document.createElement('div');\n row.setAttribute('role', 'group');\n row.setAttribute('aria-label', this.tf('picker.levels', 'Levels'));\n const pills: HTMLButtonElement[] = [];\n const select = (index: number | null): void => {\n if (!handle.focusFloor(index)) return;\n pills.forEach((p) => {\n p.setAttribute('aria-pressed', String((p.dataset.floor === '' ? null : Number(p.dataset.floor)) === index));\n });\n };\n const add = (label: string, index: number | null): void => {\n const b = document.createElement('button');\n b.type = 'button';\n b.textContent = label;\n b.dataset.floor = index === null ? '' : String(index);\n b.setAttribute('aria-pressed', String(index === null));\n b.addEventListener('click', () => select(index));\n pills.push(b);\n row.appendChild(b);\n };\n add(this.tf('picker.allLevels', 'All levels'), null);\n for (const f of floors) add(f.label || `Level ${f.index + 1}`, f.index);\n nav.appendChild(row);\n }\n\n if (wantZones || wantSections) {\n const row = document.createElement('div');\n row.setAttribute('role', 'group');\n row.setAttribute('aria-label', this.tf('picker.areas', 'Areas'));\n const entries: Array<{ id: string; label: string; go: () => void }> = wantZones\n ? zones.map((z) => ({ id: z.id, label: z.label || z.id, go: () => { handle.focusZone(z.id); } }))\n : sections.map((s) => ({ id: s.id, label: s.label || s.id, go: () => { handle.focusSection(s.id); } }));\n for (const e of entries) {\n const b = document.createElement('button');\n b.type = 'button';\n b.textContent = e.label;\n b.addEventListener('click', e.go);\n row.appendChild(b);\n }\n nav.appendChild(row);\n }\n\n overlay.appendChild(nav);\n }\n\n private async enter3d(flySeatId?: string): Promise<void> {\n if (this.view3dEl || !this.canOffer3d() || !this.els.map) return;\n const doc = this.controller.doc;\n if (!doc) return;\n this.buyerView = 'venue3d';\n this.root?.setAttribute('data-view3d', 'on');\n this.dismissConfirm();\n this.syncProjection();\n\n const overlay = document.createElement('div');\n overlay.className = 'sl-view3d';\n overlay.setAttribute('role', 'group');\n overlay.setAttribute('aria-label', 'Interactive 3D venue view');\n const back = document.createElement('button');\n back.type = 'button';\n back.className = 'sl-view3d-back';\n back.innerHTML =\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M15 18l-6-6 6-6\"/></svg>'\n + `<span>${this.tf('picker.backToMap', 'Back to map')}</span>`;\n back.addEventListener('click', () => this.exit3d());\n overlay.appendChild(back);\n this.els.map.appendChild(overlay);\n this.view3dEl = overlay;\n requestAnimationFrame(() => { overlay.style.opacity = '1'; });\n\n const gen = ++this.view3dGen;\n try {\n const seats = expandChart(doc);\n const mod = await loadVenue3d();\n // Left 3D (or was torn down) while the OGL chunk loaded → abandon.\n if (gen !== this.view3dGen || this.buyerView !== 'venue3d' || this.view3dEl !== overlay) return;\n const handle = mod.mountVenue3D(overlay, { doc, seats }, {\n onSeatPick: (id) => this.onView3dSeatPick(id),\n // Deferred off the tap gesture: generateSeatPanorama walks every seat\n // (O(n) on a 13k chart), and the module prefetches at pick — by the\n // time the flight lands (~2.5s) the idle render has long finished. A\n // null view REJECTS so the module's no-panorama path keeps the buyer\n // in orbit instead of dissolving into an empty overlay.\n getSeatView: (id) =>\n new Promise((resolve, reject) => {\n const run = () => {\n void this.seatViewFor3d(id).then((view) => {\n if (view) resolve(view);\n else reject(new Error('seat_view_unavailable'));\n });\n };\n const ric = (globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => void }).requestIdleCallback;\n if (typeof ric === 'function') ric(run, { timeout: 1500 });\n else setTimeout(run, 50);\n }),\n onAnalytics: (event, props) => this.emit3dAnalytics(event, props),\n });\n this.view3dHandle = handle;\n this.pushAvailabilityTo3d();\n this.syncSelectionTo3d();\n this.buildView3dNav(overlay, handle);\n if (flySeatId) void handle.flyToSeat(flySeatId);\n } catch (err) {\n this.opts.onError?.(err);\n this.exit3d();\n }\n }\n\n private exit3d(): void {\n if (this.buyerView !== 'venue3d' && !this.view3dEl) return;\n this.view3dGen++; // supersede any in-flight mount\n this.buyerView = 'map';\n this.root?.removeAttribute('data-view3d');\n try { this.view3dHandle?.dispose(); } catch { /* GL teardown best-effort */ }\n this.view3dHandle = null;\n const overlay = this.view3dEl;\n this.view3dEl = null;\n if (overlay) {\n overlay.style.opacity = '0';\n setTimeout(() => overlay.remove(), 320);\n }\n this.syncProjection();\n // Zoom/pan of the underlying 2D stage was never touched, so the map is\n // restored exactly. Re-offer the confirm the buyer left via \"See it in 3D\".\n const seat = this.view3dReturnSeat;\n this.view3dReturnSeat = null;\n if (seat && this.committedSelection().some((s) => s.id === seat.id)\n && this.opts.confirmSelection !== false) {\n this.showConfirm(seat);\n }\n }\n\n /** Current active/restored hold reflected in the tray. */\n getCurrentHold(): HoldResult | null {\n return this.hold;\n }\n\n /** Explicit host-driven hold restore (automatic session restore is on by default). */\n async resumeHold(holdId: string): Promise<HoldResult | null> {\n return this.resumeHoldFromServer(holdId, false);\n }\n\n /** Remove one server-held ticket while keeping the rest of the hold active. */\n async removeHeldTicket(label: string): Promise<boolean> {\n return this.removeHeldLabel(label);\n }\n\n async bestAvailable(\n qty: number,\n categoryKey?: string,\n opts: { preferPremium?: boolean; zoneId?: string } = {},\n ): Promise<HoldResult | null> {\n if (this.salesClosed || this.bestAvailableBusy) return null;\n qty = Math.max(1, Math.min(this.maxTickets, Math.floor(qty)));\n if (this.confirmSeat) this.cancelConfirm();\n this.bestAvailableConfirm = false;\n this.bestAvailableBusy = true;\n const button = this.els.tray?.querySelector<HTMLButtonElement>('.sl-ba-go');\n if (button) {\n button.disabled = true;\n button.innerHTML = '<span class=\"sl-ba-spin\" aria-hidden=\"true\"></span>Finding…';\n }\n try {\n // Same checkout window as a clicked selection — see the CTA's hold() call.\n const h = await this.controller.bestAvailable(qty, categoryKey, { ...opts, ttlMs: this.opts.holdTtlMs });\n if (h) {\n this.hold = { holdId: h.holdId, expiresAt: h.expiresAt, seats: h.seats, items: h.items };\n this.handedOff = false;\n this.bookedShown = false;\n this.gaQty.clear();\n this.startHoldTimer(h.expiresAt);\n this.flashHeldSeats(this.hold);\n this.syncTray();\n this.emitHoldChange();\n // Premium quick-pick asked for a premium block but no full block of\n // `qty` existed → we held the best overall instead. Surface a subtle note.\n if (opts.preferPremium && h.seats.length && !h.seats.every((s) => s.commercial?.premium)) {\n this.toast(t('picker.premiumFallbackNote', { count: qty }), 'neutral');\n }\n return this.hold;\n }\n return null;\n } catch (err) {\n this.opts.onError?.(err);\n const reason = (err as { reason?: string })?.reason;\n const message = reason === 'not_enough_together'\n ? `We couldn't find ${qty} seats together. Try fewer seats or another ticket type.`\n : reason === 'sold_out'\n ? 'That ticket type is sold out. Try another ticket type.'\n : reason === 'event_closed'\n ? 'Seat sales have closed for this event.'\n : 'Those seats are no longer available. Try another quantity or ticket type.';\n this.toast(message, 'error');\n return null;\n } finally {\n this.bestAvailableBusy = false;\n this.syncTray();\n }\n }\n\n async release(): Promise<void> {\n const tracked = this.hold;\n const controllerHold = this.controller.currentHold();\n let released = true;\n if (controllerHold) {\n released = await this.controller.release();\n } else if (tracked) {\n // The live controller can legitimately settle/clear its local hold before\n // the shell finishes dismissing. The shell still owns the server handoff,\n // so release from that authoritative copy instead of silently no-oping.\n const labels = [...new Set([\n ...(tracked.items ?? []).map((item) => item.label),\n ...(tracked.seats ?? []).map((seat) => seat.label),\n ])];\n if (labels.length) {\n try {\n await this.api.release(this.opts.event, labels, tracked.holdId);\n } catch (error) {\n this.opts.onError?.(error);\n released = false;\n }\n }\n }\n if (!released) {\n this.toast(\"Couldn't release your tickets. Your hold is unchanged.\", 'error');\n return;\n }\n this.hold = null;\n this.forgetHold();\n this.handedOff = false;\n this.bookedShown = false;\n this.ctaPhase = 'idle';\n this.stopHoldTimer();\n this.gaQty.clear();\n this.syncTray();\n this.emitHoldChange();\n }\n\n // ---- buyer access (Sales Channels) ---------------------------------------\n\n /**\n * Realtime for an access-scoped picker.\n *\n * A tokenless picker never gets here: `access` is null, `PubApi.socketUrl()`\n * returns the URL it always has, and PickerController keeps its own socket\n * and its own legacy frames. Nothing about the public path changes.\n */\n private startRealtime(): void {\n if (!this.access?.configured || !this.pubApi || this.realtime) return;\n const event = this.opts.event;\n this.realtime = new BuyerRealtimeClient({\n url: this.pubApi.subscribeUrl(event),\n mintTicket: () => this.pubApi!.subscribeTicket(event),\n onAccessUnavailable: (state) => {\n this.opts.onAccessUnavailable?.(state);\n this.showAccessPanel(state);\n },\n sink: createControllerSink(this.controller, {\n flashOnLiveChange: true,\n onStatusChange: () => {\n this.syncPrices();\n this.detectBooked();\n this.refreshMinimap();\n this.pushAvailabilityTo3d();\n },\n onSelectedObjectUnavailable: (labels, reason) => {\n this.opts.onSelectedObjectUnavailable?.({ labels, reason });\n this.syncTray();\n this.toast(\n reason === 'ineligible'\n ? this.tf(\n 'picker.seatNoLongerYours',\n 'Some seats are no longer available to you. They have been removed from your order.',\n )\n : this.tf(\n 'picker.seatTaken',\n 'Someone else took a seat you had picked. It has been removed from your order.',\n ),\n 'warning',\n );\n },\n }),\n });\n this.realtime.start();\n }\n\n /**\n * Re-acquire the buyer access session — call after your app has re-authorized\n * the buyer. A revoked session cannot recover any other way. Resolves true\n * when a fresh bearer is held; the map and the realtime feed resume with it.\n */\n async refreshAccess(): Promise<boolean> {\n if (!this.access?.configured) return false;\n const ok = await this.access.refresh('manual');\n if (!ok) return false;\n this.dismissAccessPanel();\n await this.controller.refresh();\n if (this.realtime) this.realtime.restart();\n else this.startRealtime();\n return true;\n }\n\n /**\n * The buyer-facing access state. Plain language, no internal vocabulary, and\n * never a channel name, id or count — the buyer is told what happened and\n * what to do, not which allocation they missed (guide §7, §10).\n *\n * Held seats are deliberately left alone: a hold is relinquished by its own\n * opaque capability, not by channel access, so losing access never strands\n * inventory and never silently drops a buyer's cart (guide §9).\n */\n private showAccessPanel(state: { reason: BuyerAccessUnavailableReason; retryable: boolean }): void {\n if (this.destroyed || !this.root) return;\n const copy = this.accessCopy(state.reason);\n this.dismissAccessPanel();\n const panel = document.createElement('div');\n panel.className = 'sl-access';\n panel.setAttribute('role', 'status');\n panel.setAttribute('aria-live', 'polite');\n const text = document.createElement('div');\n const title = document.createElement('div');\n title.className = 'sl-access-title';\n title.textContent = copy.title;\n const body = document.createElement('div');\n body.className = 'sl-access-body';\n body.textContent = copy.body;\n text.appendChild(title);\n text.appendChild(body);\n if (copy.action) {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'sl-access-act';\n button.textContent = copy.action;\n button.addEventListener('click', () => {\n void this.refreshAccess();\n });\n text.appendChild(button);\n }\n panel.appendChild(text);\n (this.regions?.['bottom-center'] ?? this.root).appendChild(panel);\n this.accessEl = panel;\n }\n\n private dismissAccessPanel(): void {\n this.accessEl?.remove();\n this.accessEl = null;\n }\n\n private accessCopy(reason: BuyerAccessUnavailableReason): {\n title: string;\n body: string;\n action?: string;\n } {\n switch (reason) {\n case 'paused':\n return {\n title: this.tf('picker.accessPausedTitle', 'These seats are on hold right now'),\n body: this.tf(\n 'picker.accessPausedBody',\n 'The organizer has paused this selection. Try again in a few minutes.',\n ),\n action: this.tf('picker.accessRetry', 'Try again'),\n };\n case 'revoked':\n return {\n title: this.tf('picker.accessRevokedTitle', 'This access link is no longer active'),\n body: this.tf(\n 'picker.accessRevokedBody',\n 'Ask whoever sent you here for a new link to keep booking these seats.',\n ),\n };\n case 'no_token':\n case 'provider_failed':\n return {\n title: this.tf('picker.accessExpiredTitle', 'Your access session has ended'),\n body: this.tf(\n 'picker.accessExpiredBody',\n 'Sign in again, or reload the page, to keep browsing these seats. Anything you are already holding stays yours.',\n ),\n action: this.tf('picker.accessRetry', 'Try again'),\n };\n default:\n return {\n title: this.tf('picker.accessInvalidTitle', 'We couldn’t verify your access'),\n body: this.tf(\n 'picker.accessInvalidBody',\n 'You can still book anything shown as available. Contact whoever sent you here for access to the rest.',\n ),\n };\n }\n }\n\n destroy(): void {\n this.destroyed = true;\n this.realtime?.stop();\n this.realtime = null;\n this.dismissAccessPanel();\n this.access?.clear();\n // Closing/tearing down before checkout means the buyer abandoned any\n // best-available hold. Release it server-side; a handed-off checkout keeps\n // its hold alive across the host's route transition.\n if (this.hold && !this.handedOff) void this.controller.release();\n this.closeConfirm();\n this.dismissTableDialog(false);\n this.closeSeatView();\n // A payment card outlives its own mount node (it listens on the document for\n // ESC), so it is torn down explicitly rather than left to root.remove().\n this.closeCheckoutPanel();\n this.exit3d(); // dispose GL + remove the 3D overlay if it's up\n this.stopHoldTimer();\n if (this.toastTimer) clearTimeout(this.toastTimer);\n if (this.liveTimer) clearTimeout(this.liveTimer);\n for (const timer of this.motionTimers) clearTimeout(timer);\n this.motionTimers.clear();\n this.ro?.disconnect();\n this.ro = null;\n // Don't strand a host frame pinned fullscreen across a route teardown.\n if (this.framedFs) this.setFramedFs(false);\n if (this.escHandler) document.removeEventListener('keydown', this.escHandler);\n if (this.fsChangeHandler) document.removeEventListener('fullscreenchange', this.fsChangeHandler);\n if (this.fsEscHandler) window.removeEventListener('keydown', this.fsEscHandler);\n this.controller.destroy();\n this.projectionEl = null;\n this.root?.remove();\n this.root = null;\n if (this.modalScrim) {\n this.modalScrim.remove();\n this.modalScrim = null;\n (this.prevFocus as HTMLElement | null)?.focus?.();\n }\n }\n}\n","/**\n * Host-side helper for embedding the SeatLayer picker as an iframe.\n *\n * The picker (the /e/:key page, mounted `position:fixed; inset:0`) reports its\n * desired height and fullscreen intent to whatever page frames it, using the\n * picker wire contract:\n *\n * • `{ type: 'seatlayer:height', px:number }` — grow the iframe to `px`.\n * • `{ type: 'seatlayer:fullscreen', on:boolean }` — pin/unpin over the host.\n *\n * A framed picker cannot escape its own iframe with CSS, so it delegates both\n * concerns to the host. `attachPickerFrame` wires those two behaviours onto a\n * picker iframe and returns a detach function that tears everything back down.\n */\nexport interface AttachPickerFrameOptions {\n /**\n * Origin to accept messages from. Defaults to the origin parsed from\n * `iframe.src`. Messages from any other origin (or any other window) are\n * ignored — the picker posts with `targetOrigin:'*'`, so the host is the side\n * that must verify `event.origin`.\n */\n origin?: string;\n}\n\n/**\n * Attach the picker resize + fullscreen protocol to a picker iframe.\n *\n * ```ts\n * const iframe = document.querySelector('iframe#seatlayer')!;\n * const detach = attachPickerFrame(iframe);\n * // …later, when removing the embed:\n * detach();\n * ```\n *\n * @param iframe The `<iframe>` element pointing at a SeatLayer picker embed.\n * @param opts Optional `{ origin }` override for the accepted message origin.\n * @returns A detach function: removes the listener and restores any pinned state.\n */\nexport function attachPickerFrame(\n iframe: HTMLIFrameElement,\n opts: AttachPickerFrameOptions = {},\n): () => void {\n let expectedOrigin = opts.origin ?? '';\n if (!expectedOrigin) {\n try {\n expectedOrigin = new URL(iframe.src, window.location.href).origin;\n } catch {\n expectedOrigin = '';\n }\n }\n\n let pinned = false;\n let frameStyleBeforeFs: string | null = null;\n let docOverflowBeforeFs: string | null = null;\n let bodyOverflowBeforeFs: string | null = null;\n let lastAutoHeight = '';\n let keyHandler: ((event: KeyboardEvent) => void) | null = null;\n\n const pin = (): void => {\n if (pinned) return;\n pinned = true;\n frameStyleBeforeFs = iframe.getAttribute('style');\n Object.assign(iframe.style, {\n position: 'fixed',\n inset: '0',\n width: '100vw',\n height: '100vh',\n margin: '0',\n border: '0',\n zIndex: '2147483000',\n background: '#101625',\n } satisfies Partial<CSSStyleDeclaration>);\n\n const docEl = document.documentElement;\n docOverflowBeforeFs = docEl.style.overflow;\n docEl.style.overflow = 'hidden';\n if (document.body) {\n bodyOverflowBeforeFs = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n keyHandler = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') unpin();\n };\n window.addEventListener('keydown', keyHandler);\n };\n\n const unpin = (): void => {\n if (!pinned) return;\n pinned = false;\n if (frameStyleBeforeFs === null) iframe.removeAttribute('style');\n else iframe.setAttribute('style', frameStyleBeforeFs);\n frameStyleBeforeFs = null;\n // Re-apply any height reported while we were pinned.\n if (lastAutoHeight) iframe.style.height = lastAutoHeight;\n\n if (docOverflowBeforeFs !== null) {\n document.documentElement.style.overflow = docOverflowBeforeFs;\n docOverflowBeforeFs = null;\n }\n if (bodyOverflowBeforeFs !== null && document.body) {\n document.body.style.overflow = bodyOverflowBeforeFs;\n bodyOverflowBeforeFs = null;\n }\n if (keyHandler) {\n window.removeEventListener('keydown', keyHandler);\n keyHandler = null;\n }\n };\n\n const onMessage = (event: MessageEvent<unknown>): void => {\n if (event.source !== iframe.contentWindow) return;\n if (expectedOrigin && event.origin !== expectedOrigin) return;\n if (!event.data || typeof event.data !== 'object') return;\n const data = event.data as Record<string, unknown>;\n\n if (data.type === 'seatlayer:height') {\n if (typeof data.px === 'number' && Number.isFinite(data.px) && data.px > 0) {\n lastAutoHeight = `${Math.round(data.px)}px`;\n // While pinned the iframe fills the viewport; the height is re-applied on unpin.\n if (!pinned) iframe.style.height = lastAutoHeight;\n }\n return;\n }\n if (data.type === 'seatlayer:fullscreen') {\n if (data.on === true) pin();\n else if (data.on === false) unpin();\n }\n };\n\n window.addEventListener('message', onMessage);\n\n return (): void => {\n window.removeEventListener('message', onMessage);\n unpin();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;;;ACgEA,IAAM,eAAe;AAO5B,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,SAAS,kBAAkB;AACpD,yBAAqB;AAErB,QAAI,eAAgB,QAAO,MAAM,SAAS;AAE1C,QAAI,wBAAwB,MAAM;AAChC,eAAS,gBAAgB,MAAM,WAAW;AAC1C,4BAAsB;AAAA,IACxB;AACA,QAAI,yBAAyB,QAAQ,SAAS,MAAM;AAClD,eAAS,KAAK,MAAM,WAAW;AAC/B,6BAAuB;AAAA,IACzB;AACA,QAAI,YAAY;AACd,aAAO,oBAAoB,WAAW,UAAU;AAChD,mBAAa;AAAA,IACf;AAAA,EACF;AAEA,QAAM,YAAY,CAAC,UAAuC;AACxD,QAAI,MAAM,WAAW,OAAO,cAAe;AAC3C,QAAI,kBAAkB,MAAM,WAAW,eAAgB;AACvD,QAAI,CAAC,MAAM,QAAQ,OAAO,MAAM,SAAS,SAAU;AACnD,UAAM,OAAO,MAAM;AAEnB,QAAI,KAAK,SAAS,oBAAoB;AACpC,UAAI,OAAO,KAAK,OAAO,YAAY,OAAO,SAAS,KAAK,EAAE,KAAK,KAAK,KAAK,GAAG;AAC1E,yBAAiB,GAAG,KAAK,MAAM,KAAK,EAAE,CAAC;AAEvC,YAAI,CAAC,OAAQ,QAAO,MAAM,SAAS;AAAA,MACrC;AACA;AAAA,IACF;AACA,QAAI,KAAK,SAAS,wBAAwB;AACxC,UAAI,KAAK,OAAO,KAAM,KAAI;AAAA,eACjB,KAAK,OAAO,MAAO,OAAM;AAAA,IACpC;AAAA,EACF;AAEA,SAAO,iBAAiB,WAAW,SAAS;AAE5C,SAAO,MAAY;AACjB,WAAO,oBAAoB,WAAW,SAAS;AAC/C,UAAM;AAAA,EACR;AACF;","names":["resolveContainer","target","PickerController","loadLocale","setStringOverrides","t","DEFAULT_API_BASE","DEFAULT_MAX_SELECTION","resolveContainer","PickerController","t","loadLocale","setStringOverrides","pano","canView"]}
|