@seatlayer/js 0.51.0 → 0.53.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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/channelPlan.ts","../src/manageApi.ts","../src/channelsMode.ts"],"sourcesContent":["/**\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>`. Browser code must\n * use a short-lived, event-scoped organizer grant (`mse_…`, minted by a\n * trusted backend). The low-level client retains tenant-secret (`sk_…`)\n * compatibility for trusted server runtimes only; never pass one to\n * SeatManager or any other browser bundle.\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 * - chart geometry and authored media use authenticated organizer Event\n * routes. A manage bearer is not buyer authority and is never sent to\n * `/pub`. The seat STATE reads are private too. `/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 * Managed sales are deliberately not exposed by this browser client. Create\n * them from trusted server code through the inventory booking API; SeatManager\n * exposes only the organizer operations it can actually complete itself.\n */\nimport type { AvailabilityRule, ChartDoc } from '@seatlayer/core';\nimport type {\n AccessLinkRecord,\n AccessLinkReveal,\n AccessLinkStatusRecord,\n AssignmentResult,\n ChannelAccessIntent,\n ChannelCounts,\n ChannelListResult,\n ChannelRecord,\n ChannelState,\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 /** Configured-price snapshots for booked inventory; not proof of payment. */\n bookedValue: number;\n /** @deprecated Use `bookedValue`. */\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 bookedValue: number;\n /** @deprecated Use `bookedValue`. */\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 /** Configured value attached to booked inventory, never payment revenue. */\n bookedValue: { gross: number; bySection: ControlRoomSectionMetric[] };\n /** @deprecated Use `bookedValue`. */\n revenue: { gross: number; bySection: ControlRoomSectionMetric[] };\n velocity: {\n windowMinutes: number;\n bySection: Array<{\n sectionId: string;\n netBooked: number;\n bookedValue: number;\n /** @deprecated Use `bookedValue`. */\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/** Platform/SDK inventory history — deliberately unrelated to commerce Orders. */\nexport type InventoryBookingState = 'booked' | 'partially_cancelled' | 'cancelled';\n\nexport interface InventoryBookingObject {\n label: string;\n objectId: string;\n objectType: 'seat' | 'booth' | 'ga' | 'table';\n categoryKey: string;\n sectionId: string | null;\n sectionLabel: string | null;\n zoneId: string | null;\n tierId: string | null;\n releaseId: string | null;\n bookingMode: 'individual' | 'whole' | 'variable';\n quantity: number;\n /** Event-configured price snapshot; not proof of what a buyer paid. */\n unitPrice: number;\n configuredValue: number;\n currency: string;\n channelId: string | null;\n channelExternalRef: string | null;\n source: string;\n state: 'booked' | 'cancelled';\n bookedAt: number;\n cancelledAt: number | null;\n}\n\nexport interface InventoryBooking {\n eventKey: string;\n eventMode: 'live' | 'test';\n bookingRef: string;\n state: InventoryBookingState;\n bookedAt: number;\n updatedAt: number;\n cancelledAt: number | null;\n source: string;\n bookedBy: string | null;\n lastActor: string | null;\n lastSource: string;\n labels: string[];\n objects: InventoryBookingObject[];\n quantity: number;\n activeQuantity: number;\n configuredValue: number;\n activeConfiguredValue: number;\n currency: string | null;\n}\n\nexport interface InventoryBookingsQuery {\n q?: string;\n state?: InventoryBookingState | null;\n cursor?: string | null;\n limit?: number;\n}\n\nexport interface InventoryBookingsPage {\n bookings: InventoryBooking[];\n nextCursor: string | null;\n}\n\nexport interface InventoryBookingActivity {\n id: number;\n action: 'book' | 'replay' | 'partial_cancel' | 'cancel' | 'reconcile';\n at: number;\n labels: string[];\n actor: string | null;\n source: string;\n}\n\nexport interface InventoryBookingDetail {\n booking: InventoryBooking;\n activity: InventoryBookingActivity[];\n activityTruncated: boolean;\n}\n\n/** Booking-time facts attached to the channel that produced the inventory move. */\nexport interface ChannelAttribution {\n sold: number;\n units: number;\n bookedValue: number | null;\n /** @deprecated Use `bookedValue`. */\n revenue: number | null;\n}\n\nexport interface ChannelReportRow {\n channelId: string;\n name: string;\n externalRef: string | null;\n state: ChannelState;\n allocation: ChannelCounts;\n attribution: ChannelAttribution;\n sellThrough: number | null;\n}\n\nexport interface ChannelReport {\n assignmentVersion: number;\n includesBookedValue: boolean;\n /** @deprecated Use `includesBookedValue`. */\n includesRevenue: boolean;\n methodology: { allocation: string; attribution: string; sellThrough: string };\n rows: ChannelReportRow[];\n totals: {\n allocated: number;\n free: number;\n held: number;\n booked: number;\n blocked: number;\n sold: number;\n bookedValue: number | null;\n /** @deprecated Use `bookedValue`. */\n revenue: number | null;\n };\n}\n\nexport interface ChannelReportResult {\n report: ChannelReport;\n event: { key: string; name: string; seatTotal?: number; currency?: string };\n}\n\nexport interface ChannelReportLinkRecord {\n id: string;\n channelId: string;\n label: string | null;\n includesBookedValue: boolean;\n /** @deprecated Use `includesBookedValue`. */\n includesRevenue: boolean;\n expiresAt: number;\n state: 'active' | 'revoked';\n status: 'active' | 'revoked' | 'expired';\n views: number;\n lastViewedAt: number | null;\n createdAt: number;\n createdBy: string | null;\n revokedAt: number | null;\n}\n\nexport interface ChannelReportLinkReveal {\n link: ChannelReportLinkRecord;\n url: string;\n capability: string;\n revealedOnce: true;\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\ntype UnknownRecord = Record<string, unknown>;\n\nfunction record(value: unknown): UnknownRecord {\n return value && typeof value === 'object' ? value as UnknownRecord : {};\n}\n\nfunction finite(primary: unknown, legacy: unknown, fallback = 0): number {\n if (typeof primary === 'number' && Number.isFinite(primary)) return primary;\n if (typeof legacy === 'number' && Number.isFinite(legacy)) return legacy;\n return fallback;\n}\n\nfunction nullableFinite(primary: unknown, legacy: unknown): number | null {\n // `null` is an authorization-safe canonical answer (for example, a channel\n // viewer may see counts but not configured booked value). Fall back only\n // when the canonical field is genuinely absent during a rolling upgrade.\n if (primary === null) return null;\n if (typeof primary === 'number' && Number.isFinite(primary)) return primary;\n if (primary !== undefined) return null;\n if (typeof legacy === 'number' && Number.isFinite(legacy)) return legacy;\n return null;\n}\n\nfunction normalizeSection(value: unknown): ControlRoomSectionMetric {\n const row = record(value);\n const bookedValue = finite(row.bookedValue, row.bookedRevenue);\n return { ...row, bookedValue, bookedRevenue: bookedValue } as unknown as ControlRoomSectionMetric;\n}\n\nfunction normalizeReportResult(value: unknown): ReportResult {\n const source = record(value);\n const report = record(source.report);\n const byCategory = Array.isArray(report.byCategory)\n ? report.byCategory.map((value) => {\n const row = record(value);\n const bookedValue = finite(row.bookedValue, row.bookedRevenue);\n return { ...row, bookedValue, bookedRevenue: bookedValue } as unknown as ReportCategoryRow;\n })\n : [];\n const bySection = Array.isArray(report.bySection)\n ? report.bySection.map(normalizeSection)\n : undefined;\n return {\n ...source,\n report: { ...report, byCategory, ...(bySection ? { bySection } : {}) },\n } as unknown as ReportResult;\n}\n\nfunction normalizeControlRoomSnapshot(value: unknown): ControlRoomSnapshot {\n const source = record(value);\n const canonical = record(source.bookedValue);\n const legacy = record(source.revenue);\n const selected = Object.keys(canonical).length ? canonical : legacy;\n const bySectionSource = Array.isArray(canonical.bySection)\n ? canonical.bySection\n : Array.isArray(legacy.bySection) ? legacy.bySection : [];\n const bookedValue = {\n ...selected,\n gross: finite(canonical.gross, legacy.gross),\n bySection: bySectionSource.map(normalizeSection),\n };\n const velocity = record(source.velocity);\n const velocityRows = Array.isArray(velocity.bySection)\n ? velocity.bySection.map((value) => {\n const row = record(value);\n const rowValue = finite(row.bookedValue, row.grossRevenue);\n return { ...row, bookedValue: rowValue, grossRevenue: rowValue };\n })\n : [];\n return {\n ...source,\n bookedValue,\n revenue: bookedValue,\n velocity: { ...velocity, bySection: velocityRows },\n } as unknown as ControlRoomSnapshot;\n}\n\nfunction normalizeChannelReportResult(value: unknown): ChannelReportResult {\n const source = record(value);\n const report = record(source.report);\n const includesBookedValue = typeof report.includesBookedValue === 'boolean'\n ? report.includesBookedValue\n : report.includesRevenue === true;\n const rows = Array.isArray(report.rows) ? report.rows.map((value) => {\n const row = record(value);\n const attribution = record(row.attribution);\n const bookedValue = nullableFinite(attribution.bookedValue, attribution.revenue);\n return {\n ...row,\n attribution: { ...attribution, bookedValue, revenue: bookedValue },\n };\n }) : [];\n const totals = record(report.totals);\n const totalBookedValue = nullableFinite(totals.bookedValue, totals.revenue);\n return {\n ...source,\n report: {\n ...report,\n includesBookedValue,\n includesRevenue: includesBookedValue,\n rows,\n totals: { ...totals, bookedValue: totalBookedValue, revenue: totalBookedValue },\n },\n } as unknown as ChannelReportResult;\n}\n\nfunction normalizeChannelReportLink(value: unknown): ChannelReportLinkRecord {\n const link = record(value);\n const includesBookedValue = typeof link.includesBookedValue === 'boolean'\n ? link.includesBookedValue\n : link.includesRevenue === true;\n return {\n ...link,\n includesBookedValue,\n includesRevenue: includesBookedValue,\n } as unknown as ChannelReportLinkRecord;\n}\n\n/**\n * Bound to one apiBase + bearer token. Browser callers use an event-scoped\n * `mse_…` grant. A tenant `sk_…` remains accepted only so trusted server code\n * can use this low-level client; SeatManager rejects it before construction.\n * Rebuild (or `setToken`) when a 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 async authBlob(path: string): Promise<Blob> {\n const res = await fetch(`${this.base}${path}`, {\n method: 'GET',\n headers: { Authorization: `Bearer ${this.token}` },\n credentials: 'omit',\n });\n if (!res.ok) await parse<never>(res);\n return res.blob();\n }\n\n // ---- realtime read ----\n\n /** Event-pinned organizer geometry. A manage token is never sent to `/pub`. */\n chart(key: string): Promise<PubChartResult> {\n return this.auth(`/v1/events/${encodeURIComponent(key)}/chart`);\n }\n\n /** Authenticated bytes for an Event-scoped organizer chart asset. */\n asset(key: string, asset: string): Promise<Blob> {\n if (!/^[a-zA-Z0-9._-]+$/.test(asset)) {\n return Promise.reject(new ManageApiError(404, 'not_found', 'not_found'));\n }\n return this.authBlob(\n `/v1/events/${encodeURIComponent(key)}/assets/${encodeURIComponent(asset)}`,\n );\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 // ---- Platform inventory booking history (token) ----\n\n /** Inventory lifecycle by stable integrator bookingRef. Absent on Managed. */\n bookings(key: string, query: InventoryBookingsQuery = {}): Promise<InventoryBookingsPage> {\n const params = new URLSearchParams();\n if (query.q) params.set('q', query.q);\n if (query.state) params.set('state', query.state);\n if (query.cursor) params.set('cursor', query.cursor);\n if (query.limit != null) params.set('limit', String(query.limit));\n const qs = params.toString();\n return this.auth(`/v1/events/${encodeURIComponent(key)}/bookings${qs ? `?${qs}` : ''}`);\n }\n\n /** Exact configured-value snapshot plus book/replay/cancellation audit. */\n booking(key: string, bookingRef: string): Promise<InventoryBookingDetail> {\n return this.auth(\n `/v1/events/${encodeURIComponent(key)}/bookings/${encodeURIComponent(bookingRef)}`,\n );\n }\n\n /** Alias matching the server SDK vocabulary. */\n listBookings(key: string, query: InventoryBookingsQuery = {}): Promise<InventoryBookingsPage> {\n return this.bookings(key, query);\n }\n\n /** Alias matching the server SDK vocabulary. */\n retrieveBooking(key: string, bookingRef: string): Promise<InventoryBookingDetail> {\n return this.booking(key, bookingRef);\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<unknown>(`/v1/events/${encodeURIComponent(key)}/report`).then(normalizeReportResult);\n }\n\n controlRoom(key: string, windowMinutes = 15): Promise<ControlRoomSnapshot> {\n return this.auth<unknown>(\n `/v1/events/${encodeURIComponent(key)}/control-room?window=${windowMinutes}`,\n ).then(normalizeControlRoomSnapshot);\n }\n\n /** Allocation beside immutable booking-time channel attribution. */\n channelReport(key: string): Promise<ChannelReportResult> {\n return this.auth<unknown>(\n `/v1/events/${encodeURIComponent(key)}/channels/report`,\n ).then(normalizeChannelReportResult);\n }\n\n createChannelReportLink(\n key: string,\n channelId: string,\n input: {\n label?: string;\n includesBookedValue?: boolean;\n /** @deprecated Use `includesBookedValue`. */\n includesRevenue?: boolean;\n expiresAt?: number;\n } = {},\n ): Promise<ChannelReportLinkReveal> {\n return this.auth<unknown>(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/report-links`,\n { method: 'POST', body: input },\n ).then((value) => {\n const reveal = record(value);\n return { ...reveal, link: normalizeChannelReportLink(reveal.link) } as unknown as ChannelReportLinkReveal;\n });\n }\n\n channelReportLinks(key: string, channelId: string): Promise<{ links: ChannelReportLinkRecord[] }> {\n return this.auth<unknown>(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}/report-links`,\n ).then((value) => {\n const result = record(value);\n return {\n links: Array.isArray(result.links) ? result.links.map(normalizeChannelReportLink) : [],\n };\n });\n }\n\n revokeChannelReportLink(\n key: string,\n channelId: string,\n linkId: string,\n ): Promise<{ ok: true; link: ChannelReportLinkRecord }> {\n return this.auth<unknown>(\n `/v1/events/${encodeURIComponent(key)}/channels/${encodeURIComponent(channelId)}`\n + `/report-links/${encodeURIComponent(linkId)}`,\n { method: 'DELETE' },\n ).then((value) => {\n const result = record(value);\n return { ...result, link: normalizeChannelReportLink(result.link) } as unknown as {\n ok: true; link: ChannelReportLinkRecord;\n };\n });\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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\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 &amp; 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":";AA6BO,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;AAG5B,SAAS,kBAAkB,IAAwC;AACxE,SAAO,MAAM,QAAQ,OAAO,MAAM,OAAO;AAC3C;AAwGO,IAAM,iBAAiB;AAAA,EAC5B;AAAA,EAAW;AAAA,EAAW;AAAA,EAAW;AAAA,EAAW;AAAA,EAC5C;AAAA,EAAW;AAAA,EAAW;AAAA,EAAW;AAAA,EAAW;AAC9C;AAGO,IAAM,uBAAuB;AAEpC,IAAM,UAAU;AAWT,SAAS,aAAa,KAAgC,UAA0B;AACrF,QAAM,QAAQ,OAAO,IAAI,KAAK;AAC9B,QAAM,SAAS,SAAS,KAAK,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,KAAK;AACtD,UAAQ,UAAU,UAAU,YAAY,EAAE,MAAM,GAAG,CAAC;AACtD;AAOO,SAAS,cACd,MACA,OACmC;AACnC,QAAM,OAAO,IAAI,IAAI,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC,EAAE,OAAO,OAAO,CAAC;A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