@seatlayer/js 0.108.0 → 0.109.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -1,10 +1,10 @@
1
- import{s as Le,t as Te}from"./chunk-X7FRGMS2.js";import{A as Wt,B as Ut,C as Gt,D as Yt,E as Zt,F as Xt,G as Jt,H as Qt,I as es,J as ts,K as ss,L as is,M as os,N as ns,O as as,P as ls,R as rs,a as k,b as F,c as O,d as z,e as G,f as Oe,g as le,h as D,i as K,j as Ie,k as B,l as Y,m as j,n as $,o as re,p as Fe,q as ze,r as Ft,s as zt,t as Dt,u as jt,v as qt,w as Nt,x as Vt,y as Kt,z as _t}from"./chunk-CNLSM36T.js";import{a as Re,b as C,c as U,e as Pe,f as ce}from"./chunk-HHV7F37Y.js";import{a as Ce,b as Me,c as ne,d as Ee,e as Ae,f as ae,g as P,h as A,i as Be,j as $e,k as He,l as M,m as g}from"./chunk-T57HSGPG.js";import{d as oe,f as Se}from"./chunk-UBFNMA7U.js";import"./chunk-OSZ7DOEH.js";var je={held:["clock","#d99a0b","in a cart"],booked:["bolt","#22a06b","booked"],expired:["x","#94a3b8","expired"],released:["x","#94a3b8","left a cart"],cancelled:["undo","#d64545","booking cancelled"],blocked:["ban","#d64545","blocked"],unblocked:["check","#64748b","back on sale"],available:["check","#22a06b","free again"],reserved:["bookmark","#c026d3","reserved"],unreserved:["check","#64748b","back on sale"]};function qe(r){return je[r]?.[2]??r}function De(r,e=[],t){let s=new Map,i=[];for(let p of r){let m=t?.(p);m?s.set(m,(s.get(m)??0)+1):i.push(p)}let o=[...s].map(([p,m])=>m>1?`${p} \xD7 ${m.toLocaleString()}`:p),n=e.length===1&&!s.has(e[0])?e[0]:"",a=i.map(p=>n&&(p.startsWith(`${n} `)||p.startsWith(`${n}-`))?p.slice(n.length+1):p),l=p=>{let m=p.lastIndexOf("-");return m>0?[p.slice(0,m),p.slice(m+1)]:[p,""]},[c]=l(a[0]??""),d=a.map(p=>l(p)).filter(([p,m])=>p===c&&/^\d+$/.test(m)).map(([,p])=>Number(p)),u=a.length>2&&d.length===a.length&&d.every((p,m)=>m===0||p===d[m-1]+1)?`${a[0]} to ${a[a.length-1]}`:a.length>3?`${a.slice(0,2).join(", ")} and ${a.length-2} more`:a.join(", ");return[n||(e.length>1?`${e.length} sections`:""),[u,...o].filter(Boolean).join(", ")].filter(Boolean).join(" \xB7 ")}var cs={held:"In a cart",booked:"Booked",expired:"Hold expired",released:"Hold released",cancelled:"Booking cancelled",blocked:"Blocked",unblocked:"Back on sale",available:"Available again",reserved:"Reserved",unreserved:"Back on sale"},Z=class{constructor(e,t,s,i=()=>{}){this.host=e;this.locate=s;this.name=i;this.items=[];this.shown=new Set;this.paused=!1;this.limit=100;this.signature="unrendered";this.abort=new AbortController;this.verbs=null;e.innerHTML='<button class="slm-new-activity" hidden></button><div class="slm-activity-list" role="region" aria-label="Recent activity" tabindex="0"></div><button class="slm-more-activity" hidden>Show more activity</button>',this.list=e.querySelector(".slm-activity-list"),this.newer=e.querySelector(".slm-new-activity"),this.more=e.querySelector(".slm-more-activity");let o={signal:this.abort.signal},n=()=>{this.paused=!1,this.signature="unrendered",this.list.scrollTop=0,this.render()};this.list.addEventListener("scroll",()=>{this.list.scrollTop>24&&(this.paused=!0)},o),this.list.addEventListener("focusin",()=>{this.paused=!0},o),this.list.addEventListener("toggle",a=>{a.target.open&&(this.paused=!0)},{...o,capture:!0}),this.newer.addEventListener("click",n,o),this.more.addEventListener("click",()=>{this.limit=200,this.signature="unrendered",this.render(!0)},o)}update(e){this.items=e,this.render()}setFilter(e){String(e)!==String(this.verbs)&&(this.verbs=e,this.signature="unrendered",this.render(!0))}render(e=!1){let t=this.verbs?this.items.filter(n=>this.verbs.includes(n.verb)):this.items,s=t.filter(n=>!this.shown.has(n.id)).length;if(this.newer.hidden=!this.paused,this.newer.textContent=s?`${s} new activit${s===1?"y":"ies"} \xB7 Back to live`:"Reading earlier activity \xB7 Back to live",this.paused&&!e)return;let i=t.slice(0,this.limit),o=i.map(n=>`${n.id}:${n.verb}`).join("|");if(o!==this.signature){if(this.signature=o,this.shown=new Set(t.map(n=>n.id)),this.list.replaceChildren(),!i.length){let n=document.createElement("p");n.className="slm-activity-empty",this.items.length?n.textContent=this.verbs?.includes("booked")?"No sales in the feed yet.":this.verbs?"No carts in the feed yet.":"No activity matches these filters.":n.innerHTML=`${k("bolt","#22a06b",36)}<b>Quiet so far</b>Bookings, carts and changes appear here as they happen.`,this.list.append(n)}for(let n of i){let a=document.createElement("article");a.className="slm-activity-entry",a.dataset.status=n.status;let l=document.createElement("button");l.type="button",l.className="slm-activity-row";let c=`${cs[n.verb]??n.verb} \xB7 ${n.count} seat${n.count===1?"":"s"} \xB7 ${n.sectionLabels?.join(", ")||"Event inventory"} \xB7 ${De(n.labels,[],this.name)} \xB7 ${C(n.at,{dateStyle:"medium",timeStyle:"short"})}`;l.title=`${c} \u2014 click to show seats on the map`,l.setAttribute("aria-label",`Show seats on map: ${c}`),l.addEventListener("click",()=>this.locate(n.id));let d=document.createElement("time");d.dateTime=new Date(n.at).toISOString(),d.textContent=C(n.at,{hour:"2-digit",minute:"2-digit"},[]);let[h,u,b]=je[n.verb]??["info","#64748b",n.verb],p=document.createElement("span");p.className="slm-activity-text";let m=document.createElement("b");m.textContent=`${n.count.toLocaleString()} ${n.count===1?"seat":"seats"} ${b}`;let v=document.createElement("span");v.className="slm-activity-seats",v.textContent=De(n.labels,n.sectionLabels,this.name),p.append(m,v),l.insertAdjacentHTML("afterbegin",k(h,u,24)),l.append(p,d),a.append(l),this.list.append(a)}this.more.hidden=t.length<=this.limit}}destroy(){this.abort.abort()}};var ds=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent)?"\u2318Z":"Ctrl Z",X=class{constructor(e){this.host=e;this.moving=!1;this.tool="select";this.space=!1;this.abort=new AbortController;let t=document.createElement("div");t.className="slm-navigation";let s=(n,a,l,c,d)=>`<button type="button" data-nav="${n}" aria-label="${l}" aria-pressed="${n==="select"}" title="${c}" aria-keyshortcuts="${d}">${O(a,"currentColor",18)}</button>`;t.innerHTML=`<div class="slm-navigation-tools" role="group" aria-label="Map tools">
1
+ import{t as Le,u as Te}from"./chunk-U2Z2AGRX.js";import{A as Wt,B as Ut,C as Gt,D as Yt,E as Zt,F as Xt,G as Jt,H as Qt,I as es,J as ts,K as ss,L as is,M as os,N as ns,O as as,P as ls,R as rs,a as x,b as F,c as I,d as z,e as G,f as Ie,g as le,h as D,i as K,j as Oe,k as B,l as Y,m as j,n as $,o as re,p as Fe,q as ze,r as Ft,s as zt,t as Dt,u as jt,v as qt,w as Nt,x as Vt,y as Kt,z as _t}from"./chunk-CNLSM36T.js";import{a as Re,b as C,c as U,e as Pe,f as ce}from"./chunk-HHV7F37Y.js";import{a as Ce,b as Me,c as ne,d as Ee,e as Ae,f as ae,g as P,h as A,i as Be,j as $e,k as He,l as M,m as g}from"./chunk-T57HSGPG.js";import{d as oe,f as Se}from"./chunk-UBFNMA7U.js";import"./chunk-OSZ7DOEH.js";var je={held:["clock","#d99a0b","in a cart"],booked:["bolt","#22a06b","booked"],expired:["x","#94a3b8","expired"],released:["x","#94a3b8","left a cart"],cancelled:["undo","#d64545","booking cancelled"],blocked:["ban","#d64545","blocked"],unblocked:["check","#64748b","back on sale"],available:["check","#22a06b","free again"],reserved:["bookmark","#c026d3","reserved"],unreserved:["check","#64748b","back on sale"]};function qe(r){return je[r]?.[2]??r}function De(r,e=[],t){let s=new Map,i=[];for(let p of r){let m=t?.(p);m?s.set(m,(s.get(m)??0)+1):i.push(p)}let o=[...s].map(([p,m])=>m>1?`${p} \xD7 ${m.toLocaleString()}`:p),n=e.length===1&&!s.has(e[0])?e[0]:"",a=i.map(p=>n&&(p.startsWith(`${n} `)||p.startsWith(`${n}-`))?p.slice(n.length+1):p),l=p=>{let m=p.lastIndexOf("-");return m>0?[p.slice(0,m),p.slice(m+1)]:[p,""]},[c]=l(a[0]??""),d=a.map(p=>l(p)).filter(([p,m])=>p===c&&/^\d+$/.test(m)).map(([,p])=>Number(p)),u=a.length>2&&d.length===a.length&&d.every((p,m)=>m===0||p===d[m-1]+1)?`${a[0]} to ${a[a.length-1]}`:a.length>3?`${a.slice(0,2).join(", ")} and ${a.length-2} more`:a.join(", ");return[n||(e.length>1?`${e.length} sections`:""),[u,...o].filter(Boolean).join(", ")].filter(Boolean).join(" \xB7 ")}var cs={held:"In a cart",booked:"Booked",expired:"Hold expired",released:"Hold released",cancelled:"Booking cancelled",blocked:"Blocked",unblocked:"Back on sale",available:"Available again",reserved:"Reserved",unreserved:"Back on sale"},Z=class{constructor(e,t,s,i=()=>{}){this.host=e;this.locate=s;this.name=i;this.items=[];this.shown=new Set;this.paused=!1;this.limit=100;this.signature="unrendered";this.abort=new AbortController;this.verbs=null;e.innerHTML='<button class="slm-new-activity" hidden></button><div class="slm-activity-list" role="region" aria-label="Recent activity" tabindex="0"></div><button class="slm-more-activity" hidden>Show more activity</button>',this.list=e.querySelector(".slm-activity-list"),this.newer=e.querySelector(".slm-new-activity"),this.more=e.querySelector(".slm-more-activity");let o={signal:this.abort.signal},n=()=>{this.paused=!1,this.signature="unrendered",this.list.scrollTop=0,this.render()};this.list.addEventListener("scroll",()=>{this.list.scrollTop>24&&(this.paused=!0)},o),this.list.addEventListener("focusin",()=>{this.paused=!0},o),this.list.addEventListener("toggle",a=>{a.target.open&&(this.paused=!0)},{...o,capture:!0}),this.newer.addEventListener("click",n,o),this.more.addEventListener("click",()=>{this.limit=200,this.signature="unrendered",this.render(!0)},o)}update(e){this.items=e,this.render()}setFilter(e){String(e)!==String(this.verbs)&&(this.verbs=e,this.signature="unrendered",this.render(!0))}render(e=!1){let t=this.verbs?this.items.filter(n=>this.verbs.includes(n.verb)):this.items,s=t.filter(n=>!this.shown.has(n.id)).length;if(this.newer.hidden=!this.paused,this.newer.textContent=s?`${s} new activit${s===1?"y":"ies"} \xB7 Back to live`:"Reading earlier activity \xB7 Back to live",this.paused&&!e)return;let i=t.slice(0,this.limit),o=i.map(n=>`${n.id}:${n.verb}`).join("|");if(o!==this.signature){if(this.signature=o,this.shown=new Set(t.map(n=>n.id)),this.list.replaceChildren(),!i.length){let n=document.createElement("p");n.className="slm-activity-empty",this.items.length?n.textContent=this.verbs?.includes("booked")?"No sales in the feed yet.":this.verbs?"No carts in the feed yet.":"No activity matches these filters.":n.innerHTML=`${x("bolt","#22a06b",36)}<b>Quiet so far</b>Bookings, carts and changes appear here as they happen.`,this.list.append(n)}for(let n of i){let a=document.createElement("article");a.className="slm-activity-entry",a.dataset.status=n.status;let l=document.createElement("button");l.type="button",l.className="slm-activity-row";let c=`${cs[n.verb]??n.verb} \xB7 ${n.count} seat${n.count===1?"":"s"} \xB7 ${n.sectionLabels?.join(", ")||"Event inventory"} \xB7 ${De(n.labels,[],this.name)} \xB7 ${C(n.at,{dateStyle:"medium",timeStyle:"short"})}`;l.title=`${c} \u2014 click to show seats on the map`,l.setAttribute("aria-label",`Show seats on map: ${c}`),l.addEventListener("click",()=>this.locate(n.id));let d=document.createElement("time");d.dateTime=new Date(n.at).toISOString(),d.textContent=C(n.at,{hour:"2-digit",minute:"2-digit"},[]);let[h,u,b]=je[n.verb]??["info","#64748b",n.verb],p=document.createElement("span");p.className="slm-activity-text";let m=document.createElement("b");m.textContent=`${n.count.toLocaleString()} ${n.count===1?"seat":"seats"} ${b}`;let v=document.createElement("span");v.className="slm-activity-seats",v.textContent=De(n.labels,n.sectionLabels,this.name),p.append(m,v),l.insertAdjacentHTML("afterbegin",x(h,u,24)),l.append(p,d),a.append(l),this.list.append(a)}this.more.hidden=t.length<=this.limit}}destroy(){this.abort.abort()}};var ds=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent)?"\u2318Z":"Ctrl Z",X=class{constructor(e){this.host=e;this.moving=!1;this.tool="select";this.space=!1;this.abort=new AbortController;let t=document.createElement("div");t.className="slm-navigation";let s=(n,a,l,c,d)=>`<button type="button" data-nav="${n}" aria-label="${l}" aria-pressed="${n==="select"}" title="${c}" aria-keyshortcuts="${d}">${I(a,"currentColor",18)}</button>`;t.innerHTML=`<div class="slm-navigation-tools" role="group" aria-label="Map tools">
2
2
  ${s("select","cursor","Select","Select \xB7 click a seat or drag a box (V)","V")}
3
3
  ${s("lasso","lasso","Lasso","Lasso \xB7 draw a loop around seats (L)","L")}
4
4
  ${s("move","hand","Move the map","Move the map \xB7 or hold Space","Space")}
5
5
  <span class="slm-navigation-rule" aria-hidden="true"></span>
6
- <button type="button" data-nav="undo" aria-label="Undo selection" title="Undo the last change to the selection (${ds}) \xB7 redo with Shift" aria-keyshortcuts="Meta+Z Control+Z" disabled>${O("undo","currentColor",18)}</button>
7
- </div>`,e.map.after(t),this.bar=t,this.undo=t.querySelector('[data-nav="undo"]'),this.location=document.createElement("div"),this.location.className="slm-location",this.location.hidden=!0,this.location.setAttribute("role","status"),e.map.after(this.location);let i={signal:this.abort.signal};t.addEventListener("click",n=>{let a=n.target.closest("[data-nav]")?.dataset.nav;a==="undo"?e.stepSelection(-1):a&&this.choose(a)},i),e.map.addEventListener("pointerdown",()=>{this.location.hidden=!0,e.pauseFollow(),e.root.focus({preventScroll:!0})},{...i,capture:!0}),e.root.querySelector(".slm-rail")?.addEventListener("pointerdown",()=>e.pauseFollow(),{...i,capture:!0}),e.map.addEventListener("wheel",()=>{this.location.hidden=!0,e.pauseFollow()},{...i,passive:!0,capture:!0}),e.root.addEventListener("keydown",n=>{n.target?.closest('input,textarea,select,button,[contenteditable="true"]')||n.code!=="Space"||n.ctrlKey||n.metaKey||n.altKey||(n.preventDefault(),this.space||(this.space=!0,e.pauseFollow(),e.setMoving(!0)))},i);let o=()=>{this.space&&(this.space=!1,e.setMoving(this.moving))};window.addEventListener("keyup",n=>{n.code==="Space"&&o()},i),window.addEventListener("blur",o,i),window.addEventListener("resize",()=>{this.location.hidden=!0},i),e.root.querySelector(".slm-mapchrome")?.addEventListener("click",()=>{this.location.hidden=!0},i),e.root.addEventListener("focusout",n=>{e.root.contains(n.relatedTarget)||o()},i)}choose(e){this.tool=e,this.moving=e==="move",this.host.pauseFollow(),e!=="move"&&this.host.setShape(e==="lasso"?"lasso":"box"),this.host.setMoving(this.moving||this.space),this.bar.querySelectorAll("[aria-pressed]").forEach(t=>t.setAttribute("aria-pressed",String(t.dataset.nav===e)))}resetTool(){this.tool==="move"&&(this.tool="select",this.moving=!1,this.host.setShape("box"),this.host.setMoving(this.space),this.bar.querySelectorAll("[aria-pressed]").forEach(e=>e.setAttribute("aria-pressed",String(e.dataset.nav==="select"))))}update(e){this.bar.querySelector(".slm-navigation-tools").hidden=!e,!e&&this.tool==="move"&&this.choose("select")}historyChanged(e,t){this.undo.disabled=!e}destroy(){this.abort.abort(),this.bar.remove(),this.location.remove()}};function de(r,e,t){let s=r.findIndex(o=>o.label===e),i=r.findIndex(o=>o.label===t);return s<0||i<0?[]:r.slice(Math.min(s,i),Math.max(s,i)+1).map(o=>o.label)}function hs(r,e){let t=1/0;for(let s=0;s<e.length;s++){let i=e[s],o=e[(s+1)%e.length],n=o.x-i.x,a=o.y-i.y,l=n||a?Math.max(0,Math.min(1,((r.x-i.x)*n+(r.y-i.y)*a)/(n*n+a*a))):0;t=Math.min(t,Math.hypot(r.x-(i.x+l*n),r.y-(i.y+l*a)))}return t}function Ne(r,e,t,s=6){let i=null;for(let o of e){if(o.state==="inactive"||o.outline.length<3)continue;let n=hs(r,o.outline.map(t));n<=s&&(!i||n<i.d)&&(i={id:o.id,d:n})}return i?.id??null}import{SeatmapRenderer as Ss,applyOrganizerSeatGlyph as Ls,clearOrganizerSeatGlyph as Et,isOrganizerGlyphPainted as Ts,expandChart as Cs,allObjects as Ms,computeSections as Rs,floorsOf as Es,gaAreasOf as At,gaUnitLabels as As,UNGROUPED_ID as S}from"@seatlayer/core";var ps=/^[a-zA-Z0-9._-]+$/;function us(r){let e;try{e=new URL(r,"https://seatlayer.invalid")}catch{return null}if(e.search||e.hash)return null;let t=/^\/v1\/events\/([^/]+)\/assets\/([^/]+)$/.exec(e.pathname);if(!t)return null;try{let s=decodeURIComponent(t[1]),i=decodeURIComponent(t[2]);return!s||!ps.test(i)?null:{eventKey:s,asset:i}}catch{return null}}function ms(r){try{return/^\/v1\/events\/[^/]+\/assets(?:\/|$)/.test(new URL(r,"https://seatlayer.invalid").pathname)}catch{return!1}}var J=class{constructor(e,t){this.eventKey=e;this.load=t;this.pending=new Map;this.created=new Set;this.disposed=!1}resolve(e){let t=us(e);if(!t)return Promise.resolve(ms(e)?null:e);if(t.eventKey!==this.eventKey||this.disposed)return Promise.resolve(null);let s=`${t.eventKey}/${t.asset}`,i=this.pending.get(s);if(i)return i;let o=this.load(t.eventKey,t.asset).then(n=>{let a=URL.createObjectURL(n);return this.disposed?(URL.revokeObjectURL(a),null):(this.created.add(a),a)}).catch(n=>{throw this.pending.delete(s),n});return this.pending.set(s,o),o}async prepareRendererChart(e){let t=async o=>{if(!o?.url)return;let n=await this.resolve(o.url);if(!n)throw new Error("organizer_event_asset_scope_mismatch");o.url=n},s=async o=>{for(let n of o){if(n.type!=="decorImage")continue;let a=n,l=await this.resolve(a.href);if(!l)throw new Error("organizer_event_asset_scope_mismatch");a.href=l}},i=async o=>{await t(o.backgroundImage),await s(o.objects)};await i(e);for(let o of e.floors??[])await i(o);return e}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.created)URL.revokeObjectURL(e);this.created.clear(),this.pending.clear()}}};function he(){return'<div class="slm-opening" data-ref="opening" role="status"><span class="slm-opening-spin" aria-hidden="true"></span><b>Opening the Control room\u2026</b><span>Loading the seats and their live state</span></div>'}function pe(){let r=(e,t=12)=>`<span class="slm-skel" style="width:${e}px;height:${t}px"></span>`;return`<div class="slm-railskel" aria-hidden="true">${r(140,16)}${r(280)}${r(240)}<span class="slm-skel" style="width:100%;height:120px;border-radius:14px"></span>${r(200)}${r(280)}${r(260)}</div>`}var bs={offline:{glyph:"alert",hue:"#d64545",title:"The Control room couldn't open",body:"We could not reach SeatLayer. Check the connection; nothing about the event has changed.",action:"Try again"},access:{glyph:"lock",hue:"#3b82f6",title:"You don't have access to this room",body:'Your role can see the event but not its Control room. Ask an admin for "View the Control room".',action:null},missing:{glyph:"alert",hue:"#d64545",title:"This event is not here",body:"It may have been removed, or the link points at another event. Nothing was changed.",action:null},signedout:{glyph:"user",hue:"#0ea5a5",title:"You were signed out",body:"For your security the session ended. Sign in again and the room comes back as it was.",action:"Sign in again"}};function Ve(r,e){let t=bs[r],s=r==="access"&&e?.trim()?t.body.replace("Your role can",`Your role in ${e.trim()} can`):t.body;return`<div class="slm-roomcard" data-ref="roomcard" data-kind="${r}"><div role="alertdialog" aria-labelledby="slm-roomcard-title">${k(t.glyph,t.hue,44)}<b id="slm-roomcard-title">${t.title}</b><p>${g(s)}</p>${t.action?`<button type="button" class="slm-btn" data-roomcard-act>${t.action}</button>`:""}</div></div>`}function Ke(r){return r==="live"?"":r==="paused"?'<div class="slm-connbanner warn" role="status"><span>Live updates paused. Reconnecting\u2026 The map and numbers may be up to 30 s old. Anything you change is kept.</span></div>':`<div class="slm-connbanner err" role="alert"><span>Couldn't reconnect for 2 minutes. The map may be out of date; changes can't be saved until it's back.</span><button type="button" data-conn-retry>Try now</button></div>`}function _e(r,e,t){return`<b>${g(r)}${e?` \xB7 ${g(e)}`:""}</b>`+(t?`<span class="slm-fsline-counts">${t.booked.toLocaleString()} sold \xB7 ${t.held.toLocaleString()} in carts \xB7 ${t.free.toLocaleString()} free</span>`:"")+'<span class="slm-fsline-gap"></span><button type="button" class="slm-btn ghost" data-fs-exit>Exit full screen</button><kbd>esc</kbd>'}function We(r){return`<div class="slm-nosales">${k("bolt","#22a06b",40)}<b>No sales yet</b><p>The first booking shows here the moment it happens.</p></div>`+(r?`<p class="slm-nosales-viewers">${r.toLocaleString()} ${r===1?"person is":"people are"} looking at the seat map right now.</p>`:"")}var Ue=`
6
+ <button type="button" data-nav="undo" aria-label="Undo selection" title="Undo the last change to the selection (${ds}) \xB7 redo with Shift" aria-keyshortcuts="Meta+Z Control+Z" disabled>${I("undo","currentColor",18)}</button>
7
+ </div>`,e.map.after(t),this.bar=t,this.undo=t.querySelector('[data-nav="undo"]'),this.location=document.createElement("div"),this.location.className="slm-location",this.location.hidden=!0,this.location.setAttribute("role","status"),e.map.after(this.location);let i={signal:this.abort.signal};t.addEventListener("click",n=>{let a=n.target.closest("[data-nav]")?.dataset.nav;a==="undo"?e.stepSelection(-1):a&&this.choose(a)},i),e.map.addEventListener("pointerdown",()=>{this.location.hidden=!0,e.pauseFollow(),e.root.focus({preventScroll:!0})},{...i,capture:!0}),e.root.querySelector(".slm-rail")?.addEventListener("pointerdown",()=>e.pauseFollow(),{...i,capture:!0}),e.map.addEventListener("wheel",()=>{this.location.hidden=!0,e.pauseFollow()},{...i,passive:!0,capture:!0}),e.root.addEventListener("keydown",n=>{n.target?.closest('input,textarea,select,button,[contenteditable="true"]')||n.code!=="Space"||n.ctrlKey||n.metaKey||n.altKey||(n.preventDefault(),this.space||(this.space=!0,e.pauseFollow(),e.setMoving(!0)))},i);let o=()=>{this.space&&(this.space=!1,e.setMoving(this.moving))};window.addEventListener("keyup",n=>{n.code==="Space"&&o()},i),window.addEventListener("blur",o,i),window.addEventListener("resize",()=>{this.location.hidden=!0},i),e.root.querySelector(".slm-mapchrome")?.addEventListener("click",()=>{this.location.hidden=!0},i),e.root.addEventListener("focusout",n=>{e.root.contains(n.relatedTarget)||o()},i)}choose(e){this.tool=e,this.moving=e==="move",this.host.pauseFollow(),e!=="move"&&this.host.setShape(e==="lasso"?"lasso":"box"),this.host.setMoving(this.moving||this.space),this.bar.querySelectorAll("[aria-pressed]").forEach(t=>t.setAttribute("aria-pressed",String(t.dataset.nav===e)))}resetTool(){this.tool==="move"&&(this.tool="select",this.moving=!1,this.host.setShape("box"),this.host.setMoving(this.space),this.bar.querySelectorAll("[aria-pressed]").forEach(e=>e.setAttribute("aria-pressed",String(e.dataset.nav==="select"))))}update(e){this.bar.querySelector(".slm-navigation-tools").hidden=!e,!e&&this.tool==="move"&&this.choose("select")}historyChanged(e,t){this.undo.disabled=!e}destroy(){this.abort.abort(),this.bar.remove(),this.location.remove()}};function de(r,e,t){let s=r.findIndex(o=>o.label===e),i=r.findIndex(o=>o.label===t);return s<0||i<0?[]:r.slice(Math.min(s,i),Math.max(s,i)+1).map(o=>o.label)}function hs(r,e){let t=1/0;for(let s=0;s<e.length;s++){let i=e[s],o=e[(s+1)%e.length],n=o.x-i.x,a=o.y-i.y,l=n||a?Math.max(0,Math.min(1,((r.x-i.x)*n+(r.y-i.y)*a)/(n*n+a*a))):0;t=Math.min(t,Math.hypot(r.x-(i.x+l*n),r.y-(i.y+l*a)))}return t}function Ne(r,e,t,s=6){let i=null;for(let o of e){if(o.state==="inactive"||o.outline.length<3)continue;let n=hs(r,o.outline.map(t));n<=s&&(!i||n<i.d)&&(i={id:o.id,d:n})}return i?.id??null}import{SeatmapRenderer as Ss,applyOrganizerSeatGlyph as Ls,clearOrganizerSeatGlyph as Et,isOrganizerGlyphPainted as Ts,expandChart as Cs,allObjects as Ms,computeSections as Rs,floorsOf as Es,gaAreasOf as At,gaUnitLabels as As,UNGROUPED_ID as S}from"@seatlayer/core";var ps=/^[a-zA-Z0-9._-]+$/;function us(r){let e;try{e=new URL(r,"https://seatlayer.invalid")}catch{return null}if(e.search||e.hash)return null;let t=/^\/v1\/events\/([^/]+)\/assets\/([^/]+)$/.exec(e.pathname);if(!t)return null;try{let s=decodeURIComponent(t[1]),i=decodeURIComponent(t[2]);return!s||!ps.test(i)?null:{eventKey:s,asset:i}}catch{return null}}function ms(r){try{return/^\/v1\/events\/[^/]+\/assets(?:\/|$)/.test(new URL(r,"https://seatlayer.invalid").pathname)}catch{return!1}}var J=class{constructor(e,t){this.eventKey=e;this.load=t;this.pending=new Map;this.created=new Set;this.disposed=!1}resolve(e){let t=us(e);if(!t)return Promise.resolve(ms(e)?null:e);if(t.eventKey!==this.eventKey||this.disposed)return Promise.resolve(null);let s=`${t.eventKey}/${t.asset}`,i=this.pending.get(s);if(i)return i;let o=this.load(t.eventKey,t.asset).then(n=>{let a=URL.createObjectURL(n);return this.disposed?(URL.revokeObjectURL(a),null):(this.created.add(a),a)}).catch(n=>{throw this.pending.delete(s),n});return this.pending.set(s,o),o}async prepareRendererChart(e){let t=async o=>{if(!o?.url)return;let n=await this.resolve(o.url);if(!n)throw new Error("organizer_event_asset_scope_mismatch");o.url=n},s=async o=>{for(let n of o){if(n.type!=="decorImage")continue;let a=n,l=await this.resolve(a.href);if(!l)throw new Error("organizer_event_asset_scope_mismatch");a.href=l}},i=async o=>{await t(o.backgroundImage),await s(o.objects)};await i(e);for(let o of e.floors??[])await i(o);return e}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.created)URL.revokeObjectURL(e);this.created.clear(),this.pending.clear()}}};function he(){return'<div class="slm-opening" data-ref="opening" role="status"><span class="slm-opening-spin" aria-hidden="true"></span><b>Opening the Control room\u2026</b><span>Loading the seats and their live state</span></div>'}function pe(){let r=(e,t=12)=>`<span class="slm-skel" style="width:${e}px;height:${t}px"></span>`;return`<div class="slm-railskel" aria-hidden="true">${r(140,16)}${r(280)}${r(240)}<span class="slm-skel" style="width:100%;height:120px;border-radius:14px"></span>${r(200)}${r(280)}${r(260)}</div>`}var bs={offline:{glyph:"alert",hue:"#d64545",title:"The Control room couldn't open",body:"We could not reach SeatLayer. Check the connection; nothing about the event has changed.",action:"Try again"},access:{glyph:"lock",hue:"#3b82f6",title:"You don't have access to this room",body:'Your role can see the event but not its Control room. Ask an admin for "View the Control room".',action:null},missing:{glyph:"alert",hue:"#d64545",title:"This event is not here",body:"It may have been removed, or the link points at another event. Nothing was changed.",action:null},signedout:{glyph:"user",hue:"#0ea5a5",title:"You were signed out",body:"For your security the session ended. Sign in again and the room comes back as it was.",action:"Sign in again"}};function Ve(r,e){let t=bs[r],s=r==="access"&&e?.trim()?t.body.replace("Your role can",`Your role in ${e.trim()} can`):t.body;return`<div class="slm-roomcard" data-ref="roomcard" data-kind="${r}"><div role="alertdialog" aria-labelledby="slm-roomcard-title">${x(t.glyph,t.hue,44)}<b id="slm-roomcard-title">${t.title}</b><p>${g(s)}</p>${t.action?`<button type="button" class="slm-btn" data-roomcard-act>${t.action}</button>`:""}</div></div>`}function Ke(r){return r==="live"?"":r==="paused"?'<div class="slm-connbanner warn" role="status"><span>Live updates paused. Reconnecting\u2026 The map and numbers may be up to 30 s old. Anything you change is kept.</span></div>':`<div class="slm-connbanner err" role="alert"><span>Couldn't reconnect for 2 minutes. The map may be out of date; changes can't be saved until it's back.</span><button type="button" data-conn-retry>Try now</button></div>`}function _e(r,e,t){return`<b>${g(r)}${e?` \xB7 ${g(e)}`:""}</b>`+(t?`<span class="slm-fsline-counts">${t.booked.toLocaleString()} sold \xB7 ${t.held.toLocaleString()} in carts \xB7 ${t.free.toLocaleString()} free</span>`:"")+'<span class="slm-fsline-gap"></span><button type="button" class="slm-btn ghost" data-fs-exit>Exit full screen</button><kbd>esc</kbd>'}function We(r){return`<div class="slm-nosales">${x("bolt","#22a06b",40)}<b>No sales yet</b><p>The first booking shows here the moment it happens.</p></div>`+(r?`<p class="slm-nosales-viewers">${r.toLocaleString()} ${r===1?"person is":"people are"} looking at the seat map right now.</p>`:"")}var Ue=`
8
8
  .slm-opening{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;background:var(--slm-bg);text-align:center}
9
9
  .slm-opening b{margin-top:10px;font-size:14px;font-weight:600;color:var(--slm-text)}.slm-opening span:last-child{font-size:12.5px;color:var(--slm-muted)}
10
10
  .slm-opening-spin{width:32px;height:32px;border-radius:50%;border:3px solid var(--slm-line);border-top-color:var(--slm-accent);animation:slm-open-spin calc(var(--slm-mo-slow) * 3) linear infinite}
@@ -38,7 +38,7 @@ import{s as Le,t as Te}from"./chunk-X7FRGMS2.js";import{A as Wt,B as Ut,C as Gt,
38
38
  .slm-nosales b{display:block;margin-top:10px;font-size:14px}
39
39
  .slm-nosales p{margin:6px 0 0;font-size:12.5px;line-height:1.5;color:var(--slm-muted)}
40
40
  .slm-nosales-viewers{margin:14px 0 0;font-size:12.5px;line-height:1.5;color:var(--slm-muted)}
41
- `;var _={view:{glyph:"eye",hue:"#3b82f6"},inspect:{glyph:"eye",hue:"#3b82f6"},block:{glyph:"ban",hue:"#d64545"},reserve:{glyph:"bookmark",hue:"#c026d3"},sections:{glyph:"layers",hue:"#0ea5a5"},categories:{glyph:"tag",hue:"#8b5cf6"},tables:{glyph:"table",hue:"#65a30d"},channels:{glyph:"route",hue:"#ea7a1e"},select:{glyph:"cursor",hue:"#d99a0b"},filterSections:{glyph:"search",hue:"#4c6fff"}},fs='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>',Q=r=>_[r]??_.view;function Ge(r,e,t){let s=`<button type="button" class="slm-taskpick-btn" data-taskpick aria-haspopup="menu" aria-expanded="${t}">${k(Q(r.mode).glyph,Q(r.mode).hue,26)}<span>${g(r.label)}</span>${fs}</button>`;if(!t)return s;let i=e.map(o=>o.tools.map(n=>`<button type="button" role="menuitemradio" aria-checked="${n.mode===r.mode}" data-taskpick-mode="${g(n.mode)}">${k(Q(n.mode).glyph,Q(n.mode).hue,26)}<span>${g(n.label)}</span></button>`).join("")).join("<hr>");return`${s}<div class="slm-taskmenu" role="menu" aria-label="Tasks">${i}</div>`}var Ye=`
41
+ `;var _={view:{glyph:"eye",hue:"#3b82f6"},inspect:{glyph:"eye",hue:"#3b82f6"},block:{glyph:"ban",hue:"#d64545"},reserve:{glyph:"bookmark",hue:"#c026d3"},sections:{glyph:"layers",hue:"#0ea5a5"},categories:{glyph:"tag",hue:"#8b5cf6"},tables:{glyph:"table",hue:"#65a30d"},channels:{glyph:"route",hue:"#ea7a1e"},select:{glyph:"cursor",hue:"#d99a0b"},filterSections:{glyph:"search",hue:"#4c6fff"}},fs='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>',Q=r=>_[r]??_.view;function Ge(r,e,t){let s=`<button type="button" class="slm-taskpick-btn" data-taskpick aria-haspopup="menu" aria-expanded="${t}">${x(Q(r.mode).glyph,Q(r.mode).hue,26)}<span>${g(r.label)}</span>${fs}</button>`;if(!t)return s;let i=e.map(o=>o.tools.map(n=>`<button type="button" role="menuitemradio" aria-checked="${n.mode===r.mode}" data-taskpick-mode="${g(n.mode)}">${x(Q(n.mode).glyph,Q(n.mode).hue,26)}<span>${g(n.label)}</span></button>`).join("")).join("<hr>");return`${s}<div class="slm-taskmenu" role="menu" aria-label="Tasks">${i}</div>`}var Ye=`
42
42
  .slm-taskpick{display:none;position:relative}
43
43
  .slm .slm-taskpick-btn{display:inline-flex;align-items:center;gap:8px;height:44px;padding:0 12px 0 8px;border-radius:10px;border:1px solid var(--slm-line);
44
44
  background:var(--slm-surface);color:var(--slm-text);font:inherit;font-size:13.5px;font-weight:600;white-space:nowrap;cursor:pointer}
@@ -602,8 +602,8 @@ ${Ue}${Ye}`;function Qe(){if(typeof document>"u"||document.getElementById(Ze))re
602
602
  <button type="button" class="slm-zoombtn slm-zoombtn-venue" data-ref="zfit" aria-label="Show the whole venue" title="Show the whole venue"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/></svg></button>
603
603
  </div>
604
604
  <div class="slm-minimap-mount" data-ref="minimap"></div>
605
- </div>`}function nt(r,e){r.crumb&&(r.crumb.textContent=e.crumb,r.crumb.hidden=!e.crumbShown);let t=(s,i)=>{s&&(s.disabled=!i,s.setAttribute("aria-disabled",String(!i)))};t(r.zin,e.zoomInEnabled),t(r.zout,e.zoomOutEnabled),t(r.zfit,e.venueEnabled)}var ue={plenty:{min:.5,color:"#1f9d6b",label:"Plenty left",detail:"over half"},tight:{min:.15,color:"#6cc39c",label:"Filling up",detail:"under half"},gone:{min:0,color:"#b9e2cf",label:"Nearly gone",detail:"under 15%"}},me=[{key:"status",label:"Status",hint:"What a buyer can buy right now",dots:["#1f9d6b","#f4b740","#9ca3af"]},{key:"type",label:"Ticket type",hint:"Which ticket type each seat sells as",dots:["#bc800b","#e8456b","#2f9d46","#5b7bff"]},{key:"price",label:"Price",hint:"What each seat costs, darker costs more",dots:["#bfd3ff","#5f88ee","#1f43a8"]},{key:"channel",label:"Channel",hint:"Who can sell each seat",dots:["#c9d0dc","#e8782a","#7c5cff"]}],I={free:"#1f9d6b",held:"#f4b740",sold:"#9ca3af",blocked:"#ffffff"};function ys(r,e){let t=e>0?r/e:0;return t>=ue.plenty.min?"plenty":t>=ue.tight.min?"tight":"gone"}function xs(r,e,t,s=Date.now()){return r?.mode==="closed"||t?"Closed":r?.mode==="timed"&&r.revealAt&&r.revealAt>s?`Hidden until ${ct(r.revealAt,s)}`:r?.mode==="threshold"&&e?`Hidden until ${r.thresholdPct??0}% sold`:r?.mode==="hidden"||e?"Hidden":null}function ct(r,e){let t=C(r,{hour:"numeric",minute:U(r).minute?"2-digit":void 0}),s=(r-e)/864e5;return s<1&&U(r).day===U(e).day?t:s<6?`${C(r,{weekday:"short"})} ${t}`:C(r,{day:"numeric",month:"short"})}function dt(r,e){let t=r.state==="sold-out"?e.allBlocked==="reserved"?"All reserved":e.allBlocked?"All blocked":"Sold out":xs(e.rule,e.hiddenNow,e.closedNow),s=t==="All blocked"||t==="All reserved"?I.blocked:t==="Closed"||t==="Sold out"||e.colourBy==="channel"?null:e.colourBy==="type"||e.colourBy==="price"?e.typeTint??null:ue[ys(r.free,r.total)].color,i=e.rule,o=Date.now(),n=i?.mode==="timed"&&i.revealAt&&i.revealAt>o?` \xB7 opens ${ct(i.revealAt,o)}`:"",a=t==="Sold out"?"SOLD OUT":t==="All blocked"?"BLOCKED":t==="All reserved"?"RESERVED":t==="Closed"||n?`CLOSED${n}`:"";return a?{tint:s,stateWord:t,caption:a,solid:t==="Sold out",hatch:s===I.blocked}:{tint:s,stateWord:t}}var ks='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><circle cx="8.5" cy="11" r="1"/><circle cx="12" cy="7.5" r="1"/><circle cx="15.5" cy="11" r="1"/></svg>';function ht(){let r=me.map(e=>`<button type="button" role="option" data-colour-by="${e.key}" aria-selected="false"><em>${e.dots.map(t=>`<i style="background:${t}"></i>`).join("")}</em><span><b>${e.label}</b>${e.hint}</span></button>`).join("");return`<div class="slm-blocklegend" data-ref="blocklegend" role="group" aria-label="Map colours"><button type="button" class="slm-colourby" data-ref="colourby" aria-haspopup="listbox" aria-expanded="false">${ks}<span>Colour by</span> <b data-ref="colourname">Status</b><i aria-hidden="true">\u25BE</i></button><span class="slm-legend-items" data-ref="legenditems"></span><div class="slm-colourmenu" role="listbox" aria-label="Colour by" hidden>${r}<p>Each task remembers its own choice. <button type="button" class="slm-howlink" data-how="colours">How colours work \u203A</button></p></div></div>`}var at={free:"buyers can pick them now",held:"in buyers\u2019 carts right now",booked:"booked by buyers",reserved:"kept aside under a name",blocked:"off sale for this event",shown:"shown from the page around the room"};function lt(r){let e=r.shown;return e?[...rt(r),{label:e.name,color:"transparent",seat:!0,reserved:!0,count:e.count,key:"shown"}]:rt(r)}function rt(r){let e=r.seats,t=r.counts,s={label:e?"Sold":"Sold out",color:I.sold,seat:e,count:e?t?.booked:void 0,...e?{key:"booked"}:{}},i=t?.reserved??0,o=i?[{label:"Reserved",color:"transparent",seat:!0,reserved:!0,count:i,key:"reserved"}]:[],n={label:"Blocked",color:I.blocked,seat:!0,blocked:!0,count:t?t.blocked-i:void 0,key:"blocked"};if(r.colourBy==="status")return[{label:"Free",color:I.free,seat:!0,count:t?.free,key:"free"},{label:"In a cart",color:I.held,seat:!0,count:t?.held,key:"held"},{label:"Sold",color:I.sold,seat:!0,count:t?.booked,key:"booked"},...o,...!t||(n.count??0)>0||r.lit==="blocked"?[n]:[]];let a=e?[{label:"In a cart",color:I.held,seat:!0,count:t?.held,key:"held"}]:[];return[...(r.colourBy==="channel"?r.channels??[]:r.types).map(c=>{let d=c.key;return{label:c.label,color:c.color,seat:e,count:c.free,soldOut:c.free===0,...e&&d?{key:d.startsWith("price:")?d:`type:${d}`}:{}}}),...a,s,...e?o:[]]}function pt(r,e){let t=me.find(n=>n.key===e.colourBy)??me[0],s=r.querySelector('[data-ref="colourname"]');s&&(s.textContent=t.label),r.querySelectorAll("[data-colour-by]").forEach(n=>{let a=n.dataset.colourBy===e.colourBy;n.setAttribute("aria-selected",String(a)),n.classList.toggle("on",a),n.dataset.colourBy==="channel"&&(n.disabled=!e.channelAvailable,n.title=e.channelAvailable?"":"Open the Channels tool to colour by channel")});let i=r.querySelector('[data-ref="legenditems"]');if(!i)return;i.replaceChildren(...lt(e).map(n=>{let a=document.createElement(n.key?"button":"span"),l=null;if(n.key){let d=e.lit===n.key,h=at[n.key],u=n.count===void 0?"":`${n.count.toLocaleString()} ${h?n.label.toLowerCase():"free"}`,b=`${u?" \xB7 ":""}${h??`seats that ${n.key.startsWith("price:")?"cost":"sell as"} ${n.label}`}.
606
- Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:"button",className:"slm-legendchip"}),a.dataset.legend=n.key,a.setAttribute("aria-description",u+b),l=document.createElement("span"),l.className="tip",l.setAttribute("aria-hidden","true"),l.append(Object.assign(document.createElement("b"),{textContent:u}),b),a.setAttribute("aria-pressed",String(d))}let c=document.createElement("i");if(c.style.background=n.color,n.seat&&c.classList.add("seat"),n.blocked&&c.classList.add("blocked"),n.reserved&&c.classList.add("reserved"),a.append(c,document.createTextNode(n.label)),n.count!==void 0){let d=document.createElement("b");d.textContent=n.count<0?"no seats yet":n.soldOut?"sold out":n.count.toLocaleString(),a.append(d)}return n.key&&e.lit===n.key&&a.insertAdjacentHTML("beforeend",'<em aria-hidden="true">\xD7</em>'),l&&a.append(l),a})),(e.colourBy==="type"||e.colourBy==="price")&&i.insertAdjacentHTML("afterbegin","<small>Free</small>");let o=lt(e).find(n=>n.key&&n.key===e.lit);if(o){let n=document.createElement("span");n.className="slm-litnote",n.setAttribute("role","status"),n.textContent=e.picked!=null?`\u21E7 click selected all ${e.picked.toLocaleString()} ${at[o.key]?o.label.toLowerCase():o.label} seats`:`Lighting up ${o.label}${o.count!==void 0?` \xB7 ${o.count.toLocaleString()}`:""} \xB7 Esc or \xD7 to clear`,i.append(n)}}var ut="#c026d3";function mt(r){let e=this;e._sceneFunc(r);let t=e.attrs.reservedRadius||1,s=e.getStage(),i=Math.abs((s?s.scaleX():1)*(e.scaleX()||1))||1;if(t*1.2*i<6)return;let o=t*.34,n=-t*.44,a=t*.44;r.save(),r.setAttr("strokeStyle",ut),r.setAttr("lineWidth",Math.max(t*.16,.75)),r.beginPath(),r.arc(0,0,t*.9,0,Math.PI*2,!1),r.stroke(),r.setAttr("fillStyle",ut),r.beginPath(),r.moveTo(-o,n),r.lineTo(o,n),r.lineTo(o,a),r.lineTo(0,a-o*.9),r.lineTo(-o,a),r.closePath(),r.fill(),r.restore()}function ee(r){return r.attrs.sceneFunc===mt}function be(r){ee(r)&&r.setAttr("sceneFunc",void 0)}function bt(r,e){r.attrs.reservedRadius=e>0?e:1,ee(r)||r.setAttr("sceneFunc",mt)}var ft=r=>r.attrs?.seatId;var gt=[{key:"seatLabels",label:"Seat labels",letter:"S",hint:"Seat numbers where the zoom can carry them"},{key:"rowLabels",label:"Row labels",letter:"R",hint:"Row letters beside each row"},{key:"momentum",label:"Booking momentum",letter:"M",hint:"Warm the sections booking fastest in the selected window"}],vt="seatlayer.controlRoom.mapView",yt="seatlayer.controlRoom.colourBy";function xt(r){return r==="categories"?"type":r==="channels"?"channel":"status"}function kt(r=se()){try{let e=JSON.parse(r?.getItem(yt)??"{}"),t={};for(let[s,i]of Object.entries(e??{}))(i==="status"||i==="type"||i==="price"||i==="channel")&&(t[s]=i);return t}catch{return{}}}function wt(r,e=se()){try{e?.setItem(yt,JSON.stringify(r))}catch{}}function te(){return{seatLabels:!0,rowLabels:!0,categoryColours:!1,channelColours:!0,momentum:!1}}function St(r){return r==="g"?"categoryColours":r==="h"?"channelColours":gt.find(t=>t.letter.toLowerCase()===r)?.key??null}function Lt(r=se()){let e=te();if(!r)return e;try{let t=r.getItem(vt);if(!t)return e;let s=JSON.parse(t),i={...e};for(let o of Object.keys(e))typeof s[o]=="boolean"&&(i[o]=s[o]);return i}catch{return e}}function Tt(r,e=se()){if(e)try{e.setItem(vt,JSON.stringify(r))}catch{}}function se(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Ct(r,e){e.renderer?.setLabelLayers?.({seatLabels:r.seatLabels,rowLabels:r.rowLabels}),e.renderer?.setCategoryColours?.(r.categoryColours),e.channelsOverlay(r.channelColours)}function Mt(){return`
605
+ </div>`}function nt(r,e){r.crumb&&(r.crumb.textContent=e.crumb,r.crumb.hidden=!e.crumbShown);let t=(s,i)=>{s&&(s.disabled=!i,s.setAttribute("aria-disabled",String(!i)))};t(r.zin,e.zoomInEnabled),t(r.zout,e.zoomOutEnabled),t(r.zfit,e.venueEnabled)}var ue={plenty:{min:.5,color:"#1f9d6b",label:"Plenty left",detail:"over half"},tight:{min:.15,color:"#6cc39c",label:"Filling up",detail:"under half"},gone:{min:0,color:"#b9e2cf",label:"Nearly gone",detail:"under 15%"}},me=[{key:"status",label:"Status",hint:"What a buyer can buy right now",dots:["#1f9d6b","#f4b740","#9ca3af"]},{key:"type",label:"Ticket type",hint:"Which ticket type each seat sells as",dots:["#bc800b","#e8456b","#2f9d46","#5b7bff"]},{key:"price",label:"Price",hint:"What each seat costs, darker costs more",dots:["#bfd3ff","#5f88ee","#1f43a8"]},{key:"channel",label:"Channel",hint:"Who can sell each seat",dots:["#c9d0dc","#e8782a","#7c5cff"]}],O={free:"#1f9d6b",held:"#f4b740",sold:"#9ca3af",blocked:"#ffffff"};function ys(r,e){let t=e>0?r/e:0;return t>=ue.plenty.min?"plenty":t>=ue.tight.min?"tight":"gone"}function ks(r,e,t,s=Date.now()){return r?.mode==="closed"||t?"Closed":r?.mode==="timed"&&r.revealAt&&r.revealAt>s?`Hidden until ${ct(r.revealAt,s)}`:r?.mode==="threshold"&&e?`Hidden until ${r.thresholdPct??0}% sold`:r?.mode==="hidden"||e?"Hidden":null}function ct(r,e){let t=C(r,{hour:"numeric",minute:U(r).minute?"2-digit":void 0}),s=(r-e)/864e5;return s<1&&U(r).day===U(e).day?t:s<6?`${C(r,{weekday:"short"})} ${t}`:C(r,{day:"numeric",month:"short"})}function dt(r,e){let t=r.state==="sold-out"?e.allBlocked==="reserved"?"All reserved":e.allBlocked?"All blocked":"Sold out":ks(e.rule,e.hiddenNow,e.closedNow),s=t==="All blocked"||t==="All reserved"?O.blocked:t==="Closed"||t==="Sold out"||e.colourBy==="channel"?null:e.colourBy==="type"||e.colourBy==="price"?e.typeTint??null:ue[ys(r.free,r.total)].color,i=e.rule,o=Date.now(),n=i?.mode==="timed"&&i.revealAt&&i.revealAt>o?` \xB7 opens ${ct(i.revealAt,o)}`:"",a=t==="Sold out"?"SOLD OUT":t==="All blocked"?"BLOCKED":t==="All reserved"?"RESERVED":t==="Closed"||n?`CLOSED${n}`:"";return a?{tint:s,stateWord:t,caption:a,solid:t==="Sold out",hatch:s===O.blocked}:{tint:s,stateWord:t}}var xs='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><circle cx="8.5" cy="11" r="1"/><circle cx="12" cy="7.5" r="1"/><circle cx="15.5" cy="11" r="1"/></svg>';function ht(){let r=me.map(e=>`<button type="button" role="option" data-colour-by="${e.key}" aria-selected="false"><em>${e.dots.map(t=>`<i style="background:${t}"></i>`).join("")}</em><span><b>${e.label}</b>${e.hint}</span></button>`).join("");return`<div class="slm-blocklegend" data-ref="blocklegend" role="group" aria-label="Map colours"><button type="button" class="slm-colourby" data-ref="colourby" aria-haspopup="listbox" aria-expanded="false">${xs}<span>Colour by</span> <b data-ref="colourname">Status</b><i aria-hidden="true">\u25BE</i></button><span class="slm-legend-items" data-ref="legenditems"></span><div class="slm-colourmenu" role="listbox" aria-label="Colour by" hidden>${r}<p>Each task remembers its own choice. <button type="button" class="slm-howlink" data-how="colours">How colours work \u203A</button></p></div></div>`}var at={free:"buyers can pick them now",held:"in buyers\u2019 carts right now",booked:"booked by buyers",reserved:"kept aside under a name",blocked:"off sale for this event",shown:"shown from the page around the room"};function lt(r){let e=r.shown;return e?[...rt(r),{label:e.name,color:"transparent",seat:!0,reserved:!0,count:e.count,key:"shown"}]:rt(r)}function rt(r){let e=r.seats,t=r.counts,s={label:e?"Sold":"Sold out",color:O.sold,seat:e,count:e?t?.booked:void 0,...e?{key:"booked"}:{}},i=t?.reserved??0,o=i?[{label:"Reserved",color:"transparent",seat:!0,reserved:!0,count:i,key:"reserved"}]:[],n={label:"Blocked",color:O.blocked,seat:!0,blocked:!0,count:t?t.blocked-i:void 0,key:"blocked"};if(r.colourBy==="status")return[{label:"Free",color:O.free,seat:!0,count:t?.free,key:"free"},{label:"In a cart",color:O.held,seat:!0,count:t?.held,key:"held"},{label:"Sold",color:O.sold,seat:!0,count:t?.booked,key:"booked"},...o,...!t||(n.count??0)>0||r.lit==="blocked"?[n]:[]];let a=e?[{label:"In a cart",color:O.held,seat:!0,count:t?.held,key:"held"}]:[];return[...(r.colourBy==="channel"?r.channels??[]:r.types).map(c=>{let d=c.key;return{label:c.label,color:c.color,seat:e,count:c.free,soldOut:c.free===0,...e&&d?{key:d.startsWith("price:")?d:`type:${d}`}:{}}}),...a,s,...e?o:[]]}function pt(r,e){let t=me.find(n=>n.key===e.colourBy)??me[0],s=r.querySelector('[data-ref="colourname"]');s&&(s.textContent=t.label),r.querySelectorAll("[data-colour-by]").forEach(n=>{let a=n.dataset.colourBy===e.colourBy;n.setAttribute("aria-selected",String(a)),n.classList.toggle("on",a),n.dataset.colourBy==="channel"&&(n.disabled=!e.channelAvailable,n.title=e.channelAvailable?"":"Open the Channels tool to colour by channel")});let i=r.querySelector('[data-ref="legenditems"]');if(!i)return;i.replaceChildren(...lt(e).map(n=>{let a=document.createElement(n.key?"button":"span"),l=null;if(n.key){let d=e.lit===n.key,h=at[n.key],u=n.count===void 0?"":`${n.count.toLocaleString()} ${h?n.label.toLowerCase():"free"}`,b=`${u?" \xB7 ":""}${h??`seats that ${n.key.startsWith("price:")?"cost":"sell as"} ${n.label}`}.
606
+ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:"button",className:"slm-legendchip"}),a.dataset.legend=n.key,a.setAttribute("aria-description",u+b),l=document.createElement("span"),l.className="tip",l.setAttribute("aria-hidden","true"),l.append(Object.assign(document.createElement("b"),{textContent:u}),b),a.setAttribute("aria-pressed",String(d))}let c=document.createElement("i");if(c.style.background=n.color,n.seat&&c.classList.add("seat"),n.blocked&&c.classList.add("blocked"),n.reserved&&c.classList.add("reserved"),a.append(c,document.createTextNode(n.label)),n.count!==void 0){let d=document.createElement("b");d.textContent=n.count<0?"no seats yet":n.soldOut?"sold out":n.count.toLocaleString(),a.append(d)}return n.key&&e.lit===n.key&&a.insertAdjacentHTML("beforeend",'<em aria-hidden="true">\xD7</em>'),l&&a.append(l),a})),(e.colourBy==="type"||e.colourBy==="price")&&i.insertAdjacentHTML("afterbegin","<small>Free</small>");let o=lt(e).find(n=>n.key&&n.key===e.lit);if(o){let n=document.createElement("span");n.className="slm-litnote",n.setAttribute("role","status"),n.textContent=e.picked!=null?`\u21E7 click selected all ${e.picked.toLocaleString()} ${at[o.key]?o.label.toLowerCase():o.label} seats`:`Lighting up ${o.label}${o.count!==void 0?` \xB7 ${o.count.toLocaleString()}`:""} \xB7 Esc or \xD7 to clear`,i.append(n)}}var ut="#c026d3";function mt(r){let e=this;e._sceneFunc(r);let t=e.attrs.reservedRadius||1,s=e.getStage(),i=Math.abs((s?s.scaleX():1)*(e.scaleX()||1))||1;if(t*1.2*i<6)return;let o=t*.34,n=-t*.44,a=t*.44;r.save(),r.setAttr("strokeStyle",ut),r.setAttr("lineWidth",Math.max(t*.16,.75)),r.beginPath(),r.arc(0,0,t*.9,0,Math.PI*2,!1),r.stroke(),r.setAttr("fillStyle",ut),r.beginPath(),r.moveTo(-o,n),r.lineTo(o,n),r.lineTo(o,a),r.lineTo(0,a-o*.9),r.lineTo(-o,a),r.closePath(),r.fill(),r.restore()}function ee(r){return r.attrs.sceneFunc===mt}function be(r){ee(r)&&r.setAttr("sceneFunc",void 0)}function bt(r,e){r.attrs.reservedRadius=e>0?e:1,ee(r)||r.setAttr("sceneFunc",mt)}var ft=r=>r.attrs?.seatId;var gt=[{key:"seatLabels",label:"Seat labels",letter:"S",hint:"Seat numbers where the zoom can carry them"},{key:"rowLabels",label:"Row labels",letter:"R",hint:"Row letters beside each row"},{key:"momentum",label:"Booking momentum",letter:"M",hint:"Warm the sections booking fastest in the selected window"}],vt="seatlayer.controlRoom.mapView",yt="seatlayer.controlRoom.colourBy";function kt(r){return r==="categories"?"type":r==="channels"?"channel":"status"}function xt(r=se()){try{let e=JSON.parse(r?.getItem(yt)??"{}"),t={};for(let[s,i]of Object.entries(e??{}))(i==="status"||i==="type"||i==="price"||i==="channel")&&(t[s]=i);return t}catch{return{}}}function wt(r,e=se()){try{e?.setItem(yt,JSON.stringify(r))}catch{}}function te(){return{seatLabels:!0,rowLabels:!0,categoryColours:!1,channelColours:!0,momentum:!1}}function St(r){return r==="g"?"categoryColours":r==="h"?"channelColours":gt.find(t=>t.letter.toLowerCase()===r)?.key??null}function Lt(r=se()){let e=te();if(!r)return e;try{let t=r.getItem(vt);if(!t)return e;let s=JSON.parse(t),i={...e};for(let o of Object.keys(e))typeof s[o]=="boolean"&&(i[o]=s[o]);return i}catch{return e}}function Tt(r,e=se()){if(e)try{e.setItem(vt,JSON.stringify(r))}catch{}}function se(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Ct(r,e){e.renderer?.setLabelLayers?.({seatLabels:r.seatLabels,rowLabels:r.rowLabels}),e.renderer?.setCategoryColours?.(r.categoryColours),e.channelsOverlay(r.channelColours)}function Mt(){return`
607
607
  <details class="slm-view" data-ref="view">
608
608
  <summary class="slm-barbtn slm-view-summary" aria-haspopup="menu" aria-label="View" title="How the map reads: labels, colours, momentum"><span class="slm-view-eye" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#3b82f6" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 12s3.5-6.5 9.5-6.5 9.5 6.5 9.5 6.5-3.5 6.5-9.5 6.5S2.5 12 2.5 12z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="slm-view-text">View</span> <span class="slm-view-caret" aria-hidden="true">\u25BE</span></summary>
609
609
  <div class="slm-view-menu" role="menu" aria-label="Map view">${gt.map(e=>`
@@ -618,16 +618,16 @@ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:
618
618
  </button>
619
619
  <div class="slm-view-note" data-ref="viewnote" hidden></div>
620
620
  </div>
621
- </details>`}function Rt(r,e,t){let s=te(),i=!1;r.querySelectorAll("[data-view]").forEach(n=>{let a=n.dataset.view,l=e[a];n.setAttribute("aria-checked",String(l)),n.classList.toggle("on",l),l!==s[a]&&(i=!0)}),r.querySelector("summary")?.classList.toggle("away",i);let o=r.querySelector('[data-ref="viewnote"]');o&&(o.hidden=!t.momentumLoading,o.textContent=t.momentumLoading?"Booking momentum: loading the first snapshot\u2026":"")}import{UNGROUPED_ID as ws}from"@seatlayer/core";function fe(r){return Object.entries(r).filter(([,e])=>e.mode==="closed").map(([e])=>e)}function ge(r){let e=r.sectionsBase;if(!e)return{rows:[],hiddenSections:0,closedSections:0};let t=r.doc?.zones??[],s=new Map,i=[];for(let c of e.sections)if(c.zone&&t.some(d=>d.id===c.zone)){let d=s.get(c.zone)??[];d.push(c),s.set(c.zone,d)}else i.push(c);let o=[],n=0,a=0,l=(c,d,h,u=!1,b)=>{let p=r.availabilityRules[d.id]??null,m=r.effectiveClosed.has(d.id)||u,v=r.effectiveHidden.has(d.id)||h&&!m;c==="section"&&v&&(n+=1),c==="section"&&m&&(a+=1),o.push({kind:c,id:d.id,label:d.label,seatCount:d.seatCount,seatLabels:d.seatLabels,rule:p,hidden:v,closed:m,followsZone:c==="section"&&h,...b?{zoneId:b}:{}})};for(let c of t){let d=s.get(c.id);if(!d||!d.length)continue;let h={id:c.id,label:c.label||"Zone",seatCount:d.reduce((p,m)=>p+m.seatCount,0),seatLabels:d.flatMap(p=>p.seatLabels)},u=!!r.availabilityRules[c.id],b=r.availabilityRules[c.id]?.mode==="closed";l("zone",h,!1);for(let p of d)l("section",p,u,b,c.id)}for(let c of i)l("section",c,!1);if(e.ungrouped){let c=e.ungrouped;l("section",{id:ws,label:c.label,seatCount:c.seatCount,seatLabels:c.seatLabels},!1)}return{rows:o,hiddenSections:n,closedSections:a}}var $s="https://api.seatlayer.io",ie=200,Bt=16,$t=4,Ot=[{key:"watch",label:"Watch",tools:[{mode:"view",label:"Watch",shortcut:"M",title:"See what is selling, where buyers are, and answer questions about any seat."}]},{key:"manage",label:"Manage",tools:[{mode:"reserve",label:"Reserve",shortcut:"R",title:"Keep seats aside under a name (guests, press, comps) until you release them or the time runs out."},{mode:"block",label:"Block",shortcut:"B",title:"Take seats off sale for this event, or put them back."},{mode:"categories",label:"Ticket types",shortcut:"G",title:"Change which ticket type seats sell as, for this event only."},{mode:"sections",label:"Sections",shortcut:"S",title:"Open, close or hide sections for this event, on a schedule or on demand."},{mode:"tables",label:"Tables",shortcut:"T",title:"Sell each table per chair or as one whole-table booking."},{mode:"channels",label:"Channels",shortcut:"C",title:"Allocate inventory to sales channels and share their links."}]},{key:"host",label:"Host tools",tools:[{mode:"select",label:"Select",shortcut:"X",title:"Select seats for your own back-office operation. The selection is handed to your app; nothing changes here."},{mode:"filterSections",label:"Filter",shortcut:"L",title:"Filter the map to one section for your own reporting."}]}],Hs=new Set(["select","block","reserve","categories","channels"]),Os=3;function ve(r){return r==="resale"?"booked":r==="held"||r==="booked"||r==="blocked"?r:"free"}function Is(r){let e=r?.status;return e===401||e===403}var Ht=r=>`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${r}</svg>`,ye={enter:Ht('<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/>'),exit:Ht('<path d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5"/>')},Ps=Object.fromEntries(Ot.flatMap(r=>r.tools.map(e=>[e.shortcut.toLowerCase(),e.mode]))),w=r=>`${r.toLocaleString()} ${r===1?"seat":"seats"}`,q=r=>C(r,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}),xe=class{constructor(e){this.els={};this.renderer=null;this.doc=null;this.selectObserver=null;this.seatHistoryPanel=null;this.changes=null;this.changesLoading=null;this.feedFilter="all";this.saved=null;this.savedCount=null;this.savedApplied=null;this.arrival=[];this.activityPanel=null;this.navigation=null;this.movingMap=!1;this.marqueeShape="box";this.hintUntil=0;this.socketSnapshotSeen=!1;this.monitorRefreshTimer=null;this.themeMode=null;this.colorSchemeStop=null;this.inventoryModelVersion=1;this.selectableObjectLabels=new Set;this.unavailableLabels=new Set;this.lastSelectionLabels=new Set;this.selBack=[];this.selAhead=[];this.channelsReturn=null;this.selRestoring=!1;this.selectionWasValid=null;this.initialSelectionApplied=!1;this.labelToId=new Map;this.idToLabel=new Map;this.labelToSeat=new Map;this.allIds=[];this.gaUnitLabelSet=new Set;this.tableChairIds=new Map;this.labelNames=new Map;this.status=new Map;this.counts={held:0,booked:0,blocked:0};this.modelSynced=!1;this.controlRoomSettled=!1;this.currency="USD";this.authoritativeCurrency=null;this.authoritativeGrossRevenue=0;this.revenueStatus="loading";this.revenueRequest=0;this.controlRoomSnapshot=null;this.serverBaseline=null;this.reservationsLoaded=!1;this.livePresence=null;this.liveGross=null;this.paintHandle=null;this.trendWindowMinutes=15;this.heatEnabled=!1;this.mapView=te();this.categoryChoice=null;this.lastSectionTap=null;this.press=null;this.lastPick=null;this.categoryBusy=!1;this.categoryDone=null;this.categoryFailed=!1;this.categoryUndoing=!1;this.lockedTypes=null;this.selJustSold=new Set;this.selLeft=null;this.reconcilingSel=!1;this.selWhole=!1;this.blockBusy=!1;this.panelAlert=null;this.categoryTotalsCache=null;this.rowLabelCache=null;this.colourChoices={};this.extras=null;this.reserve=null;this.alerts=null;this.sectionsPanel=null;this.tablesPanel=null;this.findBlocked=null;this.reservedBy=new Map;this.reserving=new Set;this.reservationWheres=new Map;this.reservedIds=new Set;this.reservationsTimer=null;this.blockGroups=null;this.eventStartsAt=null;this.search=null;this.searchSeatList=null;this.minimap=null;this.lastKpiValues=new Map;this.activeKpiDeltas=new Map;this.ws=null;this.reconnectTimer=null;this.pingTimer=null;this.pongTimer=null;this.attempt=0;this.closed=!1;this.connectionStatus="reconnecting";this.lastMessageAt=null;this.ready=!1;this.feed=[];this.feedTimer=null;this.toastTimer=null;this.liveEventTimer=null;this.kpiCleanupTimer=null;this.followLiveTimer=null;this.followSeatTimer=null;this.releaseAt=null;this.blockEnd="never";this.blockDone=null;this.blockFailedNow=!1;this.blockDenied=!1;this.layoutObserver=null;this.chromeClearance=-1;this.chromeClearanceWidth=-1;this.legendInset="";this.tokenExpiresAt=null;this.tokenRefreshTimer=null;this.tokenRefreshInFlight=!1;this.tokenRefreshFailures=0;this.sessionEnded=!1;this.taskGroups=[];this.taskMenuOpen=!1;this.detents=new Map;this.linkState="live";this.linkTimers=null;this.everLive=!1;this.announcedRoomState=null;this.sectionByObject=new Map;this.sectionLabelById=new Map;this.sectionsBase=null;this.filteredSectionLabel=null;this.availabilityRules={};this.effectiveHidden=new Set;this.effectiveClosed=new Set;this.blockCaptions=new Map;this.captionsOn=!1;this.lastSyncedAt=null;this.blockBrowse=!1;this.channels=null;this.chooser=null;this.chooserDialog=null;this.extrasReady=null;this.categoryDifferences=null;this.channelCaps={view:!1,manage:!1};this.categoryCanManage=!1;this.tableCanManage=!1;this.tableBookingSaving=!1;this.channelCapabilityResolution=0;this.channelsLoading=null;this.onFullscreenChange=()=>{this.paintFullscreenButton(),this.paintFullscreenLine(),this.updateContainerLayout(),this.renderer?.forceDraw()};this.onKeyDown=e=>{if((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()==="k"){e.preventDefault(),this.openSearch();return}let s=!!e.target?.closest('input,select,textarea,[contenteditable="true"]');if((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()==="z"){!s&&this.stepSelection(e.shiftKey?1:-1)&&e.preventDefault();return}if(e.metaKey||e.ctrlKey||e.altKey||s)return;let i=e.key.toLowerCase();if(/^[1-9]$/.test(i)){let a=this.taskGroups.flatMap(l=>l.tools)[Number(i)-1];a&&(this.setMode(a.mode),e.preventDefault());return}if((i==="l"||i==="v")&&!e.shiftKey&&this.isBulkSelectMode()){this.navigation?.choose(i==="l"?"lasso":"select"),e.preventDefault();return}let o=e.shiftKey?St(i):null;if(o){this.toggleMapView(o),e.preventDefault();return}if(i==="/"){e.preventDefault(),this.openSearch();return}let n=Ps[i];if(n){if(!this.toolAvailable(n))return;this.setMode(n)}else if(i==="f")this.toggleFullscreen();else if(i==="escape"){let a=this.els.view;if(a?.open)a.open=!1,a.querySelector("summary")?.focus();else if(this.litChip)this.onLegendChip(this.litChip,!1);else if(this.taskMenuOpen)this.taskMenuOpen=!1,this.paintTaskPicker(),this.els.taskpick?.querySelector("[data-taskpick]")?.focus();else if(!this.channels?.handleBack())if(this.isSheet()&&this.sheetDetent()==="full")this.setDetent("half");else if(this.getSelection().length)this.clearSelection();else return}else return;e.preventDefault()};this.onSelectAllKey=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.key.toLowerCase()!=="a"||e.target?.closest('input,select,textarea,[contenteditable="true"]')||(e.preventDefault(),e.stopPropagation(),this.isBulkSelectMode()?this.selectInView():this.mode==="select"&&this.selectAll())};this.onHowClick=e=>{let t=e.target?.closest("[data-how]")?.dataset.how;if(!t)return;let i=t==="current"?{view:"watch",reserve:"reserve",block:"block",categories:"types",sections:"sections",tables:"tables",channels:"channels"}[this.mode]??"watch":t;this.loadExtras().then(o=>{this.closed||!this.root||o.openExplainer({root:this.root,plate:k,touch:D(),guideUrl:"https://docs.seatlayer.io/platform/embedded-control-room/#operator-modes",tryIt:n=>{let a={watch:"view",reserve:"reserve",block:"block",types:"categories",sections:"sections",tables:"tables",channels:"channels"};n==="search"?this.openSearch():n==="colours"?this.root?.querySelector('[data-ref="colourby"]')?.click():a[n]&&a[n]!==this.mode&&this.toolAvailable(a[n])&&this.setMode(a[n])}},i)}).catch(o=>this.opts.onError?.(o))};this.onRailClick=e=>{let t=e.target,s=t?.closest("[data-section-focus]");if(s?.dataset.sectionFocus){this.locateSection(s.dataset.sectionFocus);return}let i=t?.closest("[data-feed-id]");i?.dataset.feedId&&this.locateActivity(i.dataset.feedId),t?.closest("[data-sel-clear]")&&this.clearSelection(),t?.closest("[data-sel-undo]")&&this.stepSelection(-1),t?.closest("[data-sel-save]")&&this.ensureSaved().then(n=>n?.openSave());let o=t?.closest("[data-sel-similar]");o&&this.openSimilar(o),t?.closest("[data-saved-list], [data-saved-open]")&&this.ensureSaved().then(n=>n?.openList())};this.priceMode=!1;this.priceShadesOn="";this.bandIndex=null;this.typeKeyBySection=null;this.typeKeyBase=null;this.legendSeats=null;this.litChip=null;this.chipPicked=null;this.shownObjects=null;this.barNeed=[0,0,0];this.sectionOptions=[];this.addByPinned=!1;ae(e.token),this.assertSelectionOptions(e.maxSelectedObjects,e.numberOfPlacesToSelect),this.opts=e,this.key=e.eventKey,this.mode=e.mode??"view",this.selectableObjectLabels=new Set(e.selectableObjects??[]),this.unavailableLabels=new Set(e.unavailableObjects??[]),this.categoryCanManage=new Set(e.capabilities??[]).has("event:categories:manage"),this.tableCanManage=new Set(e.capabilities??[]).has("event:tables:manage"),this.keepLive=e.keepLiveWhileHidden??!0,Re(e.timeZone),this.themeMode=e.themeMode??null,this.followLive=e.followLive??!1,this.currency=e.currency??"USD",this.tokenExpiresAt=e.tokenExpiresAt??null,this.api=new re(e.apiBase??$s,e.token),this.organizerAssetUrls=new J(this.key,(t,s)=>this.withAuthRetry(()=>this.api.asset(t,s))),this.host=Ae(e.container)}selectInView(){let e=this.renderer?.getVisibleWorldRect?.();if(!e)return;let t=[...this.labelToSeat.values()].filter(s=>s.x>=e.x&&s.x<=e.x+e.width&&s.y>=e.y&&s.y<=e.y+e.height);this.renderer?.selectByLabels(t.map(s=>s.label)),this.syncSelection(),this.selWhole=t.length===this.labelToSeat.size&&this.getSelection().length>0,this.selWhole&&this.syncSelection()}assertSelectionOptions(e,t){let s=i=>i===void 0||Number.isInteger(i)&&i>0;if(!s(e))throw new TypeError("maxSelectedObjects must be a positive integer");if(!s(t))throw new TypeError("numberOfPlacesToSelect must be a positive integer");if(e!==void 0&&t!==void 0&&e<t)throw new TypeError("maxSelectedObjects cannot be lower than numberOfPlacesToSelect")}async render(){return Qe(),this.buildChrome(),await this.load(),this}async load(){try{let e=await this.withAuthRetry(()=>this.api.chart(this.key));this.inventoryModelVersion=e.event.inventoryModelVersion===2?2:1,this.eventStartsAt=e.event.startsAt??null,this.doc=await this.organizerAssetUrls.prepareRendererChart(e.doc),this.authoritativeCurrency=e.event.currency??null,this.currency=this.authoritativeCurrency??this.opts.currency??this.currency,this.buildUnitUniverse(this.doc),this.buildRenderer(),this.buildSectionOptions(),this.settleMode();let[,t]=await Promise.all([this.resnapshot(),this.refreshControlRoom().catch(s=>this.opts.onError?.(s)),this.refreshAvailability()]);t?.activity?this.seedFeed(t.activity):this.api.log(this.key,{limit:24}).then(s=>{this.adoptLabelNames(s.displayLabels),this.seedFeed(s.entries)}).catch(()=>{}),this.connect(),this.startFeedClock(),this.ready=!0,await this.resolveChannelCapabilities(),this.setMode(this.mode),this.root?.querySelector('[data-ref="opening"]')?.remove(),this.applyInitialSelection(),this.scheduleTokenRefresh(),this.opts.onReady?.(),this.mountAlerts(),this.ensureSaved().then(s=>s?.refresh()),this.withExtras(()=>{}),(this.opts.focusSection||this.opts.focusSeat||this.opts.focusSeats?.length||this.opts.focusCategory||this.opts.arrivedFrom||this.opts.onOpenTrend&&this.opts.kpis!==!1)&&this.mountArrival()}catch(e){this.fail(e)}}setMode(e){e==="inspect"&&(e="view"),this.toolAvailable(e)||(e="view"),e==="channels"&&!this.channels&&this.ensureChannels();let t=e!==this.mode,s=this.mode==="channels",i=this.mode==="filterSections";this.mode=e,t&&e!=="view"&&this.setFollowLive(!1),t&&this.navigation?.resetTool(),!this.renderer&&this.doc?this.buildRenderer():this.updateRendererInteraction(),t&&(this.renderer?.clearSelection(),this.syncSelection(),this.selBack=[],this.selAhead=[],this.navigation?.historyChanged(!1,!1)),t&&e==="channels"&&(this.channelsReturn=this.mapReturnPoint()),s&&e!=="channels"&&(this.channels?.leave(),this.restoreMapReturn()),t&&(this.litChip=null,this.highlightLabels(null),this.wireBarFind()),this.paintModeTabs(),t&&this.setColourBy(this.colourChoices[e]??this.startingColourBy(e),!1);let o=!t&&(e==="tables"?this.tablesPanel:e==="sections"?this.sectionsPanel:null);o?o.update():this.paintRail(),this.applyDetent(),this.paintMapViewMenu(),this.applyMapView(),this.applySectionCanvasTreatment(),i&&e!=="filterSections"&&this.renderer?.zoomToFit(),e==="channels"&&this.channels?.enter(),e==="select"&&this.applyInitialSelection(),t&&this.opts.onModeChange?.(e)}async resolveChannelCapabilities(){let e=++this.channelCapabilityResolution,t=this.opts.capabilities,s;if(t){let i=new Set(t);s={view:i.has("event:channels:view"),manage:i.has("event:channels:view")&&i.has("event:channels:manage")}}else s={view:!1,manage:!1};if(!s.view&&!t)try{await this.api.channels(this.key),s={view:!0,manage:!1}}catch{s={view:!1,manage:!1}}if(e===this.channelCapabilityResolution){if(this.channelCaps=s,!this.channelCaps.view){this.channels?.destroy(),this.channels=null,this.mode==="channels"?this.setMode("view"):this.paintModeTabs();return}this.channels?.setCapabilities(this.channelCaps),this.paintModeTabs()}}ensureChannels(){if(this.channelsLoading)return this.channelsLoading;if(this.channels)return Promise.resolve();let e=(async()=>{try{let t=await import("./channelsMode-W5KNSQSJ.js");if(this.closed||!this.channelCaps.view||(this.channels||(et(t.CHANNELS_CSS),this.channels=new t.ChannelsMode(this.buildChannelsHost(),this.channelCaps),this.channels.onInteractionChange=()=>this.updateRendererInteraction()),this.mode!=="channels"))return;this.updateRendererInteraction(),this.paintRail(),this.channels.enter(),this.setColourBy(this.colourChoices.channels??this.startingColourBy("channels"),!1)}catch(t){if(this.closed)return;this.channelsLoading=null,this.mode==="channels"&&this.paintRail(),this.opts.onError?.(t)}})();return this.channelsLoading=e,e}buildChooserHost(){let e=s=>{let i=this.labelToSeat.get(s);return i?this.mode==="block"?this.isBlockSelectable(s):this.mode==="reserve"?this.isReserveSelectable(s):this.mode==="select"?this.canSelectObject(i):!0:!1};return{selectionLabels:()=>this.selectionLabels(),selectByLabels:s=>{this.selectByLabels(s)},clearSelection:()=>this.clearSelection(),selectSection:s=>{this.selectSection(s)},sections:()=>this.sectionOptions,sectionInfo:s=>{let i=this.filterableSections().find(n=>n.id===s),o=this.sectionTypeKeys().get(s);return{total:i?.seatCount??0,color:this.doc?.categories.find(n=>n.key===o)?.color}},labelsInSection:s=>(this.renderer?.getSelectableInSection(s)??[]).map(i=>i.label).filter(e),rows:()=>{let s=new Map((this.doc?.objects??[]).map(o=>[o.id,o])),i=new Map;for(let o of this.labelToSeat.values()){let n=s.get(o.rowId);if(!n||n.type!=="row"&&n.type!=="table")continue;let a=o.logicalRowId??o.rowId,l=this.sectionByObject.get(o.rowId)??S,c=i.get(a)??{id:a,label:n.type==="row"?n.segmentedRow?.displayLabel??n.displayLabel??n.label:n.displayLabel??n.label,sectionId:l,sectionLabel:this.sectionLabelById.get(l)??"Other seats",labels:[],all:[]};c.all.push(o.label),e(o.label)&&c.labels.push(o.label),i.set(a,c)}return[...i.values()].sort((o,n)=>o.sectionLabel.localeCompare(n.sectionLabel,void 0,{numeric:!0,sensitivity:"base"})||o.label.localeCompare(n.label,void 0,{numeric:!0,sensitivity:"base"}))},categories:()=>(this.doc?.categories??[]).map(s=>({key:s.key,label:s.label??s.key,color:s.color,total:this.categoryTotals().get(s.key)??0})),labelsInCategory:s=>[...this.labelToSeat.values()].filter(i=>i.categoryKey===s&&e(i.label)).map(i=>i.label),seats:()=>[...this.labelToSeat.values()].filter(s=>e(s.label)).map(s=>({label:s.label})),statusOf:s=>this.status.get(s)??(this.labelToSeat.has(s)?"free":void 0),sectionOfLabel:s=>{let i=this.labelToSeat.get(s);if(!i)return null;let o=this.sectionByObject.get(i.rowId)??S;return{id:o,label:this.sectionLabelById.get(o)??"Other seats"}},openDialog:(s,i)=>{let o=n=>{this.chooserDialog=n.openManagerDialog(this.root,s,i,{previous:this.chooserDialog,onClose:()=>{this.chooserDialog=null}})};this.extrasReady?o(this.extrasReady):this.withExtras(o)},closeDialog:()=>this.chooserDialog?.close(),enhanceDialog:s=>this.withExtras(i=>i.pickerKeys(s)),pickers:()=>this.extrasReady??this.loadExtras().then(s=>this.extrasReady=s),pickerFailed:s=>this.pickerFailed(s),highlight:s=>this.highlightLabels(s),...this.mode==="select"?{cap:this.selectionCap()}:{}}}wireBarFind(){let e=this.els.findbar;!e||e.dataset.wired||(e.dataset.wired="1",e.innerHTML=`<button type="button" class="slm-findtrigger" aria-keyshortcuts="Meta+K Control+K"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#4c6fff" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l4.5 4.5"/></svg><span>Seat, row or booking</span>${le()}</button>`,e.querySelector("button").addEventListener("click",()=>{this.openSearch()}))}async loadExtras(){if(!this.extras){let t=typeof __SEATLAYER_CDN__<"u"&&__SEATLAYER_CDN__?Bs("seatlayer-manager-extras.mjs"):import("./managerExtras-K2UGS5TD.js");this.extras=t.catch(s=>{throw this.extras=null,s})}let e=await this.extras;return tt(e.EXTRAS_CSS),e}withExtras(e){this.loadExtras().then(t=>{this.extrasReady=t,this.closed||e(t)},()=>{})}pickerFailed(e){this.toast("Couldn't open that list. Check the connection.","err",{label:"Try again",run:e})}async openSearch(e=""){try{let t=await this.loadExtras();if(this.closed||!this.root)return;this.search?.close(),this.search=t.openEventSearch({root:this.root,touch:D(),seats:()=>this.searchSeats(),statusOf:s=>this.status.get(s)??"free",describe:s=>{let i=this.doc?.categories.find(o=>o.key===this.labelToSeat.get(s)?.categoryKey);return i?`${i.label}${typeof i.price=="number"?` ${M(i.price,this.currency)}`:""}`:""},canSelect:()=>this.isChoosingTool(),show:s=>this.showLabels(s),select:s=>{this.selectByLabels(s)},lookupOrders:this.canReadOrders()?s=>this.api.lookupOrders(this.key,s):void 0,lookupSeats:this.canReadOrders()?s=>this.api.eventRequest(this.key,`seats/lookup?q=${encodeURIComponent(s)}`):void 0,openOrder:this.opts.onOpenOrder?s=>this.opts.onOpenOrder(s):void 0,blockReasons:()=>this.blockGroups?new Set(this.blockGroups.groups.map(s=>s.reason??"")).size:null,blockedBy:s=>{let i=s.trim().toLowerCase();return i.length<3?[]:(this.blockGroups?.groups??[]).filter(o=>o.reason&&o.reason.toLowerCase().includes(i)).map(o=>({reason:o.reason,labels:o.labels}))},saved:()=>this.saved?.rows()??null,useSaved:(s,i)=>{this.saved?.use(s,i)},reserved:()=>{!this.blockGroups&&this.toolAvailable("block")&&this.loadBlockGroups().catch(()=>{});let s=[...this.reservedBy.keys()].filter(i=>this.status.get(i)==="blocked");return{labels:s,count:new Set(s.map(i=>this.reservedBy.get(i).id)).size}},recents:{read:()=>{try{return JSON.parse(localStorage.getItem(`seatlayer.controlRoom.search.${this.key}`)??"[]")}catch{return[]}},write:s=>{try{localStorage.setItem(`seatlayer.controlRoom.search.${this.key}`,JSON.stringify(s))}catch{}}}},e)}catch(t){this.toastErr("Search could not load. Check the connection and try again."),this.opts.onError?.(t)}}canReadOrders(){return this.opts.capabilities?.includes("event:orders:read")===!0}searchSeats(){if(this.searchSeatList?.base===this.sectionsBase)return this.searchSeatList.seats;let e=new Map;for(let s of this.doc?.objects??[])s.type==="row"?e.set(s.id,s.segmentedRow?.displayLabel??s.displayLabel):s.type==="table"&&e.set(s.id,s.displayLabel);let t=[];for(let s of this.labelToSeat.values()){let i=this.sectionByObject.get(s.rowId)??S;t.push({label:s.label,sectionId:i,sectionLabel:this.sectionLabelById.get(i)??"Other seats",rowKey:s.logicalRowId??s.rowId,rowDisplay:e.get(s.rowId)})}return this.searchSeatList={base:this.sectionsBase,seats:t},t}isChoosingTool(){return this.isBulkSelectMode()||this.mode==="select"}frameLabels(e){let t=e.map(s=>this.labelToSeat.get(s)?.id).filter(s=>!!s);t.length&&(this.setFollowLive(!1),this.renderer?.focusSeats?.(t,{animate:!0}))}highlightLabels(e){if(!e){this.renderer?.setSeatHighlight?.(null);return}this.renderer?.setSeatHighlight?.(e.map(t=>this.labelToSeat.get(t)?.id).filter(t=>!!t))}toolChooser(){return this.chooserDialog?.close({restoreFocus:!1}),this.chooser=new ze(this.buildChooserHost()),this.chooser}toolSelectionBar(e,t,s,i){return Fe({count:0,noun:"selected",breakdown:`<span class="slm-selactions"><button type="button" class="slm-linkbtn" data-ref="${i}">Select all</button></span>`,clearAttr:`data-ref="${s}"`}).replace('class="slm-selnum"',`class="slm-selnum" data-ref="${e}"`).replace('class="slm-sellabel"',`class="slm-sellabel" data-ref="${t}"`)}buildChannelsHost(){return{moved:e=>this.recordChange({kind:"channel",...e}),channelsChanged:()=>{this.getColourBy()==="channel"&&this.paintColourLegend()},eventKey:this.key,api:this.api,rail:this.els.rail,pickers:()=>this.extrasReady??this.loadExtras().then(e=>this.extrasReady=e),pickerFailed:e=>this.pickerFailed(e),enhanceDialog:e=>this.withExtras(t=>t.pickerKeys(e)),mapLayer:this.root.querySelector(".slm-map"),pillLane:this.els.lane,root:this.root,seats:()=>[...this.labelToSeat.values()].map(e=>({id:e.id,label:e.label,x:e.x,y:e.y})),statusOf:e=>this.status.get(e)??(this.labelToSeat.has(e)?"free":void 0),selectionLabels:()=>this.selectionLabels(),selectByLabels:e=>{this.selectByLabels(e)},clearSelection:()=>this.clearSelection(),selectSection:e=>{this.selectSection(e)},sections:()=>this.sectionOptions,labelsInSection:e=>this.renderer?.getSelectableInSection(e).map(t=>t.label)??[],rows:()=>{let e=new Map((this.doc?.objects??[]).map(s=>[s.id,s])),t=new Map;for(let s of this.labelToSeat.values()){let i=e.get(s.rowId);if(!i||i.type!=="row"&&i.type!=="table")continue;let o=s.logicalRowId??s.rowId,n=this.sectionByObject.get(s.rowId)??S,a=t.get(o)??{id:o,label:i.type==="row"?i.segmentedRow?.displayLabel??i.displayLabel??i.label:i.displayLabel??i.label,sectionId:n,sectionLabel:this.sectionLabelById.get(n)??"Other seats",labels:[]};a.labels.push(s.label),t.set(o,a)}return[...t.values()].sort((s,i)=>s.sectionLabel.localeCompare(i.sectionLabel,void 0,{numeric:!0,sensitivity:"base"})||s.label.localeCompare(i.label,void 0,{numeric:!0,sensitivity:"base"}))},categories:()=>(this.doc?.categories??[]).map(e=>({key:e.key,label:e.label??e.key,color:e.color,price:e.price,tiers:e.tiers?.map(t=>({id:t.id,name:t.name,price:t.price}))})),labelsInCategory:e=>[...this.labelToSeat.entries()].filter(([,t])=>t.categoryKey===e).map(([t])=>t),sectionOfLabel:e=>{let t=this.labelToSeat.get(e);if(!t)return null;let s=this.sectionByObject.get(t.rowId)??S;return{id:s,label:this.sectionLabelById.get(s)??"Other seats"}},worldToScreen:e=>this.renderer?.worldToScreen(e)??null,seatPixelSize:()=>this.seatPixelSize(),isSeatDetail:()=>this.renderer?.getRung?.()==="seats",showSectionOverview:()=>{this.renderer?.clearSectionFocus(),this.renderer?.setRung?.("sections")},focusSection:e=>this.renderer?.focusSection(e),isCompact:()=>!!this.root?.classList.contains("compact"),setMapInert:e=>{this.mapHost.toggleAttribute("inert",e),this.mapHost.setAttribute("aria-hidden",String(e))},toast:(e,t)=>this.toast(e,t),onError:e=>this.opts.onError?.(e)}}seatPixelSize(){let e=this.renderer?.getVisibleWorldRect?.(),t=this.mapHost?.clientWidth??0;return!e?.width||!t?6:Math.max(3,t/e.width*18)}setHeatOverlay(e){this.heatEnabled=e,this.mapView.momentum!==e&&this.setMapView({momentum:e}),this.applyHeatOverlay(),this.paintHeatButton()}setMapView(e){let t={...this.mapView,...e};if(!Object.keys(t).some(o=>t[o]!==this.mapView[o]))return;let i=t.categoryColours!==this.mapView.categoryColours||t.channelColours!==this.mapView.channelColours;this.mapView=t,Tt(t),t.momentum!==this.heatEnabled&&this.setHeatOverlay(t.momentum),this.applyMapView(),this.paintMapViewMenu(),i&&(this.refreshBlockPaint(),this.paintMapChrome())}getColourBy(){return this.mapView.channelColours&&this.channelColoursAvailable()?"channel":this.mapView.categoryColours?this.priceMode?"price":"type":"status"}setColourBy(e,t=!0){let s=e==="full"||e==="channel"&&!this.channelColoursAvailable()?"status":e;t&&(this.colourChoices={...this.colourChoices,[this.mode]:s},wt(this.colourChoices)),this.litChip&&s!==this.getColourBy()&&(this.litChip=null,this.highlightLabels(null)),this.priceMode=s==="price",this.setMapView({categoryColours:s==="type"||s==="price",channelColours:s==="channel"}),this.applyPriceColours(),this.paintColourLegend()}startingColourBy(e){let t=this.opts.colourBy;return t&&e!=="channels"?t==="full"?"status":t:xt(e)}getMapView(){return{...this.mapView}}toggleMapView(e){if(e==="categoryColours"||e==="channelColours"){let t=e==="categoryColours"?"type":"channel";this.setColourBy(this.getColourBy()===t?"status":t);return}this.setMapView({[e]:!this.mapView[e]})}channelColoursAvailable(){return this.mode==="channels"&&this.channels!=null}applyMapView(){Ct(this.mapView,{renderer:this.renderer,channelsOverlay:e=>this.channels?.setOverlayVisible(e)}),this.applyPriceColours()}applyPriceColours(){let e=this.extrasReady;if(this.priceMode&&!e){this.withExtras(()=>{this.applyPriceColours(),this.paintColourLegend()});return}let t=this.priceMode?e.priceShades(this.typePrices(),this.root?.dataset.theme==="light"):null,s=JSON.stringify(t);!this.renderer||s===this.priceShadesOn||(this.priceShadesOn=s,this.renderer.setCategoryColourOverride?.(t),this.refreshBlockPaint())}typePrices(){let e=this.hoverPriceRanges(),t=new Map;for(let s of this.doc?.categories??[]){let i=e===null?void 0:e?.[s.key]?.min??s.price;typeof i=="number"&&t.set(s.key,i)}return t}paintMapViewMenu(){let e=this.els.view;e&&Rt(e,this.mapView,{momentumLoading:this.mapView.momentum&&!this.controlRoomSnapshot})}setFollowLive(e){let t=this.followLive!==e;this.followLive=e,e||(this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.followLiveTimer=null,this.followSeatTimer=null),this.paintFollowLiveButton(),t&&this.opts.onFollowLiveChange?.(e)}setKeepLiveWhileHidden(e){this.keepLive=e??!0,this.opts.keepLiveWhileHidden=e}setCurrency(e){this.opts.currency=e,!this.authoritativeCurrency&&(this.currency=e??"USD",this.ready&&this.recomputeTallies())}setSale(e){this.opts.sale=e,this.paintFullscreenLine(),this.paintMonitorInsights()}setTheme(e){this.opts.theme=e,this.applyThemeVars()}applyThemeVars(){if(!this.root)return;let e=oe(this.themeMode);for(let[t,s]of Object.entries(Be(this.opts.theme,e)))this.root.style.setProperty(t,s);e?this.root.dataset.theme=e:delete this.root.dataset.theme,this.applyPriceColours()}watchThemeMode(){this.colorSchemeStop?.(),this.colorSchemeStop=null,this.themeMode==="auto"&&(this.colorSchemeStop=Se(()=>{this.closed||this.repaintForThemeMode()}))}repaintForThemeMode(){this.applyThemeVars();let e=this.renderer;if(!e||!this.doc)return;let t=e.getSelection().map(o=>o.id),s=e.getCameraPose(),i=e.getFocusedSection();e.setChart(this.themedDoc()),this.repaintAll(),this.applyHeatOverlay(),t.length&&e.select(t),i&&e.focusSection(i),e.setCameraPose(s),this.updateZoomHint()}setThemeMode(e){let t=e??null;this.closed||t===this.themeMode||(this.themeMode=t,this.opts.themeMode=t??void 0,this.watchThemeMode(),this.repaintForThemeMode())}getThemeMode(){return this.themeMode}themedDoc(){let e=this.doc,t=$e(oe(this.themeMode));return t?{...e,theme:{...e.theme??{},background:t}}:e}setCapabilities(e){this.opts.capabilities=e,this.categoryCanManage=new Set(e??[]).has("event:categories:manage"),this.tableCanManage=new Set(e??[]).has("event:tables:manage"),this.mode==="categories"&&!this.toolAvailable("categories")||!this.tableCanManage&&this.mode==="tables"?this.setMode("view"):this.mode==="categories"?this.paintRail():this.paintModeTabs(),this.ready&&this.resolveChannelCapabilities()}setTokenRefresh(e){this.opts.onTokenRefresh=e,this.scheduleTokenRefresh()}setTrendWindow(e){let t=Number.isFinite(e)?Math.floor(e):15;return this.trendWindowMinutes=Math.max(5,Math.min(60,t)),this.paintTrendWindow(),this.refreshControlRoom()}async enterFullscreen(){!this.root?.requestFullscreen||this.isFullscreen()||(await this.root.requestFullscreen(),this.root.focus({preventScroll:!0}))}async exitFullscreen(){typeof document>"u"||!this.isFullscreen()||await document.exitFullscreen()}isFullscreen(){return typeof document<"u"&&document.fullscreenElement===this.root}toggleFullscreen(){(this.isFullscreen()?this.exitFullscreen():this.enterFullscreen()).catch(t=>this.opts.onError?.(t))}setToken(e,t){ae(e),this.api.setToken(e),this.opts.token=e,this.opts.tokenExpiresAt=t,this.tokenExpiresAt=t??null,this.scheduleTokenRefresh(),this.ready&&this.resolveChannelCapabilities()}scheduleTokenRefresh(){this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null;let e=this.opts.onTokenRefresh,t=this.tokenExpiresAt;if(this.closed||!e||!t||!Number.isFinite(t))return;let s=t-Date.now(),i=Math.min(12e4,Math.max(3e4,s*.2)),o=Math.max(0,s-i);this.tokenRefreshTimer=setTimeout(()=>{this.tokenRefreshTimer=null,this.rotateToken()},o)}async rotateToken(){if(!(this.closed||this.sessionEnded||this.tokenRefreshInFlight||!this.opts.onTokenRefresh)){this.tokenRefreshInFlight=!0;try{let e=await this.opts.onTokenRefresh();if(!e?.token||!Number.isFinite(e.expiresAt))throw new Error("invalid_token_refresh_result");this.tokenRefreshFailures=0,this.setToken(e.token,e.expiresAt)}catch(e){this.opts.onError?.(e),this.tokenRefreshFailures+=1,!this.closed&&(this.tokenRefreshFailures>=Os||Is(e))?this.endSession():this.closed||(this.tokenRefreshTimer=setTimeout(()=>{this.tokenRefreshTimer=null,this.rotateToken()},3e4))}finally{this.tokenRefreshInFlight=!1}}}endSession(){if(this.sessionEnded)return;this.sessionEnded=!0,this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.monitorRefreshTimer&&clearTimeout(this.monitorRefreshTimer),this.monitorRefreshTimer=null;let e=this.ws;if(this.ws=null,e){e.onclose=null;try{e.close()}catch{}}this.stopKeepalive(),this.setLive(!1),this.paintSessionEnded()}async retrySession(){if(this.closed||!this.sessionEnded)return!this.sessionEnded;if(!this.opts.onTokenRefresh)return!1;this.sessionEnded=!1,this.tokenRefreshFailures=0;let e=this.root?.querySelector('[data-ref="roomcard"]');return e?.setAttribute("data-busy","true"),await this.rotateToken(),this.sessionEnded?(e?.removeAttribute("data-busy"),!1):(e?.remove(),this.attempt=0,this.connect(),!0)}paintSessionEnded(){if(this.root?.querySelector('[data-ref="roomcard"][data-kind="signedout"]'))return;this.showRoomCard("signedout");let e=this.root?.querySelector('[data-ref="roomcard"] p'),t=this.mode==="view"?null:this.taskGroups.flatMap(i=>i.tools).find(i=>i.mode===this.mode)?.label??null,s=this.getSelection().length;e&&this.withExtras(i=>i.nameWorkInHand(e,t,s,this.els.rail??null))}async block(e,t={}){let s=(e??this.selectionLabels()).filter(l=>this.status.get(l)==="free");if(!s.length||this.blockBusy)return;let i=t.releaseAt??this.releaseAt??void 0,o=`${w(s.length)}`;this.setSeatsLocal(s,"blocked"),this.blockBusy=!0,this.panelAlert=null,this.paintSelBar(this.getSelection());let n=this.selectionSummary(s.flatMap(l=>this.labelToSeat.get(l)??[])).where,a=i?`They go back on sale ${q(i)}.`:"They stay off sale until you put them back.";try{await this.api.block(this.key,s,{...t,releaseAt:i}),this.blockBusy=!1,this.blockFailedNow=!1,this.clearSelection(),this.blockDone={labels:s,until:Date.now()+3e4},setTimeout(()=>{!this.closed&&this.mode==="block"&&this.paintSelBar(this.getSelection())},30100),this.panelAlert=B("ok",`${o} blocked${t.reason?` \xB7 ${t.reason}`:""}`,` ${n}. ${a}`),this.paintSelBar(this.getSelection()),this.doneQuietly("block",s,`${o} blocked${t.reason?` \xB7 ${t.reason}`:""}.`),this.recordChange({kind:"block",labels:s,reason:t.reason??null,releaseAt:i??null})}catch(l){this.blockBusy=!1,this.setSeatsLocal(s,"free");let c=l instanceof $&&l.status===409?(l.conflicts??[]).map(h=>h.label).filter(h=>s.includes(h)):[],d=s.filter(h=>!c.includes(h));if(c.length&&d.length){this.renderer?.deselect(c.map(h=>this.labelToId.get(h)).filter(h=>!!h)),this.syncSelection();try{this.setSeatsLocal(d,"blocked"),await this.api.block(this.key,d,{...t,releaseAt:i}),this.blockDone={labels:d,until:Date.now()+3e4,partial:!0},this.panelAlert=B("warn",`${c.length.toLocaleString()} ${c.length===1?"seat was":"seats were"} sold while you chose`,` ${w(d.length)} blocked. ${ce(c)} ${c.length===1?"is":"are"} sold and stay${c.length===1?"s":""} with ${c.length===1?"its buyer":"their buyers"}.`),this.paintSelBar(this.getSelection()),this.paintSelBar(this.getSelection()),this.doneQuietly("block",d,`${d.length.toLocaleString()} blocked.`),this.recordChange({kind:"block",labels:d,reason:t.reason??null,releaseAt:i??null});return}catch(h){this.setSeatsLocal(d,"free"),l=h}}if(this.blockFailedNow=!c.length,l instanceof $&&l.status===403){this.blockFailedNow=!1,this.blockDenied=!0,this.withExtras(h=>this.blockFailed(h.blockRefused(this.opts.organizationName),"info")),this.opts.onError?.(l);return}this.blockFailed(c.length?["Those seats were just taken"," Nothing was blocked. They are sold or in a cart now."]:["Couldn\u2019t block the seats"," The connection dropped before the change was saved. Buyers can still pick them."]),this.opts.onError?.(l)}}async unblock(e){let t=(e??this.selectionLabels()).filter(i=>this.status.get(i)==="blocked");if(!t.length||this.blockBusy)return;let s=this.blockGroups?.groups.find(i=>i.labels.includes(t[0]));this.setSeatsLocal(t,"free"),this.blockBusy=!0,this.panelAlert=null,this.paintSelBar(this.getSelection());try{await this.api.unblock(this.key,t),this.blockBusy=!1,this.clearSelection(),this.doneQuietly("unblock",t,`${t.length.toLocaleString()} ${t.length===1?"seat is":"seats are"} back on sale.`),this.recordChange({kind:"unblock",labels:t,reason:s?.reason??null,releaseAt:s?.releaseAt??null})}catch(i){this.blockBusy=!1,this.setSeatsLocal(t,"blocked"),this.blockFailed(["Couldn\u2019t put the seats back on sale"," They are still blocked. Your selection is kept; try again."]),this.opts.onError?.(i)}}blockFailed([e,t],s="error"){this.mode==="block"&&this.els.rail?.querySelector('[data-ref="blockfoot"]')?(this.panelAlert=B(s,e,t,s==="info"?"lock":void 0),this.paintSelBar(this.getSelection())):this.toastErr(`${e}.${t}`)}async unblockAll(){let e=[...this.status.entries()].filter(([t,s])=>s==="blocked"&&!this.reservedBy.has(t)).map(([t])=>t);if(e.length){this.setSeatsLocal(e,"free");try{let t=await this.api.unblockAll(this.key);this.clearSelection(),this.doneQuietly("unblockAll",e,`Unblocked ${t.freed} seat${t.freed===1?"":"s"}.`),this.recordChange({kind:"unblock",labels:e})}catch(t){await this.resnapshot(),this.toastErr("Couldn't mark everything for sale."),this.opts.onError?.(t)}}}async cancelBooking(e,t){let s=e.filter(i=>this.status.get(i)==="booked");if(!(!s.length||!t)){this.setSeatsLocal(s,"free");try{await this.api.unbook(this.key,s,t),this.clearSelection(),this.doneQuietly("cancelBooking",s,`Released ${s.length} booked unit${s.length===1?"":"s"}.`)}catch(i){this.setSeatsLocal(s,"booked"),this.toastErr("Couldn't release that booked inventory. Check the booking reference."),this.opts.onError?.(i)}}}async setCategory(e,t){let s=this.doc?.categories.find(a=>a.key===e),i=[...new Set(t??this.selectionLabels())].filter(a=>this.labelToSeat.has(a));if(!s||!i.length||this.categoryBusy||!this.categoryCanManage)return;let o=s.label??s.key,n=new Map(i.map(a=>[a,this.labelToSeat.get(a).categoryKey]));this.categoryBusy=!0,this.categoryFailed=!1,this.categoryDone=null,this.panelAlert=null,this.paintCategorySelection(this.getSelection());try{let a=await this.withAuthRetry(()=>this.api.setCategory(this.key,i,e));this.applyCategory(a.labels,e);let l=new Set(a.labels),c=i.filter(d=>!l.has(d));if(this.categoryBusy=!1,c.length){let d=c.every(h=>this.status.get(h)==="booked"||this.status.get(h)==="held");this.panelAlert=this.alertOf((await this.loadExtras()).typesPartly(c,a.labels.length,o,d)),this.reconcilingSel=!0;try{this.renderer?.deselect(c.map(h=>this.labelToId.get(h)).filter(h=>!!h)),this.syncSelection()}finally{this.reconcilingSel=!1}}this.categoryDone={labels:a.labels,name:o,prev:n,until:Date.now()+3e4,partial:c.length>0},setTimeout(()=>{!this.closed&&this.mode==="categories"&&this.paintCategorySelection(this.getSelection())},30100),this.categoryTotalsCache=null,this.paintCategorySelection(this.getSelection()),this.mode==="categories"&&this.loadCategoryDifferences(),this.done("setCategory",a.labels,`${a.labels.length.toLocaleString()} ${a.labels.length===1?"seat now sells":"seats now sell"} as ${o}.`),this.recordChange({kind:"types",labels:a.labels,title:`Changed ${w(a.labels.length)} to ${o}`})}catch(a){this.categoryBusy=!1;let l=await this.loadExtras().catch(()=>null);a instanceof $&&a.status===403?this.categoryCanManage=!1:this.categoryFailed=!0,l&&(this.panelAlert=this.alertOf(this.categoryCanManage?l.TYPES_FAILED:l.typesLocked(this.opts.organizationName))),this.mode==="categories"?this.paintCategorySelection(this.getSelection()):this.toastErr("Couldn\u2019t move the seats. Nothing changed for buyers."),this.opts.onError?.(a)}}applyCategory(e,t){let s={};for(let i of e){let o=this.labelToSeat.get(i),n=this.labelToId.get(i);o&&(o.categoryKey=t),n&&(s[n]=t)}this.categoryTotalsCache=null,this.renderer?.setSeatCategories?.(s)}async undoCategory(){let e=this.categoryDone;if(!(!e||this.categoryBusy)){this.categoryBusy=this.categoryUndoing=!0,this.categoryDone=this.panelAlert=null,this.paintCategorySelection(this.getSelection());try{await(await this.loadExtras()).undoTypes(e.labels,e.prev,async(t,s)=>{this.applyCategory((await this.withAuthRetry(()=>this.api.setCategory(this.key,t,s))).labels,s)}),this.categoryBusy=this.categoryUndoing=!1,this.clearSelection(),this.mode==="categories"&&this.loadCategoryDifferences(),this.done("setCategory",e.labels,`${w(e.labels.length)} back as they were.`),this.recordChange({kind:"types",labels:e.labels,title:`Undid the move of ${w(e.labels.length)} to ${e.name}`})}catch(t){this.categoryBusy=this.categoryUndoing=!1,this.categoryDone={...e,until:Date.now()+3e4},this.paintCategorySelection(this.getSelection()),this.opts.onError?.(t)}}}alertOf(e){return B(e[0],e[1],e[2],e[3])}async setTableBooking(e,t,s={}){if(this.inventoryModelVersion!==2){this.toastErr("Table booking controls require inventory model 2 for this event.");return}let i=await this.saveTableBooking(e,t,s);i==="conflict"?this.toastErr("Release table seats that are in a cart, booked or blocked before changing its booking mode."):i==="failed"&&this.toastErr("Couldn't update table booking. No table mode was changed.")}async saveTableBooking(e,t,s={}){let i=[...new Set(e)].filter(Boolean);if(!i.length||this.tableBookingSaving||this.inventoryModelVersion!==2)return"skipped";this.tableBookingSaving=!0;try{let o=await this.withAuthRetry(()=>this.api.setTableBooking(this.key,i,t,s));return await this.reloadEventChart(),this.doneQuietly("setTableBooking",o.tableIds,`Updated ${o.tableIds.length.toLocaleString()} table${o.tableIds.length===1?"":"s"} to ${t==="individual"?"per-chair":t==="whole"?"whole-table":"flexible-group"} booking.`),this.recordChange({kind:"tables",labels:o.tableIds.map(n=>this.tableInfos().find(a=>a.id===n)?.label??n),title:`${o.tableIds.length===1?"A table now books":`${o.tableIds.length.toLocaleString()} tables now book`} ${t==="individual"?"by the chair":t==="whole"?"as a whole":"as a group"}`}),"ok"}catch(o){return this.opts.onError?.(o),o instanceof $&&o.code==="table_inventory_in_use"?"conflict":"failed"}finally{this.tableBookingSaving=!1}}async reloadEventChart(){let e=await this.withAuthRetry(()=>this.api.chart(this.key));this.inventoryModelVersion=e.event.inventoryModelVersion===2?2:1;let t=await this.organizerAssetUrls.prepareRendererChart(e.doc);this.renderer?.destroy(),this.renderer=null,this.doc=t,this.labelToId.clear(),this.labelToSeat.clear(),this.allIds=[],this.gaUnitLabelSet.clear(),this.tableChairIds.clear(),this.labelNames.clear(),this.status.clear(),this.counts={held:0,booked:0,blocked:0},this.serverBaseline=null,this.modelSynced=!1,this.controlRoomSettled=!1,this.lastSelectionLabels.clear(),this.selBack=[],this.selAhead=[],this.buildUnitUniverse(t),this.buildRenderer(),this.buildSectionOptions(),this.settleMode(),await Promise.all([this.resnapshot(),this.refreshControlRoom().catch(s=>this.opts.onError?.(s)),this.refreshAvailability()]),this.mode==="tables"&&this.tablesPanel?this.tablesPanel.update():this.paintRail()}selectAll(){if(this.mode==="select")return this.selectByLabels([...this.labelToSeat.values()].filter(t=>this.canSelectObject(t)).map(t=>t.label));let e=this.renderer?.selectAllSelectable()??[];return this.syncSelection(),this.selWhole=e.length>0,this.selWhole&&this.syncSelection(),e}applyBand(e,t,s){let i=this.renderer;if(!i?.getSelectableInSection||i.getRung?.()==="seats")return!1;if(this.bandIndex?.base!==this.sectionsBase){let a=new Map,l=new Map;for(let[d,h]of this.labelToSeat){let u=this.sectionByObject.get(h.rowId),b=this.labelToId.get(d);if(!u||!b)continue;a.set(b,u);let p=l.get(u)??{x:0,y:0,n:0};p.x+=h.x,p.y+=h.y,p.n+=1,l.set(u,p)}let c=new Map([...l].map(([d,h])=>[d,{x:h.x/h.n,y:h.y/h.n}]));this.bandIndex={base:this.sectionsBase,sectionOf:a,centre:c}}let o=new Set;for(let a of e){let l=this.bandIndex.sectionOf.get(a);l&&o.add(l)}for(let[a,l]of this.bandIndex.centre)t(l)&&o.add(a);let n=[...o].flatMap(a=>i.getSelectableInSection(a));return s?i.deselect(n.map(a=>a.id)):i.selectByLabels?.(n.map(a=>a.label)),!0}handleSeatDeselect(e){let t=this.press;t&&(t.answered=!0);let s=this.lastPick;t?.shift&&s&&s.rowId===e.rowId&&s.label!==e.label&&this.isBulkSelectMode()?(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()},this.renderer?.selectByLabels(de(this.rowSeats(e.rowId),s.label,e.label))):t&&(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()}),this.syncSelection()}rowSeats(e){return[...this.labelToSeat.values()].filter(t=>t.rowId===e)}wireGestures(e){e.addEventListener("pointerdown",t=>{this.press={shift:t.shiftKey,x:t.clientX,y:t.clientY,answered:!1}},!0),e.addEventListener("click",t=>{let s=this.press;if(!s||s.answered||!this.isBulkSelectMode()||this.renderer?.getRung?.()==="seats"||Math.hypot(t.clientX-s.x,t.clientY-s.y)>5)return;let i=this.renderer,o=e.getBoundingClientRect(),n={x:t.clientX-o.left,y:t.clientY-o.top};if(!i||i.sectionAt?.(n))return;let a=Ne(n,i.getMinimapSnapshot?.().sections??[],l=>i.worldToScreen(l));a&&this.handleSectionTap(a)}),e.addEventListener("dblclick",()=>{let t=this.lastPick;!t||Date.now()-t.at>700||(this.isBulkSelectMode()?(this.renderer?.selectByLabels(this.rowSeats(t.rowId).map(s=>s.label)),this.syncSelection()):this.mode==="view"&&this.showLabels([t.label]))})}handleSectionTap(e){if(this.press&&(this.press.answered=!0),this.mode==="filterSections"){let t=this.filterableSections().find(s=>s.id===e);t&&this.setFilteredSection(t.label);return}if(this.isBulkSelectMode()&&this.renderer?.getRung?.()!=="seats"){let t=Date.now(),s=this.lastSectionTap?.id===e&&t-this.lastSectionTap.at<450;this.lastSectionTap=s?null:{id:e,at:t},s||this.selectSection(e);return}this.renderer?.focusSection(e),this.channels?.handleSectionFocus(e),this.sectionsPanel?.pick(e)}selectSection(e){if(!this.renderer)return[];let t=this.renderer.getSelectableInSection(e);return this.renderer.selectByLabels(t.map(s=>s.label)),this.syncSelection(),this.renderer.getSelection()}setFilteredSection(e){let t=e.trim(),s=this.filterableSections().filter(n=>n.label===t);if(!s.length)throw new Error(`Unknown event section: ${e}`);let i=t!==this.filteredSectionLabel;this.filteredSectionLabel=t,this.mode==="filterSections"&&(this.applyFilteredSectionCanvas(s),this.renderFilterSectionsRail());let o=s.map(({id:n,label:a,seatCount:l,zone:c})=>({id:n,label:a,seatCount:l,...c?{zone:c}:{}}));return i&&this.opts.onFilteredSectionChange?.(o),o}focusSection(e){let t=e.trim(),s=this.filterableSections().filter(i=>i.label===t);return!this.renderer||!s.length?[]:(this.frameSections(s),s.map(({id:i,label:o,seatCount:n,zone:a})=>({id:i,label:o,seatCount:n,...a?{zone:a}:{}})))}clearFilteredSection(){let e=this.filteredSectionLabel!==null;this.filteredSectionLabel=null,this.renderer?.setDimmedSections(null),this.renderer?.clearSectionFocus(),this.renderer?.zoomToFit(),this.mode==="filterSections"&&this.renderFilterSectionsRail(),e&&this.opts.onFilteredSectionChange?.([])}getFilteredSections(){return this.filteredSectionLabel?this.filterableSections().filter(e=>e.label===this.filteredSectionLabel).map(({id:e,label:t,seatCount:s,zone:i})=>({id:e,label:t,seatCount:s,...i?{zone:i}:{}})):[]}selectByLabels(e){let t=e;if(this.mode==="select"){let s=new Set(this.selectionLabels()),i=this.selectionCap(),o=[...new Set(e)].filter(a=>!s.has(a)).map(a=>this.labelToSeat.get(a)).filter(a=>!!a&&this.canSelectObject(a)),n=Math.max(0,i-s.size);o.length>n&&this.opts.onSelectionLimit?.(i),t=o.slice(0,n).map(a=>a.label)}return this.renderer?.selectByLabels(t),this.syncSelection(),this.getSelection()}selectObjects(e){return this.selectByLabels(e)}deselectObjects(e){let t=e.map(s=>this.labelToId.get(s)).filter(s=>!!s);return this.renderer?.deselect(t),this.syncSelection(),this.getSelection()}selectCategories(e){let t=new Set(e);return this.selectByLabels([...this.labelToSeat.values()].filter(s=>t.has(s.categoryKey)).map(s=>s.label))}deselectCategories(e){let t=new Set(e);return this.deselectObjects(this.getSelection().filter(s=>t.has(s.categoryKey)).map(s=>s.label))}setSelectableObjects(e){this.opts.selectableObjects=[...e],this.selectableObjectLabels=new Set(e),this.reconcileSelectPolicy()}setUnavailableObjects(e,t){this.opts.unavailableObjectsReason=t;let s=new Set(e),i=[...s].filter(n=>!this.unavailableLabels.has(n)).concat([...this.unavailableLabels].filter(n=>!s.has(n)));if(!i.length)return;if(this.opts.unavailableObjects=[...s],this.unavailableLabels=s,this.renderer){let n=new Map;for(let a of i){let l=this.paintIds(a);if(!l.length)continue;let c=this.renderStatusOf(a,this.status.get(a)??"free");n.set(c,[...n.get(c)??[],...l])}for(let[a,l]of n)this.renderer.setStatus(l,a);this.afterPaint()}let o=this.getSelection().filter(n=>this.isHostUnavailable(n.label));o.length&&(this.renderer?.deselect(o.map(n=>n.id)),this.syncSelection())}setCategoryPrices(e){this.opts.categoryPrices=e,this.renderer?.setCategoryPriceRanges(this.hoverPriceRanges()),this.applyPriceColours(),this.paintColourLegend()}hoverPriceRanges(){let e=this.opts.categoryPrices;return e==null?e:Object.fromEntries(Object.entries(e).map(([t,s])=>[t,typeof s=="number"?{min:s,max:s}:{min:s.min,max:s.max}]))}setUnavailableObjectsSelectable(e){this.opts.unavailableObjectsSelectable=e,this.reconcileSelectPolicy()}setObjectSelectable(e){this.opts.isObjectSelectable=e,this.reconcileSelectPolicy()}setMaxSelectedObjects(e){this.assertSelectionOptions(e,this.opts.numberOfPlacesToSelect),this.opts.maxSelectedObjects=e,this.trimSelectionToCap(),this.updateRendererInteraction(),this.syncSelection()}setNumberOfPlacesToSelect(e){this.assertSelectionOptions(this.opts.maxSelectedObjects,e),this.opts.numberOfPlacesToSelect=e,this.selectionWasValid=null,this.trimSelectionToCap(),this.updateRendererInteraction(),this.syncSelection()}getSelectionValidity(){let e=this.opts.numberOfPlacesToSelect;if(e===void 0)return null;let t=this.getSelection(),s=t.length;return{isValid:s===e,count:s,required:e,remaining:Math.max(0,e-s),objects:t}}clearSelection(){this.renderer?.clearSelection(),this.syncSelection()}stepSelection(e){let s=(e<0?this.selBack:this.selAhead).pop();if(!s||!this.renderer)return!1;(e<0?this.selAhead:this.selBack).push([...this.lastSelectionLabels]),this.selRestoring=!0;try{this.renderer.clearSelection();let i=s.filter(o=>this.labelToSeat.has(o));i.length&&this.renderer.selectByLabels(i),this.syncSelection()}finally{this.selRestoring=!1}return!0}getSelection(){return this.renderer?.getSelection?.()??[]}getReport(){return this.api.report(this.key).then(e=>(this.applyReportRevenue(e),e))}getControlRoomSnapshot(e=this.trendWindowMinutes){return this.setTrendWindow(e)}getConnection(){return{status:this.connectionStatus,lastMessageAt:this.lastMessageAt,room:this.roomState()}}getLog(e={}){return this.api.log(this.key,e)}async setHoldTtl(e){try{await this.api.setHoldTtl(this.key,e),this.done("setHoldTtl",[],e?`Hold window set to ${Math.round(e/6e4)} min.`:"Hold window reset.")}catch(t){this.toastErr("Couldn't update the hold window."),this.opts.onError?.(t)}}zoomToFit(){if(this.mode==="filterSections"&&this.filteredSectionLabel){this.clearFilteredSection();return}this.renderer?.clearSectionFocus(),this.renderer?.zoomToFit()}mapReturnPoint(){let e=this.renderer;return e?.getVisibleWorldRect?{rect:e.getVisibleWorldRect(),focused:e.getFocusedSection?.()??null,floor:e.getActiveFloorId?.()??"",overview:e.isFloorOverview?.()??!1}:null}restoreMapReturn(){let e=this.channelsReturn;this.channelsReturn=null;let t=this.renderer;if(!t)return;if(t.clearSectionFocus(),!e)return void t.zoomToFit();if(e.overview&&!t.isFloorOverview?.()?t.setFloorOverview?.(!0):!e.overview&&e.floor&&e.floor!==t.getActiveFloorId?.()&&t.setActiveFloor?.(e.floor),e.focused)return void t.focusSection(e.focused);let{x:s,y:i,width:o,height:n}=e.rect,a=o/1.12,l=n/1.12;t.focusRegion({x:s+(o-a)/2,y:i+(n-l)/2,width:a,height:l})}zoomOutStep(){let e=this.renderer;if(!e)return;if(!e.zoomOutLevel)return void e.zoomOut();let t=!!e.getFocusedSection?.();e.zoomOutLevel()==="venue"&&t&&e.clearSectionFocus()}paintMapChrome(){let e=this.renderer;if(!e||!this.els.crumb)return;let t=e.getFocusedSection?.()??null,s=t?e.getMinimapSnapshot?.().sections.find(a=>a.id===t)??null:null,i=e.getFloors?.()??[],o=i.length>1?e.isFloorOverview?.()?"All floors":i.find(a=>a.id===e.getActiveFloorId?.())?.name??null:null,n=e.getRung?.()==="seats";n!==this.legendSeats&&(this.legendSeats=n,this.paintColourLegend()),nt(this.els,it({focused:s?{label:s.label,free:s.free,total:s.total,allBlocked:s.free?void 0:this.sectionKeptAside(s.id)}:null,floor:o,seatsRevealed:e.seatsRevealed?.()??!0,atVenueFit:e.atVenueFit?.(),atCeiling:e.canZoomIn?.()===!1||e.seatsPickable?.()===!0}))}sectionKeptAside(e){let t=this.filterableSections().find(o=>o.id===e);if(!t)return;let s=0,i=0;for(let o of t.seatLabels){let n=this.status.get(o)??"free";if(n==="free"||n==="held")return;n==="blocked"&&(this.reservedBy.has(o)?i++:s++)}return s&&i?"both":i?"reserved":s?"blocked":void 0}sectionTypeKeys(){if(this.typeKeyBySection&&this.typeKeyBase===this.sectionsBase)return this.typeKeyBySection;let e=new Map;for(let t of this.filterableSections()){let s=new Map;for(let o of t.seatLabels){let n=this.labelToSeat.get(o)?.categoryKey;n&&s.set(n,(s.get(n)??0)+1)}let i=null;for(let[o,n]of s)(!i||n>s.get(i))&&(i=o);i&&e.set(t.id,i)}return this.typeKeyBySection=e,this.typeKeyBase=this.sectionsBase,e}typeColour(e,t){return this.renderer?.getCategoryColours?.()!==!1&&this.renderer?.categoryDisplayColor?.(e)||t||"#6e7bff"}sectionTypeTint(e){let t=this.sectionTypeKeys().get(e);return t?this.renderer?.categoryDisplayColor?.(t)??null:null}scheduleReservations(e=400){this.closed||this.reservationsTimer||(this.reservationsTimer=setTimeout(()=>{this.reservationsTimer=null,this.refreshReservations()},e))}async refreshReservations(){if(!(this.closed||!this.toolAvailable("reserve")))try{let e=await this.withAuthRetry(()=>this.api.eventRequest(this.key,"reservations"));this.closed||this.setReservations(e.reservations??[]),this.blockGroups=null,this.findBlocked?.refresh()}catch{}}setReservations(e){let t=new Map;for(let n of e){let a=n.createdByYou?"you":n.createdByName??"",l=n.createdAt?C(n.createdAt,{day:"numeric",month:"short"}):"",c=[a,l].filter(Boolean).join(" \xB7 ")||void 0;for(let d of n.labels)t.set(d,{id:n.id,name:n.name,releaseAt:n.releaseAt,count:n.labels.length,by:c})}let s=new Set;for(let n of t.keys())this.reservedBy.has(n)||s.add(n);for(let n of this.reservedBy.keys())t.has(n)||s.add(n);this.reservedBy=t,this.reservationWheres.clear(),this.reservationsLoaded=!0;let i=this.serverBaseline?.client;i&&i.reserved===null&&(i.reserved=this.reservedBlockedCount());for(let n of t.keys())this.reserving.delete(n);this.reservedIds=new Set([...t.keys()].flatMap(n=>this.paintIds(n)));let o=[...s].filter(n=>this.status.get(n)==="blocked").flatMap(n=>this.paintIds(n));o.length&&this.renderer&&(this.renderer.setStatus(o,P("booked")),this.renderer.setStatus(o,P("blocked"))),this.paintColourLegend(),this.paintMapChrome()}async loadBlockGroups(){if(this.blockGroups&&Date.now()-this.blockGroups.at<3e4)return this.blockGroups.groups;let e=await this.withAuthRetry(()=>this.api.eventRequest(this.key,"blocks"));return this.blockGroups={at:Date.now(),groups:e.groups??[]},this.blockGroups.groups}reservedBlockedCount(){let e=0;for(let t of this.reservedBy.keys())this.status.get(t)==="blocked"&&(e+=this.seatWeight(t));return e}reservedTally(e){let t=this.reservedBlockedCount(),s=this.serverBaseline,i=s?.server.reserved,o=s?.client?.reserved,n=i===void 0?t:i+(o==null?0:t-o);return Math.min(e,Math.max(0,n))}paintColourLegend(){let e=this.els.blocklegend;if(!e||!this.renderer)return;let t=this.getColourBy(),s=this.buildTallies();pt(e,{colourBy:t,seats:this.legendSeats??this.renderer.getRung?.()==="seats",types:t==="type"?this.legendTypes():t==="price"?this.extrasReady?.priceChips(this.typePrices(),this.legendTypes(),this.root?.dataset.theme==="light",i=>M(i,this.currency))??[]:[],counts:{free:s.free,held:s.held,booked:s.booked,blocked:s.blocked,reserved:this.reservedTally(s.blocked)},lit:this.litChip,picked:this.chipPicked,shown:this.litChip==="shown"&&this.shownObjects?{name:this.shownObjects.name,count:this.shownObjects.labels.length}:null,channels:t==="channel"?this.channels?.legendChannels()??[]:[],channelAvailable:this.channelColoursAvailable()})}showObjects(e,t="Seats"){let s=(e??[]).filter(i=>this.labelToSeat.has(i));this.shownObjects=s.length?{name:t,labels:s}:null,this.chipPicked=null,this.litChip=this.shownObjects?"shown":this.litChip==="shown"?null:this.litChip,this.highlightLabels(this.litChip?this.chipLabels(this.litChip):null),this.shownObjects&&this.frameLabels(s),this.paintColourLegend()}chipLabels(e){if(e==="shown")return this.shownObjects?.labels??[];let t=[...this.labelToSeat.keys()];if(e.startsWith("type:")){let s=e.slice(5);return t.filter(i=>this.labelToSeat.get(i).categoryKey===s)}if(e.startsWith("price:")){let s=this.typePrices();return t.filter(i=>s.get(this.labelToSeat.get(i).categoryKey)===+e.slice(6))}return e==="reserved"?t.filter(s=>this.reservedBy.has(s)):t.filter(s=>(this.status.get(s)??"free")===e&&(e!=="blocked"||!this.reservedBy.has(s)))}onLegendChip(e,t){let s=this.chipLabels(e);if(t&&(this.isBulkSelectMode()||this.mode==="select")){let i=this.getSelection().length;this.selectByLabels(s);let o=this.getSelection().length-i,n=s.length-o-i;n>0&&this.toast(`${o.toLocaleString()} picked. ${n.toLocaleString()} skipped: this task can\u2019t change them.`,"ok"),this.litChip=e,this.chipPicked=o,this.highlightLabels(null),this.paintColourLegend();return}this.chipPicked=null,this.litChip=this.litChip===e?null:e,this.highlightLabels(this.litChip?s:null),this.paintColourLegend()}legendTypes(){let e=new Map;for(let t of this.labelToSeat.values())e.set(t.categoryKey,(e.get(t.categoryKey)??0)+1);for(let[t,s]of this.status){if(s==="free")continue;let i=this.labelToSeat.get(t)?.categoryKey;i&&e.has(i)&&e.set(i,e.get(i)-1)}return(this.doc?.categories??[]).filter(t=>e.has(t.key)).map(t=>({key:t.key,label:t.label,color:this.renderer?.categoryDisplayColor?.(t.key)??t.color,free:Math.max(0,e.get(t.key))}))}refreshBlockPaint(){this.renderer?.refreshBlockPaint?.(),this.minimap?.refreshMinimap()}mapCamera(){return{getViewport:()=>{let e=this.renderer;return!e?.getVisibleWorldRect||!e.getWorldBounds?null:{visible:e.getVisibleWorldRect(),bounds:e.getWorldBounds()}},getMinimapSnapshot:()=>this.renderer?.getMinimapSnapshot?.()??{sections:[],seats:[]},panToWorld:e=>{this.setFollowLive(!1),this.renderer?.panToWorld?.(e)},clearSectionFocus:()=>this.renderer?.clearSectionFocus?.(),focusSection:e=>{this.setFollowLive(!1),this.renderer?.focusSection(e),this.channels?.handleSectionFocus(e)},overview:()=>{this.setFollowLive(!1),this.zoomToFit()},getFloors:()=>this.renderer?.getFloors?.()??[],getActiveFloorId:()=>this.renderer?.getActiveFloorId?.()??"",isFloorOverview:()=>this.renderer?.isFloorOverview?.()??!1,getRenderer:()=>this.renderer}}syncMinimap(){let e=this.els.minimapMount,t=!!this.root?.classList.contains("compact");if(!e||!this.renderer||t){this.minimap?.dispose(),this.minimap=null;return}if(this.minimap){this.minimap.refreshMinimap();return}this.minimap=Te({controller:this.mapCamera(),root:()=>this.root,cssVar:s=>this.cssVar(s.replace(/^--sl-/,"--slm-")),focusedSectionLabel:()=>{},tint:s=>this.renderer?.categoryDisplayColor?.(s)||void 0},e),this.minimap.refreshMinimap()}cssVar(e){return this.root?getComputedStyle(this.root).getPropertyValue(e).trim():""}destroy(){if(this.selectObserver?.disconnect(),this.closed=!0,this.minimap?.dispose(),this.minimap=null,this.monitorRefreshTimer&&clearTimeout(this.monitorRefreshTimer),this.monitorRefreshTimer=null,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.stopKeepalive(),this.alerts?.destroy(),this.alerts=null,this.linkTimers&&this.linkTimers.forEach(e=>clearTimeout(e)),this.feedTimer&&clearInterval(this.feedTimer),this.toastTimer&&clearTimeout(this.toastTimer),this.liveEventTimer&&clearTimeout(this.liveEventTimer),this.reservationsTimer&&clearTimeout(this.reservationsTimer),this.kpiCleanupTimer&&clearTimeout(this.kpiCleanupTimer),this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.paintHandle!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.paintHandle),this.paintHandle=null,this.channels?.destroy(),this.channels=null,this.channelsLoading=null,this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.layoutObserver?.disconnect(),this.layoutObserver=null,this.colorSchemeStop?.(),this.colorSchemeStop=null,this.root?.removeEventListener("keydown",this.onKeyDown),this.els.rail?.removeEventListener("click",this.onRailClick),this.root?.removeEventListener("click",this.onHowClick),typeof document<"u"&&document.removeEventListener("fullscreenchange",this.onFullscreenChange),this.ws){try{this.ws.close()}catch{}this.ws=null}this.reserve?.destroy(),this.reserve=null,this.seatHistoryPanel?.destroy(),this.seatHistoryPanel=null,this.changes?.destroy(),this.changes=null,this.saved?.destroy(),this.saved=null;for(let e of this.arrival)e.destroy();this.arrival=[],this.activityPanel?.destroy(),this.activityPanel=null,this.navigation?.destroy(),this.navigation=null,this.renderer?.destroy(),this.renderer=null,this.organizerAssetUrls.dispose(),this.root&&this.root.parentNode===this.host&&this.host.removeChild(this.root)}buildRenderer(){if(!this.doc)return;let e=this.isBulkSelectMode();this.renderer=new Ss(this.mapHost,{manageMode:!0,organizerGlyph:{apply:(s,i,o,n)=>{let a=i==="cross"?ft(s):void 0;if(a&&this.reservedIds.has(a)){Et(s),bt(s,n);return}be(s),Ls(s,i,o,n)},clear:s=>{be(s),Et(s)},isPainted:s=>Ts(s)||ee(s)},marqueeSelect:e&&!this.movingMap,marqueeShape:this.marqueeShape,rowLabelSelect:this.rowLabelSelectable(),maxSelection:this.selectionCap(),selectableStatuses:this.selectableStatuses(),currency:this.currency,onSelect:s=>this.handleSeatSelect(s),onDeselect:s=>this.handleSeatDeselect(s),onSelectionLimit:s=>this.opts.onSelectionLimit?.(s),onMarquee:()=>(this.isBulkSelectMode()&&(this.hintUntil=Date.now()+4e3,this.updateZoomHint(),setTimeout(()=>this.updateZoomHint(),4050)),this.mode==="select"?this.reconcileSelectPolicy():this.syncSelection()),onBand:(s,i,o)=>this.applyBand(s,i,o),onGAClick:s=>{if(this.mode!=="select"||!this.opts.onAreaClick||!this.doc)return;let i=At(this.doc).find(o=>o.id===s);i&&this.opts.onAreaClick({id:i.id,label:i.label,name:i.displayLabel?.trim()||i.label})},onSectionTap:s=>this.handleSectionTap(s),onViewChange:()=>{this.updateZoomHint(),this.paintMapChrome(),this.minimap?.drawMinimapRect(),this.channels?.handleViewChange()},onFocusedSectionChange:()=>{this.paintMapChrome(),this.minimap?.refreshMinimap()},hoverFacts:s=>this.hoverFactsFor(s),hoverCardHead:s=>this.hoverHeadFor(s),hoverSectionHead:(s,i)=>this.sectionHeadFor(s,i),blockPaint:s=>this.captioned(s.id,dt(s,{rule:this.availabilityRules[s.id],hiddenNow:this.effectiveHidden.has(s.id),closedNow:this.effectiveClosed.has(s.id),colourBy:this.getColourBy(),typeTint:this.sectionTypeTint(s.id),allBlocked:s.state==="sold-out"?this.sectionKeptAside(s.id):void 0})),openAtSectionsWhenDense:!0});let t=this.renderer;this.loadExtras().then(s=>{this.renderer===t&&(s.paintBlockCaptions(t,this.blockCaptions,()=>this.root?.dataset.theme==="dark"),this.captionsOn=!0,this.refreshBlockPaint())}).catch(()=>{}),this.renderer.setCategoryPriceRanges(this.hoverPriceRanges()),this.priceShadesOn="",this.renderer.setChart(this.themedDoc()),this.chromeClearance=-1,this.applyChromeClearance(),this.legendInset="",this.applyLegendInset(),this.repaintAll(),this.applyHeatOverlay(),this.applyMapView(),this.updateZoomHint(),this.minimap?.dispose(),this.minimap=null,this.syncMinimap(),this.paintMapChrome()}hoverFactsFor(e){let t=this.seatOfId(e);if(!t)return null;let s=this.status.get(t.label)??"free",i={free:"Free",held:"In a cart",booked:"Sold",blocked:"Blocked"},n=s==="free"&&this.isHostUnavailable(t.label)?this.opts.unavailableObjectsReason?.trim()||"Unavailable":i[s],a=s==="blocked"?this.reservedBy.get(t.label):void 0;if(a){let h=a.releaseAt==null?"No end":`${q(a.releaseAt)}${a.releaseAt===this.eventStartsAt?" (the start)":""}`,u=this.reservationWhere(a.id);return[{caption:"Until",value:h},...a.by?[{caption:"Reserved by",value:a.by}]:[],{caption:"Reservation",value:`${w(a.count)}${u?` \xB7 ${u}`:""}`}]}let l=[{caption:"Status",value:n}],c=this.doc?.categories.find(h=>h.key===t.categoryKey);c&&l.push({caption:"Ticket type",value:`${c.label??c.key}${typeof c.price=="number"?` \xB7 ${M(c.price,this.currency)}`:""}`});let d=this.channels?.channelNameForLabel(t.label)??null;return d&&l.push({caption:"Channel",value:d}),l}hoverHeadFor(e){let t=this.seatOfId(e);if(!t)return null;let s=this.status.get(t.label)??"free",i=s==="blocked"?this.reservedBy.get(t.label):void 0,o=this.sectionLabelById.get(this.sectionByObject.get(t.rowId)??S)??"Other seats",n=t.label.startsWith(`${o} `)?t.label.slice(o.length+1):t.label,a=n.lastIndexOf("-"),[l,c]=F[i?"reserved":s]??F.free,d=this.root?.dataset.theme==="dark"?"#e879f9":c;return{title:`${o} \xB7 ${n}`,...i?{sub:`Reserved for ${i.name}`,tone:d}:a>0?{sub:`Row ${n.slice(0,a)}, seat ${n.slice(a+1)}`}:{},plate:k(l,i?d:c,26)}}sectionHeadFor(e,t){this.idToLabel.size!==this.labelToId.size&&(this.idToLabel=new Map([...this.labelToId].map(([i,o])=>[o,i])));let s=0;for(let i of t)(this.status.get(this.idToLabel.get(i)??"")??"free")==="free"&&(s+=1);return{title:this.sectionLabelById.get(e)??e,sub:`${s.toLocaleString()} of ${t.length.toLocaleString()} free`,plate:k("layers","#0ea5a5",26)}}seatOfId(e){for(let t of this.labelToSeat.values())if(t.id===e)return t}reservationWhere(e){let t=this.reservationWheres.get(e);if(t==null){let s=[...this.reservedBy].filter(([,n])=>n.id===e).flatMap(([n])=>this.labelToSeat.get(n)??[]),i=this.rowLabels(),o=new Set(s.map(n=>i.get(n.rowId)??n.rowId)).size===2;t=this.selectionSummary(s).where.replace(/ · (rows? )([^\s–]+)(?:–([^\s–]+))?$/,(n,a,l,c)=>` ${a}${l}${c?`${o?" and ":"\u2013"}${c}`:""}`),this.reservationWheres.set(e,t)}return t}rowLabelSelectable(){return this.isBulkSelectMode()||this.mode==="select"}isBulkSelectMode(){return this.mode==="block"||this.mode==="reserve"||this.mode==="categories"||this.mode==="channels"&&this.channels?.usesMarqueeSelection()===!0}selectableStatuses(){return this.mode==="block"?["free","not_for_sale"]:this.mode==="reserve"?["free"]:this.mode==="select"||this.mode==="categories"||this.mode==="inspect"||this.mode==="view"||this.isBulkSelectMode()||this.mode==="channels"&&this.channels?.canSelect()===!0?["free","held","booked","not_for_sale"]:[]}updateRendererInteraction(){let e=this.isBulkSelectMode();this.renderer?.setManageInteraction({manageMode:!0,organizerStatus:this.channels?.view!=="preview"||this.mode!=="channels",marqueeSelect:e&&!this.movingMap,marqueeShape:this.marqueeShape,rowLabelSelect:this.rowLabelSelectable(),maxSelection:this.selectionCap(),selectableStatuses:this.selectableStatuses()}),this.navigation?.update(e),this.updateZoomHint()}handleSeatSelect(e){let t=this.press;t&&(t.answered=!0);let s=this.lastPick;if(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()},t?.shift&&s&&s.rowId===e.rowId&&s.label!==e.label&&this.isBulkSelectMode()&&this.renderer?.selectByLabels(de(this.rowSeats(e.rowId),s.label,e.label)),this.mode==="select"&&!this.canSelectObject(e)){this.renderer?.deselect([e.id]),this.syncSelection();return}if(this.mode==="inspect"||this.mode==="view"){let i=this.getSelection().filter(o=>o.id!==e.id).map(o=>o.id);i.length&&this.renderer?.deselect(i)}this.syncSelection()}buildUnitUniverse(e){this.categoryTotalsCache=null;let t=new Map;for(let i of Ms(e))i.type==="table"&&t.set(i.id,i.label);let s=new Map;for(let i of Cs(e))if(this.labelToId.set(i.label,i.id),this.labelToSeat.set(i.label,i),this.allIds.push(i.id),t.has(i.rowId)){let o=s.get(i.rowId)??[];o.push(i.id),s.set(i.rowId,o)}for(let[i,o]of s){let n=t.get(i);this.labelToId.has(n)||this.tableChairIds.set(n,o)}for(let i of At(e)){let o=i.displayLabel||i.label;for(let n of As(i))this.labelToId.has(n)||(this.gaUnitLabelSet.add(n),this.labelNames.set(n,o))}}unitTotal(){return this.allIds.length+this.gaUnitLabelSet.size}paintIds(e){let t=this.labelToId.get(e);return t?[t]:this.tableChairIds.get(e)??[]}knownLabels(){return[...this.labelToId.keys(),...this.gaUnitLabelSet]}repaintAll(){let e=this.renderer;if(!e)return;this.allIds.length&&e.setStatus(this.allIds,"free");let t={free:[],held:[],booked:[],not_for_sale:[]};for(let[s,i]of this.status.entries())t[this.renderStatusOf(s,i)].push(...this.paintIds(s));for(let s of this.unavailableLabels)this.status.has(s)||t.held.push(...this.paintIds(s));["held","booked","not_for_sale"].forEach(s=>{t[s].length&&e.setStatus(t[s],s)})}async connect(){if(this.closed||this.sessionEnded)return;let e;try{if(e=(await this.withAuthRetry(()=>this.api.subscribeTicket(this.key))).protocols,!e.length)throw new Error("manage_subscribe_ticket_missing")}catch(s){this.setLive(!1),this.opts.onError?.(s),this.scheduleReconnect();return}if(this.closed)return;let t;try{t=new WebSocket(this.api.socketUrl(this.key),e)}catch(s){this.opts.onError?.(s),this.scheduleReconnect();return}this.ws=t,this.socketSnapshotSeen=!1,t.onopen=()=>{this.attempt=0,this.setLive(!0),this.startKeepalive(t),this.resnapshot().then(()=>this.refreshControlRoom()).catch(s=>this.opts.onError?.(s)),this.refreshAvailability()},t.onmessage=s=>this.onMessage(s),t.onclose=()=>{this.ws===t&&(this.ws=null),this.stopKeepalive(),this.setLive(!1),this.scheduleReconnect()},t.onerror=()=>{try{t.close()}catch{}}}startKeepalive(e){this.stopKeepalive(),this.pingTimer=setInterval(()=>{if(this.ws===e){try{e.send(JSON.stringify({type:"ping"}))}catch{return}this.pongTimer||(this.pongTimer=setTimeout(()=>{if(this.pongTimer=null,this.ws===e){e.onclose=null,e.onmessage=null;try{e.close()}catch{}this.ws=null,this.stopKeepalive(),this.setLive(!1),this.paintLink("paused"),this.scheduleReconnect()}},5e3))}},1e4)}stopKeepalive(){this.pingTimer&&clearInterval(this.pingTimer),this.pongTimer&&clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}scheduleReconnect(){if(this.closed||this.sessionEnded||this.reconnectTimer)return;let e=Math.min(1e3*2**Math.min(this.attempt++,5),15e3);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}onMessage(e){let t;try{t=JSON.parse(typeof e.data=="string"?e.data:"")}catch{return}if(!t||typeof t!="object"||(this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null),t.type==="pong"))return;this.lastMessageAt=Date.now();let s=t;if((Array.isArray(s.hidden)||Array.isArray(s.closed))&&this.updateEffectiveAvailability(s.hidden,s.closed),s.type==="presence"){typeof s.shoppingSessions=="number"&&typeof s.activeHolds=="number"&&(this.livePresence={at:Date.now(),value:{shoppingSessions:s.shoppingSessions,activeHolds:s.activeHolds}},this.controlRoomSnapshot&&(this.controlRoomSnapshot={...this.controlRoomSnapshot,presence:this.livePresence.value},this.opts.onControlRoom?.(this.controlRoomSnapshot)),this.lastSyncedAt=Date.now(),this.recomputeTallies(),this.paintMonitorInsights());return}if(s.type!=="hidden"){if(s.seats&&typeof s.seats=="object")this.applySocketSnapshot(s.seats,typeof s.default=="string"?s.default:void 0);else if(Array.isArray(s.changes)){let i=[],o=new Map;for(let a of s.changes){let l=ve(a.status),c=this.status.get(a.label)??"free";if(c===l)continue;(c==="blocked"||l==="blocked")&&this.scheduleReservations(),this.setStatusLabel(a.label,l,c);let d=this.paintIds(a.label);d.length&&(this.renderer?.setStatus(d,this.renderStatusOf(a.label,l)),i.push(...d));let h=this.verbFor(c,l,a.label),u=`${h}:${l}`,b=o.get(u)??{labels:[],verb:h,status:l};b.labels.push(a.label),o.set(u,b)}for(let a of o.values()){let l=this.pushActivity(a.labels,a.verb,a.status);l&&this.paintSpatialActivity(l)}o.size&&this.scheduleMonitorRefresh(),i.length&&(this.lastSyncedAt=Date.now(),this.afterPaint()),this.reconcileSelectionWithStatus([...o.values()].flatMap(a=>a.labels));let n=typeof s.bookedValue?.gross=="number"?s.bookedValue.gross:s.revenue?.gross;typeof n=="number"&&Number.isFinite(n)&&this.applyLiveGross(n),this.recomputeTallies()}}}applyLiveGross(e){if(this.liveGross={at:Date.now(),value:e},this.authoritativeGrossRevenue=e,this.revenueStatus="current",this.controlRoomSnapshot){let s={...this.controlRoomSnapshot.bookedValue??this.controlRoomSnapshot.revenue,gross:e};this.controlRoomSnapshot={...this.controlRoomSnapshot,bookedValue:s,revenue:s},this.opts.onControlRoom?.(this.controlRoomSnapshot)}}setStatusLabel(e,t,s=this.status.get(e)??"free"){if(this.status.set(e,t),s===t)return;let i=this.seatWeight(e);if(s!=="free"&&(this.counts[s]-=i),t!=="free"&&(this.counts[t]+=i),this.alerts){let o=this.labelToSeat.get(e);this.alerts.seatChanged(o?this.sectionByObject.get(o.rowId)??null:null,s,t)}}applySocketSnapshot(e,t){let s=this.socketSnapshotSeen?this.status:null;if(this.applySnapshot(e,t),this.socketSnapshotSeen=!0,!s)return;let i=new Map;for(let o of new Set([...s.keys(),...this.status.keys()])){let n=s.get(o)??"free",a=this.status.get(o)??"free";if(n===a)continue;let l=this.verbFor(n,a,o),c=`${l}:${a}`,d=i.get(c)??{labels:[],verb:l,status:a};d.labels.push(o),i.set(c,d)}for(let o of i.values()){let n=this.pushActivity(o.labels,o.verb,o.status);n&&this.paintSpatialActivity(n)}i.size&&this.scheduleMonitorRefresh()}scheduleMonitorRefresh(){this.monitorRefreshTimer||(this.monitorRefreshTimer=setTimeout(()=>{this.monitorRefreshTimer=null,!this.closed&&(this.refreshControlRoom().catch(e=>this.opts.onError?.(e)),this.paintFullscreenLine(),this.tablesPanel?.update(),this.sectionsPanel?.update())},150))}async resnapshot(){try{let e=await this.api.objects(this.key);this.applySnapshot(e.seats),this.updateEffectiveAvailability(e.hidden,e.closed),this.lastMessageAt=Date.now()}catch{}}applySnapshot(e,t){let s=new Map;if(t!==void 0){let i=ve(t);for(let o of this.knownLabels())s.set(o,i)}for(let[i,o]of Object.entries(e))s.set(i,ve(o));this.status=s,this.recountAll(),this.serverBaseline&&!this.serverBaseline.client&&(this.serverBaseline.client=this.pairedClient()),this.modelSynced=!0,this.scheduleReservations(),this.lastSyncedAt=Date.now(),this.repaintAll(),this.afterPaint(),this.recomputeTallies(),this.reconcileSelectionWithStatus(null)}reconcileSelectionWithStatus(e){if(!this.renderer)return;let t=this.getSelection();if(!t.length)return;if(e){let o=new Set(e);if(!t.some(n=>o.has(n.label)))return}if(this.mode==="select"){this.reconcileSelectPolicy();return}if(e)for(let o of t)this.status.get(o.label)==="booked"&&e.includes(o.label)&&this.selJustSold.add(o.label);let s=new Set(this.selectableStatuses()),i=t.filter(o=>!s.has(this.renderStatusOf(o.label,this.status.get(o.label)??"free")));this.reconcilingSel=!0;try{i.length&&this.renderer.deselect(i.map(o=>o.id)),this.syncSelection()}finally{this.reconcilingSel=!1}}recountAll(){let e={held:0,booked:0,blocked:0};for(let[t,s]of this.status)s!=="free"&&(e[s]+=this.seatWeight(t));this.counts=e}seatWeight(e){return this.tableChairIds.get(e)?.length??1}setSeatsLocal(e,t){let s=[],i=[];for(let o of e)this.setStatusLabel(o,t),(this.renderStatusOf(o,t)===P(t)?s:i).push(...this.paintIds(o));s.length&&this.renderer?.setStatus(s,P(t)),i.length&&this.renderer?.setStatus(i,"held"),this.afterPaint(),this.recomputeTallies()}afterPaint(){this.keepLive&&typeof document<"u"&&document.hidden&&this.renderer?.forceDraw()}activityColor(e){return e==="held"?A.held:e==="booked"?A.booked:e==="blocked"?A.blocked:A.free}sectionsForLabels(e){let t=new Set;for(let i of e){let o=this.labelToSeat.get(i);if(!o)continue;let n=this.sectionByObject.get(o.rowId);n&&n!==S&&t.add(n)}let s=[...t];return{ids:s,labels:s.map(i=>this.sectionLabelById.get(i)??i)}}pulseSeatLabels(e,t){let s=this.activityColor(t);for(let i of e.slice(0,Bt)){let o=this.labelToId.get(i);o&&this.renderer?.flashSeat(o,s)}}paintSpatialActivity(e){let t=e.sectionIds??this.sectionsForLabels(e.labels).ids,s=this.renderer?.getFocusedSection()??null;if(this.followLive&&t.length===1&&(e.status==="held"||e.status==="booked")){let o=this.root?.querySelector('[data-ref="followstatus"]');o&&(o.textContent=`Following ${e.labels.length===1?this.labelNames.get(e.labels[0])??e.labels[0]:`${e.labels.length} seats`} \xB7 ${e.status}`),this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.followLiveTimer=setTimeout(()=>{this.followLiveTimer=null,this.focusActivitySeats(e.labels,t[0]),this.followSeatTimer=setTimeout(()=>{this.followSeatTimer=null,this.pulseSeatLabels(e.labels,e.status)},520)},220);return}if(!s&&t.length){let o=this.activityColor(e.status);for(let n of t.slice(0,$t))this.renderer?.flashSection(n,o);return}(!t.length||s&&t.includes(s))&&this.pulseSeatLabels(e.labels,e.status)}locateSection(e){this.renderer?.focusSection(e)}focusActivitySeats(e,t){this.renderer?.focusSection(t);let s=e.slice(0,Bt).map(l=>this.labelToSeat.get(l)).filter(l=>!!l);if(!s.length)return;let i=s.map(l=>l.x),o=s.map(l=>l.y),n=Math.min(...i),a=Math.min(...o);this.renderer?.focusRegion({x:n-150,y:a-100,width:Math.max(...i)-n+300,height:Math.max(...o)-a+200})}locateActivity(e){let t=this.feed.find(i=>i.id===e);if(!t)return;let s=t.sectionIds??this.sectionsForLabels(t.labels).ids;if(this.followSeatTimer&&clearTimeout(this.followSeatTimer),s.length===1){this.focusActivitySeats(t.labels,s[0]),this.followSeatTimer=setTimeout(()=>{this.followSeatTimer=null,this.pulseSeatLabels(t.labels,t.status)},520);return}this.zoomToFit(),this.followSeatTimer=setTimeout(()=>{if(this.followSeatTimer=null,s.length){let i=this.activityColor(t.status);for(let o of s.slice(0,$t))this.renderer?.flashSection(o,i)}else this.pulseSeatLabels(t.labels,t.status)},280)}showLiveEvent(e){let t=this.els.liveevent;if(!t)return;let s=e.sectionLabels??[],i=s.length===1?s[0]:s.length>1?`${s.length} sections`:this.labelNames.get(e.label)??e.label,o=e.count===1?"seat":"seats";t.innerHTML=`<span class="slm-liveeventdot" style="background:${this.activityColor(e.status)}"></span>
621
+ </details>`}function Rt(r,e,t){let s=te(),i=!1;r.querySelectorAll("[data-view]").forEach(n=>{let a=n.dataset.view,l=e[a];n.setAttribute("aria-checked",String(l)),n.classList.toggle("on",l),l!==s[a]&&(i=!0)}),r.querySelector("summary")?.classList.toggle("away",i);let o=r.querySelector('[data-ref="viewnote"]');o&&(o.hidden=!t.momentumLoading,o.textContent=t.momentumLoading?"Booking momentum: loading the first snapshot\u2026":"")}import{UNGROUPED_ID as ws}from"@seatlayer/core";function fe(r){return Object.entries(r).filter(([,e])=>e.mode==="closed").map(([e])=>e)}function ge(r){let e=r.sectionsBase;if(!e)return{rows:[],hiddenSections:0,closedSections:0};let t=r.doc?.zones??[],s=new Map,i=[];for(let c of e.sections)if(c.zone&&t.some(d=>d.id===c.zone)){let d=s.get(c.zone)??[];d.push(c),s.set(c.zone,d)}else i.push(c);let o=[],n=0,a=0,l=(c,d,h,u=!1,b)=>{let p=r.availabilityRules[d.id]??null,m=r.effectiveClosed.has(d.id)||u,v=r.effectiveHidden.has(d.id)||h&&!m;c==="section"&&v&&(n+=1),c==="section"&&m&&(a+=1),o.push({kind:c,id:d.id,label:d.label,seatCount:d.seatCount,seatLabels:d.seatLabels,rule:p,hidden:v,closed:m,followsZone:c==="section"&&h,...b?{zoneId:b}:{}})};for(let c of t){let d=s.get(c.id);if(!d||!d.length)continue;let h={id:c.id,label:c.label||"Zone",seatCount:d.reduce((p,m)=>p+m.seatCount,0),seatLabels:d.flatMap(p=>p.seatLabels)},u=!!r.availabilityRules[c.id],b=r.availabilityRules[c.id]?.mode==="closed";l("zone",h,!1);for(let p of d)l("section",p,u,b,c.id)}for(let c of i)l("section",c,!1);if(e.ungrouped){let c=e.ungrouped;l("section",{id:ws,label:c.label,seatCount:c.seatCount,seatLabels:c.seatLabels},!1)}return{rows:o,hiddenSections:n,closedSections:a}}var $s="https://api.seatlayer.io",ie=200,Bt=16,$t=4,It=[{key:"watch",label:"Watch",tools:[{mode:"view",label:"Watch",shortcut:"M",title:"See what is selling, where buyers are, and answer questions about any seat."}]},{key:"manage",label:"Manage",tools:[{mode:"reserve",label:"Reserve",shortcut:"R",title:"Keep seats aside under a name (guests, press, comps) until you release them or the time runs out."},{mode:"block",label:"Block",shortcut:"B",title:"Take seats off sale for this event, or put them back."},{mode:"categories",label:"Ticket types",shortcut:"G",title:"Change which ticket type seats sell as, for this event only."},{mode:"sections",label:"Sections",shortcut:"S",title:"Open, close or hide sections for this event, on a schedule or on demand."},{mode:"tables",label:"Tables",shortcut:"T",title:"Sell each table per chair or as one whole-table booking."},{mode:"channels",label:"Channels",shortcut:"C",title:"Allocate inventory to sales channels and share their links."}]},{key:"host",label:"Host tools",tools:[{mode:"select",label:"Select",shortcut:"X",title:"Select seats for your own back-office operation. The selection is handed to your app; nothing changes here."},{mode:"filterSections",label:"Filter",shortcut:"L",title:"Filter the map to one section for your own reporting."}]}],Hs=new Set(["select","block","reserve","categories","channels"]),Is=3;function ve(r){return r==="resale"?"booked":r==="held"||r==="booked"||r==="blocked"?r:"free"}function Os(r){let e=r?.status;return e===401||e===403}var Ht=r=>`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${r}</svg>`,ye={enter:Ht('<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/>'),exit:Ht('<path d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5"/>')},Ps=Object.fromEntries(It.flatMap(r=>r.tools.map(e=>[e.shortcut.toLowerCase(),e.mode]))),w=r=>`${r.toLocaleString()} ${r===1?"seat":"seats"}`,q=r=>C(r,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}),ke=class{constructor(e){this.els={};this.renderer=null;this.doc=null;this.selectObserver=null;this.seatHistoryPanel=null;this.changes=null;this.changesLoading=null;this.feedFilter="all";this.saved=null;this.savedCount=null;this.savedApplied=null;this.arrival=[];this.activityPanel=null;this.navigation=null;this.movingMap=!1;this.marqueeShape="box";this.hintUntil=0;this.socketSnapshotSeen=!1;this.monitorRefreshTimer=null;this.themeMode=null;this.colorSchemeStop=null;this.inventoryModelVersion=1;this.selectableObjectLabels=new Set;this.unavailableLabels=new Set;this.lastSelectionLabels=new Set;this.selBack=[];this.selAhead=[];this.channelsReturn=null;this.selRestoring=!1;this.selectionWasValid=null;this.initialSelectionApplied=!1;this.labelToId=new Map;this.idToLabel=new Map;this.labelToSeat=new Map;this.allIds=[];this.gaUnitLabelSet=new Set;this.tableChairIds=new Map;this.labelNames=new Map;this.status=new Map;this.counts={held:0,booked:0,blocked:0};this.modelSynced=!1;this.controlRoomSettled=!1;this.currency="USD";this.authoritativeCurrency=null;this.authoritativeGrossRevenue=0;this.revenueStatus="loading";this.revenueRequest=0;this.controlRoomSnapshot=null;this.serverBaseline=null;this.reservationsLoaded=!1;this.livePresence=null;this.liveGross=null;this.paintHandle=null;this.trendWindowMinutes=15;this.heatEnabled=!1;this.mapView=te();this.categoryChoice=null;this.lastSectionTap=null;this.press=null;this.lastPick=null;this.categoryBusy=!1;this.categoryDone=null;this.categoryFailed=!1;this.categoryUndoing=!1;this.lockedTypes=null;this.selJustSold=new Set;this.selLeft=null;this.reconcilingSel=!1;this.selWhole=!1;this.blockBusy=!1;this.panelAlert=null;this.categoryTotalsCache=null;this.rowLabelCache=null;this.colourChoices={};this.extras=null;this.reserve=null;this.alerts=null;this.sectionsPanel=null;this.tablesPanel=null;this.findBlocked=null;this.reservedBy=new Map;this.reserving=new Set;this.reservationWheres=new Map;this.reservedIds=new Set;this.pricedIds=[];this.reservationsTimer=null;this.blockGroups=null;this.eventStartsAt=null;this.search=null;this.searchSeatList=null;this.minimap=null;this.lastKpiValues=new Map;this.activeKpiDeltas=new Map;this.ws=null;this.reconnectTimer=null;this.pingTimer=null;this.pongTimer=null;this.attempt=0;this.closed=!1;this.connectionStatus="reconnecting";this.lastMessageAt=null;this.ready=!1;this.feed=[];this.feedTimer=null;this.toastTimer=null;this.liveEventTimer=null;this.kpiCleanupTimer=null;this.followLiveTimer=null;this.followSeatTimer=null;this.releaseAt=null;this.blockEnd="never";this.blockDone=null;this.blockFailedNow=!1;this.blockDenied=!1;this.layoutObserver=null;this.chromeClearance=-1;this.chromeClearanceWidth=-1;this.legendInset="";this.tokenExpiresAt=null;this.tokenRefreshTimer=null;this.tokenRefreshInFlight=!1;this.tokenRefreshFailures=0;this.sessionEnded=!1;this.taskGroups=[];this.taskMenuOpen=!1;this.detents=new Map;this.linkState="live";this.linkTimers=null;this.everLive=!1;this.announcedRoomState=null;this.sectionByObject=new Map;this.sectionLabelById=new Map;this.sectionsBase=null;this.filteredSectionLabel=null;this.availabilityRules={};this.effectiveHidden=new Set;this.effectiveClosed=new Set;this.blockCaptions=new Map;this.captionsOn=!1;this.lastSyncedAt=null;this.blockBrowse=!1;this.channels=null;this.chooser=null;this.chooserDialog=null;this.extrasReady=null;this.categoryDifferences=null;this.channelCaps={view:!1,manage:!1};this.categoryCanManage=!1;this.tableCanManage=!1;this.tableBookingSaving=!1;this.channelCapabilityResolution=0;this.channelsLoading=null;this.onFullscreenChange=()=>{this.paintFullscreenButton(),this.paintFullscreenLine(),this.updateContainerLayout(),this.renderer?.forceDraw()};this.onKeyDown=e=>{if((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()==="k"){e.preventDefault(),this.openSearch();return}let s=!!e.target?.closest('input,select,textarea,[contenteditable="true"]');if((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()==="z"){!s&&this.stepSelection(e.shiftKey?1:-1)&&e.preventDefault();return}if(e.metaKey||e.ctrlKey||e.altKey||s)return;let i=e.key.toLowerCase();if(/^[1-9]$/.test(i)){let a=this.taskGroups.flatMap(l=>l.tools)[Number(i)-1];a&&(this.setMode(a.mode),e.preventDefault());return}if((i==="l"||i==="v")&&!e.shiftKey&&this.isBulkSelectMode()){this.navigation?.choose(i==="l"?"lasso":"select"),e.preventDefault();return}let o=e.shiftKey?St(i):null;if(o){this.toggleMapView(o),e.preventDefault();return}if(i==="/"){e.preventDefault(),this.openSearch();return}let n=Ps[i];if(n){if(!this.toolAvailable(n))return;this.setMode(n)}else if(i==="f")this.toggleFullscreen();else if(i==="escape"){let a=this.els.view;if(a?.open)a.open=!1,a.querySelector("summary")?.focus();else if(this.litChip)this.onLegendChip(this.litChip,!1);else if(this.taskMenuOpen)this.taskMenuOpen=!1,this.paintTaskPicker(),this.els.taskpick?.querySelector("[data-taskpick]")?.focus();else if(!this.channels?.handleBack())if(this.isSheet()&&this.sheetDetent()==="full")this.setDetent("half");else if(this.getSelection().length)this.clearSelection();else return}else return;e.preventDefault()};this.onSelectAllKey=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.key.toLowerCase()!=="a"||e.target?.closest('input,select,textarea,[contenteditable="true"]')||(e.preventDefault(),e.stopPropagation(),this.isBulkSelectMode()?this.selectInView():this.mode==="select"&&this.selectAll())};this.onHowClick=e=>{let t=e.target?.closest("[data-how]")?.dataset.how;if(!t)return;let i=t==="current"?{view:"watch",reserve:"reserve",block:"block",categories:"types",sections:"sections",tables:"tables",channels:"channels"}[this.mode]??"watch":t;this.loadExtras().then(o=>{this.closed||!this.root||o.openExplainer({root:this.root,plate:x,touch:D(),guideUrl:"https://docs.seatlayer.io/platform/embedded-control-room/#operator-modes",tryIt:n=>{let a={watch:"view",reserve:"reserve",block:"block",types:"categories",sections:"sections",tables:"tables",channels:"channels"};n==="search"?this.openSearch():n==="colours"?this.root?.querySelector('[data-ref="colourby"]')?.click():a[n]&&a[n]!==this.mode&&this.toolAvailable(a[n])&&this.setMode(a[n])}},i)}).catch(o=>this.opts.onError?.(o))};this.onRailClick=e=>{let t=e.target,s=t?.closest("[data-section-focus]");if(s?.dataset.sectionFocus){this.locateSection(s.dataset.sectionFocus);return}let i=t?.closest("[data-feed-id]");i?.dataset.feedId&&this.locateActivity(i.dataset.feedId),t?.closest("[data-sel-clear]")&&this.clearSelection(),t?.closest("[data-sel-undo]")&&this.stepSelection(-1),t?.closest("[data-sel-save]")&&this.ensureSaved().then(n=>n?.openSave());let o=t?.closest("[data-sel-similar]");o&&this.openSimilar(o),t?.closest("[data-saved-list], [data-saved-open]")&&this.ensureSaved().then(n=>n?.openList())};this.priceMode=!1;this.priceShadesOn="";this.bandIndex=null;this.typeKeyBySection=null;this.typeKeyBase=null;this.legendSeats=null;this.litChip=null;this.chipPicked=null;this.shownObjects=null;this.barNeed=[0,0,0];this.sectionOptions=[];this.addByPinned=!1;ae(e.token),this.assertSelectionOptions(e.maxSelectedObjects,e.numberOfPlacesToSelect),this.opts=e,this.key=e.eventKey,this.mode=e.mode??"view",this.selectableObjectLabels=new Set(e.selectableObjects??[]),this.unavailableLabels=new Set(e.unavailableObjects??[]),this.categoryCanManage=new Set(e.capabilities??[]).has("event:categories:manage"),this.tableCanManage=new Set(e.capabilities??[]).has("event:tables:manage"),this.keepLive=e.keepLiveWhileHidden??!0,Re(e.timeZone),this.themeMode=e.themeMode??null,this.followLive=e.followLive??!1,this.currency=e.currency??"USD",this.tokenExpiresAt=e.tokenExpiresAt??null,this.api=new re(e.apiBase??$s,e.token),this.organizerAssetUrls=new J(this.key,(t,s)=>this.withAuthRetry(()=>this.api.asset(t,s))),this.host=Ae(e.container)}selectInView(){let e=this.renderer?.getVisibleWorldRect?.();if(!e)return;let t=[...this.labelToSeat.values()].filter(s=>s.x>=e.x&&s.x<=e.x+e.width&&s.y>=e.y&&s.y<=e.y+e.height);this.renderer?.selectByLabels(t.map(s=>s.label)),this.syncSelection(),this.selWhole=t.length===this.labelToSeat.size&&this.getSelection().length>0,this.selWhole&&this.syncSelection()}assertSelectionOptions(e,t){let s=i=>i===void 0||Number.isInteger(i)&&i>0;if(!s(e))throw new TypeError("maxSelectedObjects must be a positive integer");if(!s(t))throw new TypeError("numberOfPlacesToSelect must be a positive integer");if(e!==void 0&&t!==void 0&&e<t)throw new TypeError("maxSelectedObjects cannot be lower than numberOfPlacesToSelect")}async render(){return Qe(),this.buildChrome(),await this.load(),this}async load(){try{let e=await this.withAuthRetry(()=>this.api.chart(this.key));this.inventoryModelVersion=e.event.inventoryModelVersion===2?2:1,this.eventStartsAt=e.event.startsAt??null,this.doc=await this.organizerAssetUrls.prepareRendererChart(e.doc),this.authoritativeCurrency=e.event.currency??null,this.currency=this.authoritativeCurrency??this.opts.currency??this.currency,this.buildUnitUniverse(this.doc),this.buildRenderer(),this.buildSectionOptions(),this.settleMode();let[,t]=await Promise.all([this.resnapshot(),this.refreshControlRoom().catch(s=>this.opts.onError?.(s)),this.refreshAvailability()]);t?.activity?this.seedFeed(t.activity):this.api.log(this.key,{limit:24}).then(s=>{this.adoptLabelNames(s.displayLabels),this.seedFeed(s.entries)}).catch(()=>{}),this.connect(),this.startFeedClock(),this.ready=!0,await this.resolveChannelCapabilities(),this.setMode(this.mode),this.root?.querySelector('[data-ref="opening"]')?.remove(),this.applyInitialSelection(),this.scheduleTokenRefresh(),this.opts.onReady?.(),this.mountAlerts(),this.ensureSaved().then(s=>s?.refresh()),this.withExtras(()=>{}),(this.opts.focusSection||this.opts.focusSeat||this.opts.focusSeats?.length||this.opts.focusCategory||this.opts.arrivedFrom||this.opts.onOpenTrend&&this.opts.kpis!==!1)&&this.mountArrival()}catch(e){this.fail(e)}}setMode(e){e==="inspect"&&(e="view"),this.toolAvailable(e)||(e="view"),e==="channels"&&!this.channels&&this.ensureChannels();let t=e!==this.mode,s=this.mode==="channels",i=this.mode==="filterSections";this.mode=e,t&&e!=="view"&&this.setFollowLive(!1),t&&this.navigation?.resetTool(),!this.renderer&&this.doc?this.buildRenderer():this.updateRendererInteraction(),t&&(this.renderer?.clearSelection(),this.syncSelection(),this.selBack=[],this.selAhead=[],this.navigation?.historyChanged(!1,!1)),t&&e==="channels"&&(this.channelsReturn=this.mapReturnPoint()),s&&e!=="channels"&&(this.channels?.leave(),this.restoreMapReturn()),t&&(this.litChip=null,this.highlightLabels(null),this.wireBarFind()),this.paintModeTabs(),t&&this.setColourBy(this.colourChoices[e]??this.startingColourBy(e),!1);let o=!t&&(e==="tables"?this.tablesPanel:e==="sections"?this.sectionsPanel:null);o?o.update():this.paintRail(),this.applyDetent(),this.paintMapViewMenu(),this.applyMapView(),this.applySectionCanvasTreatment(),i&&e!=="filterSections"&&this.renderer?.zoomToFit(),e==="channels"&&this.channels?.enter(),e==="select"&&this.applyInitialSelection(),t&&this.opts.onModeChange?.(e)}async resolveChannelCapabilities(){let e=++this.channelCapabilityResolution,t=this.opts.capabilities,s;if(t){let i=new Set(t);s={view:i.has("event:channels:view"),manage:i.has("event:channels:view")&&i.has("event:channels:manage")}}else s={view:!1,manage:!1};if(!s.view&&!t)try{await this.api.channels(this.key),s={view:!0,manage:!1}}catch{s={view:!1,manage:!1}}if(e===this.channelCapabilityResolution){if(this.channelCaps=s,!this.channelCaps.view){this.channels?.destroy(),this.channels=null,this.mode==="channels"?this.setMode("view"):this.paintModeTabs();return}this.channels?.setCapabilities(this.channelCaps),this.paintModeTabs()}}ensureChannels(){if(this.channelsLoading)return this.channelsLoading;if(this.channels)return Promise.resolve();let e=(async()=>{try{let t=await import("./channelsMode-W5KNSQSJ.js");if(this.closed||!this.channelCaps.view||(this.channels||(et(t.CHANNELS_CSS),this.channels=new t.ChannelsMode(this.buildChannelsHost(),this.channelCaps),this.channels.onInteractionChange=()=>this.updateRendererInteraction()),this.mode!=="channels"))return;this.updateRendererInteraction(),this.paintRail(),this.channels.enter(),this.setColourBy(this.colourChoices.channels??this.startingColourBy("channels"),!1)}catch(t){if(this.closed)return;this.channelsLoading=null,this.mode==="channels"&&this.paintRail(),this.opts.onError?.(t)}})();return this.channelsLoading=e,e}buildChooserHost(){let e=s=>{let i=this.labelToSeat.get(s);return i?this.mode==="block"?this.isBlockSelectable(s):this.mode==="reserve"?this.isReserveSelectable(s):this.mode==="select"?this.canSelectObject(i):!0:!1};return{selectionLabels:()=>this.selectionLabels(),selectByLabels:s=>{this.selectByLabels(s)},clearSelection:()=>this.clearSelection(),selectSection:s=>{this.selectSection(s)},sections:()=>this.sectionOptions,sectionInfo:s=>{let i=this.filterableSections().find(n=>n.id===s),o=this.sectionTypeKeys().get(s);return{total:i?.seatCount??0,color:this.doc?.categories.find(n=>n.key===o)?.color}},labelsInSection:s=>(this.renderer?.getSelectableInSection(s)??[]).map(i=>i.label).filter(e),rows:()=>{let s=new Map((this.doc?.objects??[]).map(o=>[o.id,o])),i=new Map;for(let o of this.labelToSeat.values()){let n=s.get(o.rowId);if(!n||n.type!=="row"&&n.type!=="table")continue;let a=o.logicalRowId??o.rowId,l=this.sectionByObject.get(o.rowId)??S,c=i.get(a)??{id:a,label:n.type==="row"?n.segmentedRow?.displayLabel??n.displayLabel??n.label:n.displayLabel??n.label,sectionId:l,sectionLabel:this.sectionLabelById.get(l)??"Other seats",labels:[],all:[]};c.all.push(o.label),e(o.label)&&c.labels.push(o.label),i.set(a,c)}return[...i.values()].sort((o,n)=>o.sectionLabel.localeCompare(n.sectionLabel,void 0,{numeric:!0,sensitivity:"base"})||o.label.localeCompare(n.label,void 0,{numeric:!0,sensitivity:"base"}))},categories:()=>(this.doc?.categories??[]).map(s=>({key:s.key,label:s.label??s.key,color:s.color,total:this.categoryTotals().get(s.key)??0})),labelsInCategory:s=>[...this.labelToSeat.values()].filter(i=>i.categoryKey===s&&e(i.label)).map(i=>i.label),seats:()=>[...this.labelToSeat.values()].filter(s=>e(s.label)).map(s=>({label:s.label})),statusOf:s=>this.status.get(s)??(this.labelToSeat.has(s)?"free":void 0),sectionOfLabel:s=>{let i=this.labelToSeat.get(s);if(!i)return null;let o=this.sectionByObject.get(i.rowId)??S;return{id:o,label:this.sectionLabelById.get(o)??"Other seats"}},openDialog:(s,i)=>{let o=n=>{this.chooserDialog=n.openManagerDialog(this.root,s,i,{previous:this.chooserDialog,onClose:()=>{this.chooserDialog=null}})};this.extrasReady?o(this.extrasReady):this.withExtras(o)},closeDialog:()=>this.chooserDialog?.close(),enhanceDialog:s=>this.withExtras(i=>i.pickerKeys(s)),pickers:()=>this.extrasReady??this.loadExtras().then(s=>this.extrasReady=s),pickerFailed:s=>this.pickerFailed(s),highlight:s=>this.highlightLabels(s),...this.mode==="select"?{cap:this.selectionCap()}:{}}}wireBarFind(){let e=this.els.findbar;!e||e.dataset.wired||(e.dataset.wired="1",e.innerHTML=`<button type="button" class="slm-findtrigger" aria-keyshortcuts="Meta+K Control+K"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#4c6fff" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l4.5 4.5"/></svg><span>Seat, row or booking</span>${le()}</button>`,e.querySelector("button").addEventListener("click",()=>{this.openSearch()}))}async loadExtras(){if(!this.extras){let t=typeof __SEATLAYER_CDN__<"u"&&__SEATLAYER_CDN__?Bs("seatlayer-manager-extras.mjs"):import("./managerExtras-CHNB5GFR.js");this.extras=t.catch(s=>{throw this.extras=null,s})}let e=await this.extras;return tt(e.EXTRAS_CSS),e}withExtras(e){this.loadExtras().then(t=>{this.extrasReady=t,this.closed||e(t)},()=>{})}pickerFailed(e){this.toast("Couldn't open that list. Check the connection.","err",{label:"Try again",run:e})}async openSearch(e=""){try{let t=await this.loadExtras();if(this.closed||!this.root)return;this.search?.close(),this.search=t.openEventSearch({root:this.root,touch:D(),seats:()=>this.searchSeats(),statusOf:s=>this.status.get(s)??"free",describe:s=>{let i=this.doc?.categories.find(o=>o.key===this.labelToSeat.get(s)?.categoryKey);return i?`${i.label}${typeof i.price=="number"?` ${M(i.price,this.currency)}`:""}`:""},canSelect:()=>this.isChoosingTool(),show:s=>this.showLabels(s),select:s=>{this.selectByLabels(s)},lookupOrders:this.canReadOrders()?s=>this.api.lookupOrders(this.key,s):void 0,lookupSeats:this.canReadOrders()?s=>this.api.eventRequest(this.key,`seats/lookup?q=${encodeURIComponent(s)}`):void 0,openOrder:this.opts.onOpenOrder?s=>this.opts.onOpenOrder(s):void 0,blockReasons:()=>this.blockGroups?new Set(this.blockGroups.groups.map(s=>s.reason??"")).size:null,blockedBy:s=>{let i=s.trim().toLowerCase();return i.length<3?[]:(this.blockGroups?.groups??[]).filter(o=>o.reason&&o.reason.toLowerCase().includes(i)).map(o=>({reason:o.reason,labels:o.labels}))},saved:()=>this.saved?.rows()??null,useSaved:(s,i)=>{this.saved?.use(s,i)},reserved:()=>{!this.blockGroups&&this.toolAvailable("block")&&this.loadBlockGroups().catch(()=>{});let s=[...this.reservedBy.keys()].filter(i=>this.status.get(i)==="blocked");return{labels:s,count:new Set(s.map(i=>this.reservedBy.get(i).id)).size}},recents:{read:()=>{try{return JSON.parse(localStorage.getItem(`seatlayer.controlRoom.search.${this.key}`)??"[]")}catch{return[]}},write:s=>{try{localStorage.setItem(`seatlayer.controlRoom.search.${this.key}`,JSON.stringify(s))}catch{}}}},e)}catch(t){this.toastErr("Search could not load. Check the connection and try again."),this.opts.onError?.(t)}}canReadOrders(){return this.opts.capabilities?.includes("event:orders:read")===!0}searchSeats(){if(this.searchSeatList?.base===this.sectionsBase)return this.searchSeatList.seats;let e=new Map;for(let s of this.doc?.objects??[])s.type==="row"?e.set(s.id,s.segmentedRow?.displayLabel??s.displayLabel):s.type==="table"&&e.set(s.id,s.displayLabel);let t=[];for(let s of this.labelToSeat.values()){let i=this.sectionByObject.get(s.rowId)??S;t.push({label:s.label,sectionId:i,sectionLabel:this.sectionLabelById.get(i)??"Other seats",rowKey:s.logicalRowId??s.rowId,rowDisplay:e.get(s.rowId)})}return this.searchSeatList={base:this.sectionsBase,seats:t},t}isChoosingTool(){return this.isBulkSelectMode()||this.mode==="select"}frameLabels(e){let t=e.map(s=>this.labelToSeat.get(s)?.id).filter(s=>!!s);t.length&&(this.setFollowLive(!1),this.renderer?.focusSeats?.(t,{animate:!0}))}highlightLabels(e){if(!e){this.renderer?.setSeatHighlight?.(null);return}this.renderer?.setSeatHighlight?.(e.map(t=>this.labelToSeat.get(t)?.id).filter(t=>!!t))}toolChooser(){return this.chooserDialog?.close({restoreFocus:!1}),this.chooser=new ze(this.buildChooserHost()),this.chooser}toolSelectionBar(e,t,s,i){return Fe({count:0,noun:"selected",breakdown:`<span class="slm-selactions"><button type="button" class="slm-linkbtn" data-ref="${i}">Select all</button></span>`,clearAttr:`data-ref="${s}"`}).replace('class="slm-selnum"',`class="slm-selnum" data-ref="${e}"`).replace('class="slm-sellabel"',`class="slm-sellabel" data-ref="${t}"`)}buildChannelsHost(){return{moved:e=>this.recordChange({kind:"channel",...e}),channelsChanged:()=>{this.getColourBy()==="channel"&&this.paintColourLegend()},eventKey:this.key,api:this.api,rail:this.els.rail,pickers:()=>this.extrasReady??this.loadExtras().then(e=>this.extrasReady=e),pickerFailed:e=>this.pickerFailed(e),enhanceDialog:e=>this.withExtras(t=>t.pickerKeys(e)),mapLayer:this.root.querySelector(".slm-map"),pillLane:this.els.lane,root:this.root,seats:()=>[...this.labelToSeat.values()].map(e=>({id:e.id,label:e.label,x:e.x,y:e.y})),statusOf:e=>this.status.get(e)??(this.labelToSeat.has(e)?"free":void 0),selectionLabels:()=>this.selectionLabels(),selectByLabels:e=>{this.selectByLabels(e)},clearSelection:()=>this.clearSelection(),selectSection:e=>{this.selectSection(e)},sections:()=>this.sectionOptions,labelsInSection:e=>this.renderer?.getSelectableInSection(e).map(t=>t.label)??[],rows:()=>{let e=new Map((this.doc?.objects??[]).map(s=>[s.id,s])),t=new Map;for(let s of this.labelToSeat.values()){let i=e.get(s.rowId);if(!i||i.type!=="row"&&i.type!=="table")continue;let o=s.logicalRowId??s.rowId,n=this.sectionByObject.get(s.rowId)??S,a=t.get(o)??{id:o,label:i.type==="row"?i.segmentedRow?.displayLabel??i.displayLabel??i.label:i.displayLabel??i.label,sectionId:n,sectionLabel:this.sectionLabelById.get(n)??"Other seats",labels:[]};a.labels.push(s.label),t.set(o,a)}return[...t.values()].sort((s,i)=>s.sectionLabel.localeCompare(i.sectionLabel,void 0,{numeric:!0,sensitivity:"base"})||s.label.localeCompare(i.label,void 0,{numeric:!0,sensitivity:"base"}))},categories:()=>(this.doc?.categories??[]).map(e=>({key:e.key,label:e.label??e.key,color:e.color,price:e.price,tiers:e.tiers?.map(t=>({id:t.id,name:t.name,price:t.price}))})),labelsInCategory:e=>[...this.labelToSeat.entries()].filter(([,t])=>t.categoryKey===e).map(([t])=>t),sectionOfLabel:e=>{let t=this.labelToSeat.get(e);if(!t)return null;let s=this.sectionByObject.get(t.rowId)??S;return{id:s,label:this.sectionLabelById.get(s)??"Other seats"}},worldToScreen:e=>this.renderer?.worldToScreen(e)??null,seatPixelSize:()=>this.seatPixelSize(),isSeatDetail:()=>this.renderer?.getRung?.()==="seats",showSectionOverview:()=>{this.renderer?.clearSectionFocus(),this.renderer?.setRung?.("sections")},focusSection:e=>this.renderer?.focusSection(e),isCompact:()=>!!this.root?.classList.contains("compact"),setMapInert:e=>{this.mapHost.toggleAttribute("inert",e),this.mapHost.setAttribute("aria-hidden",String(e))},toast:(e,t)=>this.toast(e,t),onError:e=>this.opts.onError?.(e)}}seatPixelSize(){let e=this.renderer?.getVisibleWorldRect?.(),t=this.mapHost?.clientWidth??0;return!e?.width||!t?6:Math.max(3,t/e.width*18)}setHeatOverlay(e){this.heatEnabled=e,this.mapView.momentum!==e&&this.setMapView({momentum:e}),this.applyHeatOverlay(),this.paintHeatButton()}setMapView(e){let t={...this.mapView,...e};if(!Object.keys(t).some(o=>t[o]!==this.mapView[o]))return;let i=t.categoryColours!==this.mapView.categoryColours||t.channelColours!==this.mapView.channelColours;this.mapView=t,Tt(t),t.momentum!==this.heatEnabled&&this.setHeatOverlay(t.momentum),this.applyMapView(),this.paintMapViewMenu(),i&&(this.refreshBlockPaint(),this.paintMapChrome())}getColourBy(){return this.mapView.channelColours&&this.channelColoursAvailable()?"channel":this.mapView.categoryColours?this.priceMode?"price":"type":"status"}setColourBy(e,t=!0){let s=e==="full"||e==="channel"&&!this.channelColoursAvailable()?"status":e;t&&(this.colourChoices={...this.colourChoices,[this.mode]:s},wt(this.colourChoices)),this.litChip&&s!==this.getColourBy()&&(this.litChip=null,this.highlightLabels(null)),this.priceMode=s==="price",this.setMapView({categoryColours:s==="type"||s==="price",channelColours:s==="channel"}),this.applyPriceColours(),this.paintColourLegend()}startingColourBy(e){let t=this.opts.colourBy;return t&&e!=="channels"?t==="full"?"status":t:kt(e)}getMapView(){return{...this.mapView}}toggleMapView(e){if(e==="categoryColours"||e==="channelColours"){let t=e==="categoryColours"?"type":"channel";this.setColourBy(this.getColourBy()===t?"status":t);return}this.setMapView({[e]:!this.mapView[e]})}channelColoursAvailable(){return this.mode==="channels"&&this.channels!=null}applyMapView(){Ct(this.mapView,{renderer:this.renderer,channelsOverlay:e=>this.channels?.setOverlayVisible(e)}),this.applyPriceColours()}applyPriceColours(){let e=this.extrasReady;if(this.priceMode&&!e){this.withExtras(()=>{this.applyPriceColours(),this.paintColourLegend()});return}let t=this.priceMode?e.priceShades(this.typePrices(),this.root?.dataset.theme==="light"):null,s=JSON.stringify(t);!this.renderer||s===this.priceShadesOn||(this.priceShadesOn=s,this.renderer.setCategoryColourOverride?.(t),this.refreshBlockPaint())}typePrices(){let e=this.hoverPriceRanges(),t=new Map;for(let s of this.doc?.categories??[]){let i=e===null?void 0:e?.[s.key]?.min??s.price;typeof i=="number"&&t.set(s.key,i)}return t}paintMapViewMenu(){let e=this.els.view;e&&Rt(e,this.mapView,{momentumLoading:this.mapView.momentum&&!this.controlRoomSnapshot})}setFollowLive(e){let t=this.followLive!==e;this.followLive=e,e||(this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.followLiveTimer=null,this.followSeatTimer=null),this.paintFollowLiveButton(),t&&this.opts.onFollowLiveChange?.(e)}setKeepLiveWhileHidden(e){this.keepLive=e??!0,this.opts.keepLiveWhileHidden=e}setCurrency(e){this.opts.currency=e,!this.authoritativeCurrency&&(this.currency=e??"USD",this.ready&&this.recomputeTallies())}setSale(e){this.opts.sale=e,this.paintFullscreenLine(),this.paintMonitorInsights()}setTheme(e){this.opts.theme=e,this.applyThemeVars()}applyThemeVars(){if(!this.root)return;let e=oe(this.themeMode);for(let[t,s]of Object.entries(Be(this.opts.theme,e)))this.root.style.setProperty(t,s);e?this.root.dataset.theme=e:delete this.root.dataset.theme,this.applyPriceColours()}watchThemeMode(){this.colorSchemeStop?.(),this.colorSchemeStop=null,this.themeMode==="auto"&&(this.colorSchemeStop=Se(()=>{this.closed||this.repaintForThemeMode()}))}repaintForThemeMode(){this.applyThemeVars();let e=this.renderer;if(!e||!this.doc)return;let t=e.getSelection().map(o=>o.id),s=e.getCameraPose(),i=e.getFocusedSection();e.setChart(this.themedDoc()),this.repaintAll(),this.pricedIds=[],this.applyPricedMarks(),this.applyHeatOverlay(),t.length&&e.select(t),i&&e.focusSection(i),e.setCameraPose(s),this.updateZoomHint()}setThemeMode(e){let t=e??null;this.closed||t===this.themeMode||(this.themeMode=t,this.opts.themeMode=t??void 0,this.watchThemeMode(),this.repaintForThemeMode())}getThemeMode(){return this.themeMode}themedDoc(){let e=this.doc,t=$e(oe(this.themeMode));return t?{...e,theme:{...e.theme??{},background:t}}:e}setCapabilities(e){this.opts.capabilities=e,this.categoryCanManage=new Set(e??[]).has("event:categories:manage"),this.tableCanManage=new Set(e??[]).has("event:tables:manage"),this.mode==="categories"&&!this.toolAvailable("categories")||!this.tableCanManage&&this.mode==="tables"?this.setMode("view"):this.mode==="categories"?this.paintRail():this.paintModeTabs(),this.ready&&this.resolveChannelCapabilities()}setTokenRefresh(e){this.opts.onTokenRefresh=e,this.scheduleTokenRefresh()}setTrendWindow(e){let t=Number.isFinite(e)?Math.floor(e):15;return this.trendWindowMinutes=Math.max(5,Math.min(60,t)),this.paintTrendWindow(),this.refreshControlRoom()}async enterFullscreen(){!this.root?.requestFullscreen||this.isFullscreen()||(await this.root.requestFullscreen(),this.root.focus({preventScroll:!0}))}async exitFullscreen(){typeof document>"u"||!this.isFullscreen()||await document.exitFullscreen()}isFullscreen(){return typeof document<"u"&&document.fullscreenElement===this.root}toggleFullscreen(){(this.isFullscreen()?this.exitFullscreen():this.enterFullscreen()).catch(t=>this.opts.onError?.(t))}setToken(e,t){ae(e),this.api.setToken(e),this.opts.token=e,this.opts.tokenExpiresAt=t,this.tokenExpiresAt=t??null,this.scheduleTokenRefresh(),this.ready&&this.resolveChannelCapabilities()}scheduleTokenRefresh(){this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null;let e=this.opts.onTokenRefresh,t=this.tokenExpiresAt;if(this.closed||!e||!t||!Number.isFinite(t))return;let s=t-Date.now(),i=Math.min(12e4,Math.max(3e4,s*.2)),o=Math.max(0,s-i);this.tokenRefreshTimer=setTimeout(()=>{this.tokenRefreshTimer=null,this.rotateToken()},o)}async rotateToken(){if(!(this.closed||this.sessionEnded||this.tokenRefreshInFlight||!this.opts.onTokenRefresh)){this.tokenRefreshInFlight=!0;try{let e=await this.opts.onTokenRefresh();if(!e?.token||!Number.isFinite(e.expiresAt))throw new Error("invalid_token_refresh_result");this.tokenRefreshFailures=0,this.setToken(e.token,e.expiresAt)}catch(e){this.opts.onError?.(e),this.tokenRefreshFailures+=1,!this.closed&&(this.tokenRefreshFailures>=Is||Os(e))?this.endSession():this.closed||(this.tokenRefreshTimer=setTimeout(()=>{this.tokenRefreshTimer=null,this.rotateToken()},3e4))}finally{this.tokenRefreshInFlight=!1}}}endSession(){if(this.sessionEnded)return;this.sessionEnded=!0,this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.monitorRefreshTimer&&clearTimeout(this.monitorRefreshTimer),this.monitorRefreshTimer=null;let e=this.ws;if(this.ws=null,e){e.onclose=null;try{e.close()}catch{}}this.stopKeepalive(),this.setLive(!1),this.paintSessionEnded()}async retrySession(){if(this.closed||!this.sessionEnded)return!this.sessionEnded;if(!this.opts.onTokenRefresh)return!1;this.sessionEnded=!1,this.tokenRefreshFailures=0;let e=this.root?.querySelector('[data-ref="roomcard"]');return e?.setAttribute("data-busy","true"),await this.rotateToken(),this.sessionEnded?(e?.removeAttribute("data-busy"),!1):(e?.remove(),this.attempt=0,this.connect(),!0)}paintSessionEnded(){if(this.root?.querySelector('[data-ref="roomcard"][data-kind="signedout"]'))return;this.showRoomCard("signedout");let e=this.root?.querySelector('[data-ref="roomcard"] p'),t=this.mode==="view"?null:this.taskGroups.flatMap(i=>i.tools).find(i=>i.mode===this.mode)?.label??null,s=this.getSelection().length;e&&this.withExtras(i=>i.nameWorkInHand(e,t,s,this.els.rail??null))}async block(e,t={}){let s=(e??this.selectionLabels()).filter(l=>this.status.get(l)==="free");if(!s.length||this.blockBusy)return;let i=t.releaseAt??this.releaseAt??void 0,o=`${w(s.length)}`;this.setSeatsLocal(s,"blocked"),this.blockBusy=!0,this.panelAlert=null,this.paintSelBar(this.getSelection());let n=this.selectionSummary(s.flatMap(l=>this.labelToSeat.get(l)??[])).where,a=i?`They go back on sale ${q(i)}.`:"They stay off sale until you put them back.";try{await this.api.block(this.key,s,{...t,releaseAt:i}),this.blockBusy=!1,this.blockFailedNow=!1,this.clearSelection(),this.blockDone={labels:s,until:Date.now()+3e4},setTimeout(()=>{!this.closed&&this.mode==="block"&&this.paintSelBar(this.getSelection())},30100),this.panelAlert=B("ok",`${o} blocked${t.reason?` \xB7 ${t.reason}`:""}`,` ${n}. ${a}`),this.paintSelBar(this.getSelection()),this.doneQuietly("block",s,`${o} blocked${t.reason?` \xB7 ${t.reason}`:""}.`),this.recordChange({kind:"block",labels:s,reason:t.reason??null,releaseAt:i??null})}catch(l){this.blockBusy=!1,this.setSeatsLocal(s,"free");let c=l instanceof $&&l.status===409?(l.conflicts??[]).map(h=>h.label).filter(h=>s.includes(h)):[],d=s.filter(h=>!c.includes(h));if(c.length&&d.length){this.renderer?.deselect(c.map(h=>this.labelToId.get(h)).filter(h=>!!h)),this.syncSelection();try{this.setSeatsLocal(d,"blocked"),await this.api.block(this.key,d,{...t,releaseAt:i}),this.blockDone={labels:d,until:Date.now()+3e4,partial:!0},this.panelAlert=B("warn",`${c.length.toLocaleString()} ${c.length===1?"seat was":"seats were"} sold while you chose`,` ${w(d.length)} blocked. ${ce(c)} ${c.length===1?"is":"are"} sold and stay${c.length===1?"s":""} with ${c.length===1?"its buyer":"their buyers"}.`),this.paintSelBar(this.getSelection()),this.paintSelBar(this.getSelection()),this.doneQuietly("block",d,`${d.length.toLocaleString()} blocked.`),this.recordChange({kind:"block",labels:d,reason:t.reason??null,releaseAt:i??null});return}catch(h){this.setSeatsLocal(d,"free"),l=h}}if(this.blockFailedNow=!c.length,l instanceof $&&l.status===403){this.blockFailedNow=!1,this.blockDenied=!0,this.withExtras(h=>this.blockFailed(h.blockRefused(this.opts.organizationName),"info")),this.opts.onError?.(l);return}this.blockFailed(c.length?["Those seats were just taken"," Nothing was blocked. They are sold or in a cart now."]:["Couldn\u2019t block the seats"," The connection dropped before the change was saved. Buyers can still pick them."]),this.opts.onError?.(l)}}async unblock(e){let t=(e??this.selectionLabels()).filter(i=>this.status.get(i)==="blocked");if(!t.length||this.blockBusy)return;let s=this.blockGroups?.groups.find(i=>i.labels.includes(t[0]));this.setSeatsLocal(t,"free"),this.blockBusy=!0,this.panelAlert=null,this.paintSelBar(this.getSelection());try{await this.api.unblock(this.key,t),this.blockBusy=!1,this.clearSelection(),this.doneQuietly("unblock",t,`${t.length.toLocaleString()} ${t.length===1?"seat is":"seats are"} back on sale.`),this.recordChange({kind:"unblock",labels:t,reason:s?.reason??null,releaseAt:s?.releaseAt??null})}catch(i){this.blockBusy=!1,this.setSeatsLocal(t,"blocked"),this.blockFailed(["Couldn\u2019t put the seats back on sale"," They are still blocked. Your selection is kept; try again."]),this.opts.onError?.(i)}}blockFailed([e,t],s="error"){this.mode==="block"&&this.els.rail?.querySelector('[data-ref="blockfoot"]')?(this.panelAlert=B(s,e,t,s==="info"?"lock":void 0),this.paintSelBar(this.getSelection())):this.toastErr(`${e}.${t}`)}async unblockAll(){let e=[...this.status.entries()].filter(([t,s])=>s==="blocked"&&!this.reservedBy.has(t)).map(([t])=>t);if(e.length){this.setSeatsLocal(e,"free");try{let t=await this.api.unblockAll(this.key);this.clearSelection(),this.doneQuietly("unblockAll",e,`Unblocked ${t.freed} seat${t.freed===1?"":"s"}.`),this.recordChange({kind:"unblock",labels:e})}catch(t){await this.resnapshot(),this.toastErr("Couldn't mark everything for sale."),this.opts.onError?.(t)}}}async cancelBooking(e,t){let s=e.filter(i=>this.status.get(i)==="booked");if(!(!s.length||!t)){this.setSeatsLocal(s,"free");try{await this.api.unbook(this.key,s,t),this.clearSelection(),this.doneQuietly("cancelBooking",s,`Released ${s.length} booked unit${s.length===1?"":"s"}.`)}catch(i){this.setSeatsLocal(s,"booked"),this.toastErr("Couldn't release that booked inventory. Check the booking reference."),this.opts.onError?.(i)}}}async setCategory(e,t){let s=this.doc?.categories.find(a=>a.key===e),i=[...new Set(t??this.selectionLabels())].filter(a=>this.labelToSeat.has(a));if(!s||!i.length||this.categoryBusy||!this.categoryCanManage)return;let o=s.label??s.key,n=new Map(i.map(a=>[a,this.labelToSeat.get(a).categoryKey]));this.categoryBusy=!0,this.categoryFailed=!1,this.categoryDone=null,this.panelAlert=null,this.paintCategorySelection(this.getSelection());try{let a=await this.withAuthRetry(()=>this.api.setCategory(this.key,i,e));this.applyCategory(a.labels,e);let l=new Set(a.labels),c=i.filter(d=>!l.has(d));if(this.categoryBusy=!1,c.length){let d=c.every(h=>this.status.get(h)==="booked"||this.status.get(h)==="held");this.panelAlert=this.alertOf((await this.loadExtras()).typesPartly(c,a.labels.length,o,d)),this.reconcilingSel=!0;try{this.renderer?.deselect(c.map(h=>this.labelToId.get(h)).filter(h=>!!h)),this.syncSelection()}finally{this.reconcilingSel=!1}}this.categoryDone={labels:a.labels,name:o,prev:n,until:Date.now()+3e4,partial:c.length>0},setTimeout(()=>{!this.closed&&this.mode==="categories"&&this.paintCategorySelection(this.getSelection())},30100),this.categoryTotalsCache=null,this.paintCategorySelection(this.getSelection()),this.mode==="categories"&&this.loadCategoryDifferences(),this.done("setCategory",a.labels,`${a.labels.length.toLocaleString()} ${a.labels.length===1?"seat now sells":"seats now sell"} as ${o}.`),this.recordChange({kind:"types",labels:a.labels,title:`Changed ${w(a.labels.length)} to ${o}`})}catch(a){this.categoryBusy=!1;let l=await this.loadExtras().catch(()=>null);a instanceof $&&a.status===403?this.categoryCanManage=!1:this.categoryFailed=!0,l&&(this.panelAlert=this.alertOf(this.categoryCanManage?l.TYPES_FAILED:l.typesLocked(this.opts.organizationName))),this.mode==="categories"?this.paintCategorySelection(this.getSelection()):this.toastErr("Couldn\u2019t move the seats. Nothing changed for buyers."),this.opts.onError?.(a)}}applyCategory(e,t){let s={};for(let i of e){let o=this.labelToSeat.get(i),n=this.labelToId.get(i);o&&(o.categoryKey=t),n&&(s[n]=t)}this.categoryTotalsCache=null,this.renderer?.setSeatCategories?.(s)}async undoCategory(){let e=this.categoryDone;if(!(!e||this.categoryBusy)){this.categoryBusy=this.categoryUndoing=!0,this.categoryDone=this.panelAlert=null,this.paintCategorySelection(this.getSelection());try{await(await this.loadExtras()).undoTypes(e.labels,e.prev,async(t,s)=>{this.applyCategory((await this.withAuthRetry(()=>this.api.setCategory(this.key,t,s))).labels,s)}),this.categoryBusy=this.categoryUndoing=!1,this.clearSelection(),this.mode==="categories"&&this.loadCategoryDifferences(),this.done("setCategory",e.labels,`${w(e.labels.length)} back as they were.`),this.recordChange({kind:"types",labels:e.labels,title:`Undid the move of ${w(e.labels.length)} to ${e.name}`})}catch(t){this.categoryBusy=this.categoryUndoing=!1,this.categoryDone={...e,until:Date.now()+3e4},this.paintCategorySelection(this.getSelection()),this.opts.onError?.(t)}}}alertOf(e){return B(e[0],e[1],e[2],e[3])}async setTableBooking(e,t,s={}){if(this.inventoryModelVersion!==2){this.toastErr("Table booking controls require inventory model 2 for this event.");return}let i=await this.saveTableBooking(e,t,s);i==="conflict"?this.toastErr("Release table seats that are in a cart, booked or blocked before changing its booking mode."):i==="failed"&&this.toastErr("Couldn't update table booking. No table mode was changed.")}async saveTableBooking(e,t,s={}){let i=[...new Set(e)].filter(Boolean);if(!i.length||this.tableBookingSaving||this.inventoryModelVersion!==2)return"skipped";this.tableBookingSaving=!0;try{let o=await this.withAuthRetry(()=>this.api.setTableBooking(this.key,i,t,s));return await this.reloadEventChart(),this.doneQuietly("setTableBooking",o.tableIds,`Updated ${o.tableIds.length.toLocaleString()} table${o.tableIds.length===1?"":"s"} to ${t==="individual"?"per-chair":t==="whole"?"whole-table":"flexible-group"} booking.`),this.recordChange({kind:"tables",labels:o.tableIds.map(n=>this.tableInfos().find(a=>a.id===n)?.label??n),title:`${o.tableIds.length===1?"A table now books":`${o.tableIds.length.toLocaleString()} tables now book`} ${t==="individual"?"by the chair":t==="whole"?"as a whole":"as a group"}`}),"ok"}catch(o){return this.opts.onError?.(o),o instanceof $&&o.code==="table_inventory_in_use"?"conflict":"failed"}finally{this.tableBookingSaving=!1}}async reloadEventChart(){let e=await this.withAuthRetry(()=>this.api.chart(this.key));this.inventoryModelVersion=e.event.inventoryModelVersion===2?2:1;let t=await this.organizerAssetUrls.prepareRendererChart(e.doc);this.renderer?.destroy(),this.renderer=null,this.doc=t,this.labelToId.clear(),this.labelToSeat.clear(),this.allIds=[],this.gaUnitLabelSet.clear(),this.tableChairIds.clear(),this.labelNames.clear(),this.status.clear(),this.counts={held:0,booked:0,blocked:0},this.serverBaseline=null,this.modelSynced=!1,this.controlRoomSettled=!1,this.lastSelectionLabels.clear(),this.selBack=[],this.selAhead=[],this.buildUnitUniverse(t),this.buildRenderer(),this.buildSectionOptions(),this.settleMode(),await Promise.all([this.resnapshot(),this.refreshControlRoom().catch(s=>this.opts.onError?.(s)),this.refreshAvailability()]),this.mode==="tables"&&this.tablesPanel?this.tablesPanel.update():this.paintRail()}selectAll(){if(this.mode==="select")return this.selectByLabels([...this.labelToSeat.values()].filter(t=>this.canSelectObject(t)).map(t=>t.label));let e=this.renderer?.selectAllSelectable()??[];return this.syncSelection(),this.selWhole=e.length>0,this.selWhole&&this.syncSelection(),e}applyBand(e,t,s){let i=this.renderer;if(!i?.getSelectableInSection||i.getRung?.()==="seats")return!1;if(this.bandIndex?.base!==this.sectionsBase){let a=new Map,l=new Map;for(let[d,h]of this.labelToSeat){let u=this.sectionByObject.get(h.rowId),b=this.labelToId.get(d);if(!u||!b)continue;a.set(b,u);let p=l.get(u)??{x:0,y:0,n:0};p.x+=h.x,p.y+=h.y,p.n+=1,l.set(u,p)}let c=new Map([...l].map(([d,h])=>[d,{x:h.x/h.n,y:h.y/h.n}]));this.bandIndex={base:this.sectionsBase,sectionOf:a,centre:c}}let o=new Set;for(let a of e){let l=this.bandIndex.sectionOf.get(a);l&&o.add(l)}for(let[a,l]of this.bandIndex.centre)t(l)&&o.add(a);let n=[...o].flatMap(a=>i.getSelectableInSection(a));return s?i.deselect(n.map(a=>a.id)):i.selectByLabels?.(n.map(a=>a.label)),!0}handleSeatDeselect(e){let t=this.press;t&&(t.answered=!0);let s=this.lastPick;t?.shift&&s&&s.rowId===e.rowId&&s.label!==e.label&&this.isBulkSelectMode()?(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()},this.renderer?.selectByLabels(de(this.rowSeats(e.rowId),s.label,e.label))):t&&(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()}),this.syncSelection()}rowSeats(e){return[...this.labelToSeat.values()].filter(t=>t.rowId===e)}wireGestures(e){e.addEventListener("pointerdown",t=>{this.press={shift:t.shiftKey,x:t.clientX,y:t.clientY,answered:!1}},!0),e.addEventListener("click",t=>{let s=this.press;if(!s||s.answered||!this.isBulkSelectMode()||this.renderer?.getRung?.()==="seats"||Math.hypot(t.clientX-s.x,t.clientY-s.y)>5)return;let i=this.renderer,o=e.getBoundingClientRect(),n={x:t.clientX-o.left,y:t.clientY-o.top};if(!i||i.sectionAt?.(n))return;let a=Ne(n,i.getMinimapSnapshot?.().sections??[],l=>i.worldToScreen(l));a&&this.handleSectionTap(a)}),e.addEventListener("dblclick",()=>{let t=this.lastPick;!t||Date.now()-t.at>700||(this.isBulkSelectMode()?(this.renderer?.selectByLabels(this.rowSeats(t.rowId).map(s=>s.label)),this.syncSelection()):this.mode==="view"&&this.showLabels([t.label]))})}handleSectionTap(e){if(this.press&&(this.press.answered=!0),this.mode==="filterSections"){let t=this.filterableSections().find(s=>s.id===e);t&&this.setFilteredSection(t.label);return}if(this.isBulkSelectMode()&&this.renderer?.getRung?.()!=="seats"){let t=Date.now(),s=this.lastSectionTap?.id===e&&t-this.lastSectionTap.at<450;this.lastSectionTap=s?null:{id:e,at:t},s||this.selectSection(e);return}this.renderer?.focusSection(e),this.channels?.handleSectionFocus(e),this.sectionsPanel?.pick(e)}selectSection(e){if(!this.renderer)return[];let t=this.renderer.getSelectableInSection(e);return this.renderer.selectByLabels(t.map(s=>s.label)),this.syncSelection(),this.renderer.getSelection()}setFilteredSection(e){let t=e.trim(),s=this.filterableSections().filter(n=>n.label===t);if(!s.length)throw new Error(`Unknown event section: ${e}`);let i=t!==this.filteredSectionLabel;this.filteredSectionLabel=t,this.mode==="filterSections"&&(this.applyFilteredSectionCanvas(s),this.renderFilterSectionsRail());let o=s.map(({id:n,label:a,seatCount:l,zone:c})=>({id:n,label:a,seatCount:l,...c?{zone:c}:{}}));return i&&this.opts.onFilteredSectionChange?.(o),o}focusSection(e){let t=e.trim(),s=this.filterableSections().filter(i=>i.label===t);return!this.renderer||!s.length?[]:(this.frameSections(s),s.map(({id:i,label:o,seatCount:n,zone:a})=>({id:i,label:o,seatCount:n,...a?{zone:a}:{}})))}clearFilteredSection(){let e=this.filteredSectionLabel!==null;this.filteredSectionLabel=null,this.renderer?.setDimmedSections(null),this.renderer?.clearSectionFocus(),this.renderer?.zoomToFit(),this.mode==="filterSections"&&this.renderFilterSectionsRail(),e&&this.opts.onFilteredSectionChange?.([])}getFilteredSections(){return this.filteredSectionLabel?this.filterableSections().filter(e=>e.label===this.filteredSectionLabel).map(({id:e,label:t,seatCount:s,zone:i})=>({id:e,label:t,seatCount:s,...i?{zone:i}:{}})):[]}selectByLabels(e){let t=e;if(this.mode==="select"){let s=new Set(this.selectionLabels()),i=this.selectionCap(),o=[...new Set(e)].filter(a=>!s.has(a)).map(a=>this.labelToSeat.get(a)).filter(a=>!!a&&this.canSelectObject(a)),n=Math.max(0,i-s.size);o.length>n&&this.opts.onSelectionLimit?.(i),t=o.slice(0,n).map(a=>a.label)}return this.renderer?.selectByLabels(t),this.syncSelection(),this.getSelection()}selectObjects(e){return this.selectByLabels(e)}deselectObjects(e){let t=e.map(s=>this.labelToId.get(s)).filter(s=>!!s);return this.renderer?.deselect(t),this.syncSelection(),this.getSelection()}selectCategories(e){let t=new Set(e);return this.selectByLabels([...this.labelToSeat.values()].filter(s=>t.has(s.categoryKey)).map(s=>s.label))}deselectCategories(e){let t=new Set(e);return this.deselectObjects(this.getSelection().filter(s=>t.has(s.categoryKey)).map(s=>s.label))}setSelectableObjects(e){this.opts.selectableObjects=[...e],this.selectableObjectLabels=new Set(e),this.reconcileSelectPolicy()}setUnavailableObjects(e,t){this.opts.unavailableObjectsReason=t;let s=new Set(e),i=[...s].filter(n=>!this.unavailableLabels.has(n)).concat([...this.unavailableLabels].filter(n=>!s.has(n)));if(!i.length)return;if(this.opts.unavailableObjects=[...s],this.unavailableLabels=s,this.renderer){let n=new Map;for(let a of i){let l=this.paintIds(a);if(!l.length)continue;let c=this.renderStatusOf(a,this.status.get(a)??"free");n.set(c,[...n.get(c)??[],...l])}for(let[a,l]of n)this.renderer.setStatus(l,a);this.afterPaint()}let o=this.getSelection().filter(n=>this.isHostUnavailable(n.label));o.length&&(this.renderer?.deselect(o.map(n=>n.id)),this.syncSelection())}setPricedObjects(e){this.opts.pricedObjects=[...e],this.applyPricedMarks()}applyPricedMarks(){if(!this.renderer)return;let e=(this.opts.pricedObjects??[]).flatMap(s=>this.paintIds(s));if(!e.length&&!this.pricedIds.length)return;if(!this.extrasReady){this.withExtras(()=>this.applyPricedMarks());return}let t=Object.fromEntries(this.pricedIds.map(s=>[s,null]));for(let s of e)t[s]={kind:"priced"};this.pricedIds=e,this.renderer.setSeatMarks(t)}setCategoryPrices(e){this.opts.categoryPrices=e,this.renderer?.setCategoryPriceRanges(this.hoverPriceRanges()),this.applyPriceColours(),this.paintColourLegend()}hoverPriceRanges(){let e=this.opts.categoryPrices;return e==null?e:Object.fromEntries(Object.entries(e).map(([t,s])=>[t,typeof s=="number"?{min:s,max:s}:{min:s.min,max:s.max}]))}setUnavailableObjectsSelectable(e){this.opts.unavailableObjectsSelectable=e,this.reconcileSelectPolicy()}setObjectSelectable(e){this.opts.isObjectSelectable=e,this.reconcileSelectPolicy()}setMaxSelectedObjects(e){this.assertSelectionOptions(e,this.opts.numberOfPlacesToSelect),this.opts.maxSelectedObjects=e,this.trimSelectionToCap(),this.updateRendererInteraction(),this.syncSelection()}setNumberOfPlacesToSelect(e){this.assertSelectionOptions(this.opts.maxSelectedObjects,e),this.opts.numberOfPlacesToSelect=e,this.selectionWasValid=null,this.trimSelectionToCap(),this.updateRendererInteraction(),this.syncSelection()}getSelectionValidity(){let e=this.opts.numberOfPlacesToSelect;if(e===void 0)return null;let t=this.getSelection(),s=t.length;return{isValid:s===e,count:s,required:e,remaining:Math.max(0,e-s),objects:t}}clearSelection(){this.renderer?.clearSelection(),this.syncSelection()}stepSelection(e){let s=(e<0?this.selBack:this.selAhead).pop();if(!s||!this.renderer)return!1;(e<0?this.selAhead:this.selBack).push([...this.lastSelectionLabels]),this.selRestoring=!0;try{this.renderer.clearSelection();let i=s.filter(o=>this.labelToSeat.has(o));i.length&&this.renderer.selectByLabels(i),this.syncSelection()}finally{this.selRestoring=!1}return!0}getSelection(){return this.renderer?.getSelection?.()??[]}getReport(){return this.api.report(this.key).then(e=>(this.applyReportRevenue(e),e))}getControlRoomSnapshot(e=this.trendWindowMinutes){return this.setTrendWindow(e)}getConnection(){return{status:this.connectionStatus,lastMessageAt:this.lastMessageAt,room:this.roomState()}}getLog(e={}){return this.api.log(this.key,e)}async setHoldTtl(e){try{await this.api.setHoldTtl(this.key,e),this.done("setHoldTtl",[],e?`Hold window set to ${Math.round(e/6e4)} min.`:"Hold window reset.")}catch(t){this.toastErr("Couldn't update the hold window."),this.opts.onError?.(t)}}zoomToFit(){if(this.mode==="filterSections"&&this.filteredSectionLabel){this.clearFilteredSection();return}this.renderer?.clearSectionFocus(),this.renderer?.zoomToFit()}mapReturnPoint(){let e=this.renderer;return e?.getVisibleWorldRect?{rect:e.getVisibleWorldRect(),focused:e.getFocusedSection?.()??null,floor:e.getActiveFloorId?.()??"",overview:e.isFloorOverview?.()??!1}:null}restoreMapReturn(){let e=this.channelsReturn;this.channelsReturn=null;let t=this.renderer;if(!t)return;if(t.clearSectionFocus(),!e)return void t.zoomToFit();if(e.overview&&!t.isFloorOverview?.()?t.setFloorOverview?.(!0):!e.overview&&e.floor&&e.floor!==t.getActiveFloorId?.()&&t.setActiveFloor?.(e.floor),e.focused)return void t.focusSection(e.focused);let{x:s,y:i,width:o,height:n}=e.rect,a=o/1.12,l=n/1.12;t.focusRegion({x:s+(o-a)/2,y:i+(n-l)/2,width:a,height:l})}zoomOutStep(){let e=this.renderer;if(!e)return;if(!e.zoomOutLevel)return void e.zoomOut();let t=!!e.getFocusedSection?.();e.zoomOutLevel()==="venue"&&t&&e.clearSectionFocus()}paintMapChrome(){let e=this.renderer;if(!e||!this.els.crumb)return;let t=e.getFocusedSection?.()??null,s=t?e.getMinimapSnapshot?.().sections.find(a=>a.id===t)??null:null,i=e.getFloors?.()??[],o=i.length>1?e.isFloorOverview?.()?"All floors":i.find(a=>a.id===e.getActiveFloorId?.())?.name??null:null,n=e.getRung?.()==="seats";n!==this.legendSeats&&(this.legendSeats=n,this.paintColourLegend()),nt(this.els,it({focused:s?{label:s.label,free:s.free,total:s.total,allBlocked:s.free?void 0:this.sectionKeptAside(s.id)}:null,floor:o,seatsRevealed:e.seatsRevealed?.()??!0,atVenueFit:e.atVenueFit?.(),atCeiling:e.canZoomIn?.()===!1||e.seatsPickable?.()===!0}))}sectionKeptAside(e){let t=this.filterableSections().find(o=>o.id===e);if(!t)return;let s=0,i=0;for(let o of t.seatLabels){let n=this.status.get(o)??"free";if(n==="free"||n==="held")return;n==="blocked"&&(this.reservedBy.has(o)?i++:s++)}return s&&i?"both":i?"reserved":s?"blocked":void 0}sectionTypeKeys(){if(this.typeKeyBySection&&this.typeKeyBase===this.sectionsBase)return this.typeKeyBySection;let e=new Map;for(let t of this.filterableSections()){let s=new Map;for(let o of t.seatLabels){let n=this.labelToSeat.get(o)?.categoryKey;n&&s.set(n,(s.get(n)??0)+1)}let i=null;for(let[o,n]of s)(!i||n>s.get(i))&&(i=o);i&&e.set(t.id,i)}return this.typeKeyBySection=e,this.typeKeyBase=this.sectionsBase,e}typeColour(e,t){return this.renderer?.getCategoryColours?.()!==!1&&this.renderer?.categoryDisplayColor?.(e)||t||"#6e7bff"}sectionTypeTint(e){let t=this.sectionTypeKeys().get(e);return t?this.renderer?.categoryDisplayColor?.(t)??null:null}scheduleReservations(e=400){this.closed||this.reservationsTimer||(this.reservationsTimer=setTimeout(()=>{this.reservationsTimer=null,this.refreshReservations()},e))}async refreshReservations(){if(!(this.closed||!this.toolAvailable("reserve")))try{let e=await this.withAuthRetry(()=>this.api.eventRequest(this.key,"reservations"));this.closed||this.setReservations(e.reservations??[]),this.blockGroups=null,this.findBlocked?.refresh()}catch{}}setReservations(e){let t=new Map;for(let n of e){let a=n.createdByYou?"you":n.createdByName??"",l=n.createdAt?C(n.createdAt,{day:"numeric",month:"short"}):"",c=[a,l].filter(Boolean).join(" \xB7 ")||void 0;for(let d of n.labels)t.set(d,{id:n.id,name:n.name,releaseAt:n.releaseAt,count:n.labels.length,by:c})}let s=new Set;for(let n of t.keys())this.reservedBy.has(n)||s.add(n);for(let n of this.reservedBy.keys())t.has(n)||s.add(n);this.reservedBy=t,this.reservationWheres.clear(),this.reservationsLoaded=!0;let i=this.serverBaseline?.client;i&&i.reserved===null&&(i.reserved=this.reservedBlockedCount());for(let n of t.keys())this.reserving.delete(n);this.reservedIds=new Set([...t.keys()].flatMap(n=>this.paintIds(n)));let o=[...s].filter(n=>this.status.get(n)==="blocked").flatMap(n=>this.paintIds(n));o.length&&this.renderer&&(this.renderer.setStatus(o,P("booked")),this.renderer.setStatus(o,P("blocked"))),this.paintColourLegend(),this.paintMapChrome()}async loadBlockGroups(){if(this.blockGroups&&Date.now()-this.blockGroups.at<3e4)return this.blockGroups.groups;let e=await this.withAuthRetry(()=>this.api.eventRequest(this.key,"blocks"));return this.blockGroups={at:Date.now(),groups:e.groups??[]},this.blockGroups.groups}reservedBlockedCount(){let e=0;for(let t of this.reservedBy.keys())this.status.get(t)==="blocked"&&(e+=this.seatWeight(t));return e}reservedTally(e){let t=this.reservedBlockedCount(),s=this.serverBaseline,i=s?.server.reserved,o=s?.client?.reserved,n=i===void 0?t:i+(o==null?0:t-o);return Math.min(e,Math.max(0,n))}paintColourLegend(){let e=this.els.blocklegend;if(!e||!this.renderer)return;let t=this.getColourBy(),s=this.buildTallies();pt(e,{colourBy:t,seats:this.legendSeats??this.renderer.getRung?.()==="seats",types:t==="type"?this.legendTypes():t==="price"?this.extrasReady?.priceChips(this.typePrices(),this.legendTypes(),this.root?.dataset.theme==="light",i=>M(i,this.currency))??[]:[],counts:{free:s.free,held:s.held,booked:s.booked,blocked:s.blocked,reserved:this.reservedTally(s.blocked)},lit:this.litChip,picked:this.chipPicked,shown:this.litChip==="shown"&&this.shownObjects?{name:this.shownObjects.name,count:this.shownObjects.labels.length}:null,channels:t==="channel"?this.channels?.legendChannels()??[]:[],channelAvailable:this.channelColoursAvailable()})}showObjects(e,t="Seats"){let s=(e??[]).filter(i=>this.labelToSeat.has(i));this.shownObjects=s.length?{name:t,labels:s}:null,this.chipPicked=null,this.litChip=this.shownObjects?"shown":this.litChip==="shown"?null:this.litChip,this.highlightLabels(this.litChip?this.chipLabels(this.litChip):null),this.shownObjects&&this.frameLabels(s),this.paintColourLegend()}chipLabels(e){if(e==="shown")return this.shownObjects?.labels??[];let t=[...this.labelToSeat.keys()];if(e.startsWith("type:")){let s=e.slice(5);return t.filter(i=>this.labelToSeat.get(i).categoryKey===s)}if(e.startsWith("price:")){let s=this.typePrices();return t.filter(i=>s.get(this.labelToSeat.get(i).categoryKey)===+e.slice(6))}return e==="reserved"?t.filter(s=>this.reservedBy.has(s)):t.filter(s=>(this.status.get(s)??"free")===e&&(e!=="blocked"||!this.reservedBy.has(s)))}onLegendChip(e,t){let s=this.chipLabels(e);if(t&&(this.isBulkSelectMode()||this.mode==="select")){let i=this.getSelection().length;this.selectByLabels(s);let o=this.getSelection().length-i,n=s.length-o-i;n>0&&this.toast(`${o.toLocaleString()} picked. ${n.toLocaleString()} skipped: this task can\u2019t change them.`,"ok"),this.litChip=e,this.chipPicked=o,this.highlightLabels(null),this.paintColourLegend();return}this.chipPicked=null,this.litChip=this.litChip===e?null:e,this.highlightLabels(this.litChip?s:null),this.paintColourLegend()}legendTypes(){let e=new Map;for(let t of this.labelToSeat.values())e.set(t.categoryKey,(e.get(t.categoryKey)??0)+1);for(let[t,s]of this.status){if(s==="free")continue;let i=this.labelToSeat.get(t)?.categoryKey;i&&e.has(i)&&e.set(i,e.get(i)-1)}return(this.doc?.categories??[]).filter(t=>e.has(t.key)).map(t=>({key:t.key,label:t.label,color:this.renderer?.categoryDisplayColor?.(t.key)??t.color,free:Math.max(0,e.get(t.key))}))}refreshBlockPaint(){this.renderer?.refreshBlockPaint?.(),this.minimap?.refreshMinimap()}mapCamera(){return{getViewport:()=>{let e=this.renderer;return!e?.getVisibleWorldRect||!e.getWorldBounds?null:{visible:e.getVisibleWorldRect(),bounds:e.getWorldBounds()}},getMinimapSnapshot:()=>this.renderer?.getMinimapSnapshot?.()??{sections:[],seats:[]},panToWorld:e=>{this.setFollowLive(!1),this.renderer?.panToWorld?.(e)},clearSectionFocus:()=>this.renderer?.clearSectionFocus?.(),focusSection:e=>{this.setFollowLive(!1),this.renderer?.focusSection(e),this.channels?.handleSectionFocus(e)},overview:()=>{this.setFollowLive(!1),this.zoomToFit()},getFloors:()=>this.renderer?.getFloors?.()??[],getActiveFloorId:()=>this.renderer?.getActiveFloorId?.()??"",isFloorOverview:()=>this.renderer?.isFloorOverview?.()??!1,getRenderer:()=>this.renderer}}syncMinimap(){let e=this.els.minimapMount,t=!!this.root?.classList.contains("compact");if(!e||!this.renderer||t){this.minimap?.dispose(),this.minimap=null;return}if(this.minimap){this.minimap.refreshMinimap();return}this.minimap=Te({controller:this.mapCamera(),root:()=>this.root,cssVar:s=>this.cssVar(s.replace(/^--sl-/,"--slm-")),focusedSectionLabel:()=>{},tint:s=>this.renderer?.categoryDisplayColor?.(s)||void 0},e),this.minimap.refreshMinimap()}cssVar(e){return this.root?getComputedStyle(this.root).getPropertyValue(e).trim():""}destroy(){if(this.selectObserver?.disconnect(),this.closed=!0,this.minimap?.dispose(),this.minimap=null,this.monitorRefreshTimer&&clearTimeout(this.monitorRefreshTimer),this.monitorRefreshTimer=null,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.stopKeepalive(),this.alerts?.destroy(),this.alerts=null,this.linkTimers&&this.linkTimers.forEach(e=>clearTimeout(e)),this.feedTimer&&clearInterval(this.feedTimer),this.toastTimer&&clearTimeout(this.toastTimer),this.liveEventTimer&&clearTimeout(this.liveEventTimer),this.reservationsTimer&&clearTimeout(this.reservationsTimer),this.kpiCleanupTimer&&clearTimeout(this.kpiCleanupTimer),this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.paintHandle!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.paintHandle),this.paintHandle=null,this.channels?.destroy(),this.channels=null,this.channelsLoading=null,this.tokenRefreshTimer&&clearTimeout(this.tokenRefreshTimer),this.layoutObserver?.disconnect(),this.layoutObserver=null,this.colorSchemeStop?.(),this.colorSchemeStop=null,this.root?.removeEventListener("keydown",this.onKeyDown),this.els.rail?.removeEventListener("click",this.onRailClick),this.root?.removeEventListener("click",this.onHowClick),typeof document<"u"&&document.removeEventListener("fullscreenchange",this.onFullscreenChange),this.ws){try{this.ws.close()}catch{}this.ws=null}this.reserve?.destroy(),this.reserve=null,this.seatHistoryPanel?.destroy(),this.seatHistoryPanel=null,this.changes?.destroy(),this.changes=null,this.saved?.destroy(),this.saved=null;for(let e of this.arrival)e.destroy();this.arrival=[],this.activityPanel?.destroy(),this.activityPanel=null,this.navigation?.destroy(),this.navigation=null,this.renderer?.destroy(),this.renderer=null,this.organizerAssetUrls.dispose(),this.root&&this.root.parentNode===this.host&&this.host.removeChild(this.root)}buildRenderer(){if(!this.doc)return;let e=this.isBulkSelectMode();this.renderer=new Ss(this.mapHost,{manageMode:!0,organizerGlyph:{apply:(s,i,o,n)=>{let a=i==="cross"?ft(s):void 0;if(a&&this.reservedIds.has(a)){Et(s),bt(s,n);return}be(s),Ls(s,i,o,n)},clear:s=>{be(s),Et(s)},isPainted:s=>Ts(s)||ee(s)},ownPriceRings:(s,i)=>this.extrasReady?.ownPriceRings(s,i),marqueeSelect:e&&!this.movingMap,marqueeShape:this.marqueeShape,rowLabelSelect:this.rowLabelSelectable(),maxSelection:this.selectionCap(),selectableStatuses:this.selectableStatuses(),currency:this.currency,onSelect:s=>this.handleSeatSelect(s),onDeselect:s=>this.handleSeatDeselect(s),onSelectionLimit:s=>this.opts.onSelectionLimit?.(s),onMarquee:()=>(this.isBulkSelectMode()&&(this.hintUntil=Date.now()+4e3,this.updateZoomHint(),setTimeout(()=>this.updateZoomHint(),4050)),this.mode==="select"?this.reconcileSelectPolicy():this.syncSelection()),onBand:(s,i,o)=>this.applyBand(s,i,o),onGAClick:s=>{if(this.mode!=="select"||!this.opts.onAreaClick||!this.doc)return;let i=At(this.doc).find(o=>o.id===s);i&&this.opts.onAreaClick({id:i.id,label:i.label,name:i.displayLabel?.trim()||i.label})},onSectionTap:s=>this.handleSectionTap(s),onViewChange:()=>{this.updateZoomHint(),this.paintMapChrome(),this.minimap?.drawMinimapRect(),this.channels?.handleViewChange()},onFocusedSectionChange:()=>{this.paintMapChrome(),this.minimap?.refreshMinimap()},hoverFacts:s=>this.hoverFactsFor(s),hoverCardHead:s=>this.hoverHeadFor(s),hoverSectionHead:(s,i)=>this.sectionHeadFor(s,i),blockPaint:s=>this.captioned(s.id,dt(s,{rule:this.availabilityRules[s.id],hiddenNow:this.effectiveHidden.has(s.id),closedNow:this.effectiveClosed.has(s.id),colourBy:this.getColourBy(),typeTint:this.sectionTypeTint(s.id),allBlocked:s.state==="sold-out"?this.sectionKeptAside(s.id):void 0})),openAtSectionsWhenDense:!0});let t=this.renderer;this.loadExtras().then(s=>{this.renderer===t&&(s.paintBlockCaptions(t,this.blockCaptions,()=>this.root?.dataset.theme==="dark"),this.captionsOn=!0,this.refreshBlockPaint())}).catch(()=>{}),this.renderer.setCategoryPriceRanges(this.hoverPriceRanges()),this.priceShadesOn="",this.renderer.setChart(this.themedDoc()),this.chromeClearance=-1,this.applyChromeClearance(),this.legendInset="",this.applyLegendInset(),this.repaintAll(),this.pricedIds=[],this.applyPricedMarks(),this.applyHeatOverlay(),this.applyMapView(),this.updateZoomHint(),this.minimap?.dispose(),this.minimap=null,this.syncMinimap(),this.paintMapChrome()}hoverFactsFor(e){let t=this.seatOfId(e);if(!t)return null;let s=this.status.get(t.label)??"free",i={free:"Free",held:"In a cart",booked:"Sold",blocked:"Blocked"},n=s==="free"&&this.isHostUnavailable(t.label)?this.opts.unavailableObjectsReason?.trim()||"Unavailable":i[s],a=s==="blocked"?this.reservedBy.get(t.label):void 0;if(a){let h=a.releaseAt==null?"No end":`${q(a.releaseAt)}${a.releaseAt===this.eventStartsAt?" (the start)":""}`,u=this.reservationWhere(a.id);return[{caption:"Until",value:h},...a.by?[{caption:"Reserved by",value:a.by}]:[],{caption:"Reservation",value:`${w(a.count)}${u?` \xB7 ${u}`:""}`}]}let l=[{caption:"Status",value:n}],c=this.doc?.categories.find(h=>h.key===t.categoryKey);c&&l.push({caption:"Ticket type",value:`${c.label??c.key}${typeof c.price=="number"?` \xB7 ${M(c.price,this.currency)}`:""}`});let d=this.channels?.channelNameForLabel(t.label)??null;return d&&l.push({caption:"Channel",value:d}),l}hoverHeadFor(e){let t=this.seatOfId(e);if(!t)return null;let s=this.status.get(t.label)??"free",i=s==="blocked"?this.reservedBy.get(t.label):void 0,o=this.sectionLabelById.get(this.sectionByObject.get(t.rowId)??S)??"Other seats",n=t.label.startsWith(`${o} `)?t.label.slice(o.length+1):t.label,a=n.lastIndexOf("-"),[l,c]=F[i?"reserved":s]??F.free,d=this.root?.dataset.theme==="dark"?"#e879f9":c;return{title:`${o} \xB7 ${n}`,...i?{sub:`Reserved for ${i.name}`,tone:d}:a>0?{sub:`Row ${n.slice(0,a)}, seat ${n.slice(a+1)}`}:{},plate:x(l,i?d:c,26)}}sectionHeadFor(e,t){this.idToLabel.size!==this.labelToId.size&&(this.idToLabel=new Map([...this.labelToId].map(([i,o])=>[o,i])));let s=0;for(let i of t)(this.status.get(this.idToLabel.get(i)??"")??"free")==="free"&&(s+=1);return{title:this.sectionLabelById.get(e)??e,sub:`${s.toLocaleString()} of ${t.length.toLocaleString()} free`,plate:x("layers","#0ea5a5",26)}}seatOfId(e){for(let t of this.labelToSeat.values())if(t.id===e)return t}reservationWhere(e){let t=this.reservationWheres.get(e);if(t==null){let s=[...this.reservedBy].filter(([,n])=>n.id===e).flatMap(([n])=>this.labelToSeat.get(n)??[]),i=this.rowLabels(),o=new Set(s.map(n=>i.get(n.rowId)??n.rowId)).size===2;t=this.selectionSummary(s).where.replace(/ · (rows? )([^\s–]+)(?:–([^\s–]+))?$/,(n,a,l,c)=>` ${a}${l}${c?`${o?" and ":"\u2013"}${c}`:""}`),this.reservationWheres.set(e,t)}return t}rowLabelSelectable(){return this.isBulkSelectMode()||this.mode==="select"}isBulkSelectMode(){return this.mode==="block"||this.mode==="reserve"||this.mode==="categories"||this.mode==="channels"&&this.channels?.usesMarqueeSelection()===!0}selectableStatuses(){return this.mode==="block"?["free","not_for_sale"]:this.mode==="reserve"?["free"]:this.mode==="select"||this.mode==="categories"||this.mode==="inspect"||this.mode==="view"||this.isBulkSelectMode()||this.mode==="channels"&&this.channels?.canSelect()===!0?["free","held","booked","not_for_sale"]:[]}updateRendererInteraction(){let e=this.isBulkSelectMode();this.renderer?.setManageInteraction({manageMode:!0,organizerStatus:this.channels?.view!=="preview"||this.mode!=="channels",marqueeSelect:e&&!this.movingMap,marqueeShape:this.marqueeShape,rowLabelSelect:this.rowLabelSelectable(),maxSelection:this.selectionCap(),selectableStatuses:this.selectableStatuses()}),this.navigation?.update(e),this.updateZoomHint()}handleSeatSelect(e){let t=this.press;t&&(t.answered=!0);let s=this.lastPick;if(this.lastPick={label:e.label,rowId:e.rowId,at:Date.now()},t?.shift&&s&&s.rowId===e.rowId&&s.label!==e.label&&this.isBulkSelectMode()&&this.renderer?.selectByLabels(de(this.rowSeats(e.rowId),s.label,e.label)),this.mode==="select"&&!this.canSelectObject(e)){this.renderer?.deselect([e.id]),this.syncSelection();return}if(this.mode==="inspect"||this.mode==="view"){let i=this.getSelection().filter(o=>o.id!==e.id).map(o=>o.id);i.length&&this.renderer?.deselect(i)}this.syncSelection()}buildUnitUniverse(e){this.categoryTotalsCache=null;let t=new Map;for(let i of Ms(e))i.type==="table"&&t.set(i.id,i.label);let s=new Map;for(let i of Cs(e))if(this.labelToId.set(i.label,i.id),this.labelToSeat.set(i.label,i),this.allIds.push(i.id),t.has(i.rowId)){let o=s.get(i.rowId)??[];o.push(i.id),s.set(i.rowId,o)}for(let[i,o]of s){let n=t.get(i);this.labelToId.has(n)||this.tableChairIds.set(n,o)}for(let i of At(e)){let o=i.displayLabel||i.label;for(let n of As(i))this.labelToId.has(n)||(this.gaUnitLabelSet.add(n),this.labelNames.set(n,o))}}unitTotal(){return this.allIds.length+this.gaUnitLabelSet.size}paintIds(e){let t=this.labelToId.get(e);return t?[t]:this.tableChairIds.get(e)??[]}knownLabels(){return[...this.labelToId.keys(),...this.gaUnitLabelSet]}repaintAll(){let e=this.renderer;if(!e)return;this.allIds.length&&e.setStatus(this.allIds,"free");let t={free:[],held:[],booked:[],not_for_sale:[]};for(let[s,i]of this.status.entries())t[this.renderStatusOf(s,i)].push(...this.paintIds(s));for(let s of this.unavailableLabels)this.status.has(s)||t.held.push(...this.paintIds(s));["held","booked","not_for_sale"].forEach(s=>{t[s].length&&e.setStatus(t[s],s)})}async connect(){if(this.closed||this.sessionEnded)return;let e;try{if(e=(await this.withAuthRetry(()=>this.api.subscribeTicket(this.key))).protocols,!e.length)throw new Error("manage_subscribe_ticket_missing")}catch(s){this.setLive(!1),this.opts.onError?.(s),this.scheduleReconnect();return}if(this.closed)return;let t;try{t=new WebSocket(this.api.socketUrl(this.key),e)}catch(s){this.opts.onError?.(s),this.scheduleReconnect();return}this.ws=t,this.socketSnapshotSeen=!1,t.onopen=()=>{this.attempt=0,this.setLive(!0),this.startKeepalive(t),this.resnapshot().then(()=>this.refreshControlRoom()).catch(s=>this.opts.onError?.(s)),this.refreshAvailability()},t.onmessage=s=>this.onMessage(s),t.onclose=()=>{this.ws===t&&(this.ws=null),this.stopKeepalive(),this.setLive(!1),this.scheduleReconnect()},t.onerror=()=>{try{t.close()}catch{}}}startKeepalive(e){this.stopKeepalive(),this.pingTimer=setInterval(()=>{if(this.ws===e){try{e.send(JSON.stringify({type:"ping"}))}catch{return}this.pongTimer||(this.pongTimer=setTimeout(()=>{if(this.pongTimer=null,this.ws===e){e.onclose=null,e.onmessage=null;try{e.close()}catch{}this.ws=null,this.stopKeepalive(),this.setLive(!1),this.paintLink("paused"),this.scheduleReconnect()}},5e3))}},1e4)}stopKeepalive(){this.pingTimer&&clearInterval(this.pingTimer),this.pongTimer&&clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}scheduleReconnect(){if(this.closed||this.sessionEnded||this.reconnectTimer)return;let e=Math.min(1e3*2**Math.min(this.attempt++,5),15e3);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}onMessage(e){let t;try{t=JSON.parse(typeof e.data=="string"?e.data:"")}catch{return}if(!t||typeof t!="object"||(this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null),t.type==="pong"))return;this.lastMessageAt=Date.now();let s=t;if((Array.isArray(s.hidden)||Array.isArray(s.closed))&&this.updateEffectiveAvailability(s.hidden,s.closed),s.type==="presence"){typeof s.shoppingSessions=="number"&&typeof s.activeHolds=="number"&&(this.livePresence={at:Date.now(),value:{shoppingSessions:s.shoppingSessions,activeHolds:s.activeHolds}},this.controlRoomSnapshot&&(this.controlRoomSnapshot={...this.controlRoomSnapshot,presence:this.livePresence.value},this.opts.onControlRoom?.(this.controlRoomSnapshot)),this.lastSyncedAt=Date.now(),this.recomputeTallies(),this.paintMonitorInsights());return}if(s.type!=="hidden"){if(s.seats&&typeof s.seats=="object")this.applySocketSnapshot(s.seats,typeof s.default=="string"?s.default:void 0);else if(Array.isArray(s.changes)){let i=[],o=new Map;for(let a of s.changes){let l=ve(a.status),c=this.status.get(a.label)??"free";if(c===l)continue;(c==="blocked"||l==="blocked")&&this.scheduleReservations(),this.setStatusLabel(a.label,l,c);let d=this.paintIds(a.label);d.length&&(this.renderer?.setStatus(d,this.renderStatusOf(a.label,l)),i.push(...d));let h=this.verbFor(c,l,a.label),u=`${h}:${l}`,b=o.get(u)??{labels:[],verb:h,status:l};b.labels.push(a.label),o.set(u,b)}for(let a of o.values()){let l=this.pushActivity(a.labels,a.verb,a.status);l&&this.paintSpatialActivity(l)}o.size&&this.scheduleMonitorRefresh(),i.length&&(this.lastSyncedAt=Date.now(),this.afterPaint()),this.reconcileSelectionWithStatus([...o.values()].flatMap(a=>a.labels));let n=typeof s.bookedValue?.gross=="number"?s.bookedValue.gross:s.revenue?.gross;typeof n=="number"&&Number.isFinite(n)&&this.applyLiveGross(n),this.recomputeTallies()}}}applyLiveGross(e){if(this.liveGross={at:Date.now(),value:e},this.authoritativeGrossRevenue=e,this.revenueStatus="current",this.controlRoomSnapshot){let s={...this.controlRoomSnapshot.bookedValue??this.controlRoomSnapshot.revenue,gross:e};this.controlRoomSnapshot={...this.controlRoomSnapshot,bookedValue:s,revenue:s},this.opts.onControlRoom?.(this.controlRoomSnapshot)}}setStatusLabel(e,t,s=this.status.get(e)??"free"){if(this.status.set(e,t),s===t)return;let i=this.seatWeight(e);if(s!=="free"&&(this.counts[s]-=i),t!=="free"&&(this.counts[t]+=i),this.alerts){let o=this.labelToSeat.get(e);this.alerts.seatChanged(o?this.sectionByObject.get(o.rowId)??null:null,s,t)}}applySocketSnapshot(e,t){let s=this.socketSnapshotSeen?this.status:null;if(this.applySnapshot(e,t),this.socketSnapshotSeen=!0,!s)return;let i=new Map;for(let o of new Set([...s.keys(),...this.status.keys()])){let n=s.get(o)??"free",a=this.status.get(o)??"free";if(n===a)continue;let l=this.verbFor(n,a,o),c=`${l}:${a}`,d=i.get(c)??{labels:[],verb:l,status:a};d.labels.push(o),i.set(c,d)}for(let o of i.values()){let n=this.pushActivity(o.labels,o.verb,o.status);n&&this.paintSpatialActivity(n)}i.size&&this.scheduleMonitorRefresh()}scheduleMonitorRefresh(){this.monitorRefreshTimer||(this.monitorRefreshTimer=setTimeout(()=>{this.monitorRefreshTimer=null,!this.closed&&(this.refreshControlRoom().catch(e=>this.opts.onError?.(e)),this.paintFullscreenLine(),this.tablesPanel?.update(),this.sectionsPanel?.update())},150))}async resnapshot(){try{let e=await this.api.objects(this.key);this.applySnapshot(e.seats),this.updateEffectiveAvailability(e.hidden,e.closed),this.lastMessageAt=Date.now()}catch{}}applySnapshot(e,t){let s=new Map;if(t!==void 0){let i=ve(t);for(let o of this.knownLabels())s.set(o,i)}for(let[i,o]of Object.entries(e))s.set(i,ve(o));this.status=s,this.recountAll(),this.serverBaseline&&!this.serverBaseline.client&&(this.serverBaseline.client=this.pairedClient()),this.modelSynced=!0,this.scheduleReservations(),this.lastSyncedAt=Date.now(),this.repaintAll(),this.afterPaint(),this.recomputeTallies(),this.reconcileSelectionWithStatus(null)}reconcileSelectionWithStatus(e){if(!this.renderer)return;let t=this.getSelection();if(!t.length)return;if(e){let o=new Set(e);if(!t.some(n=>o.has(n.label)))return}if(this.mode==="select"){this.reconcileSelectPolicy();return}if(e)for(let o of t)this.status.get(o.label)==="booked"&&e.includes(o.label)&&this.selJustSold.add(o.label);let s=new Set(this.selectableStatuses()),i=t.filter(o=>!s.has(this.renderStatusOf(o.label,this.status.get(o.label)??"free")));this.reconcilingSel=!0;try{i.length&&this.renderer.deselect(i.map(o=>o.id)),this.syncSelection()}finally{this.reconcilingSel=!1}}recountAll(){let e={held:0,booked:0,blocked:0};for(let[t,s]of this.status)s!=="free"&&(e[s]+=this.seatWeight(t));this.counts=e}seatWeight(e){return this.tableChairIds.get(e)?.length??1}setSeatsLocal(e,t){let s=[],i=[];for(let o of e)this.setStatusLabel(o,t),(this.renderStatusOf(o,t)===P(t)?s:i).push(...this.paintIds(o));s.length&&this.renderer?.setStatus(s,P(t)),i.length&&this.renderer?.setStatus(i,"held"),this.afterPaint(),this.recomputeTallies()}afterPaint(){this.keepLive&&typeof document<"u"&&document.hidden&&this.renderer?.forceDraw()}activityColor(e){return e==="held"?A.held:e==="booked"?A.booked:e==="blocked"?A.blocked:A.free}sectionsForLabels(e){let t=new Set;for(let i of e){let o=this.labelToSeat.get(i);if(!o)continue;let n=this.sectionByObject.get(o.rowId);n&&n!==S&&t.add(n)}let s=[...t];return{ids:s,labels:s.map(i=>this.sectionLabelById.get(i)??i)}}pulseSeatLabels(e,t){let s=this.activityColor(t);for(let i of e.slice(0,Bt)){let o=this.labelToId.get(i);o&&this.renderer?.flashSeat(o,s)}}paintSpatialActivity(e){let t=e.sectionIds??this.sectionsForLabels(e.labels).ids,s=this.renderer?.getFocusedSection()??null;if(this.followLive&&t.length===1&&(e.status==="held"||e.status==="booked")){let o=this.root?.querySelector('[data-ref="followstatus"]');o&&(o.textContent=`Following ${e.labels.length===1?this.labelNames.get(e.labels[0])??e.labels[0]:`${e.labels.length} seats`} \xB7 ${e.status}`),this.followLiveTimer&&clearTimeout(this.followLiveTimer),this.followSeatTimer&&clearTimeout(this.followSeatTimer),this.followLiveTimer=setTimeout(()=>{this.followLiveTimer=null,this.focusActivitySeats(e.labels,t[0]),this.followSeatTimer=setTimeout(()=>{this.followSeatTimer=null,this.pulseSeatLabels(e.labels,e.status)},520)},220);return}if(!s&&t.length){let o=this.activityColor(e.status);for(let n of t.slice(0,$t))this.renderer?.flashSection(n,o);return}(!t.length||s&&t.includes(s))&&this.pulseSeatLabels(e.labels,e.status)}locateSection(e){this.renderer?.focusSection(e)}focusActivitySeats(e,t){this.renderer?.focusSection(t);let s=e.slice(0,Bt).map(l=>this.labelToSeat.get(l)).filter(l=>!!l);if(!s.length)return;let i=s.map(l=>l.x),o=s.map(l=>l.y),n=Math.min(...i),a=Math.min(...o);this.renderer?.focusRegion({x:n-150,y:a-100,width:Math.max(...i)-n+300,height:Math.max(...o)-a+200})}locateActivity(e){let t=this.feed.find(i=>i.id===e);if(!t)return;let s=t.sectionIds??this.sectionsForLabels(t.labels).ids;if(this.followSeatTimer&&clearTimeout(this.followSeatTimer),s.length===1){this.focusActivitySeats(t.labels,s[0]),this.followSeatTimer=setTimeout(()=>{this.followSeatTimer=null,this.pulseSeatLabels(t.labels,t.status)},520);return}this.zoomToFit(),this.followSeatTimer=setTimeout(()=>{if(this.followSeatTimer=null,s.length){let i=this.activityColor(t.status);for(let o of s.slice(0,$t))this.renderer?.flashSection(o,i)}else this.pulseSeatLabels(t.labels,t.status)},280)}showLiveEvent(e){let t=this.els.liveevent;if(!t)return;let s=e.sectionLabels??[],i=s.length===1?s[0]:s.length>1?`${s.length} sections`:this.labelNames.get(e.label)??e.label,o=e.count===1?"seat":"seats";t.innerHTML=`<span class="slm-liveeventdot" style="background:${this.activityColor(e.status)}"></span>
622
622
  <span class="slm-liveeventcopy">${g(i)} \xB7 ${e.count.toLocaleString()} ${o} ${g(qe(e.verb))}</span>
623
623
  <span class="slm-liveeventhint">Live</span>`,t.classList.add("on"),this.liveEventTimer&&clearTimeout(this.liveEventTimer),this.liveEventTimer=setTimeout(()=>{this.liveEventTimer=null,t.classList.remove("on"),t.innerHTML=""},2800)}applyReportRevenue(e){this.authoritativeGrossRevenue=e.report.byCategory.reduce((t,s)=>{let i=Number.isFinite(s.bookedValue)?s.bookedValue:s.bookedRevenue;return t+(Number.isFinite(i)?i:0)},0),this.revenueStatus="current",this.recomputeTallies()}async refreshControlRoom(){let e=++this.revenueRequest,t=Date.now();try{let s=await this.api.controlRoom(this.key,this.trendWindowMinutes),i=s.bookedValue??s.revenue??{gross:0,bySection:[]},o=(i.bySection??[]).map(l=>{let c=Number.isFinite(l.bookedValue)?l.bookedValue:l.bookedRevenue;return{...l,bookedValue:c??0,bookedRevenue:c??0}}),n={...i,bySection:o},a={...s,bookedValue:n,revenue:n};if(e===this.revenueRequest){if(this.livePresence&&this.livePresence.at>=t?a={...a,presence:this.livePresence.value}:this.livePresence=null,this.liveGross&&this.liveGross.at>=t){let d={...a.bookedValue,gross:this.liveGross.value};a={...a,bookedValue:d,revenue:d}}else this.liveGross=null;this.controlRoomSnapshot=a,this.adoptLabelNames(a.displayLabels),a.activity&&this.seedFeed(a.activity),this.rebaseServerTotals(a),this.controlRoomSettled=!0,this.lastSyncedAt=Date.now(),this.authoritativeGrossRevenue=a.bookedValue.gross,this.authoritativeCurrency=a.currency,this.currency=a.currency,this.revenueStatus="current",this.recomputeTallies(),this.applyHeatOverlay(),this.paintMonitorInsights(),this.seatHistoryPanel?.refresh();let l=this.getSelection().slice(-1)[0],c=this.els.rail?.querySelector("[data-seat-status]");l&&c&&(c.textContent=this.status.get(l.label)??"free"),this.opts.onControlRoom?.(a)}return a}catch(s){throw e===this.revenueRequest&&(this.revenueStatus="stale",this.controlRoomSettled=!0,this.recomputeTallies()),s}}rebaseServerTotals(e){let t=n=>!!n&&["free","held","booked","blocked"].every(a=>Number.isFinite(n[a])),s=t(e.seatTotals)?e.seatTotals:null,i=s??e.totals;if(!t(i)){this.serverBaseline=null;return}let o=s?.reserved;this.serverBaseline={server:{free:i.free,held:i.held,booked:i.booked,blocked:i.blocked,...Number.isFinite(o)?{reserved:o}:{}},client:this.modelSynced?this.pairedClient():null}}pairedClient(){return{...this.clientTallies(),reserved:this.reservationsLoaded?this.reservedBlockedCount():null}}clientTallies(){let{held:e,booked:t,blocked:s}=this.counts;return{held:e,booked:t,blocked:s,free:Math.max(0,this.unitTotal()-e-t-s)}}buildTallies(){let e=this.clientTallies(),t=this.serverBaseline,s=a=>t?Math.max(0,t.server[a]+(t.client?e[a]-t.client[a]:0)):e[a],i=this.controlRoomSnapshot?.event?.seatTotal,o={free:s("free"),held:s("held"),booked:s("booked"),blocked:s("blocked"),total:Number.isFinite(i)?i:this.unitTotal(),capacityPct:0,sellThroughPct:0,bookedValue:this.authoritativeGrossRevenue,grossRevenue:this.authoritativeGrossRevenue,bookedValueStatus:this.revenueStatus,revenueStatus:this.revenueStatus,currency:this.currency};o.capacityPct=o.total?Math.round(o.booked/o.total*100):0;let n=o.total-o.blocked;return o.sellThroughPct=n>0?Math.round(o.booked/n*100):0,o}recomputeTallies(){if(!this.closed){if(typeof requestAnimationFrame!="function"){this.flushTallies();return}this.paintHandle===null&&(this.paintHandle=requestAnimationFrame(()=>{this.paintHandle=null,this.flushTallies()}))}}talliesReady(){return this.serverBaseline!==null||this.controlRoomSettled&&this.modelSynced}flushTallies(){if(this.closed)return;let e=this.buildTallies(),t=this.talliesReady();this.paintKpis(e,t),this.paintColourLegend(),this.minimap?.refreshMinimap(),this.paintMapChrome(),this.mode==="view"?(this.paintMonitorInsights(),this.paintWatchSeat(this.getSelection())):this.mode==="block"?this.paintSelBar(this.getSelection()):this.mode==="reserve"?this.paintReserveSelection(this.getSelection()):this.mode==="channels"&&this.channels?.handleSelectionChange(),t&&this.opts.onTallies?.(e)}verbFor(e,t,s){return t==="held"?"held":t==="booked"?"booked":t==="blocked"?s&&(this.reserving.has(s)||this.reservedBy.has(s))?"reserved":"blocked":t==="free"?e==="blocked"?s&&this.reservedBy.has(s)?"unreserved":"unblocked":e==="booked"?"cancelled":"available":t}pushActivity(e,t,s,i=Date.now()){let o=e[0];if(!o)return null;let n=this.sectionsForLabels(e),a={id:`${o}:${i}:${Math.random().toString(36).slice(2,6)}`,at:i,label:o,labels:[...e],count:e.length,verb:t,status:s,sectionIds:n.ids,sectionLabels:n.labels};return this.controlRoomSnapshot?.activity||this.feed.unshift(a),this.feed.length>ie&&(this.feed.length=ie),this.mode==="view"&&this.paintFeed(),this.showLiveEvent(a),this.opts.onActivity?.(a),a}adoptLabelNames(e){for(let[t,s]of Object.entries(e??{}))typeof s=="string"&&s&&this.labelNames.set(t,s)}seedFeed(e){this.controlRoomSnapshot?.activity&&(this.feed=this.feed.filter(i=>i.id.startsWith("log:")));let t={hold:"held",book:"booked",release:"released",expire:"expired",block:"blocked",unblock:"unblocked",unbook:"cancelled",reserve:"reserved",unreserve:"unreserved","reservation.end":"unreserved"},s={hold:"held",book:"booked",release:"free",expire:"free",block:"blocked",unblock:"free",unbook:"free",reserve:"blocked",unreserve:"free","reservation.end":"free"};for(let i of e){if(this.feed.some(l=>l.id===`log:${i.id}`))continue;let o=i.labels[0];if(!o)continue;let n=this.sectionsForLabels(i.labels),a={id:`log:${i.id}`,at:i.at,label:o,labels:[...i.labels],count:i.labels.length,verb:t[i.action]??i.action,status:s[i.action]??"free",sectionIds:n.ids,sectionLabels:n.labels};this.feed.push(a),this.opts.onActivity?.(a)}this.feed.sort((i,o)=>o.at-i.at),this.feed.length>ie&&(this.feed.length=ie),this.mode==="view"&&this.paintFeed()}startFeedClock(){this.feedTimer=setInterval(()=>{this.mode==="view"&&(this.paintFeed(),this.paintMonitorInsights())},1e4)}selectionCap(){return this.mode!=="select"?1e6:this.opts.numberOfPlacesToSelect??this.opts.maxSelectedObjects??1e6}isHostUnavailable(e){return this.unavailableLabels.has(e)}renderStatusOf(e,t){return t==="free"&&this.unavailableLabels.has(e)?"held":P(t)}canSelectObject(e){if(this.isHostUnavailable(e.label))return!1;let t=this.status.get(e.label)??"free",s=this.opts.unavailableObjectsSelectable??!0,i=t==="free"||s||this.selectableObjectLabels.has(e.label);if(!this.opts.isObjectSelectable)return i;try{return this.opts.isObjectSelectable(e,i)===!0}catch(o){return this.opts.onError?.(o),!1}}applyInitialSelection(){this.initialSelectionApplied||this.mode!=="select"||!this.renderer||(this.initialSelectionApplied=!0,this.selectByLabels(this.opts.selectedObjects??[]))}trimSelectionToCap(){if(this.mode!=="select")return;let e=this.getSelection(),t=this.selectionCap();e.length<=t||this.renderer?.deselect(e.slice(t).map(s=>s.id))}reconcileSelectPolicy(){if(this.mode!=="select")return;let e=this.getSelection().filter(t=>!this.canSelectObject(t));e.length&&this.renderer?.deselect(e.map(t=>t.id)),this.trimSelectionToCap(),this.syncSelection()}selectionLabels(){return this.getSelection().map(e=>e.label)}paintTaskPicker(){let e=this.els.taskpick;if(!e)return;let t=this.taskGroups.flatMap(s=>s.tools).find(s=>s.mode===this.mode)??{mode:this.mode,label:this.mode==="view"?"Watch":this.mode};e.innerHTML=Ge(t,this.taskGroups,this.taskMenuOpen),this.taskMenuOpen&&e.querySelector('[aria-checked="true"]')?.focus()}isSheet(){return!!this.root?.classList.contains("compact")&&this.mode!=="channels"}sheetDetent(){return this.detents.get(this.mode)??"half"}setDetent(e){this.detents.set(this.mode,e),this.applyDetent()}applyDetent(){let e=this.root;e&&(this.isSheet()?e.dataset.detent=this.sheetDetent():delete e.dataset.detent,this.paintPeek())}paintPeek(){let e=this.els.peek;if(!e)return;let t=this.taskGroups.flatMap(i=>i.tools).find(i=>i.mode===this.mode)?.label??"",s=this.renderer?this.getSelection().length:0;e.textContent=s?`${w(s)} selected \xB7 ${t}`:t}wireSheet(){let e=this.els.grab;if(!e)return;let t=["peek","half","full"],s=null,i=!1;e.addEventListener("pointerdown",n=>{s=n.clientY,i=!1}),e.addEventListener("pointerup",n=>{if(s==null)return;let a=n.clientY-s;if(s=null,Math.abs(a)<40)return;i=!0;let l=t.indexOf(this.sheetDetent());this.setDetent(t[Math.max(0,Math.min(2,l+(a>0?-1:1)))])}),e.addEventListener("click",()=>{if(i){i=!1;return}let n=this.sheetDetent();this.setDetent(n==="peek"?"half":n==="half"?"full":"half")});let o=this.els.taskpick;o?.addEventListener("click",n=>{let a=n.target,l=a.closest("[data-taskpick-mode]")?.dataset.taskpickMode;if(l){this.taskMenuOpen=!1,this.setMode(l);return}a.closest("[data-taskpick]")&&(this.taskMenuOpen=!this.taskMenuOpen,this.paintTaskPicker())}),this.root?.addEventListener("click",n=>{this.taskMenuOpen&&o&&!n.composedPath().includes(o)&&(this.taskMenuOpen=!1,this.paintTaskPicker())})}syncSelection(){let e=this.getSelection(),t=this.lastSelectionLabels,s=e.length!==t.size||e.some(o=>!t.has(o.label));s&&!this.reconcilingSel&&(this.selWhole=!1,this.selJustSold.clear(),this.selLeft=null,this.blockDone?.partial&&(this.blockDone=null),this.categoryFailed=!1,this.categoryBusy||(this.categoryDone=null)),!this.selRestoring&&s&&(this.selBack.push([...t]),this.selBack.length>50&&this.selBack.shift(),this.selAhead=[]),this.savedApplied&&(e.length!==this.savedApplied.labels.size||e.some(o=>!this.savedApplied.labels.has(o.label)))&&(this.savedApplied=null,this.root?.querySelector(".slm-savedpill")?.remove()),s&&!this.reconcilingSel&&e.length&&!this.categoryBusy&&!this.blockBusy&&(this.panelAlert=this.mode==="categories"&&!this.categoryCanManage?this.lockedTypes:null),this.mode==="block"?this.paintSelBar(e):this.mode==="reserve"?this.paintReserveSelection(e):this.mode==="view"?this.paintWatchSeat(e):this.mode==="select"?this.paintSelectSelection(e):this.mode==="categories"?this.paintCategorySelection(e):this.mode==="channels"&&this.channels?.handleSelectionChange(),this.paintPeek();let i=new Map(e.map(o=>[o.label,o]));if(this.mode==="select"){for(let[n,a]of i)this.lastSelectionLabels.has(n)||this.opts.onObjectSelected?.(a);for(let n of this.lastSelectionLabels)if(!i.has(n)){let a=this.labelToSeat.get(n);a&&this.opts.onObjectDeselected?.(a)}let o=this.getSelectionValidity();o&&(this.opts.onSelectionValidityChange?.(o),this.selectionWasValid!==o.isValid&&(o.isValid?this.opts.onSelectionValid?.(o):this.opts.onSelectionInvalid?.(o)),this.selectionWasValid=o.isValid)}this.lastSelectionLabels=new Set(i.keys()),this.navigation?.historyChanged(this.selBack.length>0,this.selAhead.length>0),this.opts.onSelectionChange?.(e)}buildChrome(){let e=document.createElement("div"),t=this.opts.chrome==="minimal";e.className=`${t?"slm slm-minimal":"slm"}${this.opts.kpis===!1?" no-kpis":""}`,e.tabIndex=0,e.setAttribute("role","region"),e.setAttribute("aria-label",t?"Seat map":"SeatLayer live control room"),e.innerHTML=`
624
624
  <div class="slm-fsline" data-ref="fsline"></div>
625
625
  <div class="slm-bar">
626
626
  <div class="slm-modes" data-ref="modes" role="tablist" aria-label="Control room tools">
627
- ${Ot.map(n=>`<div class="slm-modegroup" data-group="${n.key}" role="presentation" hidden>
627
+ ${It.map(n=>`<div class="slm-modegroup" data-group="${n.key}" role="presentation" hidden>
628
628
  <span class="slm-modegroup-label" aria-hidden="true">${g(n.label)}</span>
629
629
  ${n.tools.map(a=>`<button class="slm-mode" role="tab" data-mode="${a.mode}"
630
- title="${g(a.title)} (${a.shortcut})" aria-keyshortcuts="${a.shortcut}" hidden>${k(_[a.mode].glyph,_[a.mode].hue,22)}<span>${g(a.label)}</span></button>`).join("")}
630
+ title="${g(a.title)} (${a.shortcut})" aria-keyshortcuts="${a.shortcut}" hidden>${x(_[a.mode].glyph,_[a.mode].hue,22)}<span>${g(a.label)}</span></button>`).join("")}
631
631
  </div>`).join("")}
632
632
  </div>
633
633
  <div class="slm-taskpick" data-ref="taskpick"></div>
@@ -653,7 +653,7 @@ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:
653
653
  <div class="slm-map-host" data-ref="maphost"></div>
654
654
  ${he()}
655
655
  <div class="slm-lane" data-ref="lane">
656
- <div class="slm-zoomhint" data-ref="zoomhint" hidden>${O("box","#d99a0b",15)}${D()?"Press and hold, then drag, to draw a box":"Drag anywhere to add seats \xB7 hold Alt to remove"}</div>
656
+ <div class="slm-zoomhint" data-ref="zoomhint" hidden>${I("box","#d99a0b",15)}${D()?"Press and hold, then drag, to draw a box":"Drag anywhere to add seats \xB7 hold Alt to remove"}</div>
657
657
  <div class="slm-liveevent" data-ref="liveevent" role="status" aria-live="polite"></div>
658
658
  <div class="slm-crumb" data-ref="crumb" role="status" hidden></div>
659
659
  </div>
@@ -665,7 +665,7 @@ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:
665
665
  <aside class="slm-rail"><button type="button" class="slm-grab" data-ref="grab" aria-label="Panel height"><span class="slm-grab-bar" aria-hidden="true"></span><span data-ref="peek"></span></button><div class="slm-railscroll" data-ref="rail">${pe()}</div></aside>
666
666
  </div>
667
667
  <div class="slm-toast" data-ref="toast"></div>
668
- `,this.host.appendChild(e),this.root=e,this.selectObserver=new MutationObserver(()=>{let n=e.querySelector(".slm-rail");n&&(Ce(n),Me(n))});let s=e.querySelector(".slm-rail");if(s&&this.selectObserver.observe(s,{childList:!0,subtree:!0}),this.applyThemeVars(),this.watchThemeMode(),this.updateContainerLayout(),typeof ResizeObserver<"u"){this.layoutObserver=new ResizeObserver(()=>this.updateContainerLayout()),this.layoutObserver.observe(e);let n=e.querySelector(".slm-bar-actions");n&&this.layoutObserver.observe(n)}typeof document<"u"&&document.fonts?.ready.then(()=>{this.closed||this.updateContainerLayout()});let i=n=>e.querySelector(`[data-ref="${n}"]`);this.mapHost=i("maphost"),this.els={modes:i("modes"),tools:i("tools"),livetext:i("livetext"),kpis:i("kpis"),follow:i("follow"),view:i("view"),findbar:i("findbar"),fullscreen:i("fullscreen"),lane:i("lane"),zoomhint:i("zoomhint"),liveevent:i("liveevent"),rail:i("rail"),toast:i("toast"),mapchrome:i("mapchrome"),crumb:i("crumb"),zin:i("zin"),zout:i("zout"),zfit:i("zfit"),minimapMount:i("minimap"),blocklegend:i("blocklegend"),connbanner:i("connbanner"),fsline:i("fsline"),viewonly:i("viewonly"),taskpick:i("taskpick"),grab:i("grab"),peek:i("peek"),bell:i("bell"),awaybanner:i("awaybanner")},this.wireSheet(),this.els.modes.querySelectorAll("[data-mode]").forEach(n=>n.addEventListener("click",()=>this.setMode(n.dataset.mode))),this.els.tools.addEventListener("change",()=>this.setMode(this.els.tools.value)),this.els.zfit.addEventListener("click",()=>{this.setFollowLive(!1),this.zoomToFit()}),this.els.zin.addEventListener("click",()=>{this.setFollowLive(!1),this.renderer?.zoomIn()}),this.els.zout.addEventListener("click",()=>{this.setFollowLive(!1),this.zoomOutStep()}),this.els.mapchrome&&this.layoutObserver?.observe(this.els.mapchrome),this.applyLaneRoom(),this.els.follow.addEventListener("click",()=>this.setFollowLive(!this.followLive)),this.wireColourMenu(e),this.els.view.addEventListener("click",n=>{let a=n.target?.closest("[data-view], [data-panel-toggle]");if(a?.dataset.view)this.toggleMapView(a.dataset.view);else if(a){let l=!e.classList.toggle("details-hidden");a.setAttribute("aria-checked",String(l)),a.classList.toggle("on",l)}}),e.addEventListener("pointerdown",n=>{let a=this.els.view;a.open&&!a.contains(n.target)&&(a.open=!1)}),this.mapView=Lt(),this.colourChoices=kt();let o=this.colourChoices[this.mode]??this.startingColourBy(this.mode);this.priceMode=o==="price",this.mapView={...this.mapView,categoryColours:o==="type"||o==="price",channelColours:o==="channel"},this.heatEnabled=this.mapView.momentum,this.applyMapView(),this.wireBarFind(),this.els.fullscreen.addEventListener("click",()=>this.toggleFullscreen()),e.addEventListener("keydown",this.onKeyDown),e.addEventListener("keydown",this.onSelectAllKey,!0),this.els.rail.addEventListener("click",this.onRailClick),this.root.addEventListener("click",this.onHowClick),document.addEventListener("fullscreenchange",this.onFullscreenChange),this.paintModeTabs(),this.paintFollowLiveButton(),this.paintHeatButton(),this.paintMapViewMenu(),this.paintFullscreenButton(),this.navigation=new X({root:e,map:this.mapHost,setMoving:n=>{this.movingMap=n,this.updateRendererInteraction()},setShape:n=>{this.marqueeShape=n,this.updateRendererInteraction()},pauseFollow:()=>{this.followLive&&this.setFollowLive(!1)},stepSelection:n=>{this.stepSelection(n)}}),this.navigation.update(this.isBulkSelectMode()),this.wireGestures(this.mapHost),this.els.blocklegend&&e.querySelector(".slm-navigation")?.prepend(this.els.blocklegend)}wireColourMenu(e){let t=this.els.blocklegend,s=t?.querySelector('[data-ref="colourby"]'),i=t?.querySelector('[role="listbox"]');if(!t||!s||!i)return;this.paintColourLegend();let o=n=>{i.hidden=!n,s.setAttribute("aria-expanded",String(n))};t.querySelector('[data-ref="legenditems"]')?.addEventListener("click",n=>{let a=n.target.closest("[data-legend]");a?.dataset.legend&&this.onLegendChip(a.dataset.legend,n.shiftKey)}),s.addEventListener("click",()=>{i.hidden&&this.paintColourLegend(),o(i.hidden),i.hidden||i.querySelector('[aria-selected="true"]')?.focus()}),i.addEventListener("click",n=>{let a=n.target?.closest("[data-colour-by]");!a||a.disabled||(this.setColourBy(a.dataset.colourBy),o(!1),s.focus())}),i.addEventListener("keydown",n=>{n.key==="Escape"&&(o(!1),s.focus(),n.stopPropagation())}),e.addEventListener("pointerdown",n=>{!i.hidden&&!t.contains(n.target)&&o(!1)})}showLabels(e){this.setFollowLive(!1);let t=e.length===1?this.labelToSeat.get(e[0]):null;if(!t){this.frameLabels(e);return}let s=this.sectionByObject.get(t.rowId);s&&this.renderer?.focusSection(s),this.renderer?.focusRegion({x:t.x-180,y:t.y-120,width:360,height:240},{animate:!1,minScale:1.5}),this.renderer?.flashSeat(t.id,this.activityColor(this.status.get(t.label)??"free"))}applyChromeClearance(){if(this.opts.chrome!=="minimal"||!this.renderer)return;let e=this.els.mapchrome,t=e?.parentElement;if(!e||!t)return;let s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),o=e.offsetHeight>0&&i.bottom>s.top,n=o?Math.ceil(i.bottom-s.top)+8:0,a=o?Math.ceil(i.right-s.left)+8:0;n===this.chromeClearance&&a===this.chromeClearanceWidth||(this.chromeClearance=n,this.chromeClearanceWidth=a,this.renderer.setFitClearance(n,a))}applyLaneRoom(){let e=this.els.mapchrome,t=e?.parentElement;if(!e||!t)return;let s=e.offsetWidth;t.style.setProperty("--slm-chrome-w",`${s}px`),t.style.setProperty("--slm-chrome-h",`${e.offsetHeight}px`),t.classList.toggle("slm-lane-above",t.clientWidth-s-42<240)}applyLegendInset(){let e=this.opts.mapInsets;if(this.opts.chrome==="minimal"&&!e||!this.renderer?.setViewportInsets)return;let t=this.opts.chrome==="minimal"?null:this.els.blocklegend,s=t&&t.offsetHeight?Math.max(0,Math.ceil(t.getBoundingClientRect().bottom-this.mapHost.getBoundingClientRect().top)+8):0,i=l=>Number.isFinite(l)&&l>0?Math.ceil(l):0,o={top:Math.max(s,i(e?.top)),right:i(e?.right),bottom:i(e?.bottom),left:i(e?.left)},n=`${o.top},${o.right},${o.bottom},${o.left}`;if(n===this.legendInset)return;this.legendInset=n;let a=Object.fromEntries(Object.entries(o).filter(([,l])=>l>0));this.renderer.setViewportInsets(Object.keys(a).length?a:null)}setMapInsets(e){this.opts.mapInsets=e??void 0,this.applyLegendInset()}fitBar(e,t){let s=this.root;if(!s)return;let i=["tightsearch","tightbar","tighterbar"];if(t){s.classList.remove(...i);return}let o=i.filter(l=>s.classList.contains(l)).length;for(;o>0&&e>=this.barNeed[o];)s.classList.remove(i[--o]);let n=()=>{let l=s.querySelector(".slm-bar")?.getBoundingClientRect(),c=s.querySelector(".slm-bar-actions > :last-child")?.getBoundingClientRect(),d=parseFloat(getComputedStyle(s.querySelector(".slm-bar")).paddingRight)||0;return l&&c&&l.width?Math.ceil(c.right-(l.right-d)):0},a=n();for(;a>0&&o<i.length;)this.barNeed[o+1]=e+a+12,s.classList.add(i[o++]),a=n()}updateContainerLayout(){let e=this.root?.getBoundingClientRect().width||this.host.clientWidth,t=e>0&&e<1e3&&this.opts.chrome!=="minimal";t!==this.root?.classList.contains("compact")&&(this.root?.classList.toggle("compact",t),this.applyDetent()),this.fitBar(e,t),this.applyChromeClearance(),this.applyLaneRoom(),this.applyLegendInset(),this.channels?.handleLayoutChange(),this.syncMinimap()}filterableSections(){return this.sectionsBase?[...this.sectionsBase.sections,...this.sectionsBase.ungrouped?[this.sectionsBase.ungrouped]:[]]:[]}applyFilteredSectionCanvas(e=this.filterableSections().filter(t=>t.label===this.filteredSectionLabel)){if(!this.renderer||this.mode!=="filterSections"||!e.length)return;let t=new Set(e.map(i=>i.id)),s=this.filterableSections().filter(i=>!t.has(i.id)).map(i=>i.id);this.renderer.clearSectionFocus(),this.renderer.setClosedSections(null),this.renderer.setDimmedSections(s),this.frameSections(e)}frameSections(e){if(!this.renderer||!e.length)return;let t=e.flatMap(l=>l.seatLabels).map(l=>this.labelToSeat.get(l)).filter(l=>!!l&&Number.isFinite(l.x)&&Number.isFinite(l.y));if(!t.length){this.renderer.focusRegion(e[0].id);return}let s=Math.min(...t.map(l=>l.x)),i=Math.min(...t.map(l=>l.y)),o=Math.max(...t.map(l=>l.x)),n=Math.max(...t.map(l=>l.y)),a=Math.max(40,Math.max(o-s,n-i)*.08);this.renderer.focusRegion({x:s-a,y:i-a,width:Math.max(1,o-s)+a*2,height:Math.max(1,n-i)+a*2})}buildSectionOptions(){if(this.doc)try{let e=Rs(this.doc);this.sectionsBase=e,this.sectionOptions=[],this.sectionByObject=new Map(e.objectToSection),this.sectionLabelById.clear();for(let t of e.sections)this.sectionOptions.push({id:t.id,label:t.label}),this.sectionLabelById.set(t.id,t.label);e.ungrouped&&(this.sectionOptions.push({id:S,label:e.ungrouped.label}),this.sectionLabelById.set(S,e.ungrouped.label))}catch{}}toolAvailable(e){return e==="view"?!0:e==="channels"&&!this.channelCaps.view||e==="categories"&&!this.categoryCanManage&&!this.typesLocked()||(e==="block"||e==="reserve"||e==="sections")&&!this.canBlock()||e==="tables"&&(!this.tableCanManage||!this.tables().length)?!1:!this.opts.tools||this.opts.tools.includes(e)}settleMode(){this.toolAvailable(this.mode)?this.paintModeTabs():this.setMode("view")}tables(){return(this.doc?Es(this.doc):[]).flatMap(e=>e.objects).filter(e=>e.type==="table")}paintModeTabs(){let e=[];this.els.modes?.querySelectorAll(".slm-modegroup").forEach(i=>{let o=[];i.querySelectorAll("[data-mode]").forEach(n=>{let a=n.dataset.mode,l=this.toolAvailable(a);if(n.hidden=!l,!l)return;o.push({mode:a,label:n.textContent??a});let c=a===this.mode;n.classList.toggle("on",c),n.setAttribute("aria-selected",String(c)),n.tabIndex=c?0:-1}),i.hidden=o.length===0,o.length&&e.push({label:i.querySelector(".slm-modegroup-label")?.textContent??"",tools:o})});let t=this.els.tools;t&&(t.innerHTML=e.map(i=>`<optgroup label="${g(i.label)}">${i.tools.map(o=>`<option value="${o.mode}"${o.mode===this.mode?" selected":""}>${g(o.label)}</option>`).join("")}</optgroup>`).join(""),t.value=this.mode),this.root?.classList.toggle("block-mode",this.mode==="block"),this.taskGroups=e,this.paintTaskPicker();let s=i=>i!=="view"&&i!=="inspect"&&i!=="select"&&i!=="filterSections";this.els.viewonly&&(this.els.viewonly.hidden=e.some(i=>i.tools.some(o=>s(o.mode)))),this.els.zoomhint&&(this.els.zoomhint.hidden=!e.some(i=>i.tools.some(o=>Hs.has(o.mode))))}typesLocked(){let e=this.opts.capabilities;return!e||this.categoryCanManage?!1:e.some(t=>t==="event:block"||t==="event:tables:manage"||t==="event:channels:manage")}canBlock(){let e=this.opts.capabilities;return!e||e.includes("event:block")}railHeader(e,t,s){let i=t==="read"?"Read-only":t==="event"?"This event only":"Your app";return`<div class="slm-railhead"><p class="slm-eyebrow">${g(e)}</p><span class="slm-scope ${t}">${i}</span></div>
668
+ `,this.host.appendChild(e),this.root=e,this.selectObserver=new MutationObserver(()=>{let n=e.querySelector(".slm-rail");n&&(Ce(n),Me(n))});let s=e.querySelector(".slm-rail");if(s&&this.selectObserver.observe(s,{childList:!0,subtree:!0}),this.applyThemeVars(),this.watchThemeMode(),this.updateContainerLayout(),typeof ResizeObserver<"u"){this.layoutObserver=new ResizeObserver(()=>this.updateContainerLayout()),this.layoutObserver.observe(e);let n=e.querySelector(".slm-bar-actions");n&&this.layoutObserver.observe(n)}typeof document<"u"&&document.fonts?.ready.then(()=>{this.closed||this.updateContainerLayout()});let i=n=>e.querySelector(`[data-ref="${n}"]`);this.mapHost=i("maphost"),this.els={modes:i("modes"),tools:i("tools"),livetext:i("livetext"),kpis:i("kpis"),follow:i("follow"),view:i("view"),findbar:i("findbar"),fullscreen:i("fullscreen"),lane:i("lane"),zoomhint:i("zoomhint"),liveevent:i("liveevent"),rail:i("rail"),toast:i("toast"),mapchrome:i("mapchrome"),crumb:i("crumb"),zin:i("zin"),zout:i("zout"),zfit:i("zfit"),minimapMount:i("minimap"),blocklegend:i("blocklegend"),connbanner:i("connbanner"),fsline:i("fsline"),viewonly:i("viewonly"),taskpick:i("taskpick"),grab:i("grab"),peek:i("peek"),bell:i("bell"),awaybanner:i("awaybanner")},this.wireSheet(),this.els.modes.querySelectorAll("[data-mode]").forEach(n=>n.addEventListener("click",()=>this.setMode(n.dataset.mode))),this.els.tools.addEventListener("change",()=>this.setMode(this.els.tools.value)),this.els.zfit.addEventListener("click",()=>{this.setFollowLive(!1),this.zoomToFit()}),this.els.zin.addEventListener("click",()=>{this.setFollowLive(!1),this.renderer?.zoomIn()}),this.els.zout.addEventListener("click",()=>{this.setFollowLive(!1),this.zoomOutStep()}),this.els.mapchrome&&this.layoutObserver?.observe(this.els.mapchrome),this.applyLaneRoom(),this.els.follow.addEventListener("click",()=>this.setFollowLive(!this.followLive)),this.wireColourMenu(e),this.els.view.addEventListener("click",n=>{let a=n.target?.closest("[data-view], [data-panel-toggle]");if(a?.dataset.view)this.toggleMapView(a.dataset.view);else if(a){let l=!e.classList.toggle("details-hidden");a.setAttribute("aria-checked",String(l)),a.classList.toggle("on",l)}}),e.addEventListener("pointerdown",n=>{let a=this.els.view;a.open&&!a.contains(n.target)&&(a.open=!1)}),this.mapView=Lt(),this.colourChoices=xt();let o=this.colourChoices[this.mode]??this.startingColourBy(this.mode);this.priceMode=o==="price",this.mapView={...this.mapView,categoryColours:o==="type"||o==="price",channelColours:o==="channel"},this.heatEnabled=this.mapView.momentum,this.applyMapView(),this.wireBarFind(),this.els.fullscreen.addEventListener("click",()=>this.toggleFullscreen()),e.addEventListener("keydown",this.onKeyDown),e.addEventListener("keydown",this.onSelectAllKey,!0),this.els.rail.addEventListener("click",this.onRailClick),this.root.addEventListener("click",this.onHowClick),document.addEventListener("fullscreenchange",this.onFullscreenChange),this.paintModeTabs(),this.paintFollowLiveButton(),this.paintHeatButton(),this.paintMapViewMenu(),this.paintFullscreenButton(),this.navigation=new X({root:e,map:this.mapHost,setMoving:n=>{this.movingMap=n,this.updateRendererInteraction()},setShape:n=>{this.marqueeShape=n,this.updateRendererInteraction()},pauseFollow:()=>{this.followLive&&this.setFollowLive(!1)},stepSelection:n=>{this.stepSelection(n)}}),this.navigation.update(this.isBulkSelectMode()),this.wireGestures(this.mapHost),this.els.blocklegend&&e.querySelector(".slm-navigation")?.prepend(this.els.blocklegend)}wireColourMenu(e){let t=this.els.blocklegend,s=t?.querySelector('[data-ref="colourby"]'),i=t?.querySelector('[role="listbox"]');if(!t||!s||!i)return;this.paintColourLegend();let o=n=>{i.hidden=!n,s.setAttribute("aria-expanded",String(n))};t.querySelector('[data-ref="legenditems"]')?.addEventListener("click",n=>{let a=n.target.closest("[data-legend]");a?.dataset.legend&&this.onLegendChip(a.dataset.legend,n.shiftKey)}),s.addEventListener("click",()=>{i.hidden&&this.paintColourLegend(),o(i.hidden),i.hidden||i.querySelector('[aria-selected="true"]')?.focus()}),i.addEventListener("click",n=>{let a=n.target?.closest("[data-colour-by]");!a||a.disabled||(this.setColourBy(a.dataset.colourBy),o(!1),s.focus())}),i.addEventListener("keydown",n=>{n.key==="Escape"&&(o(!1),s.focus(),n.stopPropagation())}),e.addEventListener("pointerdown",n=>{!i.hidden&&!t.contains(n.target)&&o(!1)})}showLabels(e){this.setFollowLive(!1);let t=e.length===1?this.labelToSeat.get(e[0]):null;if(!t){this.frameLabels(e);return}let s=this.sectionByObject.get(t.rowId);s&&this.renderer?.focusSection(s),this.renderer?.focusRegion({x:t.x-180,y:t.y-120,width:360,height:240},{animate:!1,minScale:1.5}),this.renderer?.flashSeat(t.id,this.activityColor(this.status.get(t.label)??"free"))}applyChromeClearance(){if(this.opts.chrome!=="minimal"||!this.renderer)return;let e=this.els.mapchrome,t=e?.parentElement;if(!e||!t)return;let s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),o=e.offsetHeight>0&&i.bottom>s.top,n=o?Math.ceil(i.bottom-s.top)+8:0,a=o?Math.ceil(i.right-s.left)+8:0;n===this.chromeClearance&&a===this.chromeClearanceWidth||(this.chromeClearance=n,this.chromeClearanceWidth=a,this.renderer.setFitClearance(n,a))}applyLaneRoom(){let e=this.els.mapchrome,t=e?.parentElement;if(!e||!t)return;let s=e.offsetWidth;t.style.setProperty("--slm-chrome-w",`${s}px`),t.style.setProperty("--slm-chrome-h",`${e.offsetHeight}px`),t.classList.toggle("slm-lane-above",t.clientWidth-s-42<240)}applyLegendInset(){let e=this.opts.mapInsets;if(this.opts.chrome==="minimal"&&!e||!this.renderer?.setViewportInsets)return;let t=this.opts.chrome==="minimal"?null:this.els.blocklegend,s=t&&t.offsetHeight?Math.max(0,Math.ceil(t.getBoundingClientRect().bottom-this.mapHost.getBoundingClientRect().top)+8):0,i=l=>Number.isFinite(l)&&l>0?Math.ceil(l):0,o={top:Math.max(s,i(e?.top)),right:i(e?.right),bottom:i(e?.bottom),left:i(e?.left)},n=`${o.top},${o.right},${o.bottom},${o.left}`;if(n===this.legendInset)return;this.legendInset=n;let a=Object.fromEntries(Object.entries(o).filter(([,l])=>l>0));this.renderer.setViewportInsets(Object.keys(a).length?a:null)}setMapInsets(e){this.opts.mapInsets=e??void 0,this.applyLegendInset()}fitBar(e,t){let s=this.root;if(!s)return;let i=["tightsearch","tightbar","tighterbar"];if(t){s.classList.remove(...i);return}let o=i.filter(l=>s.classList.contains(l)).length;for(;o>0&&e>=this.barNeed[o];)s.classList.remove(i[--o]);let n=()=>{let l=s.querySelector(".slm-bar")?.getBoundingClientRect(),c=s.querySelector(".slm-bar-actions > :last-child")?.getBoundingClientRect(),d=parseFloat(getComputedStyle(s.querySelector(".slm-bar")).paddingRight)||0;return l&&c&&l.width?Math.ceil(c.right-(l.right-d)):0},a=n();for(;a>0&&o<i.length;)this.barNeed[o+1]=e+a+12,s.classList.add(i[o++]),a=n()}updateContainerLayout(){let e=this.root?.getBoundingClientRect().width||this.host.clientWidth,t=e>0&&e<1e3&&this.opts.chrome!=="minimal";t!==this.root?.classList.contains("compact")&&(this.root?.classList.toggle("compact",t),this.applyDetent()),this.fitBar(e,t),this.applyChromeClearance(),this.applyLaneRoom(),this.applyLegendInset(),this.channels?.handleLayoutChange(),this.syncMinimap()}filterableSections(){return this.sectionsBase?[...this.sectionsBase.sections,...this.sectionsBase.ungrouped?[this.sectionsBase.ungrouped]:[]]:[]}applyFilteredSectionCanvas(e=this.filterableSections().filter(t=>t.label===this.filteredSectionLabel)){if(!this.renderer||this.mode!=="filterSections"||!e.length)return;let t=new Set(e.map(i=>i.id)),s=this.filterableSections().filter(i=>!t.has(i.id)).map(i=>i.id);this.renderer.clearSectionFocus(),this.renderer.setClosedSections(null),this.renderer.setDimmedSections(s),this.frameSections(e)}frameSections(e){if(!this.renderer||!e.length)return;let t=e.flatMap(l=>l.seatLabels).map(l=>this.labelToSeat.get(l)).filter(l=>!!l&&Number.isFinite(l.x)&&Number.isFinite(l.y));if(!t.length){this.renderer.focusRegion(e[0].id);return}let s=Math.min(...t.map(l=>l.x)),i=Math.min(...t.map(l=>l.y)),o=Math.max(...t.map(l=>l.x)),n=Math.max(...t.map(l=>l.y)),a=Math.max(40,Math.max(o-s,n-i)*.08);this.renderer.focusRegion({x:s-a,y:i-a,width:Math.max(1,o-s)+a*2,height:Math.max(1,n-i)+a*2})}buildSectionOptions(){if(this.doc)try{let e=Rs(this.doc);this.sectionsBase=e,this.sectionOptions=[],this.sectionByObject=new Map(e.objectToSection),this.sectionLabelById.clear();for(let t of e.sections)this.sectionOptions.push({id:t.id,label:t.label}),this.sectionLabelById.set(t.id,t.label);e.ungrouped&&(this.sectionOptions.push({id:S,label:e.ungrouped.label}),this.sectionLabelById.set(S,e.ungrouped.label))}catch{}}toolAvailable(e){return e==="view"?!0:e==="channels"&&!this.channelCaps.view||e==="categories"&&!this.categoryCanManage&&!this.typesLocked()||(e==="block"||e==="reserve"||e==="sections")&&!this.canBlock()||e==="tables"&&(!this.tableCanManage||!this.tables().length)?!1:!this.opts.tools||this.opts.tools.includes(e)}settleMode(){this.toolAvailable(this.mode)?this.paintModeTabs():this.setMode("view")}tables(){return(this.doc?Es(this.doc):[]).flatMap(e=>e.objects).filter(e=>e.type==="table")}paintModeTabs(){let e=[];this.els.modes?.querySelectorAll(".slm-modegroup").forEach(i=>{let o=[];i.querySelectorAll("[data-mode]").forEach(n=>{let a=n.dataset.mode,l=this.toolAvailable(a);if(n.hidden=!l,!l)return;o.push({mode:a,label:n.textContent??a});let c=a===this.mode;n.classList.toggle("on",c),n.setAttribute("aria-selected",String(c)),n.tabIndex=c?0:-1}),i.hidden=o.length===0,o.length&&e.push({label:i.querySelector(".slm-modegroup-label")?.textContent??"",tools:o})});let t=this.els.tools;t&&(t.innerHTML=e.map(i=>`<optgroup label="${g(i.label)}">${i.tools.map(o=>`<option value="${o.mode}"${o.mode===this.mode?" selected":""}>${g(o.label)}</option>`).join("")}</optgroup>`).join(""),t.value=this.mode),this.root?.classList.toggle("block-mode",this.mode==="block"),this.taskGroups=e,this.paintTaskPicker();let s=i=>i!=="view"&&i!=="inspect"&&i!=="select"&&i!=="filterSections";this.els.viewonly&&(this.els.viewonly.hidden=e.some(i=>i.tools.some(o=>s(o.mode)))),this.els.zoomhint&&(this.els.zoomhint.hidden=!e.some(i=>i.tools.some(o=>Hs.has(o.mode))))}typesLocked(){let e=this.opts.capabilities;return!e||this.categoryCanManage?!1:e.some(t=>t==="event:block"||t==="event:tables:manage"||t==="event:channels:manage")}canBlock(){let e=this.opts.capabilities;return!e||e.includes("event:block")}railHeader(e,t,s){let i=t==="read"?"Read-only":t==="event"?"This event only":"Your app";return`<div class="slm-railhead"><p class="slm-eyebrow">${g(e)}</p><span class="slm-scope ${t}">${i}</span></div>
669
669
  <p class="slm-hint">${s}</p>`}paintFollowLiveButton(){let e=this.els.follow;if(!e)return;e.classList.toggle("on",this.followLive),e.setAttribute("aria-pressed",String(this.followLive));let t=this.root?.querySelector('[data-ref="followstatus"]');t&&(t.hidden=!this.followLive,t.textContent="Waiting for new holds or bookings"),e.setAttribute("title",this.followLive?"Following new holds and bookings. Turn off to keep the current view.":"Stay on the current map view. Enable to follow new holds and bookings.")}paintHeatButton(){this.paintMapViewMenu(),this.paintMomentumHelp()}paintMomentumHelp(){let e=this.root?.querySelector('[data-ref="heatstatus"]');if(e){e.hidden=!this.heatEnabled;let n=this.controlRoomSnapshot?.velocity.bySection.some(a=>a.netBooked>0);e.textContent=this.controlRoomSnapshot?n?`Booking heatmap \xB7 last ${this.trendWindowMinutes}m \xB7 warmer = higher net booking rate`:`No positive net bookings in the last ${this.trendWindowMinutes}m`:"Loading booking heatmap\u2026"}let t=this.els.rail?.querySelector('[data-ref="momentumhelp"]');if(!t)return;t.hidden=!this.heatEnabled;let s=this.els.rail?.querySelector(".slm-sectionhead");s&&(s.hidden=!this.heatEnabled);let i=t.querySelector('[data-ref="momentumcopy"]');if(!i)return;let o=this.controlRoomSnapshot?.velocity.bySection.some(n=>n.netBooked>0);i.textContent=o?"Warmer sections have more completed bookings, adjusted for section size. Holds and viewers are not counted.":`No completed bookings in the last ${this.trendWindowMinutes} minutes.`}paintFullscreenButton(){let e=this.els.fullscreen;if(!e)return;let t=this.isFullscreen(),s=t?"Exit full screen":"Full screen";e.setAttribute("aria-label",s),e.title=`${s} (F)`;let i=e.querySelector(".slm-fullscreen-icon");i&&(i.innerHTML=t?ye.exit:ye.enter)}paintTrendWindow(){this.els.rail?.querySelectorAll("[data-window]").forEach(e=>{let t=Number(e.dataset.window);e.classList.toggle("on",t===this.trendWindowMinutes)})}setLive(e){this.root?.classList.toggle("live",e),this.trackLink(e),this.paintMonitorInsights();let t=e?"live":this.sessionEnded?"ended":"reconnecting";if(t!==this.connectionStatus){this.connectionStatus=t;try{this.opts.onConnectionChange?.(this.getConnection())}catch(s){this.opts.onError?.(s)}}}trackLink(e){let t=()=>{this.linkTimers&&this.linkTimers.forEach(s=>clearTimeout(s)),this.linkTimers=null};if(e){t(),this.everLive=!0,this.paintLink("live");return}if(this.sessionEnded){t(),this.paintLink("live"),this.els.livetext&&(this.els.livetext.textContent="ENDED"),this.announceRoomState();return}this.linkTimers||(!this.everLive&&this.els.livetext&&(this.els.livetext.textContent="CONNECTING"),this.linkTimers=[...this.everLive?[setTimeout(()=>{this.closed||this.paintLink("paused")},5e3)]:[],setTimeout(()=>{this.closed||this.paintLink("offline")},12e4)])}roomState(){return this.sessionEnded?"ended":this.everLive?this.linkState:this.linkState==="offline"?"offline":"connecting"}announceRoomState(){let e=this.roomState();if(e!==this.announcedRoomState){this.announcedRoomState=e;try{this.opts.onRoomStateChange?.(e)}catch(t){this.opts.onError?.(t)}}}paintLink(e){this.linkState=e,this.announceRoomState(),this.root?.classList.toggle("paused",e==="paused"),this.root?.classList.toggle("offline",e==="offline"),this.els.livetext&&(this.els.livetext.textContent=e==="paused"?"PAUSED":e==="offline"?"OFFLINE":"LIVE");let t=this.els.connbanner;t&&(t.innerHTML=Ke(e),t.querySelector("[data-conn-retry]")?.addEventListener("click",()=>{this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempt=0,this.connect()}))}paintFullscreenLine(){let e=this.els.fsline;if(!e||!this.isFullscreen())return;let t=this.controlRoomSnapshot?.event?.name??"",s=this.eventStartsAt?C(this.eventStartsAt,{month:"short",day:"numeric"}):null;e.innerHTML=_e(t,s,this.talliesReady()?this.buildTallies():null),this.opts.sale?.status&&this.withExtras(i=>i.addSalePill(e,this.opts.sale)),e.querySelector("[data-fs-exit]")?.addEventListener("click",()=>{this.exitFullscreen()})}updateZoomHint(){let e=this.els.zoomhint;if(!e)return;let t=this.isBulkSelectMode()&&!this.movingMap&&(Date.now()<this.hintUntil||this.mode==="block"&&D());e.classList.toggle("on",!!t)}formatKpiDelta(e,t,s){let i=t>0?"+":"\u2212",o=Math.abs(t);return e==="booked-value"?`${i}${M(o,s)}`:e==="booked-pct"?`${i}${o.toLocaleString()}pt`:`${i}${o.toLocaleString()}`}paintKpis(e,t=!0){if(!this.els.kpis)return;let s=l=>t?{raw:l,n:l.toLocaleString()}:{raw:null,n:"\u2014"},i=e.bookedValueStatus==="current"?M(e.bookedValue,e.currency):"\u2014",o=this.presenceCounts(),n=[{key:"booked-inventory",...s(e.booked),l:"Booked inventory",dot:A.booked,title:"Inventory units booked"},{key:"held-seats",...s(e.held),l:"In a cart",dot:A.held,title:"Inventory in buyers\u2019 carts now"},{key:"free-seats",...s(e.free),l:"Available",dot:A.free,title:"Inventory available to book"},{key:"blocked",...s(e.blocked),l:"Blocked",dot:A.blocked,title:"Inventory withheld from booking"},{key:"viewing-map",raw:o?.shoppingSessions??null,n:o?o.shoppingSessions.toLocaleString():"\u2014",l:"Viewing map",title:"Active map sessions right now"},{key:"active-holds",raw:o?.activeHolds??null,n:o?o.activeHolds.toLocaleString():"\u2014",l:"Active holds",title:"Sessions currently holding inventory"},{key:"booked-pct",...t?{raw:e.capacityPct,n:`${e.capacityPct}%`}:{raw:null,n:"\u2014"},l:"Booked",title:"Booked inventory as a share of the whole event"},{key:"booked-value",raw:e.bookedValueStatus==="current"?e.bookedValue:null,n:i,l:"Booked value",title:"Configured value attached to booked inventory"}],a=!1;this.els.kpis.innerHTML=n.map(l=>{let c=this.lastKpiValues.get(l.key),d=l.raw!=null&&c!=null&&l.raw!==c,h=d?l.raw-c:0;d&&(a=!0,this.activeKpiDeltas.set(l.key,{text:this.formatKpiDelta(l.key,h,e.currency),down:h<0})),l.raw!=null&&this.lastKpiValues.set(l.key,l.raw);let u=this.activeKpiDeltas.get(l.key),b=this.opts.onOpenTrend&&(l.key==="booked-inventory"||l.key==="booked-pct"||l.key==="booked-value");return`<div class="slm-kpi${u?" changed":""}" data-kpi="${l.key}"${b?' tabindex="0"':` title="${g(l.title)}"`}>
670
670
  <b>${l.dot?`<span class="dot" style="background:${l.dot}"></span>`:""}${l.n}</b><span>${l.l}</span>
671
671
  ${u?`<span class="slm-kpidelta${u.down?" down":""}">${u.text}</span>`:""}
@@ -719,14 +719,14 @@ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:
719
719
  <button type="button" class="slm-btn ghost" data-ref="categoryreset" disabled>Reset to chart defaults</button>
720
720
  <p class="slm-note" data-ref="categoryresetnote">Checking what differs from the chart\u2026</p>
721
721
  </div>
722
- ${Y("catfoot")}`,this.categoryCanManage||this.withExtras(o=>{this.lockedTypes=this.alertOf(o.typesLocked(this.opts.organizationName)),this.mode==="categories"&&!this.categoryCanManage&&(this.panelAlert=this.lockedTypes,this.paintCategorySelection(this.getSelection()))});let i=o=>this.els.rail.querySelector(`[data-ref="${o}"]`);this.els.rail.querySelectorAll("[data-assign-category]").forEach(o=>{o.addEventListener("click",()=>{this.categoryChoice=o.dataset.assignCategory,this.paintCategorySelection(this.getSelection())})}),i("catfoot").querySelector("[data-foot-action]").addEventListener("click",()=>{if(this.categoryDone?.partial){this.categoryDone=null,this.panelAlert=null,this.clearSelection();return}this.categoryChoice&&this.setCategory(this.categoryChoice)}),i("catfoot").querySelector("[data-foot-secondary]").addEventListener("click",()=>{this.undoCategory()}),i("categoryreset").addEventListener("click",()=>{this.resetCategoriesToChart()}),t.wire(this.els.rail),this.paintCategorySelection(this.getSelection()),this.loadCategoryDifferences()}async loadCategoryDifferences(){let e=this.els.rail;if(!e||this.closed)return;let t=e.querySelector('[data-ref="categoryreset"]'),s=e.querySelector('[data-ref="categoryresetnote"]');if(!(!t||!s))try{let i=await this.withAuthRetry(()=>this.api.categoryDifferences(this.key));if(!t.isConnected)return;this.categoryDifferences=i.differing,this.paintCategoryReset()}catch(i){if(!t.isConnected)return;s.textContent="Could not check the chart\u2019s defaults. Reset is unavailable until it can.",this.opts.onError?.(i)}}paintCategoryReset(){let e=this.els.rail;if(!e)return;let t=e.querySelector('[data-ref="categoryreset"]'),s=e.querySelector('[data-ref="categoryresetnote"]');if(!t||!s)return;let i=this.categoryDifferences;i!=null&&(t.disabled=i===0,t.textContent=i?`Reset to chart defaults \xB7 ${i.toLocaleString()} seat${i===1?"":"s"}`:"Reset to chart defaults",s.textContent=i?"Puts every seat this event moved back in its chart category. Held and booked seats keep the price they were sold at.":"Every seat sells under its chart category.")}async resetCategoriesToChart(){let e=this.els.rail.querySelector('[data-ref="categoryreset"]');e&&(e.disabled=!0,e.textContent="Resetting\u2026");try{let t=await this.withAuthRetry(()=>this.api.resetCategoriesToChart(this.key));t.changed&&await this.reloadEventChart(),this.categoryDifferences=0,this.clearSelection(),this.mode==="categories"&&this.paintRail(),this.paintCategoryReset(),this.done("resetCategories",t.labels,t.changed?`Put ${t.labels.length.toLocaleString()} seat${t.labels.length===1?"":"s"} back on the chart\u2019s categories.`:"Every seat already sells under its chart category.")}catch(t){this.paintCategoryReset(),this.toastErr("Couldn\u2019t reset those categories. Nothing changed."),this.opts.onError?.(t)}}paintCategorySelection(e){let t=this.els.rail,s=t?.querySelector('[data-ref="selcard"]'),i=t?.querySelector('[data-ref="catfoot"]');if(!s||!i)return;let o=this.categoryDone?.partial&&this.categoryDone.labels.length===e.length?this.categoryDone:null,n=this.selectionSummary(e,!0);K(s,o?{...n,parts:[{label:`${o.labels.length.toLocaleString()} moved`,tone:"ok"}]}:n),this.paintAddBy(e.length);let a=t.querySelector('[data-ref="panelalert"]');a&&(a.innerHTML=this.panelAlert??"");let l=e.length,c=this.categoryTotals(),d=e.filter(v=>v.categoryKey===this.categoryChoice).length;t.querySelectorAll("[data-assign-category]").forEach(v=>{let L=v.dataset.assignCategory,W=L===this.categoryChoice;v.setAttribute("aria-checked",String(W)),v.classList.toggle("on",W),v.disabled=this.categoryBusy,v.classList.toggle("locked",!this.categoryCanManage);let N=l>0&&n.types.length===1&&n.types[0].count!=null&&e[0].categoryKey===L,R=v.querySelector("[data-cat-current]");if(R){let V=c.get(L)??0;R.textContent=N?" \xB7 now":` \xB7 ${V.toLocaleString()}`,R.setAttribute("aria-label",N?"all selected seats are here now":w(V))}});let h=this.doc?.categories.find(v=>v.key===this.categoryChoice)?.label??this.categoryChoice??"",u=l-d,b=n.parts.filter(v=>v.tone==="muted"||v.tone==="warn").map(v=>v.label),p=this.categoryDone&&(this.categoryDone.partial||this.categoryDone.until>Date.now())?this.categoryDone:null;t.classList.toggle("slm-settled",!!p?.partial);let m=t.querySelector('[data-ref="categoryreset"]');m&&!this.categoryCanManage&&(m.disabled=!0),j(i,this.categoryBusy?{label:this.categoryUndoing?"Undoing\u2026":`Moving ${w(u)}\u2026`,busy:!0,note:"Buyers see the new price as soon as this finishes."}:p?.partial?{label:"Done",secondary:`Undo the ${p.labels.length.toLocaleString()}`,look:"settle"}:p?{label:`Done: ${w(p.labels.length)} now ${p.labels.length===1?"sells":"sell"} as ${p.name}`,disabled:!0,note:"Changed just now",secondary:"Undo",look:"done"}:this.categoryCanManage?this.categoryFailed&&l?{label:"Try again",note:"Your selection is kept."}:l?this.categoryChoice?u?{label:`Move ${w(u)} to ${h}`,note:this.selWhole?`${b.length?"Sold seats and seats in a cart keep their price. ":""}Blocked seats move too and stay blocked.`:b.length?`The ${b.join(" and ")} seats keep the price they were sold at.`:void 0}:{label:`Already ${h}`,disabled:!0,note:"Every selected seat already sells as this ticket type."}:{label:"Pick a ticket type",disabled:!0,note:`Choose where the ${l===1?"seat":`${l.toLocaleString()} seats`} should sell.`}:{label:"Select seats first",disabled:!0,note:"Pick seats on the map, then a ticket type."}:{label:l&&this.categoryChoice&&u?`Move ${w(u)} to ${h}`:l?"Pick a ticket type":"Select seats first",disabled:!0,note:'Needs the "Manage ticket types" permission.'})}addByHtml(e){return`<details class="slm-addby" data-ref="addby" open><summary class="slm-eyebrow">Add seats by</summary>${e}</details>`}paintAddBy(e){let t=this.els.rail?.querySelector('[data-ref="addby"]');if(!t)return;e||(this.addByPinned=!1),t.dataset.wired||(t.dataset.wired="1",t.addEventListener("toggle",()=>{this.getSelection().length&&(this.addByPinned=t.open)}));let s=!e||this.addByPinned;t.open!==s&&(t.open=s)}categoryTotals(){if(this.categoryTotalsCache)return this.categoryTotalsCache;let e=new Map;for(let t of this.labelToSeat.values())e.set(t.categoryKey,(e.get(t.categoryKey)??0)+1);return this.categoryTotalsCache=e,e}selectionSummary(e,t=!1){let s={free:0,booked:0,held:0,blocked:0},i=new Map,o=new Map,n=this.rowLabels();for(let p of e){s[this.status.get(p.label)??"free"]+=1,o.set(p.categoryKey,(o.get(p.categoryKey)??0)+1);let m=this.sectionByObject.get(p.rowId)??S,v=i.get(m)??{label:this.sectionLabelById.get(m)??"Other seats",rows:new Map},L=n.get(p.rowId);L&&v.rows.set(L.startsWith(`${v.label} `)?L.slice(v.label.length+1):L,!0),i.set(m,v)}let a=(p,m)=>p.localeCompare(m,void 0,{numeric:!0,sensitivity:"base"}),l=[];s.free&&l.push({label:`${s.free.toLocaleString()} free`,tone:"ok"}),s.booked&&l.push({label:`${s.booked.toLocaleString()} sold`,tone:"muted"}),s.held&&l.push({label:`${s.held.toLocaleString()} in a cart`,tone:"warn"}),s.blocked&&l.push({label:`${s.blocked.toLocaleString()} blocked`,tone:"danger"});let c=t&&this.savedApplied&&this.savedApplied.labels.size===e.length&&e.every(p=>this.savedApplied.labels.has(p.label))?this.savedApplied:null,d=c?c.sold+c.taken:0,h=c&&[s.booked?`${s.booked.toLocaleString()} of these ${s.booked===1?"was":"were"} sold since it was saved. They stay picked so you can see them; Block and Reserve skip them.`:"",d?`${d.toLocaleString()} of the ${(e.length+d+c.missing).toLocaleString()} ${c.taken?`${c.sold?"were sold or are":"are"} in a cart or blocked`:`${d===1?"was":"were"} sold`} since it was saved, so ${e.length.toLocaleString()} ${e.length===1?"is":"are"} picked.`:"",c.missing?`${c.missing.toLocaleString()} saved ${c.missing===1?"seat is":"seats are"} no longer on this chart${c.changed?` (it changed on ${c.changed})`:""}.${d?"":` The other ${e.length.toLocaleString()} are picked.`}`:""].filter(Boolean).join(" ")||null,u=t&&this.selJustSold.size?e.filter(p=>this.selJustSold.has(p.label)).length:0,b=u?`${u.toLocaleString()} ${u===1?"seat in your selection was":"seats in your selection were"} just sold.${this.mode==="categories"?` ${u===1?"It":"They"} will keep ${u===1?"its":"their"} price.`:""}`:null;return{count:e.length,where:c?`${c.name} \xB7 saved selection`:this.selWhole&&t&&i.size>1?`Whole venue \xB7 ${i.size.toLocaleString()} sections (${Oe().replace(/K$/,"A")})`:Ie([...i.values()].map(p=>({label:p.label,rows:[...p.rows.keys()].sort(a)}))),stale:[b,h,t&&this.selLeft].filter(Boolean).join(" ")||null,canSave:t&&this.canBlock(),canSimilar:t&&e.length>0&&this.isChoosingTool(),canUndo:this.selBack.length>0,saved:t?this.savedCount:null,parts:l,types:o.size>3?[{label:`${o.size} ticket types`,color:"#8b5cf6",count:null}]:[...o].map(([p,m])=>{let v=this.doc?.categories.find(L=>L.key===p);return{label:v?.label??p,color:this.typeColour(p,v?.color),count:m}})}}rowLabels(){if(this.rowLabelCache?.doc===this.doc)return this.rowLabelCache.labels;let e=new Map;for(let t of this.doc?.objects??[])t.type==="row"?e.set(t.id,t.segmentedRow?.displayLabel??t.displayLabel??t.label):t.type==="table"&&e.set(t.id,t.displayLabel??t.label);return this.rowLabelCache={doc:this.doc,labels:e},e}renderTablesRail(){let e=this.mountTask("table","#65a30d","Tables","Sell each table per chair, or as one whole-table booking.");this.loadExtras().then(t=>{this.closed||this.mode!=="tables"||!e.isConnected||(this.tablesPanel=t.mountTables({mount:e,...this.panelKit(),oldModel:this.inventoryModelVersion!==2,tables:()=>this.tableInfos(),save:async(s,i)=>{let o=await this.saveTableBooking(s,i);return o==="skipped"?"failed":o},show:s=>this.frameLabels([...this.labelToSeat.values()].filter(i=>i.rowId===s).map(i=>i.label))}))}).catch(t=>this.extrasFailed(e,t))}mountTask(e,t,s,i){let o=s==="Sections"?"sections":s==="Tables"?"tables":void 0;return this.els.rail.innerHTML=`${z({glyph:e,hue:t,title:s,badge:"This event only",purpose:i,how:o})}
723
- <div data-ref="panelalert"></div><div data-ref="taskmount"><div class="slm-empty" role="status">Loading\u2026</div></div>`,this.els.rail.querySelector('[data-ref="taskmount"]')}panelKit(){let e=this.els.rail;return{alert:t=>{let s=e.querySelector('[data-ref="panelalert"]');s&&(s.innerHTML=t??"")},alertHtml:B,plate:k}}extrasFailed(e,t){e.isConnected&&(e.innerHTML='<div class="slm-empty" role="alert">This tool could not load. Switch tools and back to try again.</div>'),this.opts.onError?.(t)}tableInfos(){return this.tables().map(e=>{let t=0,s=0,i=0;for(let[n,a]of this.labelToSeat){if(a.rowId!==e.id)continue;let l=this.status.get(n);l==="held"?t++:l==="booked"?s++:l==="blocked"&&i++}let o=[s&&`${s} booked`,i&&`${i} blocked`].filter(Boolean).join(" \xB7 ");return{id:e.id,label:e.displayLabel??e.label,chairs:e.seatCount,mode:e.variableOccupancy?"variable":e.bookAsWhole?"whole":"individual",locked:o||null,held:t}})}captioned(e,t){return t.caption?this.blockCaptions.set(e,t):this.blockCaptions.delete(e),t.caption&&this.captionsOn?{...t,stateWord:null}:t}paintWatchSeat(e){let t=this.els.rail?.querySelector('[data-ref="watchseat"]');if(!t)return;let s=e[e.length-1];if(this.seatHistoryPanel&&e.length<2&&s===this.historySeat&&!t.querySelector('[data-ref="seat-history"][hidden]'))return;if(this.seatHistoryPanel?.destroy(),this.seatHistoryPanel=null,e.length>1){t.innerHTML='<div class="slm-selcard" aria-live="polite"></div>',K(t.firstElementChild,this.selectionSummary(e,!0));return}if(!s){t.innerHTML=`<div class="slm-watchhint">${k("cursor","#3b82f6",28)}<span>${D()?"Tap any seat to read it, or search a seat or booking.":`Click any seat to read it, or press ${le()} and type a seat or booking.`}</span></div>`;return}let i=this.status.get(s.label)??"free",o=this.sectionByObject.get(s.rowId)??S,n=this.sectionLabelById.get(o)??"Other seats",a=s.label.startsWith(`${n} `)?s.label.slice(n.length+1):s.label,[l,c]=a.includes("-")?[a.slice(0,a.lastIndexOf("-")),a.slice(a.lastIndexOf("-")+1)]:["",a],d=this.doc?.categories.find(x=>x.key===s.categoryKey),h=d?`${d.label}${typeof d.price=="number"?` \xB7 ${M(d.price,this.currency)}`:""}`:s.categoryKey,u=i==="blocked"?this.reservedBy.get(s.label):void 0,b=this.channels?.channelNameForLabel(s.label)??"Public sale",p=u?[["Status","Reserved"],["For",u.name],...u.by?[["Reserved by",u.by]]:[],["Until",u.releaseAt==null?"No end":q(u.releaseAt)]]:i==="booked"?[["Status","Sold"],["Ticket type",h],["Booking","\u2026"],["Buyer","\u2026"],["Channel",b]]:i==="held"?[["Status","In a cart"],["Ticket type",h],["Where","\u2026"],["Cart","\u2026"]]:i==="blocked"?[["Status","Blocked"],["Reason","\u2026"],["Blocked by","\u2026"],["Back on sale","\u2026"]]:[["Status","Free"],["Ticket type",h],["Channel",b]],m=(x,f,y,T)=>`<button type="button" class="slm-btn ghost" data-watch="${x}">${O(y,T,15)}${f}</button>`,v=u?m("reserve","Open in Reserve","bookmark","#c026d3"):i==="blocked"?m("unblock","Put back on sale","undo",F.free[1]):i==="free"?`${this.toolAvailable("block")?m("block","Block","ban","#d64545"):""}${this.toolAvailable("reserve")?m("reserve-seat","Reserve","bookmark","#c026d3"):""}`:"",[L,W]=F[u?"reserved":i]??F.free;t.innerHTML=`<div class="slm-watchcard${u?" reserved":""}">
724
- <div class="slm-seat-heading">${k(L,W,30)}<span><h2>${g(n)} \xB7 ${g(a)}</h2>${l?`<small>Row ${g(l)}, seat ${g(c)}</small>`:""}</span>
725
- <button type="button" class="slm-watchclose" data-watch="close" aria-label="Close the seat card">${O("x","currentColor",15)}</button></div>
726
- <dl>${p.map(([x,f])=>`<div><dt>${g(x)}</dt><dd>${g(f)}</dd></div>`).join("")}</dl>
722
+ ${Y("catfoot")}`,this.categoryCanManage||this.withExtras(o=>{this.lockedTypes=this.alertOf(o.typesLocked(this.opts.organizationName)),this.mode==="categories"&&!this.categoryCanManage&&(this.panelAlert=this.lockedTypes,this.paintCategorySelection(this.getSelection()))});let i=o=>this.els.rail.querySelector(`[data-ref="${o}"]`);this.els.rail.querySelectorAll("[data-assign-category]").forEach(o=>{o.addEventListener("click",()=>{this.categoryChoice=o.dataset.assignCategory,this.paintCategorySelection(this.getSelection())})}),i("catfoot").querySelector("[data-foot-action]").addEventListener("click",()=>{if(this.categoryDone?.partial){this.categoryDone=null,this.panelAlert=null,this.clearSelection();return}this.categoryChoice&&this.setCategory(this.categoryChoice)}),i("catfoot").querySelector("[data-foot-secondary]").addEventListener("click",()=>{this.undoCategory()}),i("categoryreset").addEventListener("click",()=>{this.resetCategoriesToChart()}),t.wire(this.els.rail),this.paintCategorySelection(this.getSelection()),this.loadCategoryDifferences()}async loadCategoryDifferences(){let e=this.els.rail;if(!e||this.closed)return;let t=e.querySelector('[data-ref="categoryreset"]'),s=e.querySelector('[data-ref="categoryresetnote"]');if(!(!t||!s))try{let i=await this.withAuthRetry(()=>this.api.categoryDifferences(this.key));if(!t.isConnected)return;this.categoryDifferences=i.differing,this.paintCategoryReset()}catch(i){if(!t.isConnected)return;s.textContent="Could not check the chart\u2019s defaults. Reset is unavailable until it can.",this.opts.onError?.(i)}}paintCategoryReset(){let e=this.els.rail;if(!e)return;let t=e.querySelector('[data-ref="categoryreset"]'),s=e.querySelector('[data-ref="categoryresetnote"]');if(!t||!s)return;let i=this.categoryDifferences;i!=null&&(t.disabled=i===0,t.textContent=i?`Reset to chart defaults \xB7 ${i.toLocaleString()} seat${i===1?"":"s"}`:"Reset to chart defaults",s.textContent=i?"Puts every seat this event moved back in its chart category. Held and booked seats keep the price they were sold at.":"Every seat sells under its chart category.")}async resetCategoriesToChart(){let e=this.els.rail.querySelector('[data-ref="categoryreset"]');e&&(e.disabled=!0,e.textContent="Resetting\u2026");try{let t=await this.withAuthRetry(()=>this.api.resetCategoriesToChart(this.key));t.changed&&await this.reloadEventChart(),this.categoryDifferences=0,this.clearSelection(),this.mode==="categories"&&this.paintRail(),this.paintCategoryReset(),this.done("resetCategories",t.labels,t.changed?`Put ${t.labels.length.toLocaleString()} seat${t.labels.length===1?"":"s"} back on the chart\u2019s categories.`:"Every seat already sells under its chart category.")}catch(t){this.paintCategoryReset(),this.toastErr("Couldn\u2019t reset those categories. Nothing changed."),this.opts.onError?.(t)}}paintCategorySelection(e){let t=this.els.rail,s=t?.querySelector('[data-ref="selcard"]'),i=t?.querySelector('[data-ref="catfoot"]');if(!s||!i)return;let o=this.categoryDone?.partial&&this.categoryDone.labels.length===e.length?this.categoryDone:null,n=this.selectionSummary(e,!0);K(s,o?{...n,parts:[{label:`${o.labels.length.toLocaleString()} moved`,tone:"ok"}]}:n),this.paintAddBy(e.length);let a=t.querySelector('[data-ref="panelalert"]');a&&(a.innerHTML=this.panelAlert??"");let l=e.length,c=this.categoryTotals(),d=e.filter(v=>v.categoryKey===this.categoryChoice).length;t.querySelectorAll("[data-assign-category]").forEach(v=>{let L=v.dataset.assignCategory,W=L===this.categoryChoice;v.setAttribute("aria-checked",String(W)),v.classList.toggle("on",W),v.disabled=this.categoryBusy,v.classList.toggle("locked",!this.categoryCanManage);let N=l>0&&n.types.length===1&&n.types[0].count!=null&&e[0].categoryKey===L,R=v.querySelector("[data-cat-current]");if(R){let V=c.get(L)??0;R.textContent=N?" \xB7 now":` \xB7 ${V.toLocaleString()}`,R.setAttribute("aria-label",N?"all selected seats are here now":w(V))}});let h=this.doc?.categories.find(v=>v.key===this.categoryChoice)?.label??this.categoryChoice??"",u=l-d,b=n.parts.filter(v=>v.tone==="muted"||v.tone==="warn").map(v=>v.label),p=this.categoryDone&&(this.categoryDone.partial||this.categoryDone.until>Date.now())?this.categoryDone:null;t.classList.toggle("slm-settled",!!p?.partial);let m=t.querySelector('[data-ref="categoryreset"]');m&&!this.categoryCanManage&&(m.disabled=!0),j(i,this.categoryBusy?{label:this.categoryUndoing?"Undoing\u2026":`Moving ${w(u)}\u2026`,busy:!0,note:"Buyers see the new price as soon as this finishes."}:p?.partial?{label:"Done",secondary:`Undo the ${p.labels.length.toLocaleString()}`,look:"settle"}:p?{label:`Done: ${w(p.labels.length)} now ${p.labels.length===1?"sells":"sell"} as ${p.name}`,disabled:!0,note:"Changed just now",secondary:"Undo",look:"done"}:this.categoryCanManage?this.categoryFailed&&l?{label:"Try again",note:"Your selection is kept."}:l?this.categoryChoice?u?{label:`Move ${w(u)} to ${h}`,note:this.selWhole?`${b.length?"Sold seats and seats in a cart keep their price. ":""}Blocked seats move too and stay blocked.`:b.length?`The ${b.join(" and ")} seats keep the price they were sold at.`:void 0}:{label:`Already ${h}`,disabled:!0,note:"Every selected seat already sells as this ticket type."}:{label:"Pick a ticket type",disabled:!0,note:`Choose where the ${l===1?"seat":`${l.toLocaleString()} seats`} should sell.`}:{label:"Select seats first",disabled:!0,note:"Pick seats on the map, then a ticket type."}:{label:l&&this.categoryChoice&&u?`Move ${w(u)} to ${h}`:l?"Pick a ticket type":"Select seats first",disabled:!0,note:'Needs the "Manage ticket types" permission.'})}addByHtml(e){return`<details class="slm-addby" data-ref="addby" open><summary class="slm-eyebrow">Add seats by</summary>${e}</details>`}paintAddBy(e){let t=this.els.rail?.querySelector('[data-ref="addby"]');if(!t)return;e||(this.addByPinned=!1),t.dataset.wired||(t.dataset.wired="1",t.addEventListener("toggle",()=>{this.getSelection().length&&(this.addByPinned=t.open)}));let s=!e||this.addByPinned;t.open!==s&&(t.open=s)}categoryTotals(){if(this.categoryTotalsCache)return this.categoryTotalsCache;let e=new Map;for(let t of this.labelToSeat.values())e.set(t.categoryKey,(e.get(t.categoryKey)??0)+1);return this.categoryTotalsCache=e,e}selectionSummary(e,t=!1){let s={free:0,booked:0,held:0,blocked:0},i=new Map,o=new Map,n=this.rowLabels();for(let p of e){s[this.status.get(p.label)??"free"]+=1,o.set(p.categoryKey,(o.get(p.categoryKey)??0)+1);let m=this.sectionByObject.get(p.rowId)??S,v=i.get(m)??{label:this.sectionLabelById.get(m)??"Other seats",rows:new Map},L=n.get(p.rowId);L&&v.rows.set(L.startsWith(`${v.label} `)?L.slice(v.label.length+1):L,!0),i.set(m,v)}let a=(p,m)=>p.localeCompare(m,void 0,{numeric:!0,sensitivity:"base"}),l=[];s.free&&l.push({label:`${s.free.toLocaleString()} free`,tone:"ok"}),s.booked&&l.push({label:`${s.booked.toLocaleString()} sold`,tone:"muted"}),s.held&&l.push({label:`${s.held.toLocaleString()} in a cart`,tone:"warn"}),s.blocked&&l.push({label:`${s.blocked.toLocaleString()} blocked`,tone:"danger"});let c=t&&this.savedApplied&&this.savedApplied.labels.size===e.length&&e.every(p=>this.savedApplied.labels.has(p.label))?this.savedApplied:null,d=c?c.sold+c.taken:0,h=c&&[s.booked?`${s.booked.toLocaleString()} of these ${s.booked===1?"was":"were"} sold since it was saved. They stay picked so you can see them; Block and Reserve skip them.`:"",d?`${d.toLocaleString()} of the ${(e.length+d+c.missing).toLocaleString()} ${c.taken?`${c.sold?"were sold or are":"are"} in a cart or blocked`:`${d===1?"was":"were"} sold`} since it was saved, so ${e.length.toLocaleString()} ${e.length===1?"is":"are"} picked.`:"",c.missing?`${c.missing.toLocaleString()} saved ${c.missing===1?"seat is":"seats are"} no longer on this chart${c.changed?` (it changed on ${c.changed})`:""}.${d?"":` The other ${e.length.toLocaleString()} are picked.`}`:""].filter(Boolean).join(" ")||null,u=t&&this.selJustSold.size?e.filter(p=>this.selJustSold.has(p.label)).length:0,b=u?`${u.toLocaleString()} ${u===1?"seat in your selection was":"seats in your selection were"} just sold.${this.mode==="categories"?` ${u===1?"It":"They"} will keep ${u===1?"its":"their"} price.`:""}`:null;return{count:e.length,where:c?`${c.name} \xB7 saved selection`:this.selWhole&&t&&i.size>1?`Whole venue \xB7 ${i.size.toLocaleString()} sections (${Ie().replace(/K$/,"A")})`:Oe([...i.values()].map(p=>({label:p.label,rows:[...p.rows.keys()].sort(a)}))),stale:[b,h,t&&this.selLeft].filter(Boolean).join(" ")||null,canSave:t&&this.canBlock(),canSimilar:t&&e.length>0&&this.isChoosingTool(),canUndo:this.selBack.length>0,saved:t?this.savedCount:null,parts:l,types:o.size>3?[{label:`${o.size} ticket types`,color:"#8b5cf6",count:null}]:[...o].map(([p,m])=>{let v=this.doc?.categories.find(L=>L.key===p);return{label:v?.label??p,color:this.typeColour(p,v?.color),count:m}})}}rowLabels(){if(this.rowLabelCache?.doc===this.doc)return this.rowLabelCache.labels;let e=new Map;for(let t of this.doc?.objects??[])t.type==="row"?e.set(t.id,t.segmentedRow?.displayLabel??t.displayLabel??t.label):t.type==="table"&&e.set(t.id,t.displayLabel??t.label);return this.rowLabelCache={doc:this.doc,labels:e},e}renderTablesRail(){let e=this.mountTask("table","#65a30d","Tables","Sell each table per chair, or as one whole-table booking.");this.loadExtras().then(t=>{this.closed||this.mode!=="tables"||!e.isConnected||(this.tablesPanel=t.mountTables({mount:e,...this.panelKit(),oldModel:this.inventoryModelVersion!==2,tables:()=>this.tableInfos(),save:async(s,i)=>{let o=await this.saveTableBooking(s,i);return o==="skipped"?"failed":o},show:s=>this.frameLabels([...this.labelToSeat.values()].filter(i=>i.rowId===s).map(i=>i.label))}))}).catch(t=>this.extrasFailed(e,t))}mountTask(e,t,s,i){let o=s==="Sections"?"sections":s==="Tables"?"tables":void 0;return this.els.rail.innerHTML=`${z({glyph:e,hue:t,title:s,badge:"This event only",purpose:i,how:o})}
723
+ <div data-ref="panelalert"></div><div data-ref="taskmount"><div class="slm-empty" role="status">Loading\u2026</div></div>`,this.els.rail.querySelector('[data-ref="taskmount"]')}panelKit(){let e=this.els.rail;return{alert:t=>{let s=e.querySelector('[data-ref="panelalert"]');s&&(s.innerHTML=t??"")},alertHtml:B,plate:x}}extrasFailed(e,t){e.isConnected&&(e.innerHTML='<div class="slm-empty" role="alert">This tool could not load. Switch tools and back to try again.</div>'),this.opts.onError?.(t)}tableInfos(){return this.tables().map(e=>{let t=0,s=0,i=0;for(let[n,a]of this.labelToSeat){if(a.rowId!==e.id)continue;let l=this.status.get(n);l==="held"?t++:l==="booked"?s++:l==="blocked"&&i++}let o=[s&&`${s} booked`,i&&`${i} blocked`].filter(Boolean).join(" \xB7 ");return{id:e.id,label:e.displayLabel??e.label,chairs:e.seatCount,mode:e.variableOccupancy?"variable":e.bookAsWhole?"whole":"individual",locked:o||null,held:t}})}captioned(e,t){return t.caption?this.blockCaptions.set(e,t):this.blockCaptions.delete(e),t.caption&&this.captionsOn?{...t,stateWord:null}:t}paintWatchSeat(e){let t=this.els.rail?.querySelector('[data-ref="watchseat"]');if(!t)return;let s=e[e.length-1];if(this.seatHistoryPanel&&e.length<2&&s===this.historySeat&&!t.querySelector('[data-ref="seat-history"][hidden]'))return;if(this.seatHistoryPanel?.destroy(),this.seatHistoryPanel=null,e.length>1){t.innerHTML='<div class="slm-selcard" aria-live="polite"></div>',K(t.firstElementChild,this.selectionSummary(e,!0));return}if(!s){t.innerHTML=`<div class="slm-watchhint">${x("cursor","#3b82f6",28)}<span>${D()?"Tap any seat to read it, or search a seat or booking.":`Click any seat to read it, or press ${le()} and type a seat or booking.`}</span></div>`;return}let i=this.status.get(s.label)??"free",o=this.sectionByObject.get(s.rowId)??S,n=this.sectionLabelById.get(o)??"Other seats",a=s.label.startsWith(`${n} `)?s.label.slice(n.length+1):s.label,[l,c]=a.includes("-")?[a.slice(0,a.lastIndexOf("-")),a.slice(a.lastIndexOf("-")+1)]:["",a],d=this.doc?.categories.find(k=>k.key===s.categoryKey),h=d?`${d.label}${typeof d.price=="number"?` \xB7 ${M(d.price,this.currency)}`:""}`:s.categoryKey,u=i==="blocked"?this.reservedBy.get(s.label):void 0,b=this.channels?.channelNameForLabel(s.label)??"Public sale",p=u?[["Status","Reserved"],["For",u.name],...u.by?[["Reserved by",u.by]]:[],["Until",u.releaseAt==null?"No end":q(u.releaseAt)]]:i==="booked"?[["Status","Sold"],["Ticket type",h],["Booking","\u2026"],["Buyer","\u2026"],["Channel",b]]:i==="held"?[["Status","In a cart"],["Ticket type",h],["Where","\u2026"],["Cart","\u2026"]]:i==="blocked"?[["Status","Blocked"],["Reason","\u2026"],["Blocked by","\u2026"],["Back on sale","\u2026"]]:[["Status","Free"],["Ticket type",h],["Channel",b]],m=(k,f,y,T)=>`<button type="button" class="slm-btn ghost" data-watch="${k}">${I(y,T,15)}${f}</button>`,v=u?m("reserve","Open in Reserve","bookmark","#c026d3"):i==="blocked"?m("unblock","Put back on sale","undo",F.free[1]):i==="free"?`${this.toolAvailable("block")?m("block","Block","ban","#d64545"):""}${this.toolAvailable("reserve")?m("reserve-seat","Reserve","bookmark","#c026d3"):""}`:"",[L,W]=F[u?"reserved":i]??F.free;t.innerHTML=`<div class="slm-watchcard${u?" reserved":""}">
724
+ <div class="slm-seat-heading">${x(L,W,30)}<span><h2>${g(n)} \xB7 ${g(a)}</h2>${l?`<small>Row ${g(l)}, seat ${g(c)}</small>`:""}</span>
725
+ <button type="button" class="slm-watchclose" data-watch="close" aria-label="Close the seat card">${I("x","currentColor",15)}</button></div>
726
+ <dl>${p.map(([k,f])=>`<div><dt>${g(k)}</dt><dd>${g(f)}</dd></div>`).join("")}</dl>
727
727
  <div class="slm-watchacts">${v}${m("history","Seat history","history","#64748b")}</div>
728
728
  <div data-ref="seat-history" hidden></div>
729
- </div>`,i==="blocked"&&!u&&this.toolAvailable("block")&&this.loadBlockGroups().then(x=>{let f=x.find(T=>T.labels.includes(s.label)),y=t.querySelectorAll(".slm-watchcard dd");!y.length||!t.isConnected||(y[1].textContent=f?.reason??"No reason given",y[2].textContent=f&&[f.byYou?"you":f.byName,f.at?C(f.at,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}):null].filter(Boolean).join(" \xB7 ")||"\u2014",y[3].textContent=f?.releaseAt?q(f.releaseAt):"When you put it back")}).catch(()=>{});let N=(x,f)=>this.withAuthRetry(()=>this.api.seatStory(this.key,s.label,x,f)),R=null,V=()=>{let x=s.label+i,f=this.cardRead;if(f?.[0]===x&&Date.now()-f[1]<5e3)return f[2];let y=N();return y.catch(()=>{this.cardRead?.[2]===y&&(this.cardRead=void 0)}),(this.cardRead=[x,Date.now(),y])[2]},H=x=>[...t.querySelectorAll(".slm-watchcard dl > div")].find(f=>f.querySelector("dt")?.textContent===x);i==="held"&&(R=V(),R.then(x=>{if(!t.isConnected||t.querySelector(".slm-watchcard h2")?.textContent!==`${n} \xB7 ${a}`)return;let f=x.cart;if(!f){H("Where")?.remove(),H("Cart")?.remove();return}let y=Math.max(0,Math.ceil((f.expiresAt-Date.now())/6e4));H("Status").querySelector("dd").textContent=`In a cart \xB7 ${y<=1?"under a minute":`${y} min`} left`,f.where?H("Where").querySelector("dd").textContent=f.where:H("Where")?.remove(),H("Cart").querySelector("dd").textContent=`${w(f.seats)}`}).catch(()=>{H("Where")?.remove(),H("Cart")?.remove()})),i==="booked"&&(R=V(),R.then(x=>{if(!t.isConnected||t.querySelector(".slm-watchcard h2")?.textContent!==`${n} \xB7 ${a}`)return;let f=[...t.querySelectorAll(".slm-watchcard dl > div")],y=It=>f.find(Pt=>Pt.querySelector("dt")?.textContent===It),T=x.booking;if(T===void 0){y("Booking")?.remove(),y("Buyer")?.remove();return}let E=T?.order??null,ke=y("Booking")?.querySelector("dd");ke&&(ke.textContent=T?.displayRef??E?.displayRef??T?.ref??"\u2014");let we=E?[E.buyerName,E.buyerEmailDomain].filter(Boolean).join(" \xB7 "):"";we?y("Buyer").querySelector("dd").textContent=we:y("Buyer")?.remove(),E&&this.opts.onOpenOrder&&!t.querySelector('[data-watch="order"]')&&(t.querySelector(".slm-watchacts")?.insertAdjacentHTML("afterbegin",`<button type="button" class="slm-btn ghost" data-watch="order">${O("ticket","#8b5cf6",15)}Open order</button>`),t.querySelector('[data-watch="order"]').addEventListener("click",()=>this.opts.onOpenOrder({id:E.id,displayRef:E.displayRef})))}).catch(()=>{for(let x of t.querySelectorAll(".slm-watchcard dl > div")){let f=x.querySelector("dt")?.textContent;(f==="Booking"||f==="Buyer")&&(x.querySelector("dd").textContent="\u2014")}})),t.querySelectorAll("[data-watch]").forEach(x=>x.addEventListener("click",()=>{let f=x.dataset.watch;if(f==="history"){let y=t.querySelector('[data-ref="seat-history"]');y.hidden=!y.hidden,x.setAttribute("aria-expanded",String(!y.hidden)),!y.hidden&&!this.seatHistoryPanel&&this.loadExtras().then(T=>{y.hidden||!y.isConnected||this.seatHistoryPanel||(this.historySeat=s,this.seatHistoryPanel=T.mountSeatHistory({mount:y,free:i==="free",fetchPage:N,first:R,openOrder:this.opts.onOpenOrder?E=>this.opts.onOpenOrder(E):null}))}).catch(T=>this.extrasFailed(y,T))}else f==="close"?this.clearSelection():f==="unblock"?this.unblock([s.label]):f==="reserve"?this.setMode("reserve"):(this.setMode(f==="block"?"block":"reserve"),this.selectByLabels([s.label]))}))}async refreshAvailability(){try{let e=await this.withAuthRetry(()=>this.api.availability(this.key));this.availabilityRules=e.rules??{},this.effectiveClosed=new Set(fe(this.availabilityRules)),this.sectionsPanel?.update(),this.applySectionCanvasTreatment()}catch(e){this.opts.onError?.(e)}}async withAuthRetry(e){try{return await e()}catch(t){if(t instanceof $&&t.status===401&&this.opts.onTokenRefresh&&!this.tokenRefreshInFlight){if(await this.rotateToken(),this.sessionEnded)throw t;return e()}throw t instanceof $&&t.status===401&&!this.opts.onTokenRefresh&&this.endSession(),t}}updateEffectiveAvailability(e,t){let s=!1;if(Array.isArray(e)){let i=new Set(e.filter(o=>typeof o=="string"));for(let o of this.effectiveHidden){let n=this.availabilityRules[o];i.has(o)||n?.mode!=="timed"&&n?.mode!=="threshold"||(delete this.availabilityRules[o],this.sectionsPanel?.fired(o,n.mode,Date.now()))}this.effectiveHidden=i,s=!0}Array.isArray(t)&&(this.effectiveClosed=new Set(t.filter(i=>typeof i=="string")),s=!0),s&&(this.sectionsPanel?.update(),this.applySectionCanvasTreatment())}applySectionCanvasTreatment(){this.renderer&&(this.refreshBlockPaint(),this.mode==="sections"?(this.renderer.setDimmedSections([...this.effectiveHidden]),this.renderer.setClosedSections([...this.effectiveClosed])):this.mode==="filterSections"&&this.filteredSectionLabel?this.applyFilteredSectionCanvas():(this.renderer.setDimmedSections(null),this.renderer.setClosedSections(null)))}sectionRowsInput(){return{sectionsBase:this.sectionsBase,doc:this.doc,availabilityRules:this.availabilityRules,effectiveHidden:this.effectiveHidden,effectiveClosed:this.effectiveClosed}}renderSectionsRail(){let e=this.mountTask("layers","#0ea5a5","Sections","Decide which sections buyers can see and buy, now or at a set time.");this.applySectionCanvasTreatment(),this.loadExtras().then(t=>{if(this.closed||this.mode!=="sections"||!e.isConnected)return;let s=this.opts.capabilities;this.sectionsPanel=t.mountSections({mount:e,...this.panelKit(),readOnly:!!s&&!s.includes("event:block"),organizationName:this.opts.organizationName,openDesigner:this.opts.onOpenDesigner,rows:()=>ge(this.sectionRowsInput()).rows,soldNow:()=>this.soldShareRest(),heldIn:i=>i.reduce((o,n)=>o+(this.status.get(n)==="held"?1:0),0),change:(i,o)=>this.changeSection(i,o),restore:async i=>{let o=i,n=await this.persistAvailability({...this.availabilityRules,...o});return n&&this.recordChange({kind:"section",restores:!0,sectionId:Object.keys(o)[0],labels:[]}),n},frame:i=>{let o=this.filterableSections().find(a=>a.id===i),n=o?[o]:this.filterableSections().filter(a=>a.zone===i);this.frameSections(n)}})}).catch(t=>this.extrasFailed(e,t))}async changeSection(e,t){let s=ge(this.sectionRowsInput()).rows.find(h=>h.id===e),i=s?.seatLabels??this.availabilityRules[e]?.labels??[],o={[e]:this.availabilityRules[e]??null},n={...this.availabilityRules},a=Ee(t.mode,i,this.availabilityRules[e]);if(a&&t.revealAt!=null&&(a.revealAt=t.revealAt),a&&t.thresholdPct!=null&&(a.thresholdPct=t.thresholdPct),a?n[e]=a:delete n[e],s?.kind==="zone"&&this.sectionsBase)for(let h of this.sectionsBase.sections)h.zone===e&&n[h.id]&&(o[h.id]=n[h.id],delete n[h.id]);if(!await this.persistAvailability(n))return null;let l=ne(o[e]),c={open:"Opened",closed:"Closed",hidden:"Hid",timed:"Scheduled",threshold:"Set a threshold on"}[t.mode],d={open:"open again",closed:"closed again",hidden:"hidden again",timed:"on its schedule again",threshold:"waiting on its threshold again"}[l];return this.recordChange({kind:"section",sectionId:e,sectionLabel:s?.label??e,labels:i,before:o,after:this.availabilityRules[e]??null,verb:c,again:d}),o}soldShareRest(){let e=new Set;for(let i of Object.values(this.availabilityRules))for(let o of i.labels??[])e.add(o);let t=0,s=0;for(let i of this.labelToSeat.keys())e.has(i)||(t++,this.status.get(i)==="booked"&&s++);return t?Math.floor(s*100/t):0}async persistAvailability(e){let t=Object.fromEntries(Object.entries(e).filter(i=>!!i[1])),s=this.availabilityRules;this.availabilityRules=t;try{let i=await this.withAuthRetry(()=>this.api.setAvailability(this.key,t));return this.availabilityRules=i.rules,this.effectiveHidden=new Set(i.hidden),this.effectiveClosed=new Set(fe(i.rules)),this.applySectionCanvasTreatment(),!0}catch(i){return this.availabilityRules=s,this.opts.onError?.(i),!1}finally{this.sectionsPanel?.update()}}paintFeed(){this.activityPanel?.update(this.feed)}renderBlockRail(){let e=this.toolChooser();this.els.rail.innerHTML=`
729
+ </div>`,i==="blocked"&&!u&&this.toolAvailable("block")&&this.loadBlockGroups().then(k=>{let f=k.find(T=>T.labels.includes(s.label)),y=t.querySelectorAll(".slm-watchcard dd");!y.length||!t.isConnected||(y[1].textContent=f?.reason??"No reason given",y[2].textContent=f&&[f.byYou?"you":f.byName,f.at?C(f.at,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}):null].filter(Boolean).join(" \xB7 ")||"\u2014",y[3].textContent=f?.releaseAt?q(f.releaseAt):"When you put it back")}).catch(()=>{});let N=(k,f)=>this.withAuthRetry(()=>this.api.seatStory(this.key,s.label,k,f)),R=null,V=()=>{let k=s.label+i,f=this.cardRead;if(f?.[0]===k&&Date.now()-f[1]<5e3)return f[2];let y=N();return y.catch(()=>{this.cardRead?.[2]===y&&(this.cardRead=void 0)}),(this.cardRead=[k,Date.now(),y])[2]},H=k=>[...t.querySelectorAll(".slm-watchcard dl > div")].find(f=>f.querySelector("dt")?.textContent===k);i==="held"&&(R=V(),R.then(k=>{if(!t.isConnected||t.querySelector(".slm-watchcard h2")?.textContent!==`${n} \xB7 ${a}`)return;let f=k.cart;if(!f){H("Where")?.remove(),H("Cart")?.remove();return}let y=Math.max(0,Math.ceil((f.expiresAt-Date.now())/6e4));H("Status").querySelector("dd").textContent=`In a cart \xB7 ${y<=1?"under a minute":`${y} min`} left`,f.where?H("Where").querySelector("dd").textContent=f.where:H("Where")?.remove(),H("Cart").querySelector("dd").textContent=`${w(f.seats)}`}).catch(()=>{H("Where")?.remove(),H("Cart")?.remove()})),i==="booked"&&(R=V(),R.then(k=>{if(!t.isConnected||t.querySelector(".slm-watchcard h2")?.textContent!==`${n} \xB7 ${a}`)return;let f=[...t.querySelectorAll(".slm-watchcard dl > div")],y=Ot=>f.find(Pt=>Pt.querySelector("dt")?.textContent===Ot),T=k.booking;if(T===void 0){y("Booking")?.remove(),y("Buyer")?.remove();return}let E=T?.order??null,xe=y("Booking")?.querySelector("dd");xe&&(xe.textContent=T?.displayRef??E?.displayRef??T?.ref??"\u2014");let we=E?[E.buyerName,E.buyerEmailDomain].filter(Boolean).join(" \xB7 "):"";we?y("Buyer").querySelector("dd").textContent=we:y("Buyer")?.remove(),E&&this.opts.onOpenOrder&&!t.querySelector('[data-watch="order"]')&&(t.querySelector(".slm-watchacts")?.insertAdjacentHTML("afterbegin",`<button type="button" class="slm-btn ghost" data-watch="order">${I("ticket","#8b5cf6",15)}Open order</button>`),t.querySelector('[data-watch="order"]').addEventListener("click",()=>this.opts.onOpenOrder({id:E.id,displayRef:E.displayRef})))}).catch(()=>{for(let k of t.querySelectorAll(".slm-watchcard dl > div")){let f=k.querySelector("dt")?.textContent;(f==="Booking"||f==="Buyer")&&(k.querySelector("dd").textContent="\u2014")}})),t.querySelectorAll("[data-watch]").forEach(k=>k.addEventListener("click",()=>{let f=k.dataset.watch;if(f==="history"){let y=t.querySelector('[data-ref="seat-history"]');y.hidden=!y.hidden,k.setAttribute("aria-expanded",String(!y.hidden)),!y.hidden&&!this.seatHistoryPanel&&this.loadExtras().then(T=>{y.hidden||!y.isConnected||this.seatHistoryPanel||(this.historySeat=s,this.seatHistoryPanel=T.mountSeatHistory({mount:y,free:i==="free",fetchPage:N,first:R,openOrder:this.opts.onOpenOrder?E=>this.opts.onOpenOrder(E):null}))}).catch(T=>this.extrasFailed(y,T))}else f==="close"?this.clearSelection():f==="unblock"?this.unblock([s.label]):f==="reserve"?this.setMode("reserve"):(this.setMode(f==="block"?"block":"reserve"),this.selectByLabels([s.label]))}))}async refreshAvailability(){try{let e=await this.withAuthRetry(()=>this.api.availability(this.key));this.availabilityRules=e.rules??{},this.effectiveClosed=new Set(fe(this.availabilityRules)),this.sectionsPanel?.update(),this.applySectionCanvasTreatment()}catch(e){this.opts.onError?.(e)}}async withAuthRetry(e){try{return await e()}catch(t){if(t instanceof $&&t.status===401&&this.opts.onTokenRefresh&&!this.tokenRefreshInFlight){if(await this.rotateToken(),this.sessionEnded)throw t;return e()}throw t instanceof $&&t.status===401&&!this.opts.onTokenRefresh&&this.endSession(),t}}updateEffectiveAvailability(e,t){let s=!1;if(Array.isArray(e)){let i=new Set(e.filter(o=>typeof o=="string"));for(let o of this.effectiveHidden){let n=this.availabilityRules[o];i.has(o)||n?.mode!=="timed"&&n?.mode!=="threshold"||(delete this.availabilityRules[o],this.sectionsPanel?.fired(o,n.mode,Date.now()))}this.effectiveHidden=i,s=!0}Array.isArray(t)&&(this.effectiveClosed=new Set(t.filter(i=>typeof i=="string")),s=!0),s&&(this.sectionsPanel?.update(),this.applySectionCanvasTreatment())}applySectionCanvasTreatment(){this.renderer&&(this.refreshBlockPaint(),this.mode==="sections"?(this.renderer.setDimmedSections([...this.effectiveHidden]),this.renderer.setClosedSections([...this.effectiveClosed])):this.mode==="filterSections"&&this.filteredSectionLabel?this.applyFilteredSectionCanvas():(this.renderer.setDimmedSections(null),this.renderer.setClosedSections(null)))}sectionRowsInput(){return{sectionsBase:this.sectionsBase,doc:this.doc,availabilityRules:this.availabilityRules,effectiveHidden:this.effectiveHidden,effectiveClosed:this.effectiveClosed}}renderSectionsRail(){let e=this.mountTask("layers","#0ea5a5","Sections","Decide which sections buyers can see and buy, now or at a set time.");this.applySectionCanvasTreatment(),this.loadExtras().then(t=>{if(this.closed||this.mode!=="sections"||!e.isConnected)return;let s=this.opts.capabilities;this.sectionsPanel=t.mountSections({mount:e,...this.panelKit(),readOnly:!!s&&!s.includes("event:block"),organizationName:this.opts.organizationName,openDesigner:this.opts.onOpenDesigner,rows:()=>ge(this.sectionRowsInput()).rows,soldNow:()=>this.soldShareRest(),heldIn:i=>i.reduce((o,n)=>o+(this.status.get(n)==="held"?1:0),0),change:(i,o)=>this.changeSection(i,o),restore:async i=>{let o=i,n=await this.persistAvailability({...this.availabilityRules,...o});return n&&this.recordChange({kind:"section",restores:!0,sectionId:Object.keys(o)[0],labels:[]}),n},frame:i=>{let o=this.filterableSections().find(a=>a.id===i),n=o?[o]:this.filterableSections().filter(a=>a.zone===i);this.frameSections(n)}})}).catch(t=>this.extrasFailed(e,t))}async changeSection(e,t){let s=ge(this.sectionRowsInput()).rows.find(h=>h.id===e),i=s?.seatLabels??this.availabilityRules[e]?.labels??[],o={[e]:this.availabilityRules[e]??null},n={...this.availabilityRules},a=Ee(t.mode,i,this.availabilityRules[e]);if(a&&t.revealAt!=null&&(a.revealAt=t.revealAt),a&&t.thresholdPct!=null&&(a.thresholdPct=t.thresholdPct),a?n[e]=a:delete n[e],s?.kind==="zone"&&this.sectionsBase)for(let h of this.sectionsBase.sections)h.zone===e&&n[h.id]&&(o[h.id]=n[h.id],delete n[h.id]);if(!await this.persistAvailability(n))return null;let l=ne(o[e]),c={open:"Opened",closed:"Closed",hidden:"Hid",timed:"Scheduled",threshold:"Set a threshold on"}[t.mode],d={open:"open again",closed:"closed again",hidden:"hidden again",timed:"on its schedule again",threshold:"waiting on its threshold again"}[l];return this.recordChange({kind:"section",sectionId:e,sectionLabel:s?.label??e,labels:i,before:o,after:this.availabilityRules[e]??null,verb:c,again:d}),o}soldShareRest(){let e=new Set;for(let i of Object.values(this.availabilityRules))for(let o of i.labels??[])e.add(o);let t=0,s=0;for(let i of this.labelToSeat.keys())e.has(i)||(t++,this.status.get(i)==="booked"&&s++);return t?Math.floor(s*100/t):0}async persistAvailability(e){let t=Object.fromEntries(Object.entries(e).filter(i=>!!i[1])),s=this.availabilityRules;this.availabilityRules=t;try{let i=await this.withAuthRetry(()=>this.api.setAvailability(this.key,t));return this.availabilityRules=i.rules,this.effectiveHidden=new Set(i.hidden),this.effectiveClosed=new Set(fe(i.rules)),this.applySectionCanvasTreatment(),!0}catch(i){return this.availabilityRules=s,this.opts.onError?.(i),!1}finally{this.sectionsPanel?.update()}}paintFeed(){this.activityPanel?.update(this.feed)}renderBlockRail(){let e=this.toolChooser();this.els.rail.innerHTML=`
730
730
  ${z({glyph:"ban",hue:"#d64545",title:"Block",purpose:"Take seats off sale, for a camera, a broken seat or a sight-line. Sold seats and seats in a cart are never touched.",how:"block"})}
731
731
  <div class="slm-monitor-tabs seg" role="tablist" aria-label="Blocking tools"><button role="tab" data-block-tab="edit" aria-selected="${!this.blockBrowse}">Block seats</button><button role="tab" data-block-tab="browse" aria-selected="${this.blockBrowse}" data-ref="blockedtab">Find blocked</button></div>
732
732
  <div data-ref="panelalert"></div>
@@ -758,4 +758,4 @@ Click to light them up \xB7 \u21E7 click to select them.`;Object.assign(a,{type:
758
758
  ${G()}
759
759
  ${this.addByHtml(e.chipsHtml({saved:!0}))}
760
760
  <div data-ref="reservemount"><div class="slm-empty" role="status">Loading\u2026</div></div>
761
- ${Y("reservefoot")}`,e.wire(this.els.rail);let t=this.els.rail.querySelector('[data-ref="reservemount"]'),s=this.els.rail.querySelector('[data-ref="reservefoot"]'),i=this.els.rail;j(s,{label:"Select seats first",disabled:!0}),this.paintReserveSelection(this.getSelection()),this.loadExtras().then(o=>{this.closed||this.mode!=="reserve"||!t.isConnected||(this.reserve=o.mountReserve({rail:i,mount:t,foot:s,paintFoot:j,tabs:i.querySelector('[data-ref="reservetabs"]'),alert:n=>{let a=i.querySelector('[data-ref="panelalert"]');a&&(a.innerHTML=n??"")},alertHtml:B,selectedFree:()=>this.getSelection().filter(n=>this.isReserveSelectable(n.label)).map(n=>n.label),whereOf:n=>this.selectionSummary(n.flatMap(a=>this.labelToSeat.get(a)??[])).where,startsAt:this.eventStartsAt,request:(n,a)=>this.reserveRequest(n,a),show:n=>this.showLabels(n),select:n=>{this.selectByLabels(n)},deselect:n=>{this.renderer?.deselect(n.map(a=>this.labelToId.get(a)).filter(a=>!!a)),this.syncSelection(),this.selLeft=`${ce(n)} left your selection.`,this.syncSelection()},clearSelection:()=>{this.renderer?.clearSelection(),this.syncSelection()},toast:(n,a)=>this.toast(n,a),changed:()=>{this.refreshReservations()}}))}).catch(o=>{t.isConnected&&(t.innerHTML='<div class="slm-empty" role="alert">Reservations could not load. Switch tools and back to try again.</div>'),this.opts.onError?.(o)})}async reserveRequest(e,t){let s=t?.method==="POST"&&(/^reservations\/[^/]+\/release$/.test(e)||e==="reservations/release-all"),i=new Map;if(s)for(let[n,a]of this.reservedBy){let l=i.get(a.id)??{name:a.name,releaseAt:a.releaseAt,labels:[]};l.labels.push(n),i.set(a.id,l)}let o=await this.withAuthRetry(()=>this.api.eventRequest(this.key,e,t));if(t?.method==="POST"&&e==="reservations"){let n=o.reservation;n&&this.recordChange({kind:"reserve",reservationId:n.id,name:n.name,labels:n.labels,releaseAt:n.releaseAt})}else if(s){let n=new Set(o.released??[]),a=e==="reservations/release-all"?null:decodeURIComponent(e.split("/")[1]);for(let[l,c]of i){if(a&&l!==a)continue;let d=c.labels.filter(h=>n.has(h));d.length&&this.recordChange({kind:"release",reservationId:l,name:c.name,releaseAt:c.releaseAt,labels:d})}}return o}async mountArrival(){try{let e=await this.loadExtras();if(this.closed)return;let t=this.opts;(t.focusSection||t.focusSeat||t.focusSeats?.length||t.focusCategory||t.arrivedFrom)&&this.arrival.push(e.mountArrival({mapLayer:this.root.querySelector(".slm-map"),plate:k,focusSeats:s=>{let i=s.flatMap(o=>(this.labelToSeat.has(o)?o:[...this.labelToSeat.keys()].find(n=>n.localeCompare(o,void 0,{sensitivity:"accent"})===0))??[]);return i.length?(this.showLabels(i),(this.mode==="view"||this.isChoosingTool())&&(this.clearSelection(),this.selectByLabels(i)),i):[]},focusCategory:s=>{let i=this.doc?.categories.find(o=>o.key===s||(o.label??"").localeCompare(s,void 0,{sensitivity:"accent"})===0);return i?(this.showLabels([...this.labelToSeat.values()].filter(o=>o.categoryKey===i.key).map(o=>o.label)),i.label??i.key):null},sections:()=>this.sectionOptions,stateOf:s=>{if(this.effectiveHidden.has(s))return{kind:"hidden"};let i=this.availabilityRules[s],o=ne(i);return o==="timed"?{kind:"timed",until:i?.revealAt??null}:o==="threshold"?{kind:"threshold",pct:i?.thresholdPct??null}:o==="closed"?{kind:"closed"}:{kind:"open"}},frame:s=>{let i=this.filterableSections().find(o=>o.id===s);i&&this.frameSections([i]),this.renderer?.flashSection(s,"#3b82f6")},openSections:this.toolAvailable("sections")?()=>this.setMode("sections"):null},{section:t.focusSection,seats:t.focusSeats?.length?t.focusSeats:t.focusSeat?[t.focusSeat]:void 0,category:t.focusCategory,from:t.arrivedFrom?.from,where:t.arrivedFrom?.where,why:t.arrivedFrom?.why,back:t.arrivedFrom?.back})),t.onOpenTrend&&t.kpis!==!1&&this.els.kpis&&this.arrival.push(e.mountTrendCards({kpis:this.els.kpis,card:s=>{if(!["booked-inventory","booked-pct","booked-value"].includes(s))return null;let i=this.buildTallies(),o=this.controlRoomSnapshot?.velocity,n=o?.bySection.reduce((u,b)=>u+b.netBooked,0)??0,a=o?.bySection.slice().sort((u,b)=>b.netBooked-u.netBooked)[0],l=a&&a.netBooked>0?this.sectionLabelById.get(a.sectionId)??null:null,c=o?.windowMinutes??15,d=s==="booked-value"&&i.bookedValueStatus==="current"?`${M(i.bookedValue,i.currency)} booked value`:`${i.booked.toLocaleString()} sold \xB7 ${i.capacityPct}%`,h=n>0?`+${n.toLocaleString()} in the last ${c} minutes${l?`, most in ${l}`:""}. The room shows where; Performance shows how it got here.`:`Nothing sold in the last ${c} minutes. Performance shows how it got here.`;return{title:d,line:h,sectionId:l?a.sectionId:void 0}},open:(s,i)=>t.onOpenTrend({kpi:s,...i?{sectionId:i}:{}})}))}catch(e){this.opts.onError?.(e)}}async openSimilar(e){try{let t=await this.loadExtras();if(this.closed||!e.isConnected)return;let s=this.rowLabels(),i=new Set(this.selectableStatuses());t.openSimilar({anchor:e,plate:k,seats:()=>[...this.labelToSeat.values()].map(o=>{let n=this.sectionByObject.get(o.rowId)??S,a=this.sectionLabelById.get(n)??"Other seats",l=this.doc?.categories.find(h=>h.key===o.categoryKey),c=s.get(o.rowId)??"",d=o.label.startsWith(`${a} `)?o.label.slice(a.length+1):o.label;return{label:o.label,row:o.logicalRowId??o.rowId,rowLabel:c.startsWith(`${a} `)?c.slice(a.length+1):c,section:n,sectionLabel:a,type:o.categoryKey,typeLabel:l?.label??o.categoryKey,status:this.status.get(o.label)??"free",number:d.includes("-")?d.slice(d.lastIndexOf("-")+1):d,x:o.x,y:o.y}}),selected:()=>new Set(this.selectionLabels()),pickable:o=>i.has(P(o.status))&&!this.isHostUnavailable(o.label),view:()=>this.renderer?.getVisibleWorldRect?.()??null,add:o=>{this.selectByLabels(o)}})}catch(t){this.opts.onError?.(t)}}ensureSaved(){return this.saved?Promise.resolve(this.saved):this.loadExtras().then(e=>this.closed?null:(this.saved??=e.mountSaved({mapLayer:this.root.querySelector(".slm-map"),plate:k,request:(t,s)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,t,s)),canSave:this.canBlock(),picks:()=>this.isChoosingTool(),selection:()=>this.selectionLabels(),describe:t=>{let s=t.flatMap(a=>this.labelToSeat.get(a)??[]),i=this.selectionSummary(s),o=[...new Set(t.flatMap(a=>{let l=this.reservedBy.get(a)?.name,c=this.blockGroups?.groups.find(d=>d.labels.includes(a))?.reason;return[l,c].filter(d=>!!d)}))],n=/^\d+ sections/.test(i.where)&&i.types[0]?.count!=null?i.types.map(a=>a.label).join(", ").replace(/, ([^,]*)$/," and $1"):i.where;return{where:n,line:[`${w(s.length)}`,n.replace(" \xB7 ",", "),i.parts.map(a=>a.label).join(", ")].filter(Boolean).join(" \xB7 "),suggestions:[n,...o].filter((a,l,c)=>a&&c.indexOf(a)===l)}},apply:(t,s)=>this.applySaved(t,s),toast:(t,s)=>this.toast(t,s),changed:t=>{this.savedCount=t,this.getSelection().length||this.syncSelection()},chart:()=>({doc:this.doc,rowOf:t=>this.labelToSeat.get(t)?.rowId,sectionOfRow:t=>this.sectionByObject.get(t)})}),this.saved))}applySaved(e,t){let s=e.filter(n=>this.labelToSeat.has(n)),i=s.length;if(this.isChoosingTool()){t.add||this.clearSelection();let n=new Set(this.selectionLabels());this.selectByLabels(s);let a=new Set(this.selectionLabels()),l=s.filter(d=>!a.has(d)&&!n.has(d));i=s.length-l.length;let c=l.filter(d=>this.status.get(d)==="booked").length;this.savedApplied=t.add?null:{name:t.name,labels:a,missing:e.length-s.length,sold:c,taken:l.length-c,changed:t.changed},this.syncSelection()}else this.showLabels(s);this.root?.querySelector(".slm-savedpill")?.remove();let o=i===e.length?`${w(i)}`:`${i.toLocaleString()} of ${e.length.toLocaleString()} seats`;this.root?.querySelector(".slm-map")?.insertAdjacentHTML("beforeend",`<div class="slm-savedpill" role="status">${k("star","#d99a0b",20)}<span><b>${g(t.name)}</b> \xB7 saved selection \xB7 ${o}</span></div>`),this.isChoosingTool()||setTimeout(()=>this.root?.querySelector(".slm-savedpill")?.remove(),8e3)}recordChange(e){this.ensureChanges().then(t=>t?.record(e)).catch(t=>this.opts.onError?.(t))}ensureChanges(){return this.changes?Promise.resolve(this.changes):(this.changesLoading??=this.loadExtras().then(e=>{if(this.closed)return null;let t=(i,o)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,i,o)),s=async(i,o)=>{try{return await this.withAuthRetry(i),o?.(),!0}catch(n){return this.opts.onError?.(n),!1}};return this.changes=e.mountChanges({eventKey:this.key,startsAt:this.eventStartsAt,mapLayer:this.root.querySelector(".slm-map"),plate:k,whereOf:i=>this.selectionSummary(i.flatMap(o=>this.labelToSeat.get(o)??[])).where,seats:async()=>{let i=await this.withAuthRetry(()=>this.api.objects(this.key)),o=i.default??"free",n=new Map;for(let a of this.labelToSeat.keys())n.set(a,i.seats[a]??o);return n},reservations:async()=>{let i=await t("reservations");return this.closed||this.setReservations(i.reservations??[]),i.reservations??[]},rules:async()=>{let i=await this.withAuthRetry(()=>this.api.availability(this.key));return this.availabilityRules=i.rules??{},this.availabilityRules},block:(i,o,n)=>s(()=>this.api.block(this.key,i,{...o?{reason:o}:{},...n?{releaseAt:n}:{}}),()=>{this.setSeatsLocal(i,"blocked"),this.blockGroups=null}),unblock:i=>s(()=>this.api.unblock(this.key,i),()=>{this.setSeatsLocal(i,"free"),this.blockGroups=null}),reserve:(i,o,n)=>{for(let a of i)this.reserving.add(a);return s(()=>t("reservations",{method:"POST",body:{labels:i,name:o,releaseAt:n}}),()=>{this.refreshReservations()}).finally(()=>{for(let a of i)(this.reservedBy.has(a)||this.status.get(a)!=="blocked")&&this.reserving.delete(a)})},release:i=>s(()=>t(`reservations/${encodeURIComponent(i)}/release`,{method:"POST"}),()=>{this.refreshReservations()}),restoreRules:i=>this.persistAvailability({...this.availabilityRules,...i}),channelBack:async i=>(await this.ensureChannels(),this.channels?this.channels.sendBack(i):{moved:0,failed:!0}),show:i=>this.showLabels(i),openTask:i=>this.setMode(i==="types"?"categories":"tables"),changed:()=>{this.feedFilter==="you"&&this.paintFeedFilter()}}),this.changes}).finally(()=>{this.changesLoading=null}),this.changesLoading)}paintFeedFilter(){let e=this.els.rail,t=e?.querySelector('[data-ref="feedfilter"]');if(!e||!t||this.mode!=="view")return;let s=this.feedFilter,i={all:"All",sales:"Sales",carts:"Carts",you:"You"};t.innerHTML=`<b>${s==="you"?"Your changes":"Live activity"}</b><span role="group" aria-label="Show in the feed">${Object.keys(i).map(n=>`<button type="button" data-feed-filter="${n}" aria-pressed="${n===s}">${i[n]}</button>`).join("")}</span>`;let o=e.querySelector('[data-ref="yours"]');for(let n of["feed","alertfeed","nosales"]){let a=e.querySelector(`[data-ref="${n}"]`);a&&(a.hidden=s==="you")}o&&(o.hidden=s!=="you"),this.activityPanel?.setFilter(s==="sales"?["booked","cancelled"]:s==="carts"?["held","expired","released"]:null),s==="you"&&o&&(this.changes||(o.innerHTML='<div class="slm-empty" role="status">Loading\u2026</div>'),this.ensureChanges().then(n=>{n&&o.isConnected&&this.feedFilter==="you"&&n.paintList(o)}).catch(n=>{o.isConnected&&this.extrasFailed(o,n)}))}async mountAlerts(){if(!(this.alerts||this.closed||!this.els.bell))try{let e=await this.loadExtras();if(this.closed||this.alerts)return;let t=(s,i)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,s,i));this.alerts=e.mountAlerts({mapLayer:this.root.querySelector(".slm-map"),bellMount:this.els.bell,bannerMount:this.els.awaybanner,alertHtml:B,plate:k,sections:()=>this.sectionOptions,sectionCounts:s=>{let i=this.filterableSections().find(a=>a.id===s)?.seatLabels??[],o=0,n=0;for(let a of i){let l=this.status.get(a)??"free";l==="free"?o++:l==="booked"&&n++}return{total:i.length,free:o,booked:n}},reservations:()=>{let s=new Map;for(let[i,o]of this.reservedBy){let n=s.get(o.id)??{id:o.id,name:o.name,releaseAt:o.releaseAt,labels:[]};n.labels.push(i),s.set(o.id,n)}return[...s.values()]},where:s=>this.selectionSummary(s.flatMap(i=>this.labelToSeat.get(i)??[])).where,canManage:this.canBlock(),show:(s,i)=>{if(s.sectionId){let o=this.filterableSections().find(n=>n.id===s.sectionId);o&&this.frameSections([o]),this.renderer?.flashSection(s.sectionId,"#d99a0b")}else s.labels?.length&&this.showLabels(s.labels);this.showWhy(i)},extend:async(s,i)=>{let o=[...this.reservedBy.values()].find(n=>n.id===s)?.releaseAt;if(o==null)return!1;try{return await t(`reservations/${encodeURIComponent(s)}`,{method:"PATCH",body:{releaseAt:o+i}}),this.refreshReservations(),!0}catch{return!1}},release:async s=>{try{return await this.reserveRequest(`reservations/${encodeURIComponent(s)}/release`,{method:"POST"}),this.refreshReservations(),!0}catch{return!1}},reserveAgain:s=>{this.setMode("reserve"),this.selectByLabels(s)},ring:(s,i)=>this.renderer?.flashSection(s,i),feedSlot:()=>this.mode==="view"?this.els.rail?.querySelector('[data-ref="alertfeed"]')??null:null,store:e.eventAlertStore(this.key,t)})}catch(e){this.opts.onError?.(e)}}showWhy(e){let t=this.els.liveevent;t&&(t.innerHTML=`<span class="slm-liveeventdot" style="background:#e8782a"></span><span class="slm-liveeventcopy">${g(e)}</span>`,t.classList.add("on"),this.liveEventTimer&&clearTimeout(this.liveEventTimer),this.liveEventTimer=setTimeout(()=>{this.liveEventTimer=null,t.classList.remove("on"),t.innerHTML=""},4e3))}mountFindBlocked(e,t){let s=this.els.rail;this.loadExtras().then(i=>{this.closed||this.mode!=="block"||!this.blockBrowse||!e.isConnected||(this.findBlocked=i.mountFindBlocked({mount:e,foot:t,paintFoot:j,alertHtml:B,alert:o=>{let n=s.querySelector('[data-ref="panelalert"]');n&&(n.innerHTML=o??"")},request:o=>this.withAuthRetry(()=>this.api.eventRequest(this.key,o)),whereOf:o=>this.selectionSummary(o.flatMap(n=>this.labelToSeat.get(n)??[])).where,sections:this.sectionOptions,sectionOf:o=>{let n=this.labelToSeat.get(o);return n?this.sectionByObject.get(n.rowId)??S:null},selectedBlocked:()=>this.getSelection().filter(o=>this.status.get(o.label)==="blocked"&&!this.reservedBy.has(o.label)).map(o=>o.label),show:o=>this.showLabels(o),select:o=>{this.renderer?.clearSelection(),this.selectByLabels(o)},unblock:async o=>(await this.unblock(o),o.every(n=>this.status.get(n)!=="blocked")),block:async(o,n,a)=>(await this.block(o,{...n?{reason:n}:{},...a?{releaseAt:a}:{}}),o.every(l=>this.status.get(l)==="blocked")),unblockAll:()=>this.unblockAll(),openReserve:()=>this.setMode("reserve")}))}).catch(i=>{e.isConnected&&(e.innerHTML='<div class="slm-empty" role="alert">Blocked seats could not load. Switch tabs and back to try again.</div>'),this.opts.onError?.(i)})}paintReserveSelection(e){let t=this.els.rail?.querySelector('[data-ref="selcard"]');t&&(K(t,this.selectionSummary(e,!0)),this.paintAddBy(e.length),this.reserve?.paint())}isBlockSelectable(e){if(this.isHostUnavailable(e))return!1;let t=this.status.get(e)??"free";return t==="free"||t==="blocked"}paintSelBar(e){let t=this.els.rail,s=t?.querySelector('[data-ref="selcard"]'),i=t?.querySelector('[data-ref="blockfoot"]');if(!s||!i)return;K(s,this.selectionSummary(e,!0)),this.paintAddBy(e.length);let o=t.querySelector('[data-ref="panelalert"]');o&&(!this.blockBrowse||this.panelAlert)&&(o.innerHTML=this.panelAlert??"");let n=e.filter(p=>(this.status.get(p.label)??"free")==="free").length,a=e.filter(p=>this.status.get(p.label)==="blocked").length,l=w,c=t.querySelector('[data-ref="blockedtab"]'),{blocked:d}=this.buildTallies(),h=d-this.reservedTally(d);if(c&&(c.textContent=h>0?`Find blocked \xB7 ${h.toLocaleString()}`:"Find blocked"),this.blockBrowse){this.findBlocked?.paint();return}let u=this.blockDone&&(this.blockDone.partial||this.blockDone.until>Date.now())?this.blockDone:null;t.classList.toggle("slm-settled",!!u&&!n);let b=this.releaseAt?q(this.releaseAt):null;j(i,this.blockBusy?{label:`Blocking ${l(this.getSelection().length)}\u2026`,busy:!0,note:"Buyers already cannot pick these seats."}:u?.partial&&!n?{label:"Done",secondary:`Undo the ${u.labels.length.toLocaleString()}`,look:"settle"}:this.blockBrowse||!n&&a?{label:a?`Put ${l(a)} back on sale`:"Put back on sale",disabled:!a,note:a?"Buyers can pick them again right away.":"Select blocked seats in the list or on the map."}:n?this.blockDenied?{label:`Block ${l(n)}`,disabled:!0,note:'Needs the "Block seats" permission.'}:this.blockFailedNow?{label:"Try again",danger:!0,note:"Your selection and reason are kept."}:{label:b?`Block ${l(n)} until ${b}`:`Block ${l(n)}`,danger:!0,secondary:a?`Put the ${a.toLocaleString()} blocked back on sale`:null,note:a?`The ${a.toLocaleString()} already blocked keep their reason.`:b?"Buyers can\u2019t pick them until then.":"Buyers can\u2019t pick them. Sold seats and seats in a cart are never blocked."}:{label:"Select seats first",disabled:!0,note:u?"Blocked just now":"Pick free seats on the map. Sold seats and seats in a cart are never blocked.",secondary:u?"Undo":null,look:u?"done":void 0})}selectionFree(){return this.getSelection().filter(e=>(this.status.get(e.label)??"free")==="free").length}doneQuietly(e,t,s){try{this.done(e,t,s)}catch(i){this.opts.onError?.(i)}}done(e,t,s){let i=this.mode==="block"&&this.els.rail?.querySelector('[data-ref="blockfoot"]')||this.mode==="categories"&&e==="setCategory"&&this.els.rail?.querySelector('[data-ref="catfoot"]');if(!this.tablesPanel&&!i&&this.toastOk(s),t.length){let o=e==="block"?this.pushActivity(t,"blocked","blocked"):e==="unblock"||e==="unblockAll"?this.pushActivity(t,"unblocked","free"):e==="cancelBooking"?this.pushActivity(t,"cancelled","free"):null;o&&this.paintSpatialActivity(o)}e!=="setHoldTtl"&&this.refreshControlRoom().catch(o=>this.opts.onError?.(o)),this.opts.onActionComplete?.({action:e,labels:t,count:t.length})}toastOk(e){this.toast(e,"ok")}toastErr(e){this.toast(e,"err")}toast(e,t,s){let i=this.els.toast;if(i){if(i.textContent=e,i.className=`slm-toast on ${t}`,s){let o=document.createElement("button");o.type="button",o.textContent=s.label,o.addEventListener("click",()=>{i.className="slm-toast",s.run()}),i.append(" ",o)}this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>{i.className="slm-toast"},s?8e3:3200)}}fail(e){this.opts.onError?.(e);let t=e instanceof $?e.status:0;this.showRoomCard(t===401||t===403?"access":t===404?"missing":"offline"),this.els.rail&&(this.els.rail.innerHTML="")}showRoomCard(e){let t=this.root;if(!t)return;t.querySelector('[data-ref="opening"]')?.remove(),t.querySelector('[data-ref="roomcard"]')?.remove(),t.insertAdjacentHTML("beforeend",Ve(e,this.opts.organizationName)),t.querySelector('[data-ref="roomcard"]').querySelector("[data-roomcard-act]")?.addEventListener("click",()=>{e==="signedout"?this.retrySession():this.reopen()})}async reopen(){let e=this.root;!e||this.closed||(e.querySelector('[data-ref="roomcard"]')?.remove(),this.renderer?.destroy(),this.renderer=null,e.querySelector(".slm-map")?.insertAdjacentHTML("beforeend",he()),this.els.rail&&(this.els.rail.innerHTML=pe()),await this.load())}};export{es as ACCESS_LINK_DEFAULTS,rs as ChannelsMode,re as ManageApi,$ as ManageApiError,Ft as PUBLIC_CHANNEL_ID,zt as PUBLIC_CHANNEL_NAME,xe as SeatManager,Xt as accessIntentDescription,Zt as accessIntentLabel,Yt as accessLine,ts as accessLinkBadge,os as accessLinkErrorCopy,ss as accessLinkIsLive,is as accessLinkPolicyLines,Ut as bucketRows,ls as bucketRowsHtml,ns as dropReviewRows,Jt as intentForbidsCopy,Qt as intentSwitchBlockedCopy,Dt as isPublicChannelId,jt as markerLetter,Nt as markerOf,_t as mutationCount,Wt as needsMoveConfirmation,Kt as planAssignment,Gt as retryAfterCopy,Vt as selectionSources,as as stateBadge,qt as suggestMarker};
761
+ ${Y("reservefoot")}`,e.wire(this.els.rail);let t=this.els.rail.querySelector('[data-ref="reservemount"]'),s=this.els.rail.querySelector('[data-ref="reservefoot"]'),i=this.els.rail;j(s,{label:"Select seats first",disabled:!0}),this.paintReserveSelection(this.getSelection()),this.loadExtras().then(o=>{this.closed||this.mode!=="reserve"||!t.isConnected||(this.reserve=o.mountReserve({rail:i,mount:t,foot:s,paintFoot:j,tabs:i.querySelector('[data-ref="reservetabs"]'),alert:n=>{let a=i.querySelector('[data-ref="panelalert"]');a&&(a.innerHTML=n??"")},alertHtml:B,selectedFree:()=>this.getSelection().filter(n=>this.isReserveSelectable(n.label)).map(n=>n.label),whereOf:n=>this.selectionSummary(n.flatMap(a=>this.labelToSeat.get(a)??[])).where,startsAt:this.eventStartsAt,request:(n,a)=>this.reserveRequest(n,a),show:n=>this.showLabels(n),select:n=>{this.selectByLabels(n)},deselect:n=>{this.renderer?.deselect(n.map(a=>this.labelToId.get(a)).filter(a=>!!a)),this.syncSelection(),this.selLeft=`${ce(n)} left your selection.`,this.syncSelection()},clearSelection:()=>{this.renderer?.clearSelection(),this.syncSelection()},toast:(n,a)=>this.toast(n,a),changed:()=>{this.refreshReservations()}}))}).catch(o=>{t.isConnected&&(t.innerHTML='<div class="slm-empty" role="alert">Reservations could not load. Switch tools and back to try again.</div>'),this.opts.onError?.(o)})}async reserveRequest(e,t){let s=t?.method==="POST"&&(/^reservations\/[^/]+\/release$/.test(e)||e==="reservations/release-all"),i=new Map;if(s)for(let[n,a]of this.reservedBy){let l=i.get(a.id)??{name:a.name,releaseAt:a.releaseAt,labels:[]};l.labels.push(n),i.set(a.id,l)}let o=await this.withAuthRetry(()=>this.api.eventRequest(this.key,e,t));if(t?.method==="POST"&&e==="reservations"){let n=o.reservation;n&&this.recordChange({kind:"reserve",reservationId:n.id,name:n.name,labels:n.labels,releaseAt:n.releaseAt})}else if(s){let n=new Set(o.released??[]),a=e==="reservations/release-all"?null:decodeURIComponent(e.split("/")[1]);for(let[l,c]of i){if(a&&l!==a)continue;let d=c.labels.filter(h=>n.has(h));d.length&&this.recordChange({kind:"release",reservationId:l,name:c.name,releaseAt:c.releaseAt,labels:d})}}return o}async mountArrival(){try{let e=await this.loadExtras();if(this.closed)return;let t=this.opts;(t.focusSection||t.focusSeat||t.focusSeats?.length||t.focusCategory||t.arrivedFrom)&&this.arrival.push(e.mountArrival({mapLayer:this.root.querySelector(".slm-map"),plate:x,focusSeats:s=>{let i=s.flatMap(o=>(this.labelToSeat.has(o)?o:[...this.labelToSeat.keys()].find(n=>n.localeCompare(o,void 0,{sensitivity:"accent"})===0))??[]);return i.length?(this.showLabels(i),(this.mode==="view"||this.isChoosingTool())&&(this.clearSelection(),this.selectByLabels(i)),i):[]},focusCategory:s=>{let i=this.doc?.categories.find(o=>o.key===s||(o.label??"").localeCompare(s,void 0,{sensitivity:"accent"})===0);return i?(this.showLabels([...this.labelToSeat.values()].filter(o=>o.categoryKey===i.key).map(o=>o.label)),i.label??i.key):null},sections:()=>this.sectionOptions,stateOf:s=>{if(this.effectiveHidden.has(s))return{kind:"hidden"};let i=this.availabilityRules[s],o=ne(i);return o==="timed"?{kind:"timed",until:i?.revealAt??null}:o==="threshold"?{kind:"threshold",pct:i?.thresholdPct??null}:o==="closed"?{kind:"closed"}:{kind:"open"}},frame:s=>{let i=this.filterableSections().find(o=>o.id===s);i&&this.frameSections([i]),this.renderer?.flashSection(s,"#3b82f6")},openSections:this.toolAvailable("sections")?()=>this.setMode("sections"):null},{section:t.focusSection,seats:t.focusSeats?.length?t.focusSeats:t.focusSeat?[t.focusSeat]:void 0,category:t.focusCategory,from:t.arrivedFrom?.from,where:t.arrivedFrom?.where,why:t.arrivedFrom?.why,back:t.arrivedFrom?.back})),t.onOpenTrend&&t.kpis!==!1&&this.els.kpis&&this.arrival.push(e.mountTrendCards({kpis:this.els.kpis,card:s=>{if(!["booked-inventory","booked-pct","booked-value"].includes(s))return null;let i=this.buildTallies(),o=this.controlRoomSnapshot?.velocity,n=o?.bySection.reduce((u,b)=>u+b.netBooked,0)??0,a=o?.bySection.slice().sort((u,b)=>b.netBooked-u.netBooked)[0],l=a&&a.netBooked>0?this.sectionLabelById.get(a.sectionId)??null:null,c=o?.windowMinutes??15,d=s==="booked-value"&&i.bookedValueStatus==="current"?`${M(i.bookedValue,i.currency)} booked value`:`${i.booked.toLocaleString()} sold \xB7 ${i.capacityPct}%`,h=n>0?`+${n.toLocaleString()} in the last ${c} minutes${l?`, most in ${l}`:""}. The room shows where; Performance shows how it got here.`:`Nothing sold in the last ${c} minutes. Performance shows how it got here.`;return{title:d,line:h,sectionId:l?a.sectionId:void 0}},open:(s,i)=>t.onOpenTrend({kpi:s,...i?{sectionId:i}:{}})}))}catch(e){this.opts.onError?.(e)}}async openSimilar(e){try{let t=await this.loadExtras();if(this.closed||!e.isConnected)return;let s=this.rowLabels(),i=new Set(this.selectableStatuses());t.openSimilar({anchor:e,plate:x,seats:()=>[...this.labelToSeat.values()].map(o=>{let n=this.sectionByObject.get(o.rowId)??S,a=this.sectionLabelById.get(n)??"Other seats",l=this.doc?.categories.find(h=>h.key===o.categoryKey),c=s.get(o.rowId)??"",d=o.label.startsWith(`${a} `)?o.label.slice(a.length+1):o.label;return{label:o.label,row:o.logicalRowId??o.rowId,rowLabel:c.startsWith(`${a} `)?c.slice(a.length+1):c,section:n,sectionLabel:a,type:o.categoryKey,typeLabel:l?.label??o.categoryKey,status:this.status.get(o.label)??"free",number:d.includes("-")?d.slice(d.lastIndexOf("-")+1):d,x:o.x,y:o.y}}),selected:()=>new Set(this.selectionLabels()),pickable:o=>i.has(P(o.status))&&!this.isHostUnavailable(o.label),view:()=>this.renderer?.getVisibleWorldRect?.()??null,add:o=>{this.selectByLabels(o)}})}catch(t){this.opts.onError?.(t)}}ensureSaved(){return this.saved?Promise.resolve(this.saved):this.loadExtras().then(e=>this.closed?null:(this.saved??=e.mountSaved({mapLayer:this.root.querySelector(".slm-map"),plate:x,request:(t,s)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,t,s)),canSave:this.canBlock(),picks:()=>this.isChoosingTool(),selection:()=>this.selectionLabels(),describe:t=>{let s=t.flatMap(a=>this.labelToSeat.get(a)??[]),i=this.selectionSummary(s),o=[...new Set(t.flatMap(a=>{let l=this.reservedBy.get(a)?.name,c=this.blockGroups?.groups.find(d=>d.labels.includes(a))?.reason;return[l,c].filter(d=>!!d)}))],n=/^\d+ sections/.test(i.where)&&i.types[0]?.count!=null?i.types.map(a=>a.label).join(", ").replace(/, ([^,]*)$/," and $1"):i.where;return{where:n,line:[`${w(s.length)}`,n.replace(" \xB7 ",", "),i.parts.map(a=>a.label).join(", ")].filter(Boolean).join(" \xB7 "),suggestions:[n,...o].filter((a,l,c)=>a&&c.indexOf(a)===l)}},apply:(t,s)=>this.applySaved(t,s),toast:(t,s)=>this.toast(t,s),changed:t=>{this.savedCount=t,this.getSelection().length||this.syncSelection()},chart:()=>({doc:this.doc,rowOf:t=>this.labelToSeat.get(t)?.rowId,sectionOfRow:t=>this.sectionByObject.get(t)})}),this.saved))}applySaved(e,t){let s=e.filter(n=>this.labelToSeat.has(n)),i=s.length;if(this.isChoosingTool()){t.add||this.clearSelection();let n=new Set(this.selectionLabels());this.selectByLabels(s);let a=new Set(this.selectionLabels()),l=s.filter(d=>!a.has(d)&&!n.has(d));i=s.length-l.length;let c=l.filter(d=>this.status.get(d)==="booked").length;this.savedApplied=t.add?null:{name:t.name,labels:a,missing:e.length-s.length,sold:c,taken:l.length-c,changed:t.changed},this.syncSelection()}else this.showLabels(s);this.root?.querySelector(".slm-savedpill")?.remove();let o=i===e.length?`${w(i)}`:`${i.toLocaleString()} of ${e.length.toLocaleString()} seats`;this.root?.querySelector(".slm-map")?.insertAdjacentHTML("beforeend",`<div class="slm-savedpill" role="status">${x("star","#d99a0b",20)}<span><b>${g(t.name)}</b> \xB7 saved selection \xB7 ${o}</span></div>`),this.isChoosingTool()||setTimeout(()=>this.root?.querySelector(".slm-savedpill")?.remove(),8e3)}recordChange(e){this.ensureChanges().then(t=>t?.record(e)).catch(t=>this.opts.onError?.(t))}ensureChanges(){return this.changes?Promise.resolve(this.changes):(this.changesLoading??=this.loadExtras().then(e=>{if(this.closed)return null;let t=(i,o)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,i,o)),s=async(i,o)=>{try{return await this.withAuthRetry(i),o?.(),!0}catch(n){return this.opts.onError?.(n),!1}};return this.changes=e.mountChanges({eventKey:this.key,startsAt:this.eventStartsAt,mapLayer:this.root.querySelector(".slm-map"),plate:x,whereOf:i=>this.selectionSummary(i.flatMap(o=>this.labelToSeat.get(o)??[])).where,seats:async()=>{let i=await this.withAuthRetry(()=>this.api.objects(this.key)),o=i.default??"free",n=new Map;for(let a of this.labelToSeat.keys())n.set(a,i.seats[a]??o);return n},reservations:async()=>{let i=await t("reservations");return this.closed||this.setReservations(i.reservations??[]),i.reservations??[]},rules:async()=>{let i=await this.withAuthRetry(()=>this.api.availability(this.key));return this.availabilityRules=i.rules??{},this.availabilityRules},block:(i,o,n)=>s(()=>this.api.block(this.key,i,{...o?{reason:o}:{},...n?{releaseAt:n}:{}}),()=>{this.setSeatsLocal(i,"blocked"),this.blockGroups=null}),unblock:i=>s(()=>this.api.unblock(this.key,i),()=>{this.setSeatsLocal(i,"free"),this.blockGroups=null}),reserve:(i,o,n)=>{for(let a of i)this.reserving.add(a);return s(()=>t("reservations",{method:"POST",body:{labels:i,name:o,releaseAt:n}}),()=>{this.refreshReservations()}).finally(()=>{for(let a of i)(this.reservedBy.has(a)||this.status.get(a)!=="blocked")&&this.reserving.delete(a)})},release:i=>s(()=>t(`reservations/${encodeURIComponent(i)}/release`,{method:"POST"}),()=>{this.refreshReservations()}),restoreRules:i=>this.persistAvailability({...this.availabilityRules,...i}),channelBack:async i=>(await this.ensureChannels(),this.channels?this.channels.sendBack(i):{moved:0,failed:!0}),show:i=>this.showLabels(i),openTask:i=>this.setMode(i==="types"?"categories":"tables"),changed:()=>{this.feedFilter==="you"&&this.paintFeedFilter()}}),this.changes}).finally(()=>{this.changesLoading=null}),this.changesLoading)}paintFeedFilter(){let e=this.els.rail,t=e?.querySelector('[data-ref="feedfilter"]');if(!e||!t||this.mode!=="view")return;let s=this.feedFilter,i={all:"All",sales:"Sales",carts:"Carts",you:"You"};t.innerHTML=`<b>${s==="you"?"Your changes":"Live activity"}</b><span role="group" aria-label="Show in the feed">${Object.keys(i).map(n=>`<button type="button" data-feed-filter="${n}" aria-pressed="${n===s}">${i[n]}</button>`).join("")}</span>`;let o=e.querySelector('[data-ref="yours"]');for(let n of["feed","alertfeed","nosales"]){let a=e.querySelector(`[data-ref="${n}"]`);a&&(a.hidden=s==="you")}o&&(o.hidden=s!=="you"),this.activityPanel?.setFilter(s==="sales"?["booked","cancelled"]:s==="carts"?["held","expired","released"]:null),s==="you"&&o&&(this.changes||(o.innerHTML='<div class="slm-empty" role="status">Loading\u2026</div>'),this.ensureChanges().then(n=>{n&&o.isConnected&&this.feedFilter==="you"&&n.paintList(o)}).catch(n=>{o.isConnected&&this.extrasFailed(o,n)}))}async mountAlerts(){if(!(this.alerts||this.closed||!this.els.bell))try{let e=await this.loadExtras();if(this.closed||this.alerts)return;let t=(s,i)=>this.withAuthRetry(()=>this.api.eventRequest(this.key,s,i));this.alerts=e.mountAlerts({mapLayer:this.root.querySelector(".slm-map"),bellMount:this.els.bell,bannerMount:this.els.awaybanner,alertHtml:B,plate:x,sections:()=>this.sectionOptions,sectionCounts:s=>{let i=this.filterableSections().find(a=>a.id===s)?.seatLabels??[],o=0,n=0;for(let a of i){let l=this.status.get(a)??"free";l==="free"?o++:l==="booked"&&n++}return{total:i.length,free:o,booked:n}},reservations:()=>{let s=new Map;for(let[i,o]of this.reservedBy){let n=s.get(o.id)??{id:o.id,name:o.name,releaseAt:o.releaseAt,labels:[]};n.labels.push(i),s.set(o.id,n)}return[...s.values()]},where:s=>this.selectionSummary(s.flatMap(i=>this.labelToSeat.get(i)??[])).where,canManage:this.canBlock(),show:(s,i)=>{if(s.sectionId){let o=this.filterableSections().find(n=>n.id===s.sectionId);o&&this.frameSections([o]),this.renderer?.flashSection(s.sectionId,"#d99a0b")}else s.labels?.length&&this.showLabels(s.labels);this.showWhy(i)},extend:async(s,i)=>{let o=[...this.reservedBy.values()].find(n=>n.id===s)?.releaseAt;if(o==null)return!1;try{return await t(`reservations/${encodeURIComponent(s)}`,{method:"PATCH",body:{releaseAt:o+i}}),this.refreshReservations(),!0}catch{return!1}},release:async s=>{try{return await this.reserveRequest(`reservations/${encodeURIComponent(s)}/release`,{method:"POST"}),this.refreshReservations(),!0}catch{return!1}},reserveAgain:s=>{this.setMode("reserve"),this.selectByLabels(s)},ring:(s,i)=>this.renderer?.flashSection(s,i),feedSlot:()=>this.mode==="view"?this.els.rail?.querySelector('[data-ref="alertfeed"]')??null:null,store:e.eventAlertStore(this.key,t)})}catch(e){this.opts.onError?.(e)}}showWhy(e){let t=this.els.liveevent;t&&(t.innerHTML=`<span class="slm-liveeventdot" style="background:#e8782a"></span><span class="slm-liveeventcopy">${g(e)}</span>`,t.classList.add("on"),this.liveEventTimer&&clearTimeout(this.liveEventTimer),this.liveEventTimer=setTimeout(()=>{this.liveEventTimer=null,t.classList.remove("on"),t.innerHTML=""},4e3))}mountFindBlocked(e,t){let s=this.els.rail;this.loadExtras().then(i=>{this.closed||this.mode!=="block"||!this.blockBrowse||!e.isConnected||(this.findBlocked=i.mountFindBlocked({mount:e,foot:t,paintFoot:j,alertHtml:B,alert:o=>{let n=s.querySelector('[data-ref="panelalert"]');n&&(n.innerHTML=o??"")},request:o=>this.withAuthRetry(()=>this.api.eventRequest(this.key,o)),whereOf:o=>this.selectionSummary(o.flatMap(n=>this.labelToSeat.get(n)??[])).where,sections:this.sectionOptions,sectionOf:o=>{let n=this.labelToSeat.get(o);return n?this.sectionByObject.get(n.rowId)??S:null},selectedBlocked:()=>this.getSelection().filter(o=>this.status.get(o.label)==="blocked"&&!this.reservedBy.has(o.label)).map(o=>o.label),show:o=>this.showLabels(o),select:o=>{this.renderer?.clearSelection(),this.selectByLabels(o)},unblock:async o=>(await this.unblock(o),o.every(n=>this.status.get(n)!=="blocked")),block:async(o,n,a)=>(await this.block(o,{...n?{reason:n}:{},...a?{releaseAt:a}:{}}),o.every(l=>this.status.get(l)==="blocked")),unblockAll:()=>this.unblockAll(),openReserve:()=>this.setMode("reserve")}))}).catch(i=>{e.isConnected&&(e.innerHTML='<div class="slm-empty" role="alert">Blocked seats could not load. Switch tabs and back to try again.</div>'),this.opts.onError?.(i)})}paintReserveSelection(e){let t=this.els.rail?.querySelector('[data-ref="selcard"]');t&&(K(t,this.selectionSummary(e,!0)),this.paintAddBy(e.length),this.reserve?.paint())}isBlockSelectable(e){if(this.isHostUnavailable(e))return!1;let t=this.status.get(e)??"free";return t==="free"||t==="blocked"}paintSelBar(e){let t=this.els.rail,s=t?.querySelector('[data-ref="selcard"]'),i=t?.querySelector('[data-ref="blockfoot"]');if(!s||!i)return;K(s,this.selectionSummary(e,!0)),this.paintAddBy(e.length);let o=t.querySelector('[data-ref="panelalert"]');o&&(!this.blockBrowse||this.panelAlert)&&(o.innerHTML=this.panelAlert??"");let n=e.filter(p=>(this.status.get(p.label)??"free")==="free").length,a=e.filter(p=>this.status.get(p.label)==="blocked").length,l=w,c=t.querySelector('[data-ref="blockedtab"]'),{blocked:d}=this.buildTallies(),h=d-this.reservedTally(d);if(c&&(c.textContent=h>0?`Find blocked \xB7 ${h.toLocaleString()}`:"Find blocked"),this.blockBrowse){this.findBlocked?.paint();return}let u=this.blockDone&&(this.blockDone.partial||this.blockDone.until>Date.now())?this.blockDone:null;t.classList.toggle("slm-settled",!!u&&!n);let b=this.releaseAt?q(this.releaseAt):null;j(i,this.blockBusy?{label:`Blocking ${l(this.getSelection().length)}\u2026`,busy:!0,note:"Buyers already cannot pick these seats."}:u?.partial&&!n?{label:"Done",secondary:`Undo the ${u.labels.length.toLocaleString()}`,look:"settle"}:this.blockBrowse||!n&&a?{label:a?`Put ${l(a)} back on sale`:"Put back on sale",disabled:!a,note:a?"Buyers can pick them again right away.":"Select blocked seats in the list or on the map."}:n?this.blockDenied?{label:`Block ${l(n)}`,disabled:!0,note:'Needs the "Block seats" permission.'}:this.blockFailedNow?{label:"Try again",danger:!0,note:"Your selection and reason are kept."}:{label:b?`Block ${l(n)} until ${b}`:`Block ${l(n)}`,danger:!0,secondary:a?`Put the ${a.toLocaleString()} blocked back on sale`:null,note:a?`The ${a.toLocaleString()} already blocked keep their reason.`:b?"Buyers can\u2019t pick them until then.":"Buyers can\u2019t pick them. Sold seats and seats in a cart are never blocked."}:{label:"Select seats first",disabled:!0,note:u?"Blocked just now":"Pick free seats on the map. Sold seats and seats in a cart are never blocked.",secondary:u?"Undo":null,look:u?"done":void 0})}selectionFree(){return this.getSelection().filter(e=>(this.status.get(e.label)??"free")==="free").length}doneQuietly(e,t,s){try{this.done(e,t,s)}catch(i){this.opts.onError?.(i)}}done(e,t,s){let i=this.mode==="block"&&this.els.rail?.querySelector('[data-ref="blockfoot"]')||this.mode==="categories"&&e==="setCategory"&&this.els.rail?.querySelector('[data-ref="catfoot"]');if(!this.tablesPanel&&!i&&this.toastOk(s),t.length){let o=e==="block"?this.pushActivity(t,"blocked","blocked"):e==="unblock"||e==="unblockAll"?this.pushActivity(t,"unblocked","free"):e==="cancelBooking"?this.pushActivity(t,"cancelled","free"):null;o&&this.paintSpatialActivity(o)}e!=="setHoldTtl"&&this.refreshControlRoom().catch(o=>this.opts.onError?.(o)),this.opts.onActionComplete?.({action:e,labels:t,count:t.length})}toastOk(e){this.toast(e,"ok")}toastErr(e){this.toast(e,"err")}toast(e,t,s){let i=this.els.toast;if(i){if(i.textContent=e,i.className=`slm-toast on ${t}`,s){let o=document.createElement("button");o.type="button",o.textContent=s.label,o.addEventListener("click",()=>{i.className="slm-toast",s.run()}),i.append(" ",o)}this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>{i.className="slm-toast"},s?8e3:3200)}}fail(e){this.opts.onError?.(e);let t=e instanceof $?e.status:0;this.showRoomCard(t===401||t===403?"access":t===404?"missing":"offline"),this.els.rail&&(this.els.rail.innerHTML="")}showRoomCard(e){let t=this.root;if(!t)return;t.querySelector('[data-ref="opening"]')?.remove(),t.querySelector('[data-ref="roomcard"]')?.remove(),t.insertAdjacentHTML("beforeend",Ve(e,this.opts.organizationName)),t.querySelector('[data-ref="roomcard"]').querySelector("[data-roomcard-act]")?.addEventListener("click",()=>{e==="signedout"?this.retrySession():this.reopen()})}async reopen(){let e=this.root;!e||this.closed||(e.querySelector('[data-ref="roomcard"]')?.remove(),this.renderer?.destroy(),this.renderer=null,e.querySelector(".slm-map")?.insertAdjacentHTML("beforeend",he()),this.els.rail&&(this.els.rail.innerHTML=pe()),await this.load())}};export{es as ACCESS_LINK_DEFAULTS,rs as ChannelsMode,re as ManageApi,$ as ManageApiError,Ft as PUBLIC_CHANNEL_ID,zt as PUBLIC_CHANNEL_NAME,ke as SeatManager,Xt as accessIntentDescription,Zt as accessIntentLabel,Yt as accessLine,ts as accessLinkBadge,os as accessLinkErrorCopy,ss as accessLinkIsLive,is as accessLinkPolicyLines,Ut as bucketRows,ls as bucketRowsHtml,ns as dropReviewRows,Jt as intentForbidsCopy,Qt as intentSwitchBlockedCopy,Dt as isPublicChannelId,jt as markerLetter,Nt as markerOf,_t as mutationCount,Wt as needsMoveConfirmation,Kt as planAssignment,Gt as retryAfterCopy,Vt as selectionSources,as as stateBadge,qt as suggestMarker};