diff --git a/custom_components/houseplan/frontend/houseplan-card.js b/custom_components/houseplan/frontend/houseplan-card.js index 65eb2f49..417ed9ef 100755 --- a/custom_components/houseplan/frontend/houseplan-card.js +++ b/custom_components/houseplan/frontend/houseplan-card.js @@ -1,4 +1,4 @@ -globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="d77b8f7b11118fb07d4858dfe45d94e740fd7c490fca61a067f4a6059fdd3753";const t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),s=new WeakMap;let n=class{constructor(t,e,s){if(this._$cssResult$=!0,s!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const i=this.t;if(e&&void 0===t){const e=void 0!==i&&1===i.length;e&&(t=s.get(i)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&s.set(i,t))}return t}toString(){return this.cssText}};const o=(t,...e)=>{const s=1===t.length?t[0]:e.reduce((e,i,s)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[s+1],t[0]);return new n(s,t,i)},a=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return(t=>new n("string"==typeof t?t:t+"",void 0,i))(e)})(t):t,{is:r,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:p}=Object,u=globalThis,_=u.trustedTypes,m=_?_.emptyScript:"",g=u.reactiveElementPolyfillSupport,f=(t,e)=>t,v={toAttribute(t,e){switch(e){case Boolean:t=t?m:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},y=(t,e)=>!r(t,e),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),u.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=b){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);void 0!==s&&l(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=c(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:s,set(e){const o=s?.call(this);n?.call(this,e),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const t=p(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const t=this.properties,e=[...h(t),...d(t)];for(const i of e)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,i]of e)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const i=this._$Eu(t,e);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(a(t))}else void 0!==t&&e.push(a(t));return e}static _$Eu(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,s)=>{if(e)i.adoptedStyleSheets=s.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of s){const s=document.createElement("style"),n=t.litNonce;void 0!==n&&s.setAttribute("nonce",n),s.textContent=e.cssText,i.appendChild(s)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$ET(t,e){const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(void 0!==s&&!0===i.reflect){const n=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(e,i.type);this._$Em=t,null==n?this.removeAttribute(s):this.setAttribute(s,n),this._$Em=null}}_$AK(t,e){const i=this.constructor,s=i._$Eh.get(t);if(void 0!==s&&this._$Em!==s){const t=i.getPropertyOptions(s),n="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:v;this._$Em=s;const o=n.fromAttribute(e,t.type);this[s]=o??this._$Ej?.get(s)??o,this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(void 0!==t){const o=this.constructor;if(!1===s&&(n=this[t]),i??=o.getPropertyOptions(t),!((i.hasChanged??y)(n,e)||i.useDefault&&i.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,e,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:i,reflect:s,wrapped:n},o){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==n||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),!0===s&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,i]of t){const{wrapped:t}=i,s=this[e];!0!==t||this._$AL.has(e)||void 0===s||this.C(e,void 0,i,s)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(u.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=t=>t,$=k.trustedTypes,S=$?$.createPolicy("lit-html",{createHTML:t=>t}):void 0,M="$lit$",C=`lit$${Math.random().toFixed(9).slice(2)}$`,D="?"+C,P=`<${D}>`,T=document,R=()=>T.createComment(""),I=t=>null===t||"object"!=typeof t&&"function"!=typeof t,A=Array.isArray,z="[ \t\n\f\r]",F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,E=/-->/g,N=/>/g,O=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),L=/'/g,H=/"/g,B=/^(?:script|style|textarea|title)$/i,q=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),W=q(1),j=q(2),U=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),V=new WeakMap,K=T.createTreeWalker(T,129);function Y(t,e){if(!A(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==S?S.createHTML(e):e}const J=(t,e)=>{const i=t.length-1,s=[];let n,o=2===e?"":3===e?"":"",a=F;for(let e=0;e"===l[0]?(a=n??F,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,r=l[1],a=void 0===l[3]?O:'"'===l[3]?H:L):a===H||a===L?a=O:a===E||a===N?a=F:(a=O,n=void 0);const d=a===O&&t[e+1].startsWith("/>")?" ":"";o+=a===F?i+P:c>=0?(s.push(r),i.slice(0,c)+M+i.slice(c)+C+d):i+C+(-2===c?e:d)}return[Y(t,o+(t[i]||"")+(2===e?"":3===e?"":"")),s]};class X{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,o=0;const a=t.length-1,r=this.parts,[l,c]=J(t,e);if(this.el=X.createElement(l,i),K.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(s=K.nextNode())&&r.length0){s.textContent=$?$.emptyScript:"";for(let i=0;iA(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==G&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:i}=t,s="number"==typeof i?this._$AC(t):(void 0===i.el&&(i.el=X.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===s)this._$AH.p(e);else{const t=new Q(s,this),i=t.u(this.options);t.p(e),this.T(i),this._$AH=t}}_$AC(t){let e=V.get(t.strings);return void 0===e&&V.set(t.strings,e=new X(t)),e}k(t){A(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new tt(this.O(R()),this.O(R()),this,this.options)):i=e[s],i._$AI(n),s++;s2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(t,e=this,i,s){const n=this.strings;let o=!1;if(void 0===n)t=Z(this,t,e,0),o=!I(t)||t!==this._$AH&&t!==U,o&&(this._$AH=t);else{const s=t;let a,r;for(t=n[0],a=0;a{const s=i?.renderBefore??e;let n=s._$litPart$;if(void 0===n){const t=i?.renderBefore??null;s._$litPart$=n=new tt(e.insertBefore(R(),t),t,void 0,i??{})}return n._$AI(t),n},ct=globalThis;let ht=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=lt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};ht._$litElement$=!0,ht.finalized=!0,ct.litElementHydrateSupport?.({LitElement:ht});const dt=ct.litElementPolyfillSupport;dt?.({LitElement:ht}),(ct.litElementVersions??=[]).push("4.2.2");const pt=2,ut=t=>(...e)=>({_$litDirective$:t,values:e});let _t=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const mt={},gt=ut(class extends _t{constructor(){super(...arguments),this.ot=mt}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return U}else if(this.ot===e)return U;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}}),{I:ft}=at,vt=t=>t,yt=()=>document.createComment(""),bt=(t,e,i)=>{const s=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=s.insertBefore(yt(),n),o=s.insertBefore(yt(),n);i=new ft(e,o,t,t.options)}else{const e=i._$AB.nextSibling,o=i._$AM,a=o!==t;if(a){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==o._$AU&&i._$AP(e)}if(e!==n||a){let t=i._$AA;for(;t!==e;){const e=vt(t).nextSibling;vt(s).insertBefore(t,n),t=e}}}return i},wt=(t,e,i=t)=>(t._$AI(e,i),t),kt={},xt=(t,e=kt)=>t._$AH=e,$t=t=>{t._$AR(),t._$AA.remove()},St=(t,e,i)=>{const s=new Map;for(let n=e;n<=i;n++)s.set(t[n],n);return s},Mt=ut(class extends _t{constructor(t){if(super(t),t.type!==pt)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let s;void 0===i?i=e:void 0!==e&&(s=e);const n=[],o=[];let a=0;for(const e of t)n[a]=s?s(e,a):a,o[a]=i(e,a),a++;return{values:o,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,s]){const n=(t=>t._$AH)(t),{values:o,keys:a}=this.dt(e,i,s);if(!Array.isArray(n))return this.ut=a,o;const r=this.ut??=[],l=[];let c,h,d=0,p=n.length-1,u=0,_=o.length-1;for(;d<=p&&u<=_;)if(null===n[d])d++;else if(null===n[p])p--;else if(r[d]===a[u])l[u]=wt(n[d],o[u]),d++,u++;else if(r[p]===a[_])l[_]=wt(n[p],o[_]),p--,_--;else if(r[d]===a[_])l[_]=wt(n[d],o[_]),bt(t,l[_+1],n[d]),d++,_--;else if(r[p]===a[u])l[u]=wt(n[p],o[u]),bt(t,n[d],n[p]),p--,u++;else if(void 0===c&&(c=St(a,u,_),h=St(r,d,p)),c.has(r[d]))if(c.has(r[p])){const e=h.get(a[u]),i=void 0!==e?n[e]:null;if(null===i){const e=bt(t,n[d]);wt(e,o[u]),l[u]=e}else l[u]=wt(i,o[u]),bt(t,n[d],i),n[e]=null;u++}else $t(n[p]),p--;else $t(n[d]),d++;for(;u<=_;){const e=bt(t,l[_+1]);wt(e,o[u]),l[u++]=e}for(;d<=p;){const t=n[d++];null!==t&&$t(t)}return this.ut=a,xt(t,l),U}}),Ct=new WeakMap;let Dt=0;class Pt extends ht{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=!1,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Dt,this._focusInitial=()=>{const t=this._focusableElements(),e=t.find(t=>t.hasAttribute("autofocus"))||t[0]||(this._useHaDialog?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");e?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=t=>{if("Escape"===t.key){t.preventDefault(),t.stopImmediatePropagation(),this._pruneOverlays();const e=this._overlays[this._overlays.length-1];return e?void this._closeOverlay(e,"escape"):void this._requestClose()}if("Tab"!==t.key||this._useHaDialog)return;const e=this.renderRoot.querySelector(".close"),i=e?[e,...this._focusableElements()]:this._focusableElements();if(!i.length)return t.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const s=this._deepActiveElement(),n=i[0],o=i[i.length-1];!t.shiftKey||s!==n&&i.includes(s)?t.shiftKey||s!==o||(t.preventDefault(),n.focus()):(t.preventDefault(),o.focus())},this._onFallbackCancel=t=>{t.preventDefault(),this._requestClose()},this._onFallbackClick=t=>{this.dismissOnScrim&&t.target===t.currentTarget&&this._requestClose()}}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const t=this.getRootNode();this._focusRoot=t;const e=Ct.get(t)||{dialogs:new Set,opener:this._opener};e.dialogs.add(this),Ct.set(t,e),this._useHaDialog=!!customElements.get("ha-dialog"),this.addEventListener("keydown",this._onKeyDown,!0)}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const t=[...this._overlays];this._overlays=[];for(const e of t.reverse())e.close("disconnect");const e=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const s=e?Ct.get(e):void 0;s?.dialogs.delete(this),super.disconnectedCallback(),e&&s&&requestAnimationFrame(()=>{const t=Ct.get(e);if(!t)return;if(!t.dialogs.size)return t.opener?.isConnected&&t.opener.focus({preventScroll:!0}),void Ct.delete(e);const s=i?.closest("hp-dialog");i?.isConnected&&s&&t.dialogs.has(s)&&i.focus({preventScroll:!0})})}firstUpdated(t){if(super.firstUpdated(t),!this._useHaDialog){const t=this.renderRoot.querySelector("dialog");t&&!t.open&&t.showModal()}queueMicrotask(()=>this._focusInitial())}_deepActiveElement(){let t=document.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t&&t!==document.body?t:null}_focusableElements(){const t=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),e=[],i=new Set,s=n=>{if(!i.has(n)){if(i.add(n),n instanceof HTMLElement){if(n.matches(t)&&e.push(n),n instanceof HTMLSlotElement){for(const t of n.assignedNodes({flatten:!0}))s(t);return}if(n.shadowRoot){for(const t of n.shadowRoot.childNodes)s(t);return}}for(const t of n.childNodes)s(t)}};for(const t of this.childNodes)s(t);const n=this.overlayPortal();return n&&s(n),e.filter(t=>{let e=t;for(;e;){const t=getComputedStyle(e);if(e.hidden||e.inert||"true"===e.getAttribute("aria-hidden")||"none"===t.display||"hidden"===t.visibility)return!1;if(e=e.assignedSlot||e.parentElement||(e.getRootNode()instanceof ShadowRoot?e.getRootNode().host:null),e===this)break}return!0})}_pruneOverlays(){this._overlays=this._overlays.filter(t=>t.owner.isConnected)}_closeOverlay(t,e){const i=this._overlays.findIndex(e=>e.token===t.token);i>=0&&this._overlays.splice(i,1),t.close(e)}registerOverlay(t){this._pruneOverlays();const e=this._overlays.find(e=>e.owner===t.owner);e&&this._overlays.splice(this._overlays.indexOf(e),1);const i=t.group||"transient";for(const t of[...this._overlays].reverse())t.group===i&&this._closeOverlay(t,"exclusive");const s={...t,group:i,token:Symbol("hp-overlay")};this._overlays.push(s);let n=!1;return()=>{if(n)return;n=!0;const t=this._overlays.findIndex(t=>t.token===s.token);t>=0&&this._overlays.splice(t,1)}}closeTransientOverlays(t="outside"){this._pruneOverlays();const e=[...this._overlays].filter(t=>"transient"===(t.group||"transient"));for(const i of e.reverse())this._closeOverlay(i,t);return e.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const t=W` +globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="fe0a35cf861928503f26ca1e1b7b14f6bd9a18bf8770e41df2f1ff30332973e9";const t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),s=new WeakMap;let n=class{constructor(t,e,s){if(this._$cssResult$=!0,s!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const i=this.t;if(e&&void 0===t){const e=void 0!==i&&1===i.length;e&&(t=s.get(i)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&s.set(i,t))}return t}toString(){return this.cssText}};const o=(t,...e)=>{const s=1===t.length?t[0]:e.reduce((e,i,s)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[s+1],t[0]);return new n(s,t,i)},a=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return(t=>new n("string"==typeof t?t:t+"",void 0,i))(e)})(t):t,{is:r,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:p}=Object,u=globalThis,_=u.trustedTypes,m=_?_.emptyScript:"",g=u.reactiveElementPolyfillSupport,f=(t,e)=>t,v={toAttribute(t,e){switch(e){case Boolean:t=t?m:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},y=(t,e)=>!r(t,e),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),u.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=b){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);void 0!==s&&l(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=c(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:s,set(e){const o=s?.call(this);n?.call(this,e),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const t=p(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const t=this.properties,e=[...h(t),...d(t)];for(const i of e)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,i]of e)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const i=this._$Eu(t,e);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(a(t))}else void 0!==t&&e.push(a(t));return e}static _$Eu(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,s)=>{if(e)i.adoptedStyleSheets=s.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of s){const s=document.createElement("style"),n=t.litNonce;void 0!==n&&s.setAttribute("nonce",n),s.textContent=e.cssText,i.appendChild(s)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$ET(t,e){const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(void 0!==s&&!0===i.reflect){const n=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(e,i.type);this._$Em=t,null==n?this.removeAttribute(s):this.setAttribute(s,n),this._$Em=null}}_$AK(t,e){const i=this.constructor,s=i._$Eh.get(t);if(void 0!==s&&this._$Em!==s){const t=i.getPropertyOptions(s),n="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:v;this._$Em=s;const o=n.fromAttribute(e,t.type);this[s]=o??this._$Ej?.get(s)??o,this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(void 0!==t){const o=this.constructor;if(!1===s&&(n=this[t]),i??=o.getPropertyOptions(t),!((i.hasChanged??y)(n,e)||i.useDefault&&i.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,e,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:i,reflect:s,wrapped:n},o){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==n||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),!0===s&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,i]of t){const{wrapped:t}=i,s=this[e];!0!==t||this._$AL.has(e)||void 0===s||this.C(e,void 0,i,s)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(u.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=t=>t,$=k.trustedTypes,S=$?$.createPolicy("lit-html",{createHTML:t=>t}):void 0,M="$lit$",C=`lit$${Math.random().toFixed(9).slice(2)}$`,D="?"+C,P=`<${D}>`,T=document,R=()=>T.createComment(""),I=t=>null===t||"object"!=typeof t&&"function"!=typeof t,A=Array.isArray,z="[ \t\n\f\r]",F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,E=/-->/g,N=/>/g,O=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),L=/'/g,H=/"/g,B=/^(?:script|style|textarea|title)$/i,q=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),W=q(1),j=q(2),U=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),V=new WeakMap,K=T.createTreeWalker(T,129);function Y(t,e){if(!A(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==S?S.createHTML(e):e}const J=(t,e)=>{const i=t.length-1,s=[];let n,o=2===e?"":3===e?"":"",a=F;for(let e=0;e"===l[0]?(a=n??F,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,r=l[1],a=void 0===l[3]?O:'"'===l[3]?H:L):a===H||a===L?a=O:a===E||a===N?a=F:(a=O,n=void 0);const d=a===O&&t[e+1].startsWith("/>")?" ":"";o+=a===F?i+P:c>=0?(s.push(r),i.slice(0,c)+M+i.slice(c)+C+d):i+C+(-2===c?e:d)}return[Y(t,o+(t[i]||"")+(2===e?"":3===e?"":"")),s]};class X{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,o=0;const a=t.length-1,r=this.parts,[l,c]=J(t,e);if(this.el=X.createElement(l,i),K.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(s=K.nextNode())&&r.length0){s.textContent=$?$.emptyScript:"";for(let i=0;iA(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==G&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:i}=t,s="number"==typeof i?this._$AC(t):(void 0===i.el&&(i.el=X.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===s)this._$AH.p(e);else{const t=new Q(s,this),i=t.u(this.options);t.p(e),this.T(i),this._$AH=t}}_$AC(t){let e=V.get(t.strings);return void 0===e&&V.set(t.strings,e=new X(t)),e}k(t){A(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new tt(this.O(R()),this.O(R()),this,this.options)):i=e[s],i._$AI(n),s++;s2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(t,e=this,i,s){const n=this.strings;let o=!1;if(void 0===n)t=Z(this,t,e,0),o=!I(t)||t!==this._$AH&&t!==U,o&&(this._$AH=t);else{const s=t;let a,r;for(t=n[0],a=0;a{const s=i?.renderBefore??e;let n=s._$litPart$;if(void 0===n){const t=i?.renderBefore??null;s._$litPart$=n=new tt(e.insertBefore(R(),t),t,void 0,i??{})}return n._$AI(t),n},ct=globalThis;let ht=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=lt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};ht._$litElement$=!0,ht.finalized=!0,ct.litElementHydrateSupport?.({LitElement:ht});const dt=ct.litElementPolyfillSupport;dt?.({LitElement:ht}),(ct.litElementVersions??=[]).push("4.2.2");const pt=2,ut=t=>(...e)=>({_$litDirective$:t,values:e});let _t=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const mt={},gt=ut(class extends _t{constructor(){super(...arguments),this.ot=mt}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return U}else if(this.ot===e)return U;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}}),{I:ft}=at,vt=t=>t,yt=()=>document.createComment(""),bt=(t,e,i)=>{const s=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=s.insertBefore(yt(),n),o=s.insertBefore(yt(),n);i=new ft(e,o,t,t.options)}else{const e=i._$AB.nextSibling,o=i._$AM,a=o!==t;if(a){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==o._$AU&&i._$AP(e)}if(e!==n||a){let t=i._$AA;for(;t!==e;){const e=vt(t).nextSibling;vt(s).insertBefore(t,n),t=e}}}return i},wt=(t,e,i=t)=>(t._$AI(e,i),t),kt={},xt=(t,e=kt)=>t._$AH=e,$t=t=>{t._$AR(),t._$AA.remove()},St=(t,e,i)=>{const s=new Map;for(let n=e;n<=i;n++)s.set(t[n],n);return s},Mt=ut(class extends _t{constructor(t){if(super(t),t.type!==pt)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let s;void 0===i?i=e:void 0!==e&&(s=e);const n=[],o=[];let a=0;for(const e of t)n[a]=s?s(e,a):a,o[a]=i(e,a),a++;return{values:o,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,s]){const n=(t=>t._$AH)(t),{values:o,keys:a}=this.dt(e,i,s);if(!Array.isArray(n))return this.ut=a,o;const r=this.ut??=[],l=[];let c,h,d=0,p=n.length-1,u=0,_=o.length-1;for(;d<=p&&u<=_;)if(null===n[d])d++;else if(null===n[p])p--;else if(r[d]===a[u])l[u]=wt(n[d],o[u]),d++,u++;else if(r[p]===a[_])l[_]=wt(n[p],o[_]),p--,_--;else if(r[d]===a[_])l[_]=wt(n[d],o[_]),bt(t,l[_+1],n[d]),d++,_--;else if(r[p]===a[u])l[u]=wt(n[p],o[u]),bt(t,n[d],n[p]),p--,u++;else if(void 0===c&&(c=St(a,u,_),h=St(r,d,p)),c.has(r[d]))if(c.has(r[p])){const e=h.get(a[u]),i=void 0!==e?n[e]:null;if(null===i){const e=bt(t,n[d]);wt(e,o[u]),l[u]=e}else l[u]=wt(i,o[u]),bt(t,n[d],i),n[e]=null;u++}else $t(n[p]),p--;else $t(n[d]),d++;for(;u<=_;){const e=bt(t,l[_+1]);wt(e,o[u]),l[u++]=e}for(;d<=p;){const t=n[d++];null!==t&&$t(t)}return this.ut=a,xt(t,l),U}}),Ct=new WeakMap;let Dt=0;class Pt extends ht{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=!1,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Dt,this._focusInitial=()=>{const t=this._focusableElements(),e=t.find(t=>t.hasAttribute("autofocus"))||t[0]||(this._useHaDialog?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");e?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=t=>{if("Escape"===t.key){t.preventDefault(),t.stopImmediatePropagation(),this._pruneOverlays();const e=this._overlays[this._overlays.length-1];return e?void this._closeOverlay(e,"escape"):void this._requestClose()}if("Tab"!==t.key||this._useHaDialog)return;const e=this.renderRoot.querySelector(".close"),i=e?[e,...this._focusableElements()]:this._focusableElements();if(!i.length)return t.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const s=this._deepActiveElement(),n=i[0],o=i[i.length-1];!t.shiftKey||s!==n&&i.includes(s)?t.shiftKey||s!==o||(t.preventDefault(),n.focus()):(t.preventDefault(),o.focus())},this._onFallbackCancel=t=>{t.preventDefault(),this._requestClose()},this._onFallbackClick=t=>{this.dismissOnScrim&&t.target===t.currentTarget&&this._requestClose()}}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const t=this.getRootNode();this._focusRoot=t;const e=Ct.get(t)||{dialogs:new Set,opener:this._opener};e.dialogs.add(this),Ct.set(t,e),this._useHaDialog=!!customElements.get("ha-dialog"),this.addEventListener("keydown",this._onKeyDown,!0)}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const t=[...this._overlays];this._overlays=[];for(const e of t.reverse())e.close("disconnect");const e=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const s=e?Ct.get(e):void 0;s?.dialogs.delete(this),super.disconnectedCallback(),e&&s&&requestAnimationFrame(()=>{const t=Ct.get(e);if(!t)return;if(!t.dialogs.size)return t.opener?.isConnected&&t.opener.focus({preventScroll:!0}),void Ct.delete(e);const s=i?.closest("hp-dialog");i?.isConnected&&s&&t.dialogs.has(s)&&i.focus({preventScroll:!0})})}firstUpdated(t){if(super.firstUpdated(t),!this._useHaDialog){const t=this.renderRoot.querySelector("dialog");t&&!t.open&&t.showModal()}queueMicrotask(()=>this._focusInitial())}_deepActiveElement(){let t=document.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t&&t!==document.body?t:null}_focusableElements(){const t=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),e=[],i=new Set,s=n=>{if(!i.has(n)){if(i.add(n),n instanceof HTMLElement){if(n.matches(t)&&e.push(n),n instanceof HTMLSlotElement){for(const t of n.assignedNodes({flatten:!0}))s(t);return}if(n.shadowRoot){for(const t of n.shadowRoot.childNodes)s(t);return}}for(const t of n.childNodes)s(t)}};for(const t of this.childNodes)s(t);const n=this.overlayPortal();return n&&s(n),e.filter(t=>{let e=t;for(;e;){const t=getComputedStyle(e);if(e.hidden||e.inert||"true"===e.getAttribute("aria-hidden")||"none"===t.display||"hidden"===t.visibility)return!1;if(e=e.assignedSlot||e.parentElement||(e.getRootNode()instanceof ShadowRoot?e.getRootNode().host:null),e===this)break}return!0})}_pruneOverlays(){this._overlays=this._overlays.filter(t=>t.owner.isConnected)}_closeOverlay(t,e){const i=this._overlays.findIndex(e=>e.token===t.token);i>=0&&this._overlays.splice(i,1),t.close(e)}registerOverlay(t){this._pruneOverlays();const e=this._overlays.find(e=>e.owner===t.owner);e&&this._overlays.splice(this._overlays.indexOf(e),1);const i=t.group||"transient";for(const t of[...this._overlays].reverse())t.group===i&&this._closeOverlay(t,"exclusive");const s={...t,group:i,token:Symbol("hp-overlay")};this._overlays.push(s);let n=!1;return()=>{if(n)return;n=!0;const t=this._overlays.findIndex(t=>t.token===s.token);t>=0&&this._overlays.splice(t,1)}}closeTransientOverlays(t="outside"){this._pruneOverlays();const e=[...this._overlays].filter(t=>"transient"===(t.group||"transient"));for(const i of e.reverse())this._closeOverlay(i,t);return e.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const t=W` ${this.icon?W``:G} ${this.title} `;return this._useHaDialog?W` `})} - `}const Rr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Ir=(t,e=1)=>{const i=Number(t);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):e},Ar=t=>{let e=Number(t);return Number.isFinite(e)?(e=(e%360+360)%360,e>180?e-360:e):0};function zr(t,e,i){return Ar(e)?[t.x,t.y]:i([t.x,t.y])}const Fr=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&s>0?s/n*i:0},Er=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&i>0?s/i*n:0},Nr=(t,e,i,s=Rr.widthCm)=>{const n=Number(t?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(t?.width);return Number.isFinite(o)&&o>0?Er(o,e,i):s};function Or(t,e){return{color:t.color,opacity:Ir(t.opacity),width_cm:Math.max(.1,Math.min(100,Number(t.widthCm)||.1)),...e?{fill:t.fill,fill_color:t.fillColor,fill_opacity:Ir(t.fillOpacity,.25)}:{}}}function Lr(t){const e=t.x+t.w/2,i=t.y+t.h/2,s=Ar(t.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(t,s)=>{const a=t-e,r=s-i;return[e+a*n-r*o,i+a*o+r*n]};return[a(t.x,t.y),a(t.x+t.w,t.y),a(t.x+t.w,t.y+t.h),a(t.x,t.y+t.h)]}function Hr(t){const e=Lr(t),i=(t,e)=>[(t[0]+e[0])/2,(t[1]+e[1])/2],s=[(e[0][0]+e[2][0])/2,(e[0][1]+e[2][1])/2];return{points:[...e,i(e[0],e[1]),i(e[1],e[2]),i(e[2],e[3]),i(e[3],e[0]),s],segments:e.map((t,i)=>({a:t,b:e[(i+1)%4]}))}}function Br(t,e,i,s,n,o,a,r){const l=Ar(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=t.x+t.w/2,_=t.y+t.h/2,m=e>0?-t.w/2:t.w/2,g=i>0?-t.h/2:t.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(e>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const e=w/Math.max(t.w,r),i=k/Math.max(t.h,r);x=Math.max(r/Math.max(t.w,r),r/Math.max(t.h,r),e,i),w=t.w*x,k=t.h*x}if(a>0)if(o){const e=Math.max(1,Math.round(t.w/a)),i=Math.max(1,Math.round(t.h/a));if(Math.abs(t.w-e*a)<1e-6&&Math.abs(t.h-i*a)<1e-6){const s=(t,e)=>{let i=Math.abs(t),s=Math.abs(e);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(e,i),o=Math.max(r/t.w,r/t.h),a=Math.max(o,Math.round((x??1)/n)*n);w=t.w*a,k=t.h*a}else{t.w>=t.h?(w=Math.round(w/a)*a,k=w*(t.h/Math.max(t.w,r))):(k=Math.round(k/a)*a,w=k*(t.w/Math.max(t.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(e>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(e>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Ar(t.angle)||void 0}}const qr=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<1e-12)return[...e];const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return[e[0]+s*a,e[1]+n*a]};const Wr=10**9,jr=240,Ur=1e-4;function Gr(t){if(Array.isArray(t))return t.map(t=>Gr(t));if(null!==t&&"object"==typeof t){const e={};for(const[i,s]of Object.entries(t))e[i]=Gr(s);return e}return t}function Vr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=(t<0||Object.is(t,-0)?-1:1)*(Math.floor(Math.abs(t)*Wr+.5)/Wr);return 0===e?0:e}function Kr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=t*jr,i=Math.round(e);if(Math.abs(e-i)null!==Jr(t)):[]}function Zr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Vr(t[i]))}function Qr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Kr(t[i]))}function tl(t){if(Array.isArray(t))for(let e=0;e{for(const n of s){const s=e[n];"number"==typeof s&&Number.isFinite(s)&&i(s,t)}},s=e=>{if(Array.isArray(e))for(let s=0;s{if(Array.isArray(t))for(const e of t)s(e)};for(const i of Xr(t.rooms))e(i,["x","y","w","h"]),n(i.poly);for(const e of Xr(t.walls))s(e.a),s(e.b);for(const e of Xr(t.wall_segments))s(e.a),s(e.b);for(const i of Xr(t.openings))e(i,["x","y"]);for(const i of Xr(t.decor))"line"===i.kind?e(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?e(i,["x","y","w","h"]):"text"===i.kind&&e(i,["x","y"]);for(const e of Xr(t.room_drafts))n(e.points);for(const e of Xr(t.partitions))s(e.a),s(e.b);for(const e of Xr(t.wall_columns))s(e.center);for(const e of Xr(t.open_spans))s(e.a),s(e.b)}const n=Jr(e);if(!n)return;const o=new Map;if(s)for(const t of Xr(s.spaces))null!=t.id&&o.set(String(t.id),t);for(const t of Object.values(n)){const e=Jr(t);if(!e)continue;const s=null!=e.s&&o.get(String(e.s))||null;for(const t of["x","y"]){const n=e[t];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function sl(t){const e=Number(t?.cell_cm);return e>0?e:5}function nl(t,e={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=Xr(Jr(t)?.spaces);let n=5;for(const t of s)n=Math.max(n,sl(t));il(t,e,(t,e)=>{const s=t*jr,o=Math.abs(s-Math.round(s)),a=Kr(t),r=o>0&&o=Ur))return;const l=r&&"number"==typeof a?Math.abs(a-t):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*jr*(e?sl(e):n)),!e?.id||!r)return;const c=String(e.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(e.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*jr*sl(e))}),i.bySpace.size&&il(t,e,(t,e)=>{if(!e?.id)return;const s=i.bySpace.get(String(e.id));if(!s)return;const n=t*jr;Math.abs(n-Math.round(n))>=Ur&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function ol(t){return function(t){const e=t,i=Jr(e);i&&Qr(i,["x","y"]);return e}(Gr(t))}function al(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Object.values(i)){const e=Jr(t);e&&Qr(e,["x","y"])}return e}function rl(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Xr(i.spaces)){Zr(t,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const e of Xr(t.rooms))Qr(e,["x","y","w","h"]),el(e.poly);for(const e of Xr(t.walls))tl(e.a),tl(e.b);for(const e of Xr(t.wall_segments))tl(e.a),tl(e.b);for(const e of Xr(t.openings)){Qr(e,["x","y"]),Zr(e,["angle","length"]);const t=Jr(e.host);t&&Zr(t,["t"])}for(const e of Xr(t.decor))"line"===e.kind?Qr(e,["x1","y1","x2","y2"]):"rect"===e.kind||"ellipse"===e.kind||"furniture"===e.kind?(Qr(e,["x","y","w","h"]),Zr(e,["angle"])):"text"===e.kind&&(Qr(e,["x","y"]),Zr(e,["scale","angle"]));for(const e of Xr(t.room_drafts))el(e.points);for(const e of Xr(t.partitions))tl(e.a),tl(e.b);for(const e of Xr(t.wall_columns))tl(e.center),"square"===e.shape&&Zr(e,["angle"]);for(const e of Xr(t.open_spans))tl(e.a),tl(e.b)}for(const t of Xr(i.markers))Zr(t,["angle"]);return e}const ll=15;function cl(t,e,i,s,n){const o=i[0]-t[0],a=i[1]-t[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=e=>{const s=(e[0]-t[0])*l+(e[1]-t[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[e[0]+(i[0]-e[0])*o,e[1]+(i[1]-e[1])*o]},d=h(e),p=h(s);return d&&p?[[t[0],t[1]],e,d,p,s]:null}const hl=Math.sin(.25*Math.PI/180);function dl(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<3}function pl(t){const e=Number(t)>0?Number(t):5;if(5===e)return 8;const i=5/e*8;return Math.min(80,Math.max(.5,i))}function ul(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<2}function _l(t){return Number.isFinite(t)?Math.max(1,Math.min(100,t)):1}function ml(t,e){return!Number.isFinite(t)||t<0?"":String(e?Math.round(t/2.54*100)/100:Math.round(100*t)/100)}function gl(t,e,i){if(!Number.isFinite(t)||t<=0)return 0;const s=Number(e)>0?Number(e):5;return _l(t)/s*i}function fl(t,e){return e>0&&Number.isFinite(t)?Math.round(t/e)*e:t}function vl(t){return Math.max(1e-6*Math.abs(t),1e-9)}function yl(t,e){if(!(e>0&&Number.isFinite(t)))return t;const i=fl(t,e);return Math.abs(i-t)<=vl(e)?i:t}function bl(t,e){let i=e[0]-t[0],s=e[1]-t[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function wl(t,e,i){const s=[yl(t[0],i),yl(t[1],i)],n=[yl(e[0],i),yl(e[1],i)],o=fl((s[0]+n[0])/2,i),a=fl((s[1]+n[1])/2,i),[r,l]=bl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function kl(t,e,i,s){return 1===s?wl(t,e,i):wl([t[0]/s,t[1]/s],[e[0]/s,e[1]/s],i)}function xl(t,e){if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return null;const i=[Number(t.a[0]),Number(t.a[1]),Number(t.b[0]),Number(t.b[1])];if(!i.every(Number.isFinite))return null;const s=e>0?e:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function $l(t,e,i,s,n){const o=n>0?n:1;return{key:kl(t,e,s,o),cm:_l(i),a:[t[0]/o,t[1]/o],b:[e[0]/o,e[1]/o]}}function Sl(t,e){const i=e>0?e:1,s=[];for(const e of t){const t=e.key.lastIndexOf("@");if(t<0)continue;const[n,o]=e.key.slice(0,t).split(",").map(Number),a=Number(e.key.slice(t+1));[n,o,a].every(Number.isFinite)&&s.push({w:e,x:n*i,y:o*i,ang:a})}return s}function Ml(t,e){const[i,s]=bl(t,e);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Cl(t,e){let i=Math.abs(t-e);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Dl(t,e,i,s,n=1){if(!t?.length)return null;const o=kl(e,i,s,n),a=t.find(t=>t.key===o);if(a)return a;const r=n>0?n:1,l=vl(s)*r,c=(t,e)=>Math.abs(t[0]-e[0])<=l&&Math.abs(t[1]-e[1])<=l;for(const s of t){const t=xl(s,r);if(t&&(c(t[0],e)&&c(t[1],i)||c(t[0],i)&&c(t[1],e)))return s}const h=(e[0]+i[0])/2,d=(e[1]+i[1])/2,p=Ml(e,i),u=Math.max(.5*s,1e-9)*r;for(const e of Sl(t,r))if(Cl(e.ang,p)&&Math.hypot(e.x-h,e.y-d)<=u)return e.w;return null}function Pl(t,e,i,s,n=1){const o=Dl(t,e,i,s,n);if(o&&o.cm>0)return _l(o.cm);const a=function(t,e,i,s,n){if(!t?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-e[0],i[1]-e[1]);if(a<1e-12)return null;const r=Ml(e,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of t){if(!(s.cm>0))continue;const t=xl(s,o);if(!t)continue;const n=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);if(n<1e-12||!Cl(Ml(t[0],t[1]),r))continue;if(mc(e[0],e[1],t[0][0],t[0][1],t[1][0],t[1][1])>l||mc(i[0],i[1],t[0][0],t[0][1],t[1][0],t[1][1])>l)continue;if(n+l(o.has(t.key)||(t=>{const e=xl(t,s);if(!e)return!1;const[i,o]=e,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];return Cl(Ml(i,o),Ml(e,s))&&mc(i[0],i[1],e[0],e[1],s[0],s[1])<=l&&mc(o[0],o[1],e[0],e[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];if(!Cl(Ml(i,o),Ml(e,s)))return!1;const n=t=>Math.abs((t[0]-i[0])*c-(t[1]-i[1])*r)/h;if(n(e)>l||n(s)>l)return!1;const a=h*h,d=((e[0]-i[0])*r+(e[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(t))&&t.cm>=1&&t.cm<=100)}function Rl(t,e,i,s=8){const[n,o]=bl(t,e);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Il(t,e,i,s,n=1,o="affine",a){if(!t?.length)return[];if(e.length!==i.length)return"fixed-topology"===o&&a?.(),t.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(t,e,i)=>{const s=t.get(e)||new Set;s.add(i),t.set(e,s)};for(let t=0;t[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],m=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=c,g=(t,e)=>{if("fixed-topology"===o){const i=e.na[0]-e.oa[0],s=e.na[1]-e.oa[1],n=e.nb[0]-e.ob[0],o=e.nb[1]-e.ob[1];return Math.hypot(i-n,s-o)<=c?[t[0]+i,t[1]+s]:m(t,e.oa)?[...e.na]:m(t,e.ob)?[...e.nb]:[...t]}const i=Math.max(0,Math.min(1,((t[0]-e.oa[0])*e.dx+(t[1]-e.oa[1])*e.dy)/e.len2));return _(e.na,e.nb,i)},f=(t,e)=>{const[i,s]=bl(t,e);return(e[0]-t[0])*i+(e[1]-t[1])*s>=0?[[...t],[...e]]:[[...e],[...t]]},v=[],y=[],b=(t,e,i)=>{if(Math.hypot(e[0]-t[0],e[1]-t[1])<=c)return;const[n,o]=f(t,e),a=_l(i);if(y.some(t=>t.entry.cm===a&&m(t.span[0],n)&&m(t.span[1],o)))return;const l=$l(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const e of t){const t=xl(e,r);if(t){const[i,s]=f(t[0],t[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...e,cm:_l(e.cm)});continue}const p=[];for(const t of h){if(!Cl(Ml(i,s),Ml(t.oa,t.ob)))continue;const e=t=>Math.abs((t[0]-i[0])*a-(t[1]-i[1])*n)/d;if(e(t.oa)>l||e(t.ob)>l)continue;const o=((t.oa[0]-i[0])*n+(t.oa[1]-i[1])*a)/r,h=((t.ob[0]-i[0])*n+(t.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:t})}if(!p.length){"fixed-topology"===o?v.push({...e}):b(i,s,e.cm);continue}const u=[0,1,...p.flatMap(({lo:t,hi:e})=>[t,e])].sort((t,e)=>t-e).filter((t,e,i)=>0===e||Math.abs(t-i[e-1])*d>c),y=[];for(let t=0;t+1r>=t.lo-1e-12&&r<=t.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(t=>{const e=g(o,t.move),i=g(a,t.move);return!m(h[0],e)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(t,e)=>{const i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],n=e[1][0]-e[0][0],o=e[1][1]-e[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const t of y){const e=k[k.length-1];e&&m(e[1],t[0])&&w(e,t)?e[1]=t[1]:k.push([[...t[0]],[...t[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,t[0])&&m(s,t[1])||m(i,t[1])&&m(s,t[0])){v.push({...e});continue}}for(const[t,i]of k)b(t,i,e.cm);continue}if("fixed-topology"===o){const t=p.get(e.key);if(1===t?.size){const i=[...t][0];v.push(i===e.key?{...e}:{...e,key:i});continue}const i=[Sl([e],r)[0]];1!==r&&i.push(Sl([e],1)[0]);const s=i.filter(Boolean).some(t=>h.some(e=>{if(!Cl(t.ang,Ml(e.oa,e.ob)))return!1;const i=((t.x-e.oa[0])*e.dx+(t.y-e.oa[1])*e.dy)/e.len2;return i>=-1e-6&&i<=1.000001&&mc(t.x,t.y,e.oa[0],e.oa[1],e.ob[0],e.ob[1])<=l}));((t?.size||0)>1||s)&&a?.(),v.push({...e});continue}let i="";const n=d.get(e.key);if(1===n?.size&&(i=[...n][0]),!i){const t=Sl([e],r)[0];if(t){const e=new Set;for(const i of h){if(!Cl(t.ang,Ml(i.oa,i.ob)))continue;const n=((t.x-i.oa[0])*i.dx+(t.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(mc(t.x,t.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([t.x,t.y],i),[a,c]=bl(i.na,i.nb),h=Math.max(s*r,1e-6);e.add(kl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===e.size&&(i=[...e][0])}}v.push({...e,key:i||e.key,cm:_l(e.cm)})}return v}function Al(t,e,i,s,n=1,o="affine"){return Il(t,e,i,s,n,o)}function zl(t,e,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Ur,1e-9),l=(n||[]).flatMap(t=>{const e=xl(t,o);return e?e.map(t=>[...t]):[]}),c=t=>t.every((t,e)=>(t=>{if(!(a>0))return!0;const e=t/o/a;return Math.abs(e-Math.round(e))Math.abs(t-i[e])<=r)),h=[],d=t=>JSON.stringify([t.key,t.cm,t.a,t.b]);for(const i of t||[]){const t=xl(i,o);if(!t)continue;const[s,n]=t;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const t of e){const[e,i]=t;if(![e?.[0],e?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=t=>Math.abs((t[0]-s[0])*_-(t[1]-s[1])*u);if(n(e)>r||n(i)>r)continue;const o=(e[0]-s[0])*u+(e[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let g=0;for(const[t,e]of m){if(t>g+r)break;if(g=Math.max(g,e),g>=p-r)break}gt.key!==a);return null==s||s<1?r:[...r,$l(e,i,s,n,o)]}function El(t,e,i,s,n,o=[],a=1){let r=t?t.slice():[];for(const t of function(t,e,i,s,n=1,o=[]){const a=ec(t,e,i,s,n,o);if(!a)return[];const r=[];for(let t=0;t0||(c=Fl(c,e,i,s,n,a)))}return c}function Ol(t){const{a:e,b:i,halfDepth:s}=t;if(!Array.isArray(e)||!Array.isArray(i)||e.length<2||i.length<2||![e[0],e[1],i[0],i[1]].every(Number.isFinite))return null;const n=i[0]-e[0],o=i[1]-e[1],a=Math.hypot(n,o);if(!(a>1e-9&&s>0&&Number.isFinite(s)))return null;const r=-o/a*s,l=n/a*s;return[[e[0]+r,e[1]+l],[i[0]+r,i[1]+l],[i[0]-r,i[1]-l],[e[0]-r,e[1]-l]]}function Ll(t,e,i){return Math.hypot(t[0]-e[0],t[1]-e[1])<=i}function Hl(t,e,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=s*s+n*n;if(!(o>i*i))return!1;const a=((t[0]-e.a[0])*s+(t[1]-e.a[1])*n)/o;if(!(a>0&&a<1))return!1;const r=[e.a[0]+s*a,e.a[1]+n*a];return Math.hypot(t[0]-r[0],t[1]-r[1])<=i}function Bl(t,e,i,s){const n=Math.hypot(e,i);if(!(n>1e-9&&s>0))return;const o=[e/n,i/n],a=t.find(t=>Math.abs(t.u[0]*o[1]-t.u[1]*o[0])<1e-9&&t.u[0]*o[0]+t.u[1]*o[1]>1-1e-9);a?a.halfDepth=Math.max(a.halfDepth,s):t.push({u:o,halfDepth:s})}function ql(t,e){try{const i=oi(vc(t),vc(e));let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Kl(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function Wl(t,e=1e-6){const i=(t||[]).map((t,e)=>({segment:t,index:e})).filter(({segment:t})=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(({segment:t})=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[];for(const t of o){const e=[];let n=!1;for(const{segment:o,index:a}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Ll(t,o.a,s)?e.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Ll(t,o.b,s)?e.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Hl(t,o,s)&&(n=!0)}if(n||2!==e.length)continue;const[o,r]=e,l=o.u[0]*r.u[1]-o.u[1]*r.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-r.u[1],r.u[0]],p=[t[0]+h[0]*o.halfDepth*c,t[1]+h[1]*o.halfDepth*c],u=[t[0]-d[0]*r.halfDepth*c,t[1]-d[1]*r.halfDepth*c];if(!Xl(p,o.u,u,r.u))continue;const _=[[o,r,u,[d[0]*-c,d[1]*-c]],[r,o,p,[h[0]*c,h[1]*c]]];for(const[e,,i,n]of _){const o=Math.min(2*e.halfDepth,e.length),r=[-e.u[1]*e.halfDepth,e.u[0]*e.halfDepth],l=[[t[0]+r[0],t[1]+r[1]],[t[0]+e.u[0]*o+r[0],t[1]+e.u[1]*o+r[1]],[t[0]+e.u[0]*o-r[0],t[1]+e.u[1]*o-r[1]],[t[0]-r[0],t[1]-r[1]]],c=t=>(t[0]-i[0])*n[0]+(t[1]-i[1])*n[1],h=[];for(let t=0;t=-1e-12&&h.push(e),s>1e-12&&n<-1e-12||s<-1e-12&&n>1e-12){const t=s/(s-n);h.push([e[0]+(i[0]-e[0])*t,e[1]+(i[1]-e[1])*t])}}h.length>=3&&Math.abs(Kl(h))>s*s&&a.push({segmentIndex:e.index,wedge:h})}}return a}function jl(t,e=1e-6){const i=(t||[]).filter(t=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(t=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[],r=i.map((t,e)=>({roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`join-${e}`,kind:"outer",cm:0,open:!1,half:t.halfDepth})),l=ac(r,s);for(const t of rc(l).fans)a.push(t);const c=t=>!!lc(l,t);for(const t of o){if(c(t))continue;const e=[];for(const n of i)Ll(t,n.a,s)?Bl(e,n.b[0]-n.a[0],n.b[1]-n.a[1],n.halfDepth):Ll(t,n.b,s)?Bl(e,n.a[0]-n.b[0],n.a[1]-n.b[1],n.halfDepth):Hl(t,n,s)&&(Bl(e,n.a[0]-t[0],n.a[1]-t[1],n.halfDepth),Bl(e,n.b[0]-t[0],n.b[1]-t[1],n.halfDepth));if(!(e.length<2)){e.sort((t,e)=>Math.atan2(t.u[1],t.u[0])-Math.atan2(e.u[1],e.u[0])||t.halfDepth-e.halfDepth);for(let i=0;is*s&&a.push(m)}}}return a}function Ul(t,e,i,s){if(!(e>0)||!t||t.length<2)return"";if(i&&t.length>=3){let i=t;const n=t[t.length-1];if(t.length>=4&&Math.hypot(t[0][0]-n[0],t[0][1]-n[1])<1e-9&&(i=t.slice(0,-1)),i.length>=3){const t=i.map((t,i)=>s?.[i]||e),n=Fc(i,t),o=Zl(i,t);if(n&&o)return`${Ql(n)} ${Ql(tc(o))}`}}const n=[];for(let i=0;i=1e-9&&r>0&&n.push({a:o,b:a,halfDepth:r})}const o=n.map(Ol);for(const{segmentIndex:t,wedge:e}of Wl(n)){const i=o[t];if(!i)continue;const s=ql(i,e);s&&(o[t]=s)}const a=[...o.filter(t=>!!t),...jl(n)],r=function(t){let e=null;try{for(const i of t){if(i.length<3)continue;const t=vc(i);e=e?si(e,t):[t]}return e}catch{return null}}(a);return r?Tc(r):a.map(t=>Ql(t)).join(" ")}function Gl(t,e,i,s,n=1){if(!i.length)return!1;const o=Vl(s,n),a=(t[0]+e[0])/2,r=(t[1]+e[1])/2,[l,c]=bl(t,e);for(const t of i){const[e,i]=bl([t[0],t[1]],[t[2],t[3]]);if(!(Math.abs(l*i-c*e)>.05)&&mc(a,r,t[0],t[1],t[2],t[3])<=o)return!0}return!1}function Vl(t,e){return Math.max(t*(e>0?e:1)*.04,1e-9)}function Kl(t){let e=0;for(let i=0;it[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a+0)+o&&(i=!i)}return i}([c[0]+.001*r,c[1]+.001*l],t)||(r=-r,l=-l),[r,l]}function Jl(t,e){const i=t[0]*e[1]-t[1]*e[0],s=t[0]*e[0]+t[1]*e[1];return Math.abs(i)<1e-9&&s>0}function Xl(t,e,i,s){const n=e[0]*s[1]-e[1]*s[0];if(Math.abs(n)<1e-12)return null;const o=[i[0]-t[0],i[1]-t[1]],a=(o[0]*s[1]-o[1]*s[0])/n;return[t[0]+a*e[0],t[1]+a*e[1]]}function Zl(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);const n=[];for(let o=0;o0||p>0)){n.push([t[o][0],t[o][1]]);continue}if(d>0!=p>0){const e=t[o],i=d>0?[e[0]+u*d,e[1]+_*d]:[e[0],e[1]],s=p>0?[e[0]+m*p,e[1]+g*p]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]+u*d,e[1]+_*d],s=[e[0]+m*p,e[1]+g*p];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(d,p,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}d>0&&n.push([t[o][0]+u*d,t[o][1]+_*d]),p>0&&n.push([t[o][0]+m*p,t[o][1]+g*p]),d>0||p>0||n.push([t[o][0],t[o][1]])}return n.length>=3?n:null}function Ql(t,e=!0){if(!t.length)return"";let i=`M ${t[0][0]} ${t[0][1]}`;for(let e=1;et?.id===e),r=hi(a);if(!r||r.length<3)return null;const l=Vl(s,n),c=[];for(const i of t||[]){if(!i||i.id===e)continue;const t=hi(i);if(t)for(const e of Cs(r,t,l))c.push([e[0],e[1]],[e[2],e[3]])}for(const t of i||[])c.push([t[0],t[1]],[t[2],t[3]]);for(const t of o||[]){const e=xl(t,n);e&&c.push(e[0],e[1])}const h=[],d=[];for(let t=0;tl)continue;const a=((t[0]-e[0])*(i[0]-e[0])+(t[1]-e[1])*(i[1]-e[1]))/(s*s);a<=n||a>=1-n||(o.some(t=>Math.abs(t-a)*s<=2*l)||o.push(a))}o.sort((t,e)=>t-e);for(const s of o)h.push([e[0]+(i[0]-e[0])*s,e[1]+(i[1]-e[1])*s]),d.push(t)}return{poly:h,parent:d,orig:r}}function ic(t,e,i,s){const n=e.poly.length,o=new Array(n).fill(0);if(!t?.length)return o;const a=new Set,r=[];for(let l=0;l0?(o[l]=_l(c.cm),a.add(c.key)):r.push(l)}if(!r.length)return o;const l=s>0?s:1,c=Math.max(.5*i,1e-9)*l,h=Sl(t,l).filter(t=>t.w.cm>0);for(let t=r.length-1;t>=0;t--){const i=r[t],s=e.poly[i],a=e.poly[(i+1)%n],d=Ml(s,a);let p=null;for(const t of h){const e=xl(t.w,l);if(!e||!Cl(Ml(e[0],e[1]),d))continue;if(mc(s[0],s[1],e[0][0],e[0][1],e[1][0],e[1][1])>c||mc(a[0],a[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;const i=Math.hypot(a[0]-s[0],a[1]-s[1]),n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]),o=Math.max(0,n-i);(!p||oc||mc(n[0],n[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1])-_)}else{if(mc(t.x,t.y,s[0],s[1],n[0],n[1])>c)continue;o=Math.hypot(t.x-d,t.y-p)}(!u||i&&!u.exact||i===u.exact&&o0?i:1,o=(t||[]).filter(t=>t&&!t.open&&null!==t.kind&&Number.isFinite(t.half)&&t.half>0&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&[t.a[0],t.a[1],t.b[0],t.b[1]].every(Number.isFinite)&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>s).sort((t,e)=>t.key.localeCompare(e.key)||t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.b[0]-e.b[0]||t.b[1]-e.b[1]||t.half-e.half),a=new Map;for(const t of o){const e=a.get(t.key);e?t.half>e.half&&a.set(t.key,{...e,half:t.half}):a.set(t.key,t)}const r=[...a.values()].flatMap(t=>[{point:[t.a[0],t.a[1]],other:t.b,halfDepth:t.half,kind:t.kind,key:t.key},{point:[t.b[0],t.b[1]],other:t.a,halfDepth:t.half,kind:t.kind,key:t.key}]).sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]||t.other[0]-e.other[0]||t.other[1]-e.other[1]||t.halfDepth-e.halfDepth),l=new Map;for(const t of r){const[e,i]=sc(t.point,s),n=nc(e,i),o=l.get(n)||[];o.push(t),l.set(n,o)}const c=[],h=new Map;for(const t of r){const e=oc(h,t.point,s).filter(e=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])<=s).sort((e,i)=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])-Math.hypot(i.point[0]-t.point[0],i.point[1]-t.point[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1]);let i=e[0];if(!i){i={point:[...t.point],rays:[]},c.push(i);const[e,n]=sc(i.point,s),o=nc(e,n),a=h.get(o)||[];a.push(i),h.set(o,a)}const n=t.other[0]-t.point[0],o=t.other[1]-t.point[1],a=Math.hypot(n,o);if(!(a>s))continue;const r=[n/a,o/a];let l=Math.atan2(r[1],r[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:r,halfDepth:t.halfDepth,length:a,angle:l})}const d=[],p=t=>{const e=1e-9*Math.max(1,n),i=t.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);return i.filter((t,s)=>!i.some((i,n)=>n!==s&&i.halfDepth>=t.halfDepth-e&&i.length>=t.length-e&&(i.halfDepth>t.halfDepth+e||i.length>t.length+e||nt.length-e.length||t.halfDepth-e.halfDepth).map(t=>({...t}))};for(const t of c){const e=t.rays.sort((t,e)=>t.angle-e.angle||t.length-e.length||t.halfDepth-e.halfDepth),i=[];for(const t of e){const e=i[i.length-1];e&&Math.abs(t.angle-e.angle)<=1e-9?e.supports.push({halfDepth:t.halfDepth,length:t.length}):i.push({u:[...t.u],angle:t.angle,supports:[{halfDepth:t.halfDepth,length:t.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const t=i.pop();i[0].supports.push(...t.supports)}if(i.length<3)continue;const n=i.map(e=>{const i=p(e.supports),n=new Set,o=[];for(const a of i){const i=[t.point[0]+e.u[0]*a.length,t.point[1]+e.u[1]*a.length];for(const e of oc(l,i,s)){if("shared"!==e.kind||Math.hypot(e.point[0]-i[0],e.point[1]-i[1])>s)continue;const a=e.other[0]-e.point[0],r=e.other[1]-e.point[1],l=Math.hypot(a,r);if(!(l>s))continue;const c=a/l,h=r/l;if(Math.hypot(e.other[0]-t.point[0],e.other[1]-t.point[1])<=s)continue;const d=`${e.key}|${e.point[0]}|${e.point[1]}|${e.other[0]}|${e.other[1]}|${e.halfDepth}`;n.has(d)||(n.add(d),o.push({start:[e.point[0],e.point[1]],u:[c,h],length:l,halfDepth:e.halfDepth}))}}return o.sort((t,e)=>t.start[0]-e.start[0]||t.start[1]-e.start[1]||t.u[0]-e.u[0]||t.u[1]-e.u[1]||t.length-e.length||t.halfDepth-e.halfDepth),{u:[...e.u],halfDepth:Math.max(...i.map(t=>t.halfDepth)),length:Math.max(...i.map(t=>t.length)),supports:i,continuations:o}}).filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);if(n.length<3)continue;const o=Math.max(...n.map(t=>t.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...t.point],rays:n,halfDepth:o,limit:1.25*o})}d.sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]);const u=new Map;for(const t of d){const[e,i]=sc(t.point,s),n=nc(e,i),o=u.get(n)||[];o.push(t),u.set(n,o)}return{epsilon:s,coordinateScale:n,nodes:d,index:u}}function rc(t){const e={fans:[],supports:[]};if(!t?.nodes?.length)return e;const i=Math.max(t.epsilon,1e-9)**2;for(const s of t.nodes){const t=s.rays.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0).map(t=>({...t,thickLength:Math.max(...t.supports.filter(e=>e.halfDepth>=t.halfDepth-1e-12).map(t=>t.length),0),angle:(()=>{const e=Math.atan2(t.u[1],t.u[0]);return e<0?e+2*Math.PI:e})()})).sort((t,e)=>t.angle-e.angle);if(t.length<2)continue;const n=s.point;for(const i of t)for(const t of i.supports){if(!(t.halfDepth>0&&t.length>0))continue;const s=-i.u[1]*t.halfDepth,o=i.u[0]*t.halfDepth,a=[n[0]+i.u[0]*t.length,n[1]+i.u[1]*t.length];e.supports.push([[n[0]+s,n[1]+o],[a[0]+s,a[1]+o],[a[0]-s,a[1]-o],[n[0]-s,n[1]-o]])}for(let s=0;s{const t=a.angle-o.angle;return t>0?t:t+2*Math.PI})();if(r<1e-9)continue;const l=r>Math.PI+1e-9,c=4*Math.max(o.halfDepth,a.halfDepth),h=[n[0]-o.u[1]*o.halfDepth,n[1]+o.u[0]*o.halfDepth],d=[n[0]+a.u[1]*a.halfDepth,n[1]-a.u[0]*a.halfDepth],p=o.u[0]*a.u[1]-o.u[1]*a.u[0],u=t=>{let e=Math.atan2(t[1]-n[1],t[0]-n[0])-o.angle;for(;e<0;)e+=2*Math.PI;return e<=r+1e-9};let _=null;if(Math.abs(p)>1e-9){const t=((d[0]-h[0])*a.u[1]-(d[1]-h[1])*a.u[0])/p,e=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/p,i=[h[0]+o.u[0]*t,h[1]+o.u[1]*t];(l?t<=1e-9&&e<=1e-9:t>1e-9&&t<=o.thickLength&&e<=a.thickLength)&&Math.hypot(i[0]-n[0],i[1]-n[1])<=c&&u(i)&&(_=i)}const m=t=>{Math.abs(Kl(t))>i&&e.fans.push(t)};if(_){const t=1.5*Math.max(o.halfDepth,a.halfDepth);m(cl([n[0],n[1]],h,_,d,t)??[[n[0],n[1]],h,_,d]);continue}if(l){m([[n[0],n[1]],h,d]);continue}const g=(t,e)=>Math.min(e,Math.sqrt(Math.max(c**2-t**2,0)),2*Math.max(o.halfDepth,a.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+a.u[0]*g(a.halfDepth,a.thickLength),d[1]+a.u[1]*g(a.halfDepth,a.thickLength)];m([[n[0],n[1]],h,f,v,d])}}return e}function lc(t,e){return!t||!Array.isArray(e)||e.length<2||!e.slice(0,2).every(Number.isFinite)?null:oc(t.index,e,t.epsilon).filter(i=>Math.hypot(i.point[0]-e[0],i.point[1]-e[1])<=t.epsilon).sort((t,i)=>Math.hypot(t.point[0]-e[0],t.point[1]-e[1])-Math.hypot(i.point[0]-e[0],i.point[1]-e[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1])[0]||null}function cc(t,e,i,s,n,o,a){return ac(dc(t,e,i,s,n,o,a),4*Vl(s,a),a)}function hc(t,e,i,s,n,o,a,r=1){const l=ec(t,e,s,n,r,i);if(!l)return null;const c=function(t,e,i){const s=(t||[]).find(t=>t?.id===e),n=hi(s);if(!n)return[];const o=[];for(const s of t||[]){if(!s||s.id===e)continue;const t=hi(s);if(t)for(const e of Cs(n,t,i))o.push(e)}return o}(t,e,Vl(n,r)),h=function(t,e,i,s,n){const o=Vl(s,n),a=[];for(let r=0;rmc(h,d,t[0],t[1],t[2],t[3])<=o);a.push(p?"shared":"outer")}return a}(l.poly,c,s,n,r),d=ic(i,l,n,r),p=d.map((t,e)=>h[e]&&t>0?gl(t,o,a)/2:0);return{...l,kinds:h,cms:d,offsets:p}}function dc(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(c)for(let t=0;t0&&(r=Fl(r,t.a,t.b,t.cm,s,a));return r}function uc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=dc(t,e,i,s,n,o,a),l=new Map;for(const t of r){if(t.open||!t.kind||!t.roomId)continue;const e=l.get(t.key)||new Set;e.add(t.roomId),l.set(t.key,e)}const c=t=>{const e=[...l.get(t)||[]].sort();return 1!==e.length&&2!==e.length?`ambiguous:${t}`:`${1===e.length?"outer":"shared"}:${e.join("|")}`},h=[],d=new Set;for(const t of r)!t.open&&t.cm>0&&!d.has(t.key)&&(d.add(t.key),h.push({...t,ownerSignature:c(t.key)}));const p=[];for(const r of t||[]){if(!r?.id)continue;const l=hc(t,r.id,e,i,s,n,o,a);if(l)for(let t=0;t0)||null===l.kinds[i]){t++;continue}const o=c(kl(l.poly[i],l.poly[(i+1)%l.poly.length],s,a));let r=t;for(;r+10&&p.push({a:[d[0],d[1]],b:[u[0],u[1]],key:kl(d,u,s,a),cm:n,len:_,ownerSignature:o}),t=r+1}}}p.sort((t,e)=>e.len-t.len||t.key.localeCompare(e.key));const u=[],_=new Set,m=new Set,g=4*Vl(s,a);for(const t of p){const e=h.filter(e=>!m.has(e.key)&&e.cm===t.cm&&e.ownerSignature===t.ownerSignature&&Cl(Ml(e.a,e.b),Ml(t.a,t.b))&&mc(e.a[0],e.a[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g&&mc(e.b[0],e.b[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g);if(e.length){for(const t of e)m.add(t.key);_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)))}}for(const t of h)m.has(t.key)||_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)));return u}function _c(t,e,i,s,n,o,a,r=1){const l=Vl(n,r),c=(s[0]+s[2])/2,h=(s[1]+s[3])/2,d=Ml([s[0],s[1]],[s[2],s[3]]);let p=null;for(const s of dc(t,e,i,n,o,a,r)){if(!Cl(Ml(s.a,s.b),d))continue;const t=mc(c,h,s.a[0],s.a[1],s.b[0],s.b[1]);t>4*l||(!p||t[t[0],t[1]]),o=Math.abs(Kl(n));n.length>=3&&o>i&&(e=n,i=o)}return e}function fc(t,e,i,s,n,o,a,r=1,l,c){const h=(t||[]).find(t=>t?.id===e),d=hi(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(t=>[t[0],t[1]]);const p=hc(t,e,i,s,n,o,a,r);if(!p||!p.offsets.some(t=>t>0))return d.map(t=>[t[0],t[1]]);const u=c||cc(t,i,s,n,o,a,r),_=Zl(p.poly,p.offsets,u);if(!_)return d.map(t=>[t[0],t[1]]);if(!u.nodes.length)return _;const m=void 0===l?Rc(t,i,s,[],n,o,a,r):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const t=gc(oi(vc(p.poly),g));if(t)return t}catch{}return function(t,e){try{return gc(ni(vc(t),vc(e)))}catch{return null}}(_,p.poly)||d.map(t=>[t[0],t[1]])}function vc(t){const e=t.map(t=>[t[0],t[1]]);return e.push([t[0][0],t[0][1]]),[e]}function yc(t){return!(!Array.isArray(t)||!t.length)&&t.every(t=>Array.isArray(t)&&t.length&&t.every(t=>Array.isArray(t)&&t.length>=4&&t.every(t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])))&&Math.abs(Ti(t[0]))>1e-9)}function bc(t,e,i,s){const n=s?new Set(s):null;let o=null;for(let s=0;se.epsilon))continue;const l=Sc([[t.point[0]+r[0]*s.halfDepth,t.point[1]+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n+r[0]*s.halfDepth,t.point[1]+a.u[1]*n+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n-r[0]*s.halfDepth,t.point[1]+a.u[1]*n-r[1]*s.halfDepth],[t.point[0]-r[0]*s.halfDepth,t.point[1]-r[1]*s.halfDepth]],e.coordinateScale);if(!l)continue;const c=vc(l);o=o?si(o,c):c}}return o}function wc(t,e,i){let s=null;for(const n of t.rays)for(const t of n.continuations){const n=[-t.u[1],t.u[0]],o=[t.start[0]+t.u[0]*t.length,t.start[1]+t.u[1]*t.length],a=Sc([[t.start[0]+n[0]*t.halfDepth,t.start[1]+n[1]*t.halfDepth],[o[0]+n[0]*t.halfDepth,o[1]+n[1]*t.halfDepth],[o[0]-n[0]*t.halfDepth,o[1]-n[1]*t.halfDepth],[t.start[0]-n[0]*t.halfDepth,t.start[1]-n[1]*t.halfDepth]],e.coordinateScale);if(!a)continue;const r=ni(vc(a),i);Array.isArray(r)&&0!==r.length&&(s=s?si(s,r):r)}return s}function kc(t,e,i=2*(4*t.halfDepth+2*e.epsilon)){const s=function(t,e=hl){const i=new Set,s=Number.isFinite(e)&&e>=0?e:hl;for(let e=0;et-e)}(t);return s.length?bc(t,e,i,s):null}function xc(t,e,i,s,n){const o=function(t){let e=null;for(const i of t){const t=vc(i);try{e=e?si(e,t):t}catch{}}return e}(function(t,e,i=!1){if(!t)return[];const s=[];for(const n of t.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-a.u[1],a.u[0]],p=[-r.u[1],r.u[0]],u=[n.point[0]+d[0]*a.halfDepth,n.point[1]+d[1]*a.halfDepth],_=[n.point[0]-p[0]*r.halfDepth,n.point[1]-p[1]*r.halfDepth],m=Xl(u,a.u,_,r.u);if(!m)continue;const g=Math.hypot(m[0]-n.point[0],m[1]-n.point[1]);if(!Number.isFinite(g)||g<=n.limit)continue;const f=e?Math.sqrt(Math.max(0,n.limit*n.limit-a.halfDepth*a.halfDepth)):0,v=e?Math.sqrt(Math.max(0,n.limit*n.limit-r.halfDepth*r.halfDepth)):0,y=Sc([[u[0]+a.u[0]*f,u[1]+a.u[1]*f],[_[0]+r.u[0]*v,_[1]+r.u[1]*v],m],t.coordinateScale);if(y&&s.push(y),i){const e=m[0]-n.point[0],i=m[1]-n.point[1],o=Math.hypot(e,i),a=g-n.limit;if(o>t.epsilon&&a>t.epsilon){const r=Math.min(Math.max(8*t.epsilon,.05*n.halfDepth),.25*a),l=e/o,c=i/o,h=-c,d=l,p=Sc([[m[0]-l*r+h*r,m[1]-c*r+d*r],[m[0]-l*r-h*r,m[1]-c*r-d*r],[m[0]+l*r,m[1]+c*r]],t.coordinateScale);p&&s.push(p)}}}return s}({...e,nodes:[t]},i,s));return o&&n?oi(o,n):o}function $c(t,e,i,s){if(!t||!e.nodes.length)return t;let n=null;try{n=function(t){let e=null;for(const i of t.nodes){const s=kc(i,t);s&&(e=e?si(e,s):s)}return e}(e)}catch{return t}let o=t;for(const t of e.nodes){const a=4*t.halfDepth+2*e.epsilon,r=2*a,l=[[t.point[0]-a,t.point[1]-a],[t.point[0]+a,t.point[1]-a],[t.point[0]+a,t.point[1]+a],[t.point[0]-a,t.point[1]+a]];try{let a=o;const c=xc(t,e,!1,!0,n);c&&(a=oi(a,c));let h=bc(t,e,r);const d=xc(t,e,!0,!0,n);d&&(h=oi(h,d)),n&&(h=si(h,n));const p=.02*Math.min(...t.rays.map(t=>t.halfDepth));if(h=si(h,vc([[t.point[0]-p,t.point[1]-p],[t.point[0]+p,t.point[1]-p],[t.point[0]+p,t.point[1]+p],[t.point[0]-p,t.point[1]+p]])),!h)continue;let u=ni(h,vc(l));s?u=ni(u,s):i&&(u=ni(u,i));const _=vc(l),m=oi(a,_),g=i?oi(ni(a,_),i):null,f=wc(t,e,_);o=si(m,...g?[g]:[],...f?[f]:[],u)}catch{}}if(n)try{let t=n;s?t=ni(t,s):i&&(t=ni(t,i)),o=si(o,t)}catch{}return o}function Sc(t,e=1){if(!Array.isArray(t)||t.length<3)return null;const i=Number.isFinite(e)&&e>0?e:1,s=1e-12*Math.max(1,i),n=[];for(const e of t){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),i=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(i))return null;const o=Math.round(t/s)*s,a=Math.round(i/s)*s;if(!Number.isFinite(o)||!Number.isFinite(a))return null;n.push([Object.is(o,-0)?0:o,Object.is(a,-0)?0:a])}return Math.abs(Kl(n))>s*s?n:null}function Mc(t,e,i,s){if(mc(t[0],t[1],e[0],e[1],i[0],i[1])>s)return!1;const n=i[0]-e[0],o=i[1]-e[1],a=(t[0]-e[0])*n+(t[1]-e[1])*o,r=n*n+o*o,l=s*Math.sqrt(r);return a>=-l&&a<=r+l}function Cc(t,e,i){const s=[],n=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),p=[0,1];for(const t of e)for(const e of[t.a,t.b]){if(!Mc(e,a,r,i))continue;const t=((e[0]-a[0])*l+(e[1]-a[1])*c)/h;t>d&&t<1-d&&p.push(t)}p.sort((t,e)=>t-e);const u=p.filter((t,e)=>0===e||Math.abs(t-p[e-1])>d);for(let t=0;t=3&&n.length===s.length?{poly:s,offsets:n}:null}function Dc(t,e,i,s,n,o,a,r){const l=(t||[]).map(hi).filter(t=>!!t&&t.length>=3);if(!l.length)return null;let c=si(vc(l[0]));for(let t=1;t"outer"===t.kind&&t.half>0),p=4*Vl(s,a),u=r||ac(h,p,a);let _=null;for(const t of function(t){const e=[];for(const i of Array.isArray(t)?t:[])if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,-1).map(t=>[t[0],t[1]]);i.length>=3&&e.push(i)}return e}(c)){const e=Cc(t,d,p);if(!e||!e.offsets.some(t=>t>0))continue;const i=Fc(e.poly,e.offsets,u),s=Zl(e.poly,e.offsets,u);if(!i||!s)continue;const n=oi(vc(i),vc(s));_=_?si(_,n):n}return{centre:c,shell:_||[]}}function Pc(t,e,i,s,n,o,a=1){try{const r=Dc(t,e,i,s,n,o,a,cc(t,e,i,s,n,o,a));if(!r)return[];return r.shell?.length?si(r.centre,r.shell):r.centre}catch{return null}}function Tc(t){if(!t)return"";let e="";for(const i of t)if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,t.length-1);i.length<3||(e+=(e?" ":"")+Ql(i.map(t=>[t[0],t[1]])))}return e}function Rc(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return{status:"not-applicable",geom:[],components:[],roomGeom:[],paperGeom:[],depthUnits:0,openingIndex:null,multiWallNodes:null,degradedExtraCount:0};const h=[],d=cc(t,e,i,n,o,a,r);let p=0;for(const s of t||[]){if(!s?.id)continue;const l=hc(t,s.id,e,i,n,o,a,r);if(!l||l.poly.length<3||!l.offsets.some(t=>t>0))continue;for(const t of l.offsets)t>0&&(p=Math.max(p,2*t));const c=Fc(l.poly,l.offsets,d),u=Zl(l.poly,l.offsets,d);c&&h.push({outset:c,inset:u})}for(const t of l){const e=t.map(t=>t[0]),i=t.map(t=>t[1]);if(e.length){const s=Math.min(Math.max(...e)-Math.min(...e),Math.max(...i)-Math.min(...i)),n=Math.min(...t.map((e,i)=>{const s=t[(i+1)%t.length];return Math.hypot(s[0]-e[0],s[1]-e[1])}));p=Math.max(p,t.length>16?s:n)}}const u=function(t,e,i,s,n,o,a,r){if(!e?.length||!i?.length)return[];const l=4*Vl(s,a),c=new Map;for(const r of dc(t,e,i,s,n,o,a))!r.open&&r.half>0&&!c.has(r.key)&&c.set(r.key,r);const h=[...c.values()];if(h.length<2)return[];const d=r||ac(h,l),p=[];for(const t of i)for(const e of[[t[0],t[1]],[t[2],t[3]]])p.some(t=>Math.hypot(t[0]-e[0],t[1]-e[1])<=l)||p.push(e);const u=[],_=(t,e)=>{let i=0,s=0;if(Math.hypot(t.a[0]-e[0],t.a[1]-e[1])<=l)i=t.b[0]-t.a[0],s=t.b[1]-t.a[1];else{if(!(Math.hypot(t.b[0]-e[0],t.b[1]-e[1])<=l))return null;i=t.a[0]-t.b[0],s=t.a[1]-t.b[1]}const n=Math.hypot(i,s);return n>l?[i/n,s/n]:null};for(const t of p){const e=h.map(e=>({iv:e,u:_(e,t)})).filter(t=>!!t.u);for(let i=0;i0?[t.slice(),p,m,_]:[t.slice(),_,m,p];else{if(!f)continue;{const e=[-n.u[1],n.u[0]],i=[-o.u[1],o.u[0]],s=a<0?1:-1,r=[t[0]+e[0]*n.iv.half*s,t[1]+e[1]*n.iv.half*s],l=[t[0]-i[0]*o.iv.half*s,t[1]-i[1]*o.iv.half*s];y=a>0?[t.slice(),r,l]:[t.slice(),l,r]}}Math.abs(Kl(y))>l*l&&u.push(y)}}return u}(t,e,i,n,o,a,r,d),_=s.length?Ec(t,e,i,n,o,a,r):null;let m="exterior";try{const v=Dc(t,e,i,n,o,a,r,d);m="paper";const y=v?v.shell?.length?si(v.centre,v.shell):v.centre:[],b=t=>{const e=vc(t.outset);return t.inset?oi(e,vc(t.inset)):e};m="room-rings";let w=null;for(const t of h)try{const e=b(t);w=w?si(w,e):e}catch{}if(m="edge-bodies",v)for(const s of zc(t,e,i,n,o,a,r))try{const t=ni(vc(s.quad),v.centre);w=w?si(w,t):t}catch{}m="junctions",w=function(t,e,i=1,s=si){let n=t;for(const t of e||[]){const e=Sc(t,i);if(e)try{const t=vc(e);n=n?s(n,t):t}catch{}}return n}(w,u,r),m="facade-clip",w&&v&&(w=ni(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const t=si(w,v.shell);if(!yc(t))throw new Error("invalid shell union");w=t}catch{if(!yc(w)||!yc(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const t=t=>t.rays.some(t=>t.supports.some(t=>t.length<2*t.halfDepth)),e=d.nodes.filter(t);if(e.length){w=$c(w,{...d,nodes:e},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const s=rc(d),l=function(t,e,i,s,n,o,a,r){try{const l=Dc(t,e,i,s,n,o,a,{epsilon:r.epsilon,coordinateScale:r.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?si(l.centre,l.shell):l.centre:null}catch{return null}}(t,e,i,n,o,a,r,d);for(const t of s.fans)try{let e=[vc(t)];if(l&&(e=ni(e,l)),!e?.length)continue;w=w?si(w,e):e}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(t=>{if(!Array.isArray(t)||!t.length)return t;const[e,...i]=t;return Math.abs(Kl(e||[]))<=f?null:[e,...i.filter(t=>Math.abs(Kl(t||[]))>f)]}).filter(t=>!!t):g}const $=w||[];m="openings";for(const t of s){if(!(t.length>0))continue;const e=Lc(_,t,!0);if(!e.negative&&!e.positive)continue;const i=t.angle*Math.PI/180,s=Math.cos(i),o=Math.sin(i),a=-o,l=s,c=t.length/2,h=1.25*Math.max(p,n*r),d=[[t.x-s*c-a*h,t.y-o*c-l*h],[t.x+s*c-a*h,t.y+o*c-l*h],[t.x+s*c+a*h,t.y+o*c+l*h],[t.x-s*c+a*h,t.y-o*c+l*h]];w&&(w=oi(w,vc(d)));for(const t of k)t.geom=oi(t.geom,vc(d))}m="extras";const S=[];let M=0;const C=c.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){M++;continue}const i=[vc(e)];try{const e=C(w,i,t);if(!yc(e))throw new Error("invalid extra union");w=e}catch{M++,yc(i)&&S.push({id:`extra-${t}`,geom:i})}}S.push(...k),S.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const D=w||[];return{status:M||x?"degraded-extra":"ok",geom:D,components:[...yc(D)?[{id:"primary",geom:D}]:[],...S.map((t,e)=>({...t,id:`isolated-${e}`}))],roomGeom:$,paperGeom:y,depthUnits:p,openingIndex:_,multiWallNodes:d,degradedExtraCount:M+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],depthUnits:p,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ic(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return null;return Ac(Rc(t,e,i,s,n,o,a,r,l,c))}function Ac(t){if("failed-core"===t.status||"not-applicable"===t.status)return null;const e=t.components.map(t=>({id:t.id,d:Tc(t.geom),fillRule:"evenodd"})).filter(t=>!!t.d),i=e[0]?.d||"",s=Tc(t.paperGeom);return e.length?{status:t.status,d:i,paths:e,components:t.components,roomGeom:t.roomGeom,multiWallNodes:t.multiWallNodes,paperD:s,depthUnits:t.depthUnits,fillRule:"evenodd"}:null}function zc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=new Set,l=[];for(const c of t||[]){if(!c?.id)continue;const h=hc(t,c.id,e,i,s,n,o,a);if(!h)continue;const d=h.poly;for(let t=0;t0))continue;const u=kl(e,i,s,a);if(r.has(u))continue;r.add(u);const _=gl(p,n,o),[m,g]=Yl(d,t),f=-m,v=-g,y=_/2,b=[[e[0]+f*y,e[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[e[0]+m*y,e[1]+g*y]];l.push({key:u,kind:c,cm:p,quad:b,a:[e[0],e[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Fc(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);tc(t),e.slice().reverse();const n=[];for(let o=0;o0||l>0)){n.push([t[o][0],t[o][1]]);continue}if(r>0!=l>0){const e=t[o],i=r>0?[e[0]-c*r,e[1]-h*r]:[e[0],e[1]],s=l>0?[e[0]-d*l,e[1]-p*l]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]-c*r,e[1]-h*r],s=[e[0]-d*l,e[1]-p*l];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(r,l,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}r>0&&n.push([t[o][0]-c*r,t[o][1]-h*r]),l>0&&n.push([t[o][0]-d*l,t[o][1]-p*l])}return n.length>=3?n:null}function Ec(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(!c)continue;const h=Math.abs(Ti(c.poly));for(let t=0;t[Math.max(e,t.x0),Math.min(i,t.x1)]).filter(t=>t[1]-t[0]>s).sort((t,e)=>t[0]-e[0]||t[1]-e[1]);if(!n.length)return{coverage:0,full:!1};let o=n[0][0],a=n[0][1],r=0,l=o<=e+s;for(let t=1;t=i-s,{coverage:r,full:l}}function Oc(t,e){return Number(e.full)-Number(t.full)||t.faceDistance-e.faceDistance||t.area-e.area||t.roomId.localeCompare(e.roomId)}function Lc(t,e,i=!1){const s=Number(e?.x),n=Number(e?.y),o=Number(e?.angle),a=Number(e?.length);if(!([s,n,o,a].every(Number.isFinite)&&a>0))return{negative:null,positive:null};const r=o*Math.PI/180,l=Math.cos(r),c=Math.sin(r),h=-c,d=l,p=a/2,u=Math.max(1e-9,t.adjacencyEps),_=new Map;let m=0;for(const e of t.edges){if(i&&!(e.half>0))continue;if(!Rl(e.a,e.b,o))continue;const[t,a]=bl(e.a,e.b);if(Math.abs((s-e.a[0])*a-(n-e.a[1])*t)>u)continue;const r=(e.a[0]-s)*l+(e.a[1]-n)*c,g=(e.b[0]-s)*l+(e.b[1]-n)*c,f=Math.max(-p,Math.min(r,g)),v=Math.min(p,Math.max(r,g));if(v-f<=u)continue;const y=e.inward[0]*h+e.inward[1]*d>=0?1:-1,b=((e.a[0]+e.b[0])/2-s)*h+((e.a[1]+e.b[1])/2-n)*d,w=Math.abs(b+y*e.half),k=`${y}|${e.roomId}`,x={x0:f,x1:v,half:e.half,cm:e.cm,key:e.key,axis:[t,a]},$=_.get(k);$?($.pieces.push(x),$.faceDistance=Math.min($.faceDistance,w)):_.set(k,{roomId:e.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:e.area,coverage:0,full:!1})}for(const t of _.values()){const e=Nc(t.pieces,-p,p,u);t.coverage=e.coverage,t.full=e.full}const g=t=>{const e=[..._.values()].filter(e=>e.side===t&&e.coverage>u);return e.sort(Oc),e[0]||null};return{negative:g(-1),positive:g(1)}}function Hc(t,e){const i=Lc(t,e),s=[i.negative,i.positive].filter(t=>!!t);if(!s.length)return{ox:0,oy:0,cm:0,side:-1};const n=i.negative&&i.positive?-1:s[0].side,o=e.flip_v?-n:n,a=(-1===o?i.negative:i.positive)||s[0],r=[...a.pieces].sort((t,e)=>(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))-(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))||e.x1-e.x0-(t.x1-t.x0)||t.key.localeCompare(e.key))[0];if(!(r.half>0&&r.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=e.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*r.half,oy:h*o*r.half,cm:r.cm,side:o}}function Bc(t,e){const i=1e-9,s=e.filter(t=>Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&Number.isFinite(t.half)&&t.x1>t.x0&&t.half>0);if(!s.length)return"";const n=s.flatMap(t=>[t.x0,t.x1]).sort((t,e)=>t-e),o=[];for(const t of n){const e=o[o.length-1];(void 0===e||t>e+i)&&o.push(t)}const a=[];for(let t=0;t+1e+i))continue;const r=(e+n)/2,l=s.reduce((t,e)=>r>=e.x0-i&&r<=e.x1+i?Math.max(t,e.half):t,0);if(!(l>0))continue;const c=a[a.length-1];c&&e<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=n:a.push({x0:e,x1:n,half:l})}const r=[];for(const t of a){const e=r[r.length-1],s=e?.[e.length-1];s&&t.x0<=s.x1+i?(t.x0=s.x1,e.push(t)):r.push([t])}return r.map(e=>{const i=e[0],s=e[e.length-1],n=Math.min(.25*Math.min(...e.map(t=>t.half)),.75),o=-t*n,a=[];if(1===t){a.push(`M ${i.x0} ${o} L ${s.x1} ${o}`);for(let t=e.length-1;t>=0;t--){const i=e[t];a.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{a.push(`M ${s.x1} ${o} L ${i.x0} ${o}`);for(const t of e)a.push(`L ${t.x0} ${-t.half} L ${t.x1} ${-t.half}`)}return a.push("Z"),a.join(" ")}).join(" ")}function qc(t,e,i,s){if(!s)return i;const n=t.angle*Math.PI/180,o=Math.cos(n),a=Math.sin(n),r=[],l=1e-9;for(const n of i){const[i,c]=n.axis,h=o*i+a*c;if(Math.abs(h)<=l)continue;const d=t.x*i+t.y*c,p=d+h*n.x0,u=d+h*n.x1,_=Math.min(p,u),m=Math.max(p,u),g=`${n.key}|${e}`,f=s.get(g)||[];let v=[[_,m]];for(const[t,e]of f){const i=[];for(const[s,n]of v)e<=s+l||t>=n-l?i.push([s,n]):(t>s+l&&i.push([s,Math.min(n,t)]),et[0]-e[0]||t[1]-e[1]),b=[];for(const t of y){const e=b[b.length-1];e&&t[0]<=e[1]+l?e[1]=Math.max(e[1],t[1]):b.push([t[0],t[1]])}s.set(g,b)}return r}function Wc(t,e){const i=new Map;return e.map(e=>function(t,e,i){const s=Lc(t,e,!0),n=s.negative,o=s.positive;if(!n&&!o)return null;let a;if(n&&o)a=[{candidate:n,side:-1},{candidate:o,side:1}];else{const t=n||o;a=[{candidate:t,side:-1},{candidate:t,side:1}]}const r=a.map(({candidate:t,side:s})=>({candidate:t,side:s,pieces:qc(e,s,t.pieces,i)})),l=r.map(({candidate:t,side:e,pieces:i})=>({side:e,roomId:t.roomId,d:Bc(e,i)})),c=r.flatMap(({pieces:t})=>t);if(!c.length)return null;const h=Math.max(...c.map(t=>t.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(t=>t.key))].sort().join("|")}}(t,e,i))}const jc=150,Uc=1e-6;function Gc(t){return Number.isFinite(t)?Math.max(1,Math.min(jc,t)):1}function Vc(t){return((Number.isFinite(Number(t))?Number(t):0)%90+90)%90}const Kc=t=>{const e=t.map(t=>[t[0],t[1]]);return!e.length||e[0][0]===e[e.length-1][0]&&e[0][1]===e[e.length-1][1]||e.push([...e[0]]),[e]},Yc=(t,e)=>t[0]===e[0]&&t[1]===e[1];function Jc(t,e=1e-6){const i=Number.isFinite(e)&&e>0?e:Uc,s=[];for(const e of t||[]){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(n))return null;const o=Math.round(t/i)*i,a=Math.round(n/i)*i;if(!Number.isFinite(o)||!Number.isFinite(a))return null;const r=[Object.is(o,-0)?0:o,Object.is(a,-0)?0:a];s.length&&Yc(s[s.length-1],r)||s.push(r)}return s.length>1&&Yc(s[0],s[s.length-1])&&s.pop(),s.length<3||new Set(s.map(t=>`${t[0]},${t[1]}`)).size<3?null:Ti(s)>i*i?s:null}function Xc(t){const e=[];for(const i of t||[])for(const t of i||[]){const i=(t||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||e.push(`M ${i.slice(0,-1).map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`)}return e.join(" ")}function Zc(t,e,i,s,n){return Ol({a:t,b:e,halfDepth:gl(i,s,n)/2})}function Qc(t,e,i){const s=Number(e)>0?Number(e):5,n=Gc(t.cm)/s*i,o=t.center[0],a=t.center[1];if("circle"===t.shape){const t=n/2;return Array.from({length:96},(e,i)=>{const s=i/96*Math.PI*2;return[o+Math.cos(s)*t,a+Math.sin(s)*t]})}const r=n/2,l=Vc(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-r,-r],[r,-r],[r,r],[-r,r]].map(([t,e])=>[o+t*c-e*h,a+t*h+e*c])}function th(t,e,i=1e-9){if(!e.length)return[t];let s=[Kc(t)];try{for(const t of e){const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(e,n);if(!(o>i))continue;const a=e/o,r=n/o,l=-r,c=a,h=1.25*Math.max(Number(t.depth)||0,4*i),d=Math.max(2*i,1e-9*o),p=[[t.a[0]-a*d-l*h,t.a[1]-r*d-c*h],[t.b[0]+a*d-l*h,t.b[1]+r*d-c*h],[t.b[0]+a*d+l*h,t.b[1]+r*d+c*h],[t.a[0]-a*d+l*h,t.a[1]-r*d+c*h]];s=oi(s,Kc(p))}return hh(s)}catch{return[t]}}function eh(t,e){try{const i=oi([[...t.map(t=>[t[0],t[1]]),[t[0][0],t[0][1]]]],[[...e.map(t=>[t[0],t[1]]),[e[0][0],e[0][1]]]]);let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Ti(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function ih(t,e,i,s=Math.max(2e-4*i,1e-9),n=[]){const o=[],a=[],r=new Map;for(const t of n){const e=r.get(t.hostId)||[];e.push(t),r.set(t.hostId,e)}const l=[],c=[],h=[];for(const s of t.room_drafts||[])for(let t=0;t+10))continue;const r={a:s.points[t],b:s.points[t+1],halfDepth:a},c=Ol(r);c&&(o.push(r),l.push(c))}const d=[];for(const s of t.partitions||[]){const t={a:s.a,b:s.b,halfDepth:gl(s.cm,e,i)/2};if(!(t.halfDepth>0))continue;const n=Ol(t);n&&(a.push(t),c.push(n),d.push({id:s.id,body:n}))}const p=[...o,...a];for(const{segmentIndex:t,wedge:e}of Wl(p,s)){const i=t=o.length&&(d[i.at].body=s))}for(const t of d)h.push(...th(t.body,r.get(t.id)||[],s));const u=(t.wall_columns||[]).map(t=>Qc(t,e,i)),_=jl([...o,...a],s).flatMap(t=>th(t,n,s));return{drafts:l,partitions:c,columns:u,patches:_,all:[...l,...h,..._,...u]}}function sh(t){try{const e=t.map(t=>Jc(t)).filter(t=>!!t).map(t=>Kc(t));return e.length?si(e[0],...e.slice(1)):null}catch{return null}}const nh=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`;function oh(t){const e=[];for(const i of t||[]){if(lh([i])<=1e-6)continue;const t=[];for(const e of i||[]){const i=(e||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||t.push(nh(i.slice(0,-1)))}t.length&&e.push(t.join(" "))}return e}function ah(t,e,i={}){const s=sh(t.filter(t=>t.length>=3)),n=e.some(t=>!Jc(t))?null:sh(e);if(!s)return[];if(n)try{return oh(ni(s,n))}catch{}return function(t,e,i){let s=null;for(let n=0;n=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]));return e}function hh(t){const e=[];for(const i of t||[]){const t=i?.[0];t?.length>=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]))}return e}function dh(t,e){let i=!1;for(let s=0,n=e.length-1;st[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a||1e-12)+o&&(i=!i)}return i}function ph(t,e,i){return function(t,e){for(const i of e||[]){const e=i?.[0];if(!e?.length||!dh(t,e))continue;let s=!1;for(let e=1;edh(t,e))}function uh(t,e,i){if(Math.hypot(t.center[0]-e.center[0],t.center[1]-e.center[1])>i)return!1;if(Math.abs(Gc(t.cm)-Gc(e.cm))>1e-6)return!1;if(t.shape!==e.shape)return!0;if("circle"===t.shape||"circle"===e.shape)return!0;const s=Math.abs(Vc(t.angle)-Vc(e.angle));return Math.min(s,90-s)<=1e-6}const _h=2.54;function mh(t){const e="number"==typeof t?t:NaN;return!Number.isFinite(e)||e<=0||5===e?1:5/e}function gh(t,e){return t*mh(e)}function fh(t){return t?_h:1}function vh(t,e){if(!e)return String(t);const i=t/_h;return String(Math.round(1e6*i)/1e6)}const yh=1e3;function bh(t,e){const i=Number(t),s=Number.isFinite(i)&&i>0?i:1,n=s>=1?e:e*s,o=s>=1?e/s:e;return{x:(e-n)/2,y:(e-o)/2,w:n,h:o}}const wh=.01,kh=100;function xh(t,e=1e3){const i=bh(t?.plan_aspect,e),s=Number(t?.plan_scale),n=Number.isFinite(s)&&s>0?Math.min(kh,Math.max(wh,s)):1,o=Number(t?.plan_scale_x),a=Number(t?.plan_scale_y),r=Number.isFinite(o)&&o>0?Math.min(kh,Math.max(wh,o)):n,l=Number.isFinite(a)&&a>0?Math.min(kh,Math.max(wh,a)):n,c=Number(t?.plan_x),h=Number(t?.plan_y),d=Ar(t?.plan_angle);return{x:i.x+(Number.isFinite(c)?zh(c):0)*e,y:i.y+(Number.isFinite(h)?zh(h):0)*e,w:i.w*r,h:i.h*l,...d?{angle:d}:{}}}function $h(t){if(null==t.x||null==t.y)return{x:t.x,y:t.y,w:t.w,h:t.h};const e=Number(t.w)||0,i=Number(t.h)||0;return{x:e<0?t.x+e:t.x,y:i<0?t.y+i:t.y,w:Math.abs(e),h:Math.abs(i)}}function Sh(t){return t&&Array.isArray(t.spaces)?t.spaces.map(t=>{const e=yh,i=function(t){return Array.isArray(t)&&4===t.length&&t.every(t=>Number.isFinite(t))&&t[2]>1e-6&&t[3]>1e-6?t:[0,0,1,1]}(t.view_box);return{id:t.id,title:t.title,cellCm:Number.isFinite(Number(t.cell_cm))&&Number(t.cell_cm)>0?Number(t.cell_cm):5,vb:[i[0]*yh,i[1]*e,i[2]*yh,i[3]*e],bg:t.plan_url?{href:As(t.plan_url),...xh(t,yh)}:null,rooms:(t.rooms||[]).map(t=>{const i={...t,...$h(t)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*yh:void 0,y:null!=i.y?i.y*e:void 0,w:null!=i.w?i.w*yh:void 0,h:null!=i.h?i.h*e:void 0,poly:i.poly?i.poly.map(t=>[t[0]*yh,t[1]*e]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(t.wall_segments||[]).map(t=>({...t,id:String(t.id),a:[Number(t.a?.[0])*yh,Number(t.a?.[1])*e],b:[Number(t.b?.[0])*yh,Number(t.b?.[1])*e],cm:Number(t.cm)})),room_drafts:(t.room_drafts||[]).map(t=>({id:t.id,points:(t.points||[]).map(t=>[t[0]*yh,t[1]*e]),segments:(t.segments||[]).map(t=>({..."string"==typeof t.id&&t.id?{id:t.id}:{},cm:Number(t.cm)}))})),partitions:(t.partitions||[]).map(t=>({id:t.id,a:[t.a[0]*yh,t.a[1]*e],b:[t.b[0]*yh,t.b[1]*e],cm:Number(t.cm)})),wall_columns:(t.wall_columns||[]).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[t.center[0]*yh,t.center[1]*e],cm:Number(t.cm),..."circle"===t.shape?{}:{angle:Vc(t.angle)}}))}}):[]}const Mh=5e3,Ch=Mh*yh,Dh=240,Ph=yh/Dh,Th=1/Dh;function Rh(t){if(!Number.isFinite(t))return t;const e=Math.round(t*Dh/yh)*yh/Dh;return Math.abs(e-t)<=1e-9*Ph?t:e}function Ih(t){return{x:Rh(t.x),y:Rh(t.y)}}function Ah(t){return Number.isFinite(t)?Math.min(Ch,Math.max(-Ch,t)):0}function zh(t){return Number.isFinite(t)?Math.min(Mh,Math.max(-Mh,t)):0}const Fh=1/3,Eh=200;function Nh(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t){const t=Number(o[0]),a=Number(o[1]);Number.isFinite(t)&&Number.isFinite(a)&&(ts&&(s=t),a>n&&(n=a))}return e>s?null:{minX:e,minY:i,maxX:s,maxY:n}}function Oh(t){return t.poly&&t.poly.length?Nh(t.poly):null==t.x||null==t.y?null:Nh([[t.x,t.y],[t.x+(t.w||0),t.y+(t.h||0)]])}function Lh(t,e){const i=[];for(const e of t.rooms||[]){const t=Oh(e);t&&i.push(t)}if(t.bg){const e=Nh(Lr(t.bg));e&&i.push(e)}for(const t of e||[])if(Array.isArray(t)){const e=Nh([t]);e&&i.push(e)}else i.push(t);return i}const Hh=t=>{if(!t.length)return 0;const e=[...t].sort((t,e)=>t-e),i=e.length>>1;return e.length%2?e[i]:(e[i-1]+e[i])/2},Bh=t=>{let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t)o.minXs&&(s=o.maxX),o.maxY>n&&(n=o.maxY);return e>s||i>n?null:{x:e,y:i,w:s-e,h:n-i}};function qh(t,e){let{x:i,y:s,w:n,h:o}=t;n<30&&(i=i+n/2-100,n=Eh),o<30&&(s=s+o/2-100,o=Eh);const a=Math.max(n,o)*e;return{x:i-a,y:s-a,w:n+2*a,h:o+2*a}}function Wh(t,e={}){const i=e.pad??.05,s=e.k??10,n=e.minSpread??50,o=t.filter(t=>Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&Math.abs(t.minX)<=Ch&&Math.abs(t.maxX)<=Ch&&Math.abs(t.minY)<=Ch&&Math.abs(t.maxY)<=Ch);if(!o.length)return{core:null,all:null,outliers:0};const a=Bh(o);if(o.length<4){const t=qh(a,i);return{core:t,all:t,outliers:0}}const r=o.map(t=>(t.minX+t.maxX)/2),l=o.map(t=>(t.minY+t.maxY)/2),c=Hh(r),h=Hh(l),d=o.map((t,e)=>Math.max(Math.abs(r[e]-c),Math.abs(l[e]-h))),p=Math.max(((t,e)=>t.length?t[Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))))]:0)([...d].sort((t,e)=>t-e),.75),n),u=d.map(t=>t>s*p),_=u.filter(Boolean).length,m=_&&_<=o.length*Fh?o.filter((t,e)=>!u[e]):o;return{core:qh(Bh(m)||a,i),all:qh(a,i),outliers:m===o?0:_}}function jh(t,e,i=.05){const s=Wh(Lh(t,e),{pad:i});if(s.core)return s.core;const n=t.vb&&4===t.vb.length&&t.vb[2]>0&&t.vb[3]>0?t.vb:[0,0,yh,yh];return{x:n[0],y:n[1],w:n[2],h:n[3]}}function Uh(t){const e=jh(t);return{x:e.x+e.w/2,y:e.y+e.h/2}}function Gh(t){const e=[];for(const i of t.rooms||[]){const t=Oh(i);t&&e.push(t)}const i=Wh(e,{pad:0}).core,s=yh*mh(t.cellCm??5);return i?Math.max(s,Math.min(Ch,Math.max(i.w,i.h))):s}function Vh(t,e,i,s=1){const n=Number(i),o=Number.isFinite(s)&&s>0?s:1;return!Number.isFinite(n)||n<=0?t*o:t*Gh(e)*o/n}const Kh=[1,2,5,10,20,50,100,200,500,1e3];function Yh(t){if(t.poly&&t.poly.length){const e=t.poly.map(t=>t[0]),i=t.poly.map(t=>t[1]),s=Math.min(...e),n=Math.min(...i);return{x:s,y:n,w:Math.max(...e)-s,h:Math.max(...i)-n}}return{x:t.x??0,y:t.y??0,w:t.w??0,h:t.h??0}}function Jh(t,e,i,s){const n=i["rl_"+(t.id||"")];if(n&&n.s===e)return{x:n.x*yh,y:n.y*yh};const o=function(t){if(t.poly){const e=t.poly.length;return[t.poly.reduce((t,e)=>t+e[0],0)/e,t.poly.reduce((t,e)=>t+e[1],0)/e]}return[t.x+t.w/2,t.y+.1*Math.min(t.w,t.h)]}(t);return Ih({x:o[0],y:o[1]})}const Xh=["furniture","appliance","sanitary","other"],Zh=[{id:"sofa",group:"furniture",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Qh=new Map(Zh.map(t=>[t.id,t]));function td(t){return t&&Qh.get(t)||null}function ed(t){return Zh.filter(e=>e.group===t)}function id(t,e,i=Ph,s=1e3){const n=Number(e)>0?Number(e):5;return(Number(t)||0)/n*i/s}const sd=5e-4,nd=Mh;function od(t){return Number.isFinite(t)?Math.max(sd,Math.min(nd,t)):sd}const ad=t=>{const e=Math.round(1e3*t)/1e3;return Object.is(e,-0)?"0":String(e)};function rd(t,e,i){const s=td(t);if(!(s&&e>0&&i>0))return"";const n=t=>ad(t*e),o=t=>ad(t*i),a=[];for(const t of s.g)if("r"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}H${n(e+s)}V${o(i+r)}H${n(e)}Z`)}else if("l"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}L${n(s)} ${o(r)}`)}else if("e"===t[0]){const[,s,r,l,c]=t;a.push(`M${n(s-l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s+l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s-l)} ${o(r)}Z`)}else{const e=t.slice(1);if(e.length<4)continue;let i=`M${n(e[0])} ${o(e[1])}`;for(let t=2;t+1{let e=(t%360+360)%360;return e>180&&(e-=360),e};function cd(t,e,i,s,n,o=0){let a=null,r=n;for(const n of s){const[s,l,c,h]=n,d=c-s,p=h-l,u=d*d+p*p;if(!u)continue;const _=Math.sqrt(u);let m=((t-s)*d+(e-l)*p)/u;m=Math.max(0,Math.min(1,m));let g=s+m*d,f=l+m*p;const v=Math.hypot(t-g,e-f);if(!(v0){const t=Math.round(m*_/o)*o;g=s+t/_*d,f=l+t/_*p}a={cx:g+y*(i/2),cy:f+b*(i/2),angle:ld(180*Math.atan2(-y,b)/Math.PI),dist:v}}return a}function hd(t,e,i){const s=i>0?i:1;return{a:[t[0]/s,t[1]/s],b:[e[0]/s,e[1]/s]}}function dd(t,e){const i=e>0?e:1;return[t.a[0]*i,t.a[1]*i,t.b[0]*i,t.b[1]*i]}function pd(t){return Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1]))}function ud(t){if(!Array.isArray(t))return[];const e=[];for(const i of t){if(!i||"object"!=typeof i)continue;const t=i;if(!pd(t.a)||!pd(t.b))continue;const s=[Number(t.a[0]),Number(t.a[1])],n=[Number(t.b[0]),Number(t.b[1])];Math.hypot(n[0]-s[0],n[1]-s[1])<.001||e.push({a:s,b:n})}return e}function _d(t,e,i,s,n=!0){const o=(t||[]).filter(t=>t?.id),a=ud(e);if(a.length)return function(t,e,i,s){const n=ud(t);if(!n.length)return[];const o=function(t,e){const i=[],s=(t||[]).filter(t=>t?.id);for(let t=0;t4*s||o>4*s)continue;const a=(t[0]-n)*p+(t[1]-l)*u,c=(t[2]-n)*p+(t[3]-l)*u,h=Math.max(0,Math.min(a,c)),m=Math.min(d,Math.max(a,c));if(m-ht.lo-e.lo||t.hi-e.hi);const i=[];for(const t of e){const e=i[i.length-1];e&&t.lo<=e.hi+r?e.hi=Math.max(e.hi,t.hi):i.push({...t})}for(const e of i){const i=[n+p*e.lo,l+u*e.lo],s=[n+p*e.hi,l+u*e.hi];Math.hypot(s[0]-i[0],s[1]-i[1])i.pair===t&&Math.abs(i.ux*a-i.uy*o)<=1e-6&&Math.abs((e[0]-i.origin[0])*i.uy-(e[1]-i.origin[1])*i.ux)<=c&&Math.abs((e[2]-i.origin[0])*i.uy-(e[3]-i.origin[1])*i.ux)<=c);h||(h={pair:t,origin:[e[0],e[1]],ux:o,uy:a,ranges:[]},l.push(h));const d=(e[0]-h.origin[0])*h.ux+(e[1]-h.origin[1])*h.uy,p=(e[2]-h.origin[0])*h.ux+(e[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,p),hi:Math.max(d,p)})}const h=[];for(const t of l){t.ranges.sort((t,e)=>t.lo-e.lo||t.hi-e.hi);const e=[];for(const i of t.ranges){const t=e[e.length-1];t&&i.lo<=t.hi+r?t.hi=Math.max(t.hi,i.hi):e.push({...i})}for(const s of e){const e=[t.origin[0]+t.ux*s.lo,t.origin[1]+t.uy*s.lo],n=[t.origin[0]+t.ux*s.hi,t.origin[1]+t.uy*s.hi];Math.hypot(n[0]-e[0],n[1]-e[1])>=r&&h.push(hd(e,n,i))}}return h}(a,t,i,s).map(t=>dd(t,i));if(!n)return[];const r=[],l=(t,e)=>(t.open_to||[]).includes(e.id)||(e.open_to||[]).includes(t.id);for(let t=0;t{const e=fd.get(t);if(!e)return;const i=Date.now();if("hidden"===t.visibilityState){e.hiddenAt||(e.hiddenAt=i);const t={kind:"hidden",token:e.token,at:i,hiddenFor:0,long:!1};for(const i of[...e.subscribers])i(t);return}const s=e.hiddenAt?Math.max(0,i-e.hiddenAt):0;e.hiddenAt=0,e.token++;const n={kind:"visible",token:e.token,at:i,hiddenFor:s,long:s>=md};for(const t of[...e.subscribers])t(n)},onPageShow:e=>{const i=fd.get(t);if(!i)return;const s=Date.now();i.token++;const n={kind:"pageshow",token:i.token,at:s,hiddenFor:0,long:!!e.persisted,persisted:!!e.persisted};for(const t of[...i.subscribers])t(n)}},fd.set(t,i),t.addEventListener("visibilitychange",i.onVisibility),t.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(e),()=>{const i=fd.get(t);i&&(i.subscribers.delete(e),i.subscribers.size||(t.removeEventListener("visibilitychange",i.onVisibility),t.defaultView?.removeEventListener("pageshow",i.onPageShow),fd.delete(t)))}}const yd={now:()=>Date.now(),setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),requestAnimationFrame:t=>window.requestAnimationFrame(t),cancelAnimationFrame:t=>window.cancelAnimationFrame(t)};class bd{constructor(t,e=yd){this.onChange=t,this.clock=e,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(t=>({...t,...t.stage?{stage:[...t.stage]}:{}}))}note(t,e={}){this.record(t,void 0,e)}record(t,e,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:t,state:this._state,...e?{reason:e}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(t){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&t&&t!==this._frameFingerprint&&(this._frameFingerprint=t,this.record("frame-refreshed"))}visibility(t){return"hidden"===t.kind?(this.record("visibility-hidden"),this._token):t.long||"visible"!==t.kind&&"pageshow"!==t.kind?this.beginCandidate("pageshow"===t.kind?"pageshow":"long-resume"):(this.record("pageshow"===t.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(t,e="plan"){return this._token++,this._recoveryReason=e,this._hasCompleteFrame?(this._state="connection"===e?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(e)),this.record("candidate-start",t),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(t){return!this._disposed&&t===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(t,e){if(this._disposed||t!==this._token)return!1;let i=!0;const s=(async()=>{for(await e.updateComplete();i&&!this._disposed&&t===this._token;)if(e.stageValid()&&e.assetsReady()){if(await this.nextFrame(),t!==this._token||!e.stageValid()||!e.assetsReady())continue;if(await this.nextFrame(),t===this._token&&e.stageValid()&&e.assetsReady())return!0}else await this.nextFrame();return!1})();let n=0;const o=new Promise(t=>{n=this.clock.setTimeout(()=>t({ready:!1,timedOut:!0}),gd)}),a=await Promise.race([s.then(t=>({ready:t,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(n),!this._disposed&&t===this._token&&(!(!a.ready&&!a.timedOut)&&(a.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=e.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(t=this._recoveryReason||"plan"){return this.beginCandidate("retry",t)}nextFrame(){return new Promise(t=>{const e=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(e),t()});this._barrierRafs.add(e)})}scheduleOverlay(t){this.clearOverlayTimer(),this._recoveryReason=t,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const t=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},t)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const t of this._barrierRafs)this.clock.cancelAnimationFrame(t);this._barrierRafs.clear()}}function wd(t){let e=2166136261,i=2654435769;const s=new WeakSet,n=t=>{for(let s=0;s>>0)+(i>>>2)}},o=t=>{if(null===t)return void n("n");const e=typeof t;if("string"===e)return void n(`s${t.length}:${t}`);if("number"===e)return void n(`d${Number.isNaN(t)?"NaN":String(t)}`);if("boolean"===e)return void n(t?"t":"f");if("undefined"===e)return void n("u");if("object"!==e)return void n(`${e}:${String(t)}`);const i=t;if(s.has(i))n("[cycle]");else{if(s.add(i),Array.isArray(t)){n("[");for(const e of t)o(e);return n("]"),void s.delete(i)}n("{");for(const e of Object.keys(t).sort())n(e),o(t[e]);n("}"),s.delete(i)}};return o(t),`${(e>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function kd(t){return wd(t)}const xd=new WeakMap;class $d{constructor(t,e=()=>Date.now()){this.onUpdate=t,this.now=e,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(t){const e=((t,e)=>{const i=t?.connection||t?.callWS||e;return!i||"object"!=typeof i&&"function"!=typeof i?e:i})(t,this.fallbackAuthority);return this.shared&&this.authority===e||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=e,this.shared=(t=>{let e=xd.get(t);return e||(e={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},xd.set(t,e)),e})(e),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(t,e){this.disposed=!1,this.referenced=new Set(e());const i=this.bind(t());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(t(),e()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const t of this.queued)this.shared.queued.delete(t)}this.queued.clear()}invalidate(t){const e=this.bind(t);clearTimeout(this.batchTimer),this.queued.clear(),e.queued.clear(),e.inFlight.clear(),e.retry.clear(),e.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return i;const s=this.bind(t);this.referenced.add(i),s.references.set(this.referenceOwner,new Set(this.referenced));const n=s.signed[i],o=n?this.now()-n.at:1/0;return o{const e=[...this.queued];this.queued.clear();for(const t of e)i.queued.delete(t);this.sign(t,e)},30))}sign(t,e){if(!e.length||!t?.callWS)return;const i=this.bind(t);for(const s of function(t,e){const i=Math.max(1,Math.floor(e)),s=[];for(let e=0;e{const s=i.inFlight.get(t);return!(void 0!==s&&e-s<15e3)&&(i.inFlight.set(t,e),!0)});n.length&&t.callWS({type:"houseplan/content/sign",paths:n}).then(t=>{const e=this.now();let s=0,o=!1;for(const a of n){const n=t?.urls?.[a];if("string"==typeof n&&n){const t=i.signed[a];t?.loaded&&t.url!==n?(t.pending={url:n,at:e},this.preloadReplacement(i,a,n,e)):(i.signed[a]={url:n,at:e,loaded:t?.url===n&&!!t.loaded},o=!0),i.retry.delete(a),s++}else this.backOff(i,a)}if(s&&(this.trimShared(i),o))for(const t of[...i.listeners])t()}).catch(()=>{for(const t of n)this.backOff(i,t)}).finally(()=>{for(const t of n)i.inFlight.get(t)===e&&i.inFlight.delete(t);for(const t of[...i.settlers])t()})}}preloadReplacement(t,e,i,s){const n=()=>{const n=t.signed[e];if(n?.pending?.url===i){t.signed[e]={url:i,at:s,loaded:!0},t.retry.delete(e),this.trimShared(t);for(const e of[...t.listeners])e()}},o=()=>{const s=t.signed[e];s?.pending?.url===i&&(delete s.pending,this.backOff(t,e))};if("undefined"==typeof Image)return void n();const a=new Image;a.onload=()=>{("function"==typeof a.decode?a.decode():Promise.resolve()).then(n).catch(o)},a.onerror=o,a.src=i}preloadCurrentImage(t,e,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const s=i.url;return i.preload=new Promise(n=>{const o=new Image;let a=!1;const r=o=>{if(a)return;a=!0,clearTimeout(l);const r=t.signed[e];if(r===i&&delete r.preload,o&&r===i&&r.url===s){r.loaded=!0;for(const e of[...t.listeners])e();n(!0)}else o||r!==i||this.backOff(t,e),n(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>r(!0)).catch(()=>r(!1))},o.onerror=()=>r(!1);const l=setTimeout(()=>r(!1),gd);o.src=s}),i.preload}prepareImage(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const s=this.bind(t),n=()=>{const e=s.signed[i];if(e&&this.now()-e.atthis.now()&&!s.inFlight.has(i)&&!s.queued.has(i)?Promise.resolve(!1):null},o=n();return o?(a=o,new Promise(t=>{let e=!1;const i=i=>{e||(e=!0,clearTimeout(s),t(i))},s=setTimeout(()=>i(!1),gd);a.then(i).catch(()=>i(!1))})):new Promise(t=>{let e=!1,i=null;const o=i=>{e||(e=!0,clearTimeout(r),s.settlers.delete(a),t(i))},a=()=>{e||i||(i=n(),i&&i.then(o).catch(()=>o(!1)))},r=setTimeout(()=>o(!1),gd);s.settlers.add(a),a()});var a}backOff(t,e){const i=t.retry.get(e)?.delay||0,s=Math.min(6e4,i?2*i:2e3);t.retry.set(e,{notBefore:this.now()+s,delay:s})}trimShared(t){const e=Object.entries(t.signed);if(e.length<=512)return;const i=new Set(t.inFlight.keys());for(const e of t.references.values())for(const t of e)i.add(t);for(const[t,s]of e)(s.pending||s.preload)&&i.add(t);e.sort((t,e)=>e[1].at-t[1].at);const s=e.filter(([t])=>i.has(t));for(const t of e){if(s.length>=512)break;i.has(t[0])||s.push(t)}t.signed=Object.fromEntries(s)}resign(t,e){const i=this.bind(t);this.referenced=new Set(e),i.references.set(this.referenceOwner,new Set(this.referenced));const s=this.now(),n=new Set;for(const t of i.references.values())for(const e of t)n.add(e);const o={};for(const[t,e]of Object.entries(i.signed))n.has(t)&&s-e.at!!o[t]&&!o[t].pending))}markLoaded(t,e,i){const s=As(e);if(!s.startsWith("/api/houseplan/content/"))return;const n=this.bind(t).signed[s];if(n&&(!i||n.url===i)&&!n.loaded){n.loaded=!0;for(const e of[...this.bind(t).listeners])e()}}isReady(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return!0;const s=this.bind(t).signed[i];return!!s&&this.now()-s.att.id===e)}function Md(t="file"){const e="draw"===t;return{source:t,showBorders:e,showNames:e,displayTouched:!1}}function Cd(t,e){if(t.displayTouched)return{...t,source:e};const i="draw"===e;return{...t,source:e,showBorders:i,showNames:i}}function Dd(t,e,i){return{...t,[e]:i,displayTouched:!0}}function Pd(t,e,i){return[t[0]*e+t[1]*i+t[2],t[3]*e+t[4]*i+t[5]]}function Td(t,e){let i=0;for(const[s,n]of e){const e=Pd(t,s[0],s[1]);i=Math.max(i,Math.hypot(e[0]-n[0],e[1]-n[1]))}return i}const Rd=t=>{if(null==t||""===t)return null;const e=Number(t);return Number.isFinite(e)?e:null},Id=t=>{const e=t,i=Rd(Array.isArray(e)?e[0]:e?.x),s=Rd(Array.isArray(e)?e[1]:e?.y);return null==i||null==s?null:[i,s]};function Ad(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}if(e.length<3)return null;let i=0,s=0,n=0;for(let t=0;tt+e[0],0)/e.length,e.reduce((t,e)=>t+e[1],0)/e.length]:[s/(3*i),n/(3*i)]}function zd(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}const i=Ad(e);if(!i)return null;const s=e.map(t=>t[0]),n=e.map(t=>t[1]);return{centroid:i,bbox:[Math.min(...s),Math.min(...n),Math.max(...s),Math.max(...n)]}}function Fd(t){let e=t;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;e=t.path??t.points??e}if(!Array.isArray(e)||!e.length)return[];let i=(e.some(t=>(t=>Array.isArray(t)?t.length>=2&&!Array.isArray(t[0])&&("object"!=typeof t[0]||null==t[0]):!!t&&"object"==typeof t&&("x"in t||"y"in t))(t))?[e]:e.filter(Array.isArray)).map(t=>t.map(Id).filter(t=>null!=t)).filter(t=>t.length>=2);i.length>64&&(i=i.slice(-64));const s=i.reduce((t,e)=>t+e.length,0);if(s<=4e3)return i.map(t=>t.slice());const n=4e3-2*i.length,o=i.map(t=>t.length-2),a=o.reduce((t,e)=>t+e,0),r=o.map(t=>n*t/a),l=r.map(Math.floor);let c=n-l.reduce((t,e)=>t+e,0);const h=r.map((t,e)=>({index:e,fraction:t-Math.floor(t)})).sort((t,e)=>e.fraction-t.fraction||t.index-e.index);for(let t=0;tfunction(t,e){if(e>=t.length)return t.slice();if(e<=2)return[t[0],t[t.length-1]];const i=[];for(let s=0;st.slice()),i=e[e.length-1];return i?(i.length>2?i.pop():e.pop(),e):[]}function Od(t){if(!t)return null;const e=t.vacuum_position||t.robot_position||null,i=e&&null!=Rd(e.x)&&null!=Rd(e.y)?{x:Rd(e.x),y:Rd(e.y),a:Rd(e.a??e.angle??e.theta)}:null,s=Fd(t.path?.path??t.path?.points??t.path),n=[],o=t.rooms,a=Array.isArray(o)?o.map((t,e)=>[String(t?.id??e),t]):o&&"object"==typeof o?Object.entries(o):[];for(const[t,e]of a){if(!e||"object"!=typeof e)continue;const i=String(e.name??e.label??"").trim(),s=[[Rd(e.cx),Rd(e.cy)],[Rd(e.center?.x),Rd(e.center?.y)],[Rd(e.x),Rd(e.y)]].find(([t,e])=>null!=t&&null!=e);let o=s?.[0]??null,a=s?.[1]??null;const r=zd(e.outline),l=Rd(e.x0),c=Rd(e.y0),h=Rd(e.x1),d=Rd(e.y1),p=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||r?.bbox||null;if(null!=o&&null!=a||!r||([o,a]=r.centroid),null!=o&&null!=a||!p||(o=(p[0]+p[2])/2,a=(p[1]+p[3])/2),i&&null!=o&&null!=a){const e={id:t,name:i,cx:o,cy:a};p&&([e.x0,e.y0,e.x1,e.y1]=p),n.push(e)}}const r=function(t){return String(t.map_name??t.current_map??t.map_index??t.selected_map??"default")}(t);return i||n.length||s.length?{pos:i,path:s,rooms:n,mapId:r}:null}function Ld(t,e,i){if(!t||!e)return null;const s=e.attributes||{},n=t.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,a=!!Id(s.vacuum_position??s.robot_position),r=!(!s.rooms||"object"!=typeof s.rooms),l=Fd(s.path?.path??s.path?.points??s.path).length>0,c=[s.map_name,s.current_map,s.map_index,s.selected_map].some(t=>null!=t),h="xiaomi_cloud_map_extractor"===o,d=r||l||c;let p=null;if(a?p="compatible":h?p="known_xcme_incomplete":d?p="partial":"camera"===n&&(p="camera"),!p)return null;const u=a?"camera"===n?300:200:h?100:d?50:0;return{entityId:t,name:String(s.friendly_name||t),platform:o,category:p,hasPosition:a,hasRooms:r,hasPath:l,hasMapId:c,score:u}}const Hd=t=>t.toLowerCase().replace(/[\s_\-.,]+/g,"");function Bd(t,e){const i=new Map(e.map(t=>[Hd(t.name),t])),s=[],n=[];for(const e of t){const t=i.get(Hd(e.name));t&&(s.push([[e.cx,e.cy],[t.cx,t.cy]]),n.push(e.name))}if(s.length<3)return null;const o=function(t){if(t.length<3)return null;let e=0,i=0,s=0,n=0,o=0,a=0,r=0,l=0,c=0,h=0,d=0,p=0;for(const[[u,_],[m,g]]of t){if(![u,_,m,g].every(Number.isFinite))return null;e+=u*u,i+=u*_,s+=u,n+=_*_,o+=_,a+=1,r+=u*m,l+=_*m,c+=m,h+=u*g,d+=_*g,p+=g}const u=[e,i,s,i,n,o,s,o,a],_=t=>{const[e,i,s,n,o,a,r,l,c]=u,h=e*(o*c-a*l)-i*(n*c-a*r)+s*(n*l-o*r);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-a*l)/h,(s*l-i*c)/h,(i*a-s*o)/h,(a*r-n*c)/h,(e*c-s*r)/h,(s*n-e*a)/h,(n*l-o*r)/h,(i*r-e*l)/h,(e*o-i*n)/h];return[d[0]*t[0]+d[1]*t[1]+d[2]*t[2],d[3]*t[0]+d[4]*t[1]+d[5]*t[2],d[6]*t[0]+d[7]*t[1]+d[8]*t[2]]},m=_([r,l,c]),g=_([h,d,p]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(s);return o?{matrix:o,matched:n,residual:Td(o,s)}:null}function qd(t,e,i){const s=t[t.length-1];if(s&&s[0]===e[0]&&s[1]===e[1])return t;if(t.push(e),t.length<=600)return t;let n=function(t,e){if(t.length<3)return t.slice();const i=new Uint8Array(t.length);i[0]=i[t.length-1]=1;const s=[[0,t.length-1]];for(;s.length;){const[n,o]=s.pop(),[a,r]=t[n],[l,c]=t[o],h=l-a,d=c-r,p=Math.hypot(h,d)||1e-9;let u=0,_=-1;for(let e=n+1;eu&&(u=i,_=e)}_>0&&u>e&&(i[_]=1,s.push([n,_],[_,o]))}const n=[];for(let e=0;e600&&(n=n.filter((t,e)=>e%2==0||e===n.length-1)),n}function Wd(t){return"cleaning"===t||"returning"===t||"on"===t}const jd={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Ud(t){const[e,i]=jd[t.rot]||[1,0],s=t.mir?-1:1;return[t.s*e*s,-t.s*i,t.ox,t.s*i*s,t.s*e,t.oy]}function Gd(t){const e=t[0]*t[4]-t[1]*t[3];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;const i=e<0,s=Math.sqrt(Math.abs(e));let n=180*Math.atan2(-t[1],t[4])/Math.PI;return n=(90*Math.round(n/90)%360+360)%360,{ox:t[2],oy:t[5],s:s,rot:n,mir:i}}function Vd(t,e,i,s){const[n,o]=Pd(Ud(e),i,s),a=Ud({...t,ox:0,oy:0}),[r,l]=Pd(a,i,s);return{...t,ox:n-r,oy:o-l}}function Kd(t){const e=t?.trail_mode;return"never"===e||"cleaning"===e||"always"===e?e:!1===t?.trail?"never":"cleaning"}const Yd={offStates:["off"],unknownUsesToggle:!0},Jd={light:Yd,switch:Yd,fan:Yd,humidifier:Yd,input_boolean:Yd,automation:Yd,remote:Yd,group:Yd,climate:{...Yd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Yd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Yd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Yd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function Xd(t){return t.slice(0,t.indexOf("."))}function Zd(t,e,i){if(!t?.services||"object"!=typeof t.services)return!1;const s=t.services?.[e];return!!s&&Object.prototype.hasOwnProperty.call(s,i)}function Qd(t,e,i){return Zd(t,e,i)?{domain:e,service:i}:Zd(t,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function tp(t,e){return t?.entities?.[e]||null}function ep(t,e,i){const s=t?.states?.[i],n=tp(e,i);return s?.attributes?.friendly_name||n?.name||n?.original_name||i}function ip(t,e){const i=tp(t,e);if(null!=i?.disabled_by)return!0;const s=i?.device_id?t?.devices?.[i.device_id]:null;return null!=s?.disabled_by}function sp(t,e){const i=t?.attributes?.supported_features;if(null==i||""===i)return!1;const s=Number(i);return Number.isFinite(s)&&(s&e)===e}function np(t,e,i){const s=Xd(i);if("lock"===s||"alarm_control_panel"===s)return!0;if("cover"!==s)return!1;const n=t?.states?.[i],o=tp(e,i),a=String(n?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Ui.has(a)}function op(t,e,i,s,n){return{ref:i,entityId:s,name:s?ep(t,e,s):null,reason:n}}function ap(t,e,i,s,n,o=null){return{target:null,skipped:op(t,e,i,s,n),semantics:o,nextEffect:null,command:null}}function rp(t,e,i,s,n=i){const o=Xd(i);if("cover"!==o&&"valve"!==o)return function(t,e,i,s,n=i){const o=Xd(i),a=t?.states?.[i];if(ip(e,i))return ap(t,e,n,i,"ha-disabled","power");if(np(t,e,i))return ap(t,e,n,i,"secure");if(!a)return ap(t,e,n,i,"missing","power");if("unavailable"===a.state)return ap(t,e,n,i,"unavailable","power");const r=Jd[o];if(!r)return ap(t,e,n,i,"unsupported");let l,c;if("unknown"===a.state||""===a.state){if(!r.unknownUsesToggle)return ap(t,e,n,i,"unsupported","power");l="toggle",c="toggle"}else r.offStates.includes(String(a.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=r.featureMasks?.[c];if(h&&!sp(a,h))return ap(t,e,n,i,"unsupported","power");const d=Qd(t,o,c);return d?{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:ap(t,e,n,i,"unsupported","power")}(t,e,i,s,n);if(ip(e,i))return ap(t,e,n,i,"ha-disabled",o);if(np(t,e,i))return ap(t,e,n,i,"secure",o);const a=t?.states?.[i];if(!a)return ap(t,e,n,i,"missing",o);if("unavailable"===a.state)return ap(t,e,n,i,"unavailable",o);const r=function(t,e,i){const s=String(i?.state||""),n="closed"===s?{service:`open_${e}`,effect:"open",feature:1}:"open"===s?{service:`close_${e}`,effect:"close",feature:2}:"opening"===s||"closing"===s?{service:`stop_${e}`,effect:"stop",feature:8}:null;return n&&sp(i,n.feature)&&Zd(t,e,n.service)?n:sp(i,3)&&Zd(t,e,"toggle")?{service:"toggle",effect:"toggle"}:null}(t,o,a);if(!r)return ap(t,e,n,i,"unsupported",o);return{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:o,nextEffect:r.effect,command:{domain:o,service:r.service,data:{entity_id:i}}}}function lp(t){return"entity"===t.bindingKind?t.bindingRef&&Ms(t.bindingRef)?[t.bindingRef]:[]:"virtual"===t.bindingKind?[]:to(t)}function cp(t){const e=t.marker?.toggle_entity;return e&&lp(t).includes(e)?e:null}function hp(t,e,i){const s=function(t,e){if("entity"===t.bindingKind&&t.bindingRef){const e=t.marker?.light_entity?eo(t):null;return[...new Set([e,t.bindingRef].filter(t=>!!t))]}const i=t.entities.length?t.entities:t.allEntities||[],s=t.marker?.light_entity||t.primary&&Ms(t.primary)?eo(t):null;return[...new Set([s,...Yn(e,i)].filter(t=>!!t))]}(i,e);if(!s.length)return null;const n="entity"===i.bindingKind?"binding":"device-role";if("binding"===n)return rp(t,e,s[0],n);let o=null,a=null;for(const i of s){const s=rp(t,e,i,n);if(s.command)return s;const r=s.skipped?.reason;if("missing"===r||"unavailable"===r||"secure"===r)return s;"ha-disabled"!==r?o||=s:a||=s}return o||a}function dp(t){const e=t.skipped?.reason;return"missing"===e?"unavailable":e||"unsupported"}function pp(t,e){return{origin:t,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:e,nextEffect:null,command:null}}function up(t,e){return"cover"===t||"toggle"===t?"toggle":"more-info"===t||"run"===t||"info"===t?t:(null==t||""===t)&&"light"===e?"toggle":"info"}function _p(t,e){return{origin:t,kind:"single",semantics:e.semantics,targets:e.target?[e.target]:[],skippedTargets:e.skipped?[e.skipped]:[],noneReason:e.command?null:dp(e),nextEffect:e.nextEffect,command:e.command}}function mp(t,e,i,s=[]){const n=new Map,o=[],a=new Set,r=t=>{const e=`${t.ref}\n${t.entityId||""}\n${t.reason}`;a.has(e)||(a.add(e),o.push(t))};for(const t of s)r(t);for(const s of i){const i=rp(t,e,s.entityId,s.via,s.ref);i.target?n.set(s.entityId,n.get(s.entityId)||i.target):i.skipped&&r(i.skipped)}const l=[...n.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(t=>"secure"===t.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(t=>"on"===t.state)?"turn_off":"turn_on",h=Qd(t,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(t=>t.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>op(t,e,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function gp(t){return String(t.marker?.id||t.id||"")}function fp(t){const{hass:e,device:i}=t,s=t.registryHass||e,n=function(t){return"toggle"===t.tapAction?"explicit-toggle":"cover"===t.tapAction?"legacy-cover":!t.tapAction&&t.primary?.startsWith("light.")?"default-light":null}(i);if(!n)return null;const o=i.marker;if("explicit-toggle"===n&&yn(o)){const e=String(o?.id||i.id||""),s=ro(t.devices).get(e);if(s)return function(t,e){const i=t.registryHass||t.hass;return mp(t.hass,i,e.driverEids.map(t=>({entityId:t,via:"control-marker-driver",ref:`marker:${e.markerId}`})))}(t,s);const a=bn(o,t.virtualLights);return{origin:n,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:a?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:a?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===n){if(Zn(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(t,e=null){const{hass:i,device:s,devices:n}=t,o=t.registryHass||i,a=Zn(s.marker?.binding,s.marker?.controls??s.controls,s.entities),r=t.lightSources||ho(i,n,null,t.virtualLights),l=new Map;for(const t of r){if(!t.key.startsWith("marker:"))continue;const e=l.get(t.key)||[];e.push(t),l.set(t.key,e)}const c=ro(n),h=new Map;for(const t of n){const e=String(t.marker?.id||t.id||"");e&&h.set(e,t)}const d=[],p=[];e&&d.push({entityId:e,via:"entity"===s.bindingKind?"binding":"device-role",ref:e});for(const t of a){if(!t.startsWith("marker:")){Ms(t)?d.push({entityId:t,via:"control-entity",ref:t}):p.push(op(i,o,t,t.includes(".")?t:null,"unsupported"));continue}const e=l.get(t)||[];if(!e.length){const e=h.get(t.slice(7));if("ha_disabled"===e?.bindingStatus?.kind){const s=e.bindingStatus.allEntityIds[0]||null;p.push({ref:t,entityId:s,name:e.name||(s?ep(i,o,s):null),reason:"ha-disabled"})}else p.push(op(i,o,t,null,"missing"));continue}const n=[...new Set(e.flatMap(t=>t.serviceEids))];if(n.length){for(const e of n)d.push({entityId:e,via:"control-entity",ref:t});continue}const a=e.some(t=>t.passive),r=t.slice(7),u=gp(s),_=c.get(r)?.controllers.find(t=>gp(t.device)===u);if(a&&_?.driverEids.length)for(const e of _.driverEids)d.push({entityId:e,via:"control-marker-driver",ref:t});else p.push(op(i,o,t,null,a?"missing":"unsupported"))}return mp(i,o,d,p)}(t,cp(i))}if("legacy-cover"===n){const t=i.entities.find(t=>t.startsWith("cover."))||i.allEntities?.find(t=>t.startsWith("cover."));return t?_p(n,rp(e,s,t,"device-role")):pp(n,"no-actionable-entity")}const a=cp(i),r=a?rp(e,s,a,"entity"===i.bindingKind?"binding":"device-role"):hp(e,s,i);return r?_p(n,r):pp(n,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function vp(t){if(!t)return[];const e=Array.isArray(t.data.entity_id)?t.data.entity_id:[t.data.entity_id];return[...new Set(e)].sort()}function yp(t){return t?t.operation?t.operation:t.command?{kind:"ha-service",command:t.command}:null:null}const bp=new Set(["missing","ha-disabled","unavailable"]);function wp(t,e){const i=yp(t),s=yp(e);return!(!i||!s||i.kind!==s.kind)&&("virtual-light"===i.kind&&"virtual-light"===s.kind?i.markerId===s.markerId:"ha-service"===i.kind&&"ha-service"===s.kind&&function(t,e){const i=vp(t),s=vp(e);return i.length===s.length&&i.every((t,e)=>t===s[e])}(i.command,s.command))}const kp=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]);function xp(t,e=5,i=5){return gl(t.cm,e,i)/2}function $p(t,e,i=1,s=5,n=5,o=0){const a=t.host;if(!a||"partition"!==a.kind||"string"!=typeof a.id||!a.id)return{resolved:null,reason:"invalid-host"};const r=e.find(t=>t.id===a.id);if(!r)return{resolved:null,reason:"missing-partition"};if(!kp(r.a)||!kp(r.b)||!Number.isFinite(a.t)||a.t<0||a.t>1)return{resolved:null,reason:"invalid-position"};const l=r.b[0]-r.a[0],c=r.b[1]-r.a[1],h=Math.hypot(l,c),d=Number(t.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const p=a.t*h;if(p-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const u=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:t,host:a,partition:r,center:[r.a[0]+l*a.t,r.a[1]+c*a.t],angle:m,length:d,depth:gl(r.cm,s,n),t:a.t,axis:{a:[r.a[0],r.a[1]],b:[r.b[0],r.b[1]],ux:u,uy:_,length:h}}}}function Sp(t,e,i=1,s=5,n=5){return $p(t,e,i,s,n,0)}function Mp(t,e,i=1,s=5,n=5){const o=t.host,a="partition"===o?.kind?e.find(t=>t.id===o.id):void 0;if(!a)return Sp(t,e,i,s,n);const r=$p(t,e,i,s,n,xp(a,s,n));return"does-not-fit"===r.reason?{resolved:null,reason:"does-not-fit-jamb"}:r}function Cp(t,e){return!t||(t.length!==e.length||t.host?.kind!==e.host?.kind||t.host?.id!==e.host?.id||t.host?.t!==e.host?.t)}function Dp(t){const{center:e,length:i,axis:s,host:n}=t,o=i/2;return{hostId:n.id,a:[e[0]-s.ux*o,e[1]-s.uy*o],b:[e[0]+s.ux*o,e[1]+s.uy*o],depth:t.depth}}function Pp(t,e=!1){const i=e?1:-1,s=t.depth/2;return{ox:-t.axis.uy*i*s,oy:t.axis.ux*i*s,cm:t.partition.cm,side:i}}function Tp(t,e,i){return t.flatMap(t=>!kp(t.a)||!kp(t.b)||Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])<=1e-9?[]:[{roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`partition:${t.id}`,kind:"outer",cm:t.cm,open:!1,half:gl(t.cm,e,i)/2,partitionHost:{kind:"partition",id:t.id}}])}function Rp(t,e,i){const{center:s,length:n,axis:o}=t,a=n/2,r=e.flatMap(t=>{if(!t.kind||t.open)return[];const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(e,n);if(!(r>i))return[];const l=e/r,c=n/r;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((s[0]-t.a[0])*c-(s[1]-t.a[1])*l)>i)return[];const h=t=>(t[0]-s[0])*o.ux+(t[1]-s[1])*o.uy,d=h(t.a),p=h(t.b),u=Math.max(-a,Math.min(d,p)),_=Math.min(a,Math.max(d,p));return _>=u-i?[[u,_]]:[]});if(!r.length)return!1;r.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let l=-a;for(const[t,e]of r){if(t>l+i)return!1;if(l=Math.max(l,e),l>=a-i)return!0}return!1}function Ip(t,e,i){return{...t,x:e.center[0]/i,y:e.center[1]/i,angle:e.angle}}const Ap=.001;function zp(t){return!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function Fp(t){return`${t[0].toFixed(6)},${t[1].toFixed(6)}`}function Ep(t,e,i){return Math.abs(t[0]-e[0])"room"!==t.kind&&i.some(i=>i!==t&&function(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>i))return!1;const a=s/o,r=n/o,l=e=>Math.abs((e[0]-t.a[0])*r-(e[1]-t.a[1])*a);if(l(e.a)>i||l(e.b)>i)return!1;const c=(e.a[0]-t.a[0])*a+(e.a[1]-t.a[1])*r,h=(e.b[0]-t.a[0])*a+(e.b[1]-t.a[1])*r;return Math.min(o,Math.max(c,h))-Math.max(0,Math.min(c,h))>i}(t,i,e))),n=s.map(t=>{const[e,i]=Np(t.a,t.b);return{a:e,b:i,key:`hidden|${Lp(t,e,i)}`,sourceKind:t.kind,sourceId:t.id}}).sort((t,e)=>t.key.localeCompare(e.key)),o=s.flatMap(t=>[t.a,t.b].map((e,i)=>({point:[e[0],e[1]],key:`hidden|${Op(t)}|endpoint-${i}`,sourceKind:t.kind,sourceId:t.id}))).sort((t,e)=>t.key.localeCompare(e.key));return{segments:n,endpoints:o}}function Wp(t){const e=t.epsilon??Ap,i=t.roomCuts||[],s=new Map;for(const e of t.partitionCuts||[]){if("string"!=typeof e.hostId||!e.hostId||!zp(e.a)||!zp(e.b))continue;const t=s.get(e.hostId)||[];t.push([e.a[0],e.a[1],e.b[0],e.b[1]]),s.set(e.hostId,t)}const n=[];for(const[e,s]of pi(t.space.rooms).entries())s.length<4||n.push({a:[s[0],s[1]],b:[s[2],s[3]],kind:"room",id:`room-edge-${e}`,cuts:i});for(const e of t.space.room_drafts||[])if(e.id!==t.activeDraftId)for(let t=0;t+1Bp(s,t,e)))continue;const t=Fp(s);a.has(t)||a.set(t,{point:[s[0],s[1]],key:t})}}}return{segments:[...o.values()].sort((t,e)=>t.key.localeCompare(e.key)),endpoints:[...a.values()].sort((t,e)=>t.key.localeCompare(e.key))}}function jp(t,e,i){return e.some(e=>zp(e)&&Ep(t,e,i))}function Up(t,e,i){if(!i)return!0;const s=t-i.distance;return s<-1e-9||Math.abs(s)<=1e-9&&e.localeCompare(i.key)<0}function Gp(t,e,i){const s=i.epsilon??Ap,n=i.excludePoints||[],o=[...t.endpoints,...(i.extraEndpoints||[]).filter(t=>zp(t.point)).map(t=>({point:[t.point[0],t.point[1]],key:t.key}))],a=new Map;for(const t of o){if(jp(t.point,n,s))continue;const e=Fp(t.point),i=a.get(e);(!i||t.key.localeCompare(i.key)<0)&&a.set(e,t)}return[...a.values()].map(t=>({kind:"endpoint",point:[...t.point],key:t.key,distance:Math.hypot(e[0]-t.point[0],e[1]-t.point[1])})).filter(t=>t.distance<=i.tolerance).sort((t,e)=>t.distance-e.distance||t.key.localeCompare(e.key))}function Vp(t,e){if(!t.length)return null;if(e>0){const i=new Set;for(let s=0;s1)return{kind:"ambiguous",candidate:null,conflicts:t.filter(t=>i.has(t.key)).map(t=>({point:[...t.point],key:t.key}))}}return{kind:"resolved",candidate:t[0],conflicts:[]}}function Kp(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>0))return[...t.a];const a=s/o,r=n/o,l=Math.max(0,Math.min(o,(e[0]-t.a[0])*a+(e[1]-t.a[1])*r)),c=i>0?Math.max(0,Math.min(o,Math.round(l/i)*i)):l;return[t.a[0]+a*c,t.a[1]+r*c]}function Yp(t,e,i){if(!(zp(e)&&zp(i.anchor)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=function(t,e){const i=e[0]-t[0],s=e[1]-t[1];if(!(Math.hypot(i,s)>Number.EPSILON))return null;const n=Math.round(Math.atan2(s,i)/(Math.PI/4))*(Math.PI/4);return[Math.cos(n),Math.sin(n)]}(i.anchor,e);if(!n)return{kind:"none",candidate:null,conflicts:[]};const o=Gp(t,e,i).filter(t=>function(t,e,i,s){const n=t[0]-e[0],o=t[1]-e[1];return n*i[0]+o*i[1]>s&&Math.abs(n*i[1]-o*i[0])<=s*Math.max(Math.hypot(n,o),1)}(t.point,i.anchor,n,s)),a=Vp(o,i.distinguishTolerance||0);if(a)return a;let r=null;for(const o of t.segments){const t=o.b[0]-o.a[0],a=o.b[1]-o.a[1],l=o.a[0]-i.anchor[0],c=o.a[1]-i.anchor[1],h=n[0]*a-n[1]*t;let d=null;if(Math.abs(h)<=s*Math.max(Math.hypot(t,a),1)){if(Math.abs(l*n[1]-c*n[0])>s*Math.max(Math.hypot(l,c),1))continue;const t=[o.a,o.b].map(t=>({point:t,along:(t[0]-i.anchor[0])*n[0]+(t[1]-i.anchor[1])*n[1]})).filter(t=>t.along>s).sort((t,e)=>t.along-e.along);t.length&&(d=[...t[0].point])}else{const e=(l*a-c*t)/h,o=(l*n[1]-c*n[0])/h;e>s&&o>=-s&&o<=1+s&&(d=[i.anchor[0]+n[0]*e,i.anchor[1]+n[1]*e])}if(!d)continue;const p=Math.hypot(e[0]-d[0],e[1]-d[1]);p>i.tolerance||jp(d,i.excludePoints||[],s)||!Up(p,o.key,r)||(r={kind:"line",point:d,key:o.key,distance:p,segment:o})}return r?{kind:"resolved",candidate:r,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}const Jp=.001;function Xp(t,e,i,s){const n=Number.isFinite(t)&&t>0?Math.floor(t):0,o=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null,a=o(i),r=o(s)??0,l=[];let c=null;for(let t=0;t=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function tu(t,e,i,s){return t*s-e*i}function eu(t){let e=0;for(let i=0;it.localeCompare(e)),e[0]}function au(t,e,i){const s=[...t];for(let t=!0;t&&s.length>=3;){t=!1;for(let n=0;n=0){s.splice(n,1),t=!0;break}}}return s}function ru(t,e){const i=t.map(t=>Math.max(0,Math.min(1,t))).sort((t,e)=>t-e),s=[];for(const t of i)(!s.length||Math.abs(t-s[s.length-1])>e)&&s.push(t);return s}function lu(t,e){return[t.a[0]+(t.b[0]-t.a[0])*e,t.a[1]+(t.b[1]-t.a[1])*e]}function cu(t,e,i){const s=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n:0}(t,e);if(s<-i||s>1+i)return null;const n=lu(e,s);return Math.hypot(n[0]-t[0],n[1]-t[1])<=i?Math.max(0,Math.min(1,s)):null}function hu(t,e,i,s,n){const o=t.b[0]-t.a[0],a=t.b[1]-t.a[1],r=e.b[0]-e.a[0],l=e.b[1]-e.a[1],c=e.a[0]-t.a[0],h=e.a[1]-t.a[1],d=tu(o,a,r,l),p=Math.max(Math.hypot(o,a),Math.hypot(r,l),1);if(Math.abs(d)>n*p){const t=tu(c,h,r,l)/d,e=tu(c,h,o,a)/d;return void(t>=-n&&t<=1+n&&e>=-n&&e<=1+n&&(i.push(Math.max(0,Math.min(1,t))),s.push(Math.max(0,Math.min(1,e)))))}if(!(Math.abs(tu(c,h,o,a))>n*p)){for(const s of[e.a,e.b]){const e=cu(s,t,n);null!=e&&i.push(e)}for(const i of[t.a,t.b]){const t=cu(i,e,n);null!=t&&s.push(t)}}}function du(t){let e=t+1|0;return e^=e<<13,e^=e>>>17,e^=e<<5,e>>>0}function pu(t,e){return t.minY-e.minY||t.index-e.index}function uu(t){return t.subtreeMaxY=Math.max(t.item.maxY,t.left?.subtreeMaxY??-1/0,t.right?.subtreeMaxY??-1/0),t}function _u(t){const e=t.right;return t.right=e.left,e.left=uu(t),uu(e)}function mu(t){const e=t.left;return t.left=e.right,e.right=uu(t),uu(e)}function gu(t,e){return t?(pu(e,t.item)<0?(t.left=gu(t.left,e),t.left.priority0)t.right=fu(t.right,e);else{if(!t.left)return t.right;if(!t.right)return t.left;t.left.priority=e&&vu(t.left,e,i,s),t.item.minY<=i&&t.item.maxY>=e&&s.push(t.item),t.item.minY<=i&&vu(t.right,e,i,s))}function yu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=t.filter(t=>Qp(t.a)&&Qp(t.b)&&"string"==typeof t.key&&t.key.length>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>i),n=s.map(()=>[0,1]);!function(t,e,i){const s=t.map((t,e)=>({index:e,minX:Math.min(t.a[0],t.b[0])-i,maxX:Math.max(t.a[0],t.b[0])+i,minY:Math.min(t.a[1],t.b[1])-i,maxY:Math.max(t.a[1],t.b[1])+i})),n=[...s].sort((t,e)=>t.minX-e.minX||t.minY-e.minY||t.index-e.index),o=[...s].sort((t,e)=>t.maxX-e.maxX||t.index-e.index),a=new Set;let r=null,l=0;for(const s of n){for(;lt.index-e.index);for(const o of n)hu(t[o.index],t[s.index],e[o.index],e[s.index],i);a.add(s.index),r=gu(r,s)}}(s,n,i);const o=new Map;for(let t=0;t({key:t,a:e.a,b:e.b,sourceKeys:[...e.sourceKeys].sort((t,e)=>t.localeCompare(e))})).sort((t,e)=>t.key.localeCompare(e.key))}function bu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=yu(t,i),n=new Map,o=new Map,a=new Map(s.map(t=>[t.key,t]));for(const t of s){const e=su(t.a,i),s=su(t.b,i);n.set(e,t.a),n.set(s,t.b),o.has(e)||o.set(e,new Set),o.has(s)||o.set(s,new Set),o.get(e).add(s),o.get(s).add(e)}const r=new Map;for(const[t,e]of o){const i=n.get(t);r.set(t,[...e].sort((t,e)=>{const s=n.get(t),o=n.get(e);return Math.atan2(s[1]-i[1],s[0]-i[0])-Math.atan2(o[1]-i[1],o[0]-i[0])||t.localeCompare(e)}))}const l=new Set,c=new Map,h=(t,e)=>`${t}>${e}`;for(const t of s){const e=[su(t.a,i),su(t.b,i)];for(const[t,o]of[e,[e[1],e[0]]]){if(l.has(h(t,o)))continue;const e=[],d=[];let p=t,u=o,_=!1;for(let i=0;i<=2*s.length+2;i++){const i=h(p,u);if(l.has(i)){_=p===t&&u===o;break}l.add(i),e.push(p),d.push(nu(p,u));const s=r.get(u)||[],n=s.indexOf(p);if(n<0||!s.length)break;if(p=u,u=s[(n-1+s.length)%s.length],p===t&&u===o){_=!0;break}}if(!_||new Set(e).size<3||new Set(e).size!==e.length)continue;const m=e.map(t=>n.get(t)),g=eu(m);if(!(g>i*i))continue;const f=ou(au(e,n,i)),v=new Set;for(const t of d)for(const e of a.get(t)?.sourceKeys||[])v.add(e);const y={ring:m,key:f,area:g,atomKeys:[...d],sourceKeys:[...v].sort((t,e)=>t.localeCompare(e))};c.has(f)||c.set(f,y)}}return{atoms:s,faces:[...c.values()].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))}}function wu(t,e,i=.001){if(!Qp(e))return null;const s=t.faces.filter(t=>{if(t.ring.some((s,n)=>function(t,e,i,s){const n=i[0]-e[0],o=i[1]-e[1],a=n*n+o*o;if(!(a>0))return Math.hypot(t[0]-e[0],t[1]-e[1])<=s;const r=((t[0]-e[0])*n+(t[1]-e[1])*o)/a;return!(r<0||r>1)&&Math.hypot(e[0]+n*r-t[0],e[1]+o*r-t[1])<=s}(e,s,t.ring[(n+1)%t.ring.length],i)))return!1;let s=!1;for(let i=0,n=t.ring.length-1;ie[1]!=a[1]>e[1]&&e[0]<(a[0]-o[0])*(e[1]-o[1])/(a[1]-o[1])+o[0]&&(s=!s)}return s});return[...s].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))[0]||null}function ku(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n,a=o>0?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o)):0;return Math.hypot(e[0]+s*a-t[0],e[1]+n*a-t[1])}function xu(t,e,i=.5){let s=Math.abs(t-e)%180;return s>90&&(s=180-s),s<=i}function $u(t,e,i,s){const n=t.filter(t=>"outer"===t.kind&&!t.open&&t.cm>0).map(t=>({interval:t,reusePartitionId:e.find(e=>function(t,e,i){return!(Math.abs(t.cm-e.cm)>1e-6)&&(xu(180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI,180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI,.001)&&ku(e.a,t.a,t.b)<=i&&ku(e.b,t.a,t.b)<=i)}(e,t,s))?.id||null})),o=new Map;for(const e of i){if("partition"===e.host?.kind)continue;const i=t.map(t=>{const i=180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI;return{interval:t,distance:xu(e.angle,i)?ku([e.x,e.y],t.a,t.b):1/0}}).filter(t=>t.distance<=s).sort((t,e)=>t.distance-e.distance||t.interval.key.localeCompare(e.interval.key)),n=i[0]?.interval;"outer"===n?.kind&&!n.open&&n.cm>0&&o.set(e.id,n.key)}return{materialize:n,openingIntervals:o,removeOpeningIds:[...o.keys()].sort((t,e)=>t.localeCompare(e))}}function Su(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?Math.max(0,Math.min(1,((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n)):0}const Mu=t=>!t.key.startsWith("static:room|");function Cu(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;if(!(n>0))return null;const o=((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n,a=[e.a[0]+i*o,e.a[1]+s*o];return{point:a,t:o,distance:Math.hypot(a[0]-t[0],a[1]-t[1])}}function Du(t,e){return e>0?Math.hypot(t[0]-Math.round(t[0]/e)*e,t[1]-Math.round(t[1]/e)*e):0}function Pu(t,e,i){if(Mu(t.source)!==Mu(e.source))return Mu(t.source)?t:e;const s=Du(t.point,i),n=Du(e.point,i);return Math.abs(s-n)>1e-9?s>n?t:e:function(t,e){return t[0]-e[0]||t[1]-e[1]}(t.point,e.point)>0?t:e}function Tu(t){return[t.from[0],t.from[1],t.to[0],t.to[1],t.targetKind].map(t=>"number"==typeof t?t.toFixed(6):t).join("|")}function Ru(t,e){return t.map(t=>t.key!==e.sourceKey?t:{...t,[e.endpoint]:[...e.to]})}function Iu(t,e){const i=e.epsilon??.001;if(!(e.maxDistance>=0)||!e.point&&!e.requiredSourceKey)return{kind:"none"};const s=new Map,n=t.flatMap(t=>[{source:t,endpoint:"a",point:t.a},{source:t,endpoint:"b",point:t.b}]);for(let t=0;ti)||l>e.maxDistance)continue;const c=Pu(a,r,e.gridStep||0),h=c===a?r:a;if(!Mu(c.source))continue;const d={sourceKey:c.source.key,endpoint:c.endpoint,from:[c.point[0],c.point[1]],to:[h.point[0],h.point[1]],targetSourceKey:h.source.key,targetKind:"endpoint",distance:l};s.set(Tu(d),d)}for(const o of n)if(Mu(o.source))for(const n of t){if(n===o.source)continue;const t=Cu(o.point,n);if(!t||t.t<=i||t.t>=1-i||!(t.distance>i)||t.distance>e.maxDistance)continue;const a={sourceKey:o.source.key,endpoint:o.endpoint,from:[o.point[0],o.point[1]],to:t.point,targetSourceKey:n.key,targetKind:"line",distance:t.distance};s.set(Tu(a),a)}const o=[];for(const n of s.values()){const s=bu(Ru(t,n),i),a=e.point?wu(s,e.point,i):s.faces.find(t=>!e.requiredSourceKey||t.sourceKeys.includes(e.requiredSourceKey))||null;a&&o.push({proposal:n,face:a})}if(o.sort((t,e)=>t.proposal.distance-e.proposal.distance||Tu(t.proposal).localeCompare(Tu(e.proposal))),!o.length)return{kind:"none"};return new Set(o.map(t=>`${Tu(t.proposal)}|${t.face.key}`)).size>1?{kind:"ambiguous",proposals:o.map(t=>t.proposal)}:{kind:"repair",...o[0]}}const Au=1e-5;function zu(t){const e=t.map(()=>[]);for(let i=0;i=1-1e-9||p<=1e-9||p>=1-1e-9||(e[i].push(d),e[a].push(p))}}const i=[];for(let s=0;st-e),1];for(let t=1;t{const i=e[2]-e[0],s=e[3]-e[1],n=i*i+s*s;if(!(n>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const o=Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/n));return Math.hypot(t[0]-(e[0]+o*i),t[1]-(e[1]+o*s))},Nu=(t,e,i,s)=>{const n=s[2]-s[0],o=s[3]-s[1],a=e*o-i*n;if(Math.abs(a)<1e-12)return 1/0;const r=s[0]-t[0],l=s[1]-t[1],c=(r*o-l*n)/a;if(!(c>1e-9))return 1/0;const h=(r*i-l*e)/a;return h<-1e-9||h>1+1e-9?1/0:c};function Ou(t,e,i,s=96){if(!(e>0&&Number.isFinite(t[0])&&Number.isFinite(t[1])))return[];const n=[];for(const s of i){if(!s||s.length<4)continue;if(![s[0],s[1],s[2],s[3]].every(Number.isFinite))continue;const i=Eu(t,s);if(i<1e-7)return[];i>e||n.push(s)}const o=[],a=Math.max(12,Math.round(s));for(let t=0;tt-e);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const s=Math.cos(i),o=Math.sin(i);let a=e;for(const e of n){const i=Nu(t,s,o,e);i=3?l:[]}class Lu extends ht{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(t){this._config=t}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const t=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(t?.config?.spaces||[]).map(t=>({value:t.id,label:t.title||t.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return ra(this.hass,this._config?.language)}get _floorToken(){const t=this._config?.floor;return"number"==typeof t?`__houseplan_yaml_floor_index__:${String(t)}`:null}get _formData(){const t={...this._config},e=this._floorToken;return e?t.floor=e:Object.prototype.hasOwnProperty.call(t,"floor")||(t.floor=""),t}get _schema(){const t=this._spaces||[],e=this._lang,i=[{value:"",label:la(e,"editor.floor_none")}],s=this._floorToken;s&&i.push({value:s,label:la(e,"editor.floor_index",{index:String(this._config?.floor)})});const n="string"==typeof this._config?.floor?this._config.floor:"";n&&!t.some(t=>t.value===n)&&i.push({value:n,label:n}),i.push(...t);const o="string"==typeof this._config?.default_floor?this._config.default_floor:"",a=[...t];return o&&!t.some(t=>t.value===o)&&a.unshift({value:o,label:o}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:i}}},t.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:a}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:[{value:"",label:la(e,"editor.lang_auto")},{value:"en",label:la(e,"editor.lang_en")},{value:"ru",label:la(e,"editor.lang_ru")}]}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return G;this._loadSpaces();const t=this._lang,e={title:la(t,"editor.title"),floor:la(t,"editor.floor"),default_floor:la(t,"editor.default_floor"),language:la(t,"editor.language"),icon_size:la(t,"editor.icon_size"),show_temperature:la(t,"editor.show_temperature"),live_states:la(t,"editor.live_states"),show_signal:la(t,"editor.show_signal"),kiosk:la(t,"editor.kiosk"),cycle:la(t,"editor.cycle")},i=this._schema,s=function(t,e,i){if(!i||null===e)return null;const s="string"==typeof t?.default_floor?t.default_floor:"";return!s||e.some(t=>t.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),n=t=>W``}const Rr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Ir=(t,e=1)=>{const i=Number(t);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):e},Ar=t=>{let e=Number(t);return Number.isFinite(e)?(e=(e%360+360)%360,e>180?e-360:e):0};function zr(t,e,i){return Ar(e)?[t.x,t.y]:i([t.x,t.y])}const Fr=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&s>0?s/n*i:0},Er=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&i>0?s/i*n:0},Nr=(t,e,i,s=Rr.widthCm)=>{const n=Number(t?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(t?.width);return Number.isFinite(o)&&o>0?Er(o,e,i):s};function Or(t,e){return{color:t.color,opacity:Ir(t.opacity),width_cm:Math.max(.1,Math.min(100,Number(t.widthCm)||.1)),...e?{fill:t.fill,fill_color:t.fillColor,fill_opacity:Ir(t.fillOpacity,.25)}:{}}}function Lr(t){const e=t.x+t.w/2,i=t.y+t.h/2,s=Ar(t.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(t,s)=>{const a=t-e,r=s-i;return[e+a*n-r*o,i+a*o+r*n]};return[a(t.x,t.y),a(t.x+t.w,t.y),a(t.x+t.w,t.y+t.h),a(t.x,t.y+t.h)]}function Hr(t){const e=Lr(t),i=(t,e)=>[(t[0]+e[0])/2,(t[1]+e[1])/2],s=[(e[0][0]+e[2][0])/2,(e[0][1]+e[2][1])/2];return{points:[...e,i(e[0],e[1]),i(e[1],e[2]),i(e[2],e[3]),i(e[3],e[0]),s],segments:e.map((t,i)=>({a:t,b:e[(i+1)%4]}))}}function Br(t,e,i,s,n,o,a,r){const l=Ar(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=t.x+t.w/2,_=t.y+t.h/2,m=e>0?-t.w/2:t.w/2,g=i>0?-t.h/2:t.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(e>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const e=w/Math.max(t.w,r),i=k/Math.max(t.h,r);x=Math.max(r/Math.max(t.w,r),r/Math.max(t.h,r),e,i),w=t.w*x,k=t.h*x}if(a>0)if(o){const e=Math.max(1,Math.round(t.w/a)),i=Math.max(1,Math.round(t.h/a));if(Math.abs(t.w-e*a)<1e-6&&Math.abs(t.h-i*a)<1e-6){const s=(t,e)=>{let i=Math.abs(t),s=Math.abs(e);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(e,i),o=Math.max(r/t.w,r/t.h),a=Math.max(o,Math.round((x??1)/n)*n);w=t.w*a,k=t.h*a}else{t.w>=t.h?(w=Math.round(w/a)*a,k=w*(t.h/Math.max(t.w,r))):(k=Math.round(k/a)*a,w=k*(t.w/Math.max(t.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(e>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(e>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Ar(t.angle)||void 0}}const qr=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<1e-12)return[...e];const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return[e[0]+s*a,e[1]+n*a]};const Wr=10**9,jr=240,Ur=1e-4;function Gr(t){if(Array.isArray(t))return t.map(t=>Gr(t));if(null!==t&&"object"==typeof t){const e={};for(const[i,s]of Object.entries(t))e[i]=Gr(s);return e}return t}function Vr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=(t<0||Object.is(t,-0)?-1:1)*(Math.floor(Math.abs(t)*Wr+.5)/Wr);return 0===e?0:e}function Kr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=t*jr,i=Math.round(e);if(Math.abs(e-i)null!==Jr(t)):[]}function Zr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Vr(t[i]))}function Qr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Kr(t[i]))}function tl(t){if(Array.isArray(t))for(let e=0;e{for(const n of s){const s=e[n];"number"==typeof s&&Number.isFinite(s)&&i(s,t)}},s=e=>{if(Array.isArray(e))for(let s=0;s{if(Array.isArray(t))for(const e of t)s(e)};for(const i of Xr(t.rooms))e(i,["x","y","w","h"]),n(i.poly);for(const e of Xr(t.walls))s(e.a),s(e.b);for(const e of Xr(t.wall_segments))s(e.a),s(e.b);for(const i of Xr(t.openings))e(i,["x","y"]);for(const i of Xr(t.decor))"line"===i.kind?e(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?e(i,["x","y","w","h"]):"text"===i.kind&&e(i,["x","y"]);for(const e of Xr(t.room_drafts))n(e.points);for(const e of Xr(t.partitions))s(e.a),s(e.b);for(const e of Xr(t.wall_columns))s(e.center);for(const e of Xr(t.open_spans))s(e.a),s(e.b)}const n=Jr(e);if(!n)return;const o=new Map;if(s)for(const t of Xr(s.spaces))null!=t.id&&o.set(String(t.id),t);for(const t of Object.values(n)){const e=Jr(t);if(!e)continue;const s=null!=e.s&&o.get(String(e.s))||null;for(const t of["x","y"]){const n=e[t];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function sl(t){const e=Number(t?.cell_cm);return e>0?e:5}function nl(t,e={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=Xr(Jr(t)?.spaces);let n=5;for(const t of s)n=Math.max(n,sl(t));il(t,e,(t,e)=>{const s=t*jr,o=Math.abs(s-Math.round(s)),a=Kr(t),r=o>0&&o=Ur))return;const l=r&&"number"==typeof a?Math.abs(a-t):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*jr*(e?sl(e):n)),!e?.id||!r)return;const c=String(e.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(e.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*jr*sl(e))}),i.bySpace.size&&il(t,e,(t,e)=>{if(!e?.id)return;const s=i.bySpace.get(String(e.id));if(!s)return;const n=t*jr;Math.abs(n-Math.round(n))>=Ur&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function ol(t){return function(t){const e=t,i=Jr(e);i&&Qr(i,["x","y"]);return e}(Gr(t))}function al(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Object.values(i)){const e=Jr(t);e&&Qr(e,["x","y"])}return e}function rl(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Xr(i.spaces)){Zr(t,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const e of Xr(t.rooms))Qr(e,["x","y","w","h"]),el(e.poly);for(const e of Xr(t.walls))tl(e.a),tl(e.b);for(const e of Xr(t.wall_segments))tl(e.a),tl(e.b);for(const e of Xr(t.openings)){Qr(e,["x","y"]),Zr(e,["angle","length"]);const t=Jr(e.host);t&&Zr(t,["t"])}for(const e of Xr(t.decor))"line"===e.kind?Qr(e,["x1","y1","x2","y2"]):"rect"===e.kind||"ellipse"===e.kind||"furniture"===e.kind?(Qr(e,["x","y","w","h"]),Zr(e,["angle"])):"text"===e.kind&&(Qr(e,["x","y"]),Zr(e,["scale","angle"]));for(const e of Xr(t.room_drafts))el(e.points);for(const e of Xr(t.partitions))tl(e.a),tl(e.b);for(const e of Xr(t.wall_columns))tl(e.center),"square"===e.shape&&Zr(e,["angle"]);for(const e of Xr(t.open_spans))tl(e.a),tl(e.b)}for(const t of Xr(i.markers))Zr(t,["angle"]);return e}const ll=15;function cl(t,e,i,s,n){const o=i[0]-t[0],a=i[1]-t[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=e=>{const s=(e[0]-t[0])*l+(e[1]-t[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[e[0]+(i[0]-e[0])*o,e[1]+(i[1]-e[1])*o]},d=h(e),p=h(s);return d&&p?[[t[0],t[1]],e,d,p,s]:null}const hl=Math.sin(.25*Math.PI/180);function dl(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<3}function pl(t){const e=Number(t)>0?Number(t):5;if(5===e)return 8;const i=5/e*8;return Math.min(80,Math.max(.5,i))}function ul(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<2}function _l(t){return Number.isFinite(t)?Math.max(1,Math.min(100,t)):1}function ml(t,e){return!Number.isFinite(t)||t<0?"":String(e?Math.round(t/2.54*100)/100:Math.round(100*t)/100)}function gl(t,e,i){if(!Number.isFinite(t)||t<=0)return 0;const s=Number(e)>0?Number(e):5;return _l(t)/s*i}function fl(t,e){return e>0&&Number.isFinite(t)?Math.round(t/e)*e:t}function vl(t){return Math.max(1e-6*Math.abs(t),1e-9)}function yl(t,e){if(!(e>0&&Number.isFinite(t)))return t;const i=fl(t,e);return Math.abs(i-t)<=vl(e)?i:t}function bl(t,e){let i=e[0]-t[0],s=e[1]-t[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function wl(t,e,i){const s=[yl(t[0],i),yl(t[1],i)],n=[yl(e[0],i),yl(e[1],i)],o=fl((s[0]+n[0])/2,i),a=fl((s[1]+n[1])/2,i),[r,l]=bl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function kl(t,e,i,s){return 1===s?wl(t,e,i):wl([t[0]/s,t[1]/s],[e[0]/s,e[1]/s],i)}function xl(t,e){if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return null;const i=[Number(t.a[0]),Number(t.a[1]),Number(t.b[0]),Number(t.b[1])];if(!i.every(Number.isFinite))return null;const s=e>0?e:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function $l(t,e,i,s,n){const o=n>0?n:1;return{key:kl(t,e,s,o),cm:_l(i),a:[t[0]/o,t[1]/o],b:[e[0]/o,e[1]/o]}}function Sl(t,e){const i=e>0?e:1,s=[];for(const e of t){const t=e.key.lastIndexOf("@");if(t<0)continue;const[n,o]=e.key.slice(0,t).split(",").map(Number),a=Number(e.key.slice(t+1));[n,o,a].every(Number.isFinite)&&s.push({w:e,x:n*i,y:o*i,ang:a})}return s}function Ml(t,e){const[i,s]=bl(t,e);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Cl(t,e){let i=Math.abs(t-e);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Dl(t,e,i,s,n=1){if(!t?.length)return null;const o=kl(e,i,s,n),a=t.find(t=>t.key===o);if(a)return a;const r=n>0?n:1,l=vl(s)*r,c=(t,e)=>Math.abs(t[0]-e[0])<=l&&Math.abs(t[1]-e[1])<=l;for(const s of t){const t=xl(s,r);if(t&&(c(t[0],e)&&c(t[1],i)||c(t[0],i)&&c(t[1],e)))return s}const h=(e[0]+i[0])/2,d=(e[1]+i[1])/2,p=Ml(e,i),u=Math.max(.5*s,1e-9)*r;for(const e of Sl(t,r))if(Cl(e.ang,p)&&Math.hypot(e.x-h,e.y-d)<=u)return e.w;return null}function Pl(t,e,i,s,n=1){const o=Dl(t,e,i,s,n);if(o&&o.cm>0)return _l(o.cm);const a=function(t,e,i,s,n){if(!t?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-e[0],i[1]-e[1]);if(a<1e-12)return null;const r=Ml(e,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of t){if(!(s.cm>0))continue;const t=xl(s,o);if(!t)continue;const n=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);if(n<1e-12||!Cl(Ml(t[0],t[1]),r))continue;if(mc(e[0],e[1],t[0][0],t[0][1],t[1][0],t[1][1])>l||mc(i[0],i[1],t[0][0],t[0][1],t[1][0],t[1][1])>l)continue;if(n+l(o.has(t.key)||(t=>{const e=xl(t,s);if(!e)return!1;const[i,o]=e,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];return Cl(Ml(i,o),Ml(e,s))&&mc(i[0],i[1],e[0],e[1],s[0],s[1])<=l&&mc(o[0],o[1],e[0],e[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];if(!Cl(Ml(i,o),Ml(e,s)))return!1;const n=t=>Math.abs((t[0]-i[0])*c-(t[1]-i[1])*r)/h;if(n(e)>l||n(s)>l)return!1;const a=h*h,d=((e[0]-i[0])*r+(e[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(t))&&t.cm>=1&&t.cm<=100)}function Rl(t,e,i,s=8){const[n,o]=bl(t,e);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Il(t,e,i,s,n=1,o="affine",a){if(!t?.length)return[];if(e.length!==i.length)return"fixed-topology"===o&&a?.(),t.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(t,e,i)=>{const s=t.get(e)||new Set;s.add(i),t.set(e,s)};for(let t=0;t[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],m=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=c,g=(t,e)=>{if("fixed-topology"===o){const i=e.na[0]-e.oa[0],s=e.na[1]-e.oa[1],n=e.nb[0]-e.ob[0],o=e.nb[1]-e.ob[1];return Math.hypot(i-n,s-o)<=c?[t[0]+i,t[1]+s]:m(t,e.oa)?[...e.na]:m(t,e.ob)?[...e.nb]:[...t]}const i=Math.max(0,Math.min(1,((t[0]-e.oa[0])*e.dx+(t[1]-e.oa[1])*e.dy)/e.len2));return _(e.na,e.nb,i)},f=(t,e)=>{const[i,s]=bl(t,e);return(e[0]-t[0])*i+(e[1]-t[1])*s>=0?[[...t],[...e]]:[[...e],[...t]]},v=[],y=[],b=(t,e,i)=>{if(Math.hypot(e[0]-t[0],e[1]-t[1])<=c)return;const[n,o]=f(t,e),a=_l(i);if(y.some(t=>t.entry.cm===a&&m(t.span[0],n)&&m(t.span[1],o)))return;const l=$l(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const e of t){const t=xl(e,r);if(t){const[i,s]=f(t[0],t[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...e,cm:_l(e.cm)});continue}const p=[];for(const t of h){if(!Cl(Ml(i,s),Ml(t.oa,t.ob)))continue;const e=t=>Math.abs((t[0]-i[0])*a-(t[1]-i[1])*n)/d;if(e(t.oa)>l||e(t.ob)>l)continue;const o=((t.oa[0]-i[0])*n+(t.oa[1]-i[1])*a)/r,h=((t.ob[0]-i[0])*n+(t.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:t})}if(!p.length){"fixed-topology"===o?v.push({...e}):b(i,s,e.cm);continue}const u=[0,1,...p.flatMap(({lo:t,hi:e})=>[t,e])].sort((t,e)=>t-e).filter((t,e,i)=>0===e||Math.abs(t-i[e-1])*d>c),y=[];for(let t=0;t+1r>=t.lo-1e-12&&r<=t.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(t=>{const e=g(o,t.move),i=g(a,t.move);return!m(h[0],e)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(t,e)=>{const i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],n=e[1][0]-e[0][0],o=e[1][1]-e[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const t of y){const e=k[k.length-1];e&&m(e[1],t[0])&&w(e,t)?e[1]=t[1]:k.push([[...t[0]],[...t[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,t[0])&&m(s,t[1])||m(i,t[1])&&m(s,t[0])){v.push({...e});continue}}for(const[t,i]of k)b(t,i,e.cm);continue}if("fixed-topology"===o){const t=p.get(e.key);if(1===t?.size){const i=[...t][0];v.push(i===e.key?{...e}:{...e,key:i});continue}const i=[Sl([e],r)[0]];1!==r&&i.push(Sl([e],1)[0]);const s=i.filter(Boolean).some(t=>h.some(e=>{if(!Cl(t.ang,Ml(e.oa,e.ob)))return!1;const i=((t.x-e.oa[0])*e.dx+(t.y-e.oa[1])*e.dy)/e.len2;return i>=-1e-6&&i<=1.000001&&mc(t.x,t.y,e.oa[0],e.oa[1],e.ob[0],e.ob[1])<=l}));((t?.size||0)>1||s)&&a?.(),v.push({...e});continue}let i="";const n=d.get(e.key);if(1===n?.size&&(i=[...n][0]),!i){const t=Sl([e],r)[0];if(t){const e=new Set;for(const i of h){if(!Cl(t.ang,Ml(i.oa,i.ob)))continue;const n=((t.x-i.oa[0])*i.dx+(t.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(mc(t.x,t.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([t.x,t.y],i),[a,c]=bl(i.na,i.nb),h=Math.max(s*r,1e-6);e.add(kl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===e.size&&(i=[...e][0])}}v.push({...e,key:i||e.key,cm:_l(e.cm)})}return v}function Al(t,e,i,s,n=1,o="affine"){return Il(t,e,i,s,n,o)}function zl(t,e,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Ur,1e-9),l=(n||[]).flatMap(t=>{const e=xl(t,o);return e?e.map(t=>[...t]):[]}),c=t=>t.every((t,e)=>(t=>{if(!(a>0))return!0;const e=t/o/a;return Math.abs(e-Math.round(e))Math.abs(t-i[e])<=r)),h=[],d=t=>JSON.stringify([t.key,t.cm,t.a,t.b]);for(const i of t||[]){const t=xl(i,o);if(!t)continue;const[s,n]=t;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const t of e){const[e,i]=t;if(![e?.[0],e?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=t=>Math.abs((t[0]-s[0])*_-(t[1]-s[1])*u);if(n(e)>r||n(i)>r)continue;const o=(e[0]-s[0])*u+(e[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let g=0;for(const[t,e]of m){if(t>g+r)break;if(g=Math.max(g,e),g>=p-r)break}gt.key!==a);return null==s||s<1?r:[...r,$l(e,i,s,n,o)]}function El(t,e,i,s,n,o=[],a=1){let r=t?t.slice():[];for(const t of function(t,e,i,s,n=1,o=[]){const a=ec(t,e,i,s,n,o);if(!a)return[];const r=[];for(let t=0;t0||(c=Fl(c,e,i,s,n,a)))}return c}function Ol(t){const{a:e,b:i,halfDepth:s}=t;if(!Array.isArray(e)||!Array.isArray(i)||e.length<2||i.length<2||![e[0],e[1],i[0],i[1]].every(Number.isFinite))return null;const n=i[0]-e[0],o=i[1]-e[1],a=Math.hypot(n,o);if(!(a>1e-9&&s>0&&Number.isFinite(s)))return null;const r=-o/a*s,l=n/a*s;return[[e[0]+r,e[1]+l],[i[0]+r,i[1]+l],[i[0]-r,i[1]-l],[e[0]-r,e[1]-l]]}function Ll(t,e,i){return Math.hypot(t[0]-e[0],t[1]-e[1])<=i}function Hl(t,e,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=s*s+n*n;if(!(o>i*i))return!1;const a=((t[0]-e.a[0])*s+(t[1]-e.a[1])*n)/o;if(!(a>0&&a<1))return!1;const r=[e.a[0]+s*a,e.a[1]+n*a];return Math.hypot(t[0]-r[0],t[1]-r[1])<=i}function Bl(t,e,i,s){const n=Math.hypot(e,i);if(!(n>1e-9&&s>0))return;const o=[e/n,i/n],a=t.find(t=>Math.abs(t.u[0]*o[1]-t.u[1]*o[0])<1e-9&&t.u[0]*o[0]+t.u[1]*o[1]>1-1e-9);a?a.halfDepth=Math.max(a.halfDepth,s):t.push({u:o,halfDepth:s})}function ql(t,e){try{const i=oi(vc(t),vc(e));let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Kl(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function Wl(t,e=1e-6){const i=(t||[]).map((t,e)=>({segment:t,index:e})).filter(({segment:t})=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(({segment:t})=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[];for(const t of o){const e=[];let n=!1;for(const{segment:o,index:a}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Ll(t,o.a,s)?e.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Ll(t,o.b,s)?e.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Hl(t,o,s)&&(n=!0)}if(n||2!==e.length)continue;const[o,r]=e,l=o.u[0]*r.u[1]-o.u[1]*r.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-r.u[1],r.u[0]],p=[t[0]+h[0]*o.halfDepth*c,t[1]+h[1]*o.halfDepth*c],u=[t[0]-d[0]*r.halfDepth*c,t[1]-d[1]*r.halfDepth*c];if(!Xl(p,o.u,u,r.u))continue;const _=[[o,r,u,[d[0]*-c,d[1]*-c]],[r,o,p,[h[0]*c,h[1]*c]]];for(const[e,,i,n]of _){const o=Math.min(2*e.halfDepth,e.length),r=[-e.u[1]*e.halfDepth,e.u[0]*e.halfDepth],l=[[t[0]+r[0],t[1]+r[1]],[t[0]+e.u[0]*o+r[0],t[1]+e.u[1]*o+r[1]],[t[0]+e.u[0]*o-r[0],t[1]+e.u[1]*o-r[1]],[t[0]-r[0],t[1]-r[1]]],c=t=>(t[0]-i[0])*n[0]+(t[1]-i[1])*n[1],h=[];for(let t=0;t=-1e-12&&h.push(e),s>1e-12&&n<-1e-12||s<-1e-12&&n>1e-12){const t=s/(s-n);h.push([e[0]+(i[0]-e[0])*t,e[1]+(i[1]-e[1])*t])}}h.length>=3&&Math.abs(Kl(h))>s*s&&a.push({segmentIndex:e.index,wedge:h})}}return a}function jl(t,e=1e-6){const i=(t||[]).filter(t=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(t=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[],r=i.map((t,e)=>({roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`join-${e}`,kind:"outer",cm:0,open:!1,half:t.halfDepth})),l=ac(r,s);for(const t of rc(l).fans)a.push(t);const c=t=>!!lc(l,t);for(const t of o){if(c(t))continue;const e=[];for(const n of i)Ll(t,n.a,s)?Bl(e,n.b[0]-n.a[0],n.b[1]-n.a[1],n.halfDepth):Ll(t,n.b,s)?Bl(e,n.a[0]-n.b[0],n.a[1]-n.b[1],n.halfDepth):Hl(t,n,s)&&(Bl(e,n.a[0]-t[0],n.a[1]-t[1],n.halfDepth),Bl(e,n.b[0]-t[0],n.b[1]-t[1],n.halfDepth));if(!(e.length<2)){e.sort((t,e)=>Math.atan2(t.u[1],t.u[0])-Math.atan2(e.u[1],e.u[0])||t.halfDepth-e.halfDepth);for(let i=0;is*s&&a.push(m)}}}return a}function Ul(t,e,i,s){if(!(e>0)||!t||t.length<2)return"";if(i&&t.length>=3){let i=t;const n=t[t.length-1];if(t.length>=4&&Math.hypot(t[0][0]-n[0],t[0][1]-n[1])<1e-9&&(i=t.slice(0,-1)),i.length>=3){const t=i.map((t,i)=>s?.[i]||e),n=Fc(i,t),o=Zl(i,t);if(n&&o)return`${Ql(n)} ${Ql(tc(o))}`}}const n=[];for(let i=0;i=1e-9&&r>0&&n.push({a:o,b:a,halfDepth:r})}const o=n.map(Ol);for(const{segmentIndex:t,wedge:e}of Wl(n)){const i=o[t];if(!i)continue;const s=ql(i,e);s&&(o[t]=s)}const a=[...o.filter(t=>!!t),...jl(n)],r=function(t){let e=null;try{for(const i of t){if(i.length<3)continue;const t=vc(i);e=e?si(e,t):[t]}return e}catch{return null}}(a);return r?Tc(r):a.map(t=>Ql(t)).join(" ")}function Gl(t,e,i,s,n=1){if(!i.length)return!1;const o=Vl(s,n),a=(t[0]+e[0])/2,r=(t[1]+e[1])/2,[l,c]=bl(t,e);for(const t of i){const[e,i]=bl([t[0],t[1]],[t[2],t[3]]);if(!(Math.abs(l*i-c*e)>.05)&&mc(a,r,t[0],t[1],t[2],t[3])<=o)return!0}return!1}function Vl(t,e){return Math.max(t*(e>0?e:1)*.04,1e-9)}function Kl(t){let e=0;for(let i=0;it[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a+0)+o&&(i=!i)}return i}([c[0]+.001*r,c[1]+.001*l],t)||(r=-r,l=-l),[r,l]}function Jl(t,e){const i=t[0]*e[1]-t[1]*e[0],s=t[0]*e[0]+t[1]*e[1];return Math.abs(i)<1e-9&&s>0}function Xl(t,e,i,s){const n=e[0]*s[1]-e[1]*s[0];if(Math.abs(n)<1e-12)return null;const o=[i[0]-t[0],i[1]-t[1]],a=(o[0]*s[1]-o[1]*s[0])/n;return[t[0]+a*e[0],t[1]+a*e[1]]}function Zl(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);const n=[];for(let o=0;o0||p>0)){n.push([t[o][0],t[o][1]]);continue}if(d>0!=p>0){const e=t[o],i=d>0?[e[0]+u*d,e[1]+_*d]:[e[0],e[1]],s=p>0?[e[0]+m*p,e[1]+g*p]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]+u*d,e[1]+_*d],s=[e[0]+m*p,e[1]+g*p];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(d,p,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}d>0&&n.push([t[o][0]+u*d,t[o][1]+_*d]),p>0&&n.push([t[o][0]+m*p,t[o][1]+g*p]),d>0||p>0||n.push([t[o][0],t[o][1]])}return n.length>=3?n:null}function Ql(t,e=!0){if(!t.length)return"";let i=`M ${t[0][0]} ${t[0][1]}`;for(let e=1;et?.id===e),r=hi(a);if(!r||r.length<3)return null;const l=Vl(s,n),c=[];for(const i of t||[]){if(!i||i.id===e)continue;const t=hi(i);if(t)for(const e of Cs(r,t,l))c.push([e[0],e[1]],[e[2],e[3]])}for(const t of i||[])c.push([t[0],t[1]],[t[2],t[3]]);for(const t of o||[]){const e=xl(t,n);e&&c.push(e[0],e[1])}const h=[],d=[];for(let t=0;tl)continue;const a=((t[0]-e[0])*(i[0]-e[0])+(t[1]-e[1])*(i[1]-e[1]))/(s*s);a<=n||a>=1-n||(o.some(t=>Math.abs(t-a)*s<=2*l)||o.push(a))}o.sort((t,e)=>t-e);for(const s of o)h.push([e[0]+(i[0]-e[0])*s,e[1]+(i[1]-e[1])*s]),d.push(t)}return{poly:h,parent:d,orig:r}}function ic(t,e,i,s){const n=e.poly.length,o=new Array(n).fill(0);if(!t?.length)return o;const a=new Set,r=[];for(let l=0;l0?(o[l]=_l(c.cm),a.add(c.key)):r.push(l)}if(!r.length)return o;const l=s>0?s:1,c=Math.max(.5*i,1e-9)*l,h=Sl(t,l).filter(t=>t.w.cm>0);for(let t=r.length-1;t>=0;t--){const i=r[t],s=e.poly[i],a=e.poly[(i+1)%n],d=Ml(s,a);let p=null;for(const t of h){const e=xl(t.w,l);if(!e||!Cl(Ml(e[0],e[1]),d))continue;if(mc(s[0],s[1],e[0][0],e[0][1],e[1][0],e[1][1])>c||mc(a[0],a[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;const i=Math.hypot(a[0]-s[0],a[1]-s[1]),n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]),o=Math.max(0,n-i);(!p||oc||mc(n[0],n[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1])-_)}else{if(mc(t.x,t.y,s[0],s[1],n[0],n[1])>c)continue;o=Math.hypot(t.x-d,t.y-p)}(!u||i&&!u.exact||i===u.exact&&o0?i:1,o=(t||[]).filter(t=>t&&!t.open&&null!==t.kind&&Number.isFinite(t.half)&&t.half>0&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&[t.a[0],t.a[1],t.b[0],t.b[1]].every(Number.isFinite)&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>s).sort((t,e)=>t.key.localeCompare(e.key)||t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.b[0]-e.b[0]||t.b[1]-e.b[1]||t.half-e.half),a=new Map;for(const t of o){const e=a.get(t.key);e?t.half>e.half&&a.set(t.key,{...e,half:t.half}):a.set(t.key,t)}const r=[...a.values()].flatMap(t=>[{point:[t.a[0],t.a[1]],other:t.b,halfDepth:t.half,kind:t.kind,key:t.key},{point:[t.b[0],t.b[1]],other:t.a,halfDepth:t.half,kind:t.kind,key:t.key}]).sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]||t.other[0]-e.other[0]||t.other[1]-e.other[1]||t.halfDepth-e.halfDepth),l=new Map;for(const t of r){const[e,i]=sc(t.point,s),n=nc(e,i),o=l.get(n)||[];o.push(t),l.set(n,o)}const c=[],h=new Map;for(const t of r){const e=oc(h,t.point,s).filter(e=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])<=s).sort((e,i)=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])-Math.hypot(i.point[0]-t.point[0],i.point[1]-t.point[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1]);let i=e[0];if(!i){i={point:[...t.point],rays:[]},c.push(i);const[e,n]=sc(i.point,s),o=nc(e,n),a=h.get(o)||[];a.push(i),h.set(o,a)}const n=t.other[0]-t.point[0],o=t.other[1]-t.point[1],a=Math.hypot(n,o);if(!(a>s))continue;const r=[n/a,o/a];let l=Math.atan2(r[1],r[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:r,halfDepth:t.halfDepth,length:a,angle:l})}const d=[],p=t=>{const e=1e-9*Math.max(1,n),i=t.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);return i.filter((t,s)=>!i.some((i,n)=>n!==s&&i.halfDepth>=t.halfDepth-e&&i.length>=t.length-e&&(i.halfDepth>t.halfDepth+e||i.length>t.length+e||nt.length-e.length||t.halfDepth-e.halfDepth).map(t=>({...t}))};for(const t of c){const e=t.rays.sort((t,e)=>t.angle-e.angle||t.length-e.length||t.halfDepth-e.halfDepth),i=[];for(const t of e){const e=i[i.length-1];e&&Math.abs(t.angle-e.angle)<=1e-9?e.supports.push({halfDepth:t.halfDepth,length:t.length}):i.push({u:[...t.u],angle:t.angle,supports:[{halfDepth:t.halfDepth,length:t.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const t=i.pop();i[0].supports.push(...t.supports)}if(i.length<3)continue;const n=i.map(e=>{const i=p(e.supports),n=new Set,o=[];for(const a of i){const i=[t.point[0]+e.u[0]*a.length,t.point[1]+e.u[1]*a.length];for(const e of oc(l,i,s)){if("shared"!==e.kind||Math.hypot(e.point[0]-i[0],e.point[1]-i[1])>s)continue;const a=e.other[0]-e.point[0],r=e.other[1]-e.point[1],l=Math.hypot(a,r);if(!(l>s))continue;const c=a/l,h=r/l;if(Math.hypot(e.other[0]-t.point[0],e.other[1]-t.point[1])<=s)continue;const d=`${e.key}|${e.point[0]}|${e.point[1]}|${e.other[0]}|${e.other[1]}|${e.halfDepth}`;n.has(d)||(n.add(d),o.push({start:[e.point[0],e.point[1]],u:[c,h],length:l,halfDepth:e.halfDepth}))}}return o.sort((t,e)=>t.start[0]-e.start[0]||t.start[1]-e.start[1]||t.u[0]-e.u[0]||t.u[1]-e.u[1]||t.length-e.length||t.halfDepth-e.halfDepth),{u:[...e.u],halfDepth:Math.max(...i.map(t=>t.halfDepth)),length:Math.max(...i.map(t=>t.length)),supports:i,continuations:o}}).filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);if(n.length<3)continue;const o=Math.max(...n.map(t=>t.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...t.point],rays:n,halfDepth:o,limit:1.25*o})}d.sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]);const u=new Map;for(const t of d){const[e,i]=sc(t.point,s),n=nc(e,i),o=u.get(n)||[];o.push(t),u.set(n,o)}return{epsilon:s,coordinateScale:n,nodes:d,index:u}}function rc(t){const e={fans:[],supports:[]};if(!t?.nodes?.length)return e;const i=Math.max(t.epsilon,1e-9)**2;for(const s of t.nodes){const t=s.rays.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0).map(t=>({...t,thickLength:Math.max(...t.supports.filter(e=>e.halfDepth>=t.halfDepth-1e-12).map(t=>t.length),0),angle:(()=>{const e=Math.atan2(t.u[1],t.u[0]);return e<0?e+2*Math.PI:e})()})).sort((t,e)=>t.angle-e.angle);if(t.length<2)continue;const n=s.point;for(const i of t)for(const t of i.supports){if(!(t.halfDepth>0&&t.length>0))continue;const s=-i.u[1]*t.halfDepth,o=i.u[0]*t.halfDepth,a=[n[0]+i.u[0]*t.length,n[1]+i.u[1]*t.length];e.supports.push([[n[0]+s,n[1]+o],[a[0]+s,a[1]+o],[a[0]-s,a[1]-o],[n[0]-s,n[1]-o]])}for(let s=0;s{const t=a.angle-o.angle;return t>0?t:t+2*Math.PI})();if(r<1e-9)continue;const l=r>Math.PI+1e-9,c=4*Math.max(o.halfDepth,a.halfDepth),h=[n[0]-o.u[1]*o.halfDepth,n[1]+o.u[0]*o.halfDepth],d=[n[0]+a.u[1]*a.halfDepth,n[1]-a.u[0]*a.halfDepth],p=o.u[0]*a.u[1]-o.u[1]*a.u[0],u=t=>{let e=Math.atan2(t[1]-n[1],t[0]-n[0])-o.angle;for(;e<0;)e+=2*Math.PI;return e<=r+1e-9};let _=null;if(Math.abs(p)>1e-9){const t=((d[0]-h[0])*a.u[1]-(d[1]-h[1])*a.u[0])/p,e=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/p,i=[h[0]+o.u[0]*t,h[1]+o.u[1]*t];(l?t<=1e-9&&e<=1e-9:t>1e-9&&t<=o.thickLength&&e<=a.thickLength)&&Math.hypot(i[0]-n[0],i[1]-n[1])<=c&&u(i)&&(_=i)}const m=t=>{Math.abs(Kl(t))>i&&e.fans.push(t)};if(_){const t=1.5*Math.max(o.halfDepth,a.halfDepth);m(cl([n[0],n[1]],h,_,d,t)??[[n[0],n[1]],h,_,d]);continue}if(l){m([[n[0],n[1]],h,d]);continue}const g=(t,e)=>Math.min(e,Math.sqrt(Math.max(c**2-t**2,0)),2*Math.max(o.halfDepth,a.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+a.u[0]*g(a.halfDepth,a.thickLength),d[1]+a.u[1]*g(a.halfDepth,a.thickLength)];m([[n[0],n[1]],h,f,v,d])}}return e}function lc(t,e){return!t||!Array.isArray(e)||e.length<2||!e.slice(0,2).every(Number.isFinite)?null:oc(t.index,e,t.epsilon).filter(i=>Math.hypot(i.point[0]-e[0],i.point[1]-e[1])<=t.epsilon).sort((t,i)=>Math.hypot(t.point[0]-e[0],t.point[1]-e[1])-Math.hypot(i.point[0]-e[0],i.point[1]-e[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1])[0]||null}function cc(t,e,i,s,n,o,a){return ac(dc(t,e,i,s,n,o,a),4*Vl(s,a),a)}function hc(t,e,i,s,n,o,a,r=1){const l=ec(t,e,s,n,r,i);if(!l)return null;const c=function(t,e,i){const s=(t||[]).find(t=>t?.id===e),n=hi(s);if(!n)return[];const o=[];for(const s of t||[]){if(!s||s.id===e)continue;const t=hi(s);if(t)for(const e of Cs(n,t,i))o.push(e)}return o}(t,e,Vl(n,r)),h=function(t,e,i,s,n){const o=Vl(s,n),a=[];for(let r=0;rmc(h,d,t[0],t[1],t[2],t[3])<=o);a.push(p?"shared":"outer")}return a}(l.poly,c,s,n,r),d=ic(i,l,n,r),p=d.map((t,e)=>h[e]&&t>0?gl(t,o,a)/2:0);return{...l,kinds:h,cms:d,offsets:p}}function dc(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(c)for(let t=0;t0&&(r=Fl(r,t.a,t.b,t.cm,s,a));return r}function uc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=dc(t,e,i,s,n,o,a),l=new Map;for(const t of r){if(t.open||!t.kind||!t.roomId)continue;const e=l.get(t.key)||new Set;e.add(t.roomId),l.set(t.key,e)}const c=t=>{const e=[...l.get(t)||[]].sort();return 1!==e.length&&2!==e.length?`ambiguous:${t}`:`${1===e.length?"outer":"shared"}:${e.join("|")}`},h=[],d=new Set;for(const t of r)!t.open&&t.cm>0&&!d.has(t.key)&&(d.add(t.key),h.push({...t,ownerSignature:c(t.key)}));const p=[];for(const r of t||[]){if(!r?.id)continue;const l=hc(t,r.id,e,i,s,n,o,a);if(l)for(let t=0;t0)||null===l.kinds[i]){t++;continue}const o=c(kl(l.poly[i],l.poly[(i+1)%l.poly.length],s,a));let r=t;for(;r+10&&p.push({a:[d[0],d[1]],b:[u[0],u[1]],key:kl(d,u,s,a),cm:n,len:_,ownerSignature:o}),t=r+1}}}p.sort((t,e)=>e.len-t.len||t.key.localeCompare(e.key));const u=[],_=new Set,m=new Set,g=4*Vl(s,a);for(const t of p){const e=h.filter(e=>!m.has(e.key)&&e.cm===t.cm&&e.ownerSignature===t.ownerSignature&&Cl(Ml(e.a,e.b),Ml(t.a,t.b))&&mc(e.a[0],e.a[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g&&mc(e.b[0],e.b[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g);if(e.length){for(const t of e)m.add(t.key);_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)))}}for(const t of h)m.has(t.key)||_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)));return u}function _c(t,e,i,s,n,o,a,r=1){const l=Vl(n,r),c=(s[0]+s[2])/2,h=(s[1]+s[3])/2,d=Ml([s[0],s[1]],[s[2],s[3]]);let p=null;for(const s of dc(t,e,i,n,o,a,r)){if(!Cl(Ml(s.a,s.b),d))continue;const t=mc(c,h,s.a[0],s.a[1],s.b[0],s.b[1]);t>4*l||(!p||t[t[0],t[1]]),o=Math.abs(Kl(n));n.length>=3&&o>i&&(e=n,i=o)}return e}function fc(t,e,i,s,n,o,a,r=1,l,c){const h=(t||[]).find(t=>t?.id===e),d=hi(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(t=>[t[0],t[1]]);const p=hc(t,e,i,s,n,o,a,r);if(!p||!p.offsets.some(t=>t>0))return d.map(t=>[t[0],t[1]]);const u=c||cc(t,i,s,n,o,a,r),_=Zl(p.poly,p.offsets,u);if(!_)return d.map(t=>[t[0],t[1]]);if(!u.nodes.length)return _;const m=void 0===l?Rc(t,i,s,[],n,o,a,r):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const t=gc(oi(vc(p.poly),g));if(t)return t}catch{}return function(t,e){try{return gc(ni(vc(t),vc(e)))}catch{return null}}(_,p.poly)||d.map(t=>[t[0],t[1]])}function vc(t){const e=t.map(t=>[t[0],t[1]]);return e.push([t[0][0],t[0][1]]),[e]}function yc(t){return!(!Array.isArray(t)||!t.length)&&t.every(t=>Array.isArray(t)&&t.length&&t.every(t=>Array.isArray(t)&&t.length>=4&&t.every(t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])))&&Math.abs(Ti(t[0]))>1e-9)}function bc(t,e,i,s){const n=s?new Set(s):null;let o=null;for(let s=0;se.epsilon))continue;const l=Sc([[t.point[0]+r[0]*s.halfDepth,t.point[1]+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n+r[0]*s.halfDepth,t.point[1]+a.u[1]*n+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n-r[0]*s.halfDepth,t.point[1]+a.u[1]*n-r[1]*s.halfDepth],[t.point[0]-r[0]*s.halfDepth,t.point[1]-r[1]*s.halfDepth]],e.coordinateScale);if(!l)continue;const c=vc(l);o=o?si(o,c):c}}return o}function wc(t,e,i){let s=null;for(const n of t.rays)for(const t of n.continuations){const n=[-t.u[1],t.u[0]],o=[t.start[0]+t.u[0]*t.length,t.start[1]+t.u[1]*t.length],a=Sc([[t.start[0]+n[0]*t.halfDepth,t.start[1]+n[1]*t.halfDepth],[o[0]+n[0]*t.halfDepth,o[1]+n[1]*t.halfDepth],[o[0]-n[0]*t.halfDepth,o[1]-n[1]*t.halfDepth],[t.start[0]-n[0]*t.halfDepth,t.start[1]-n[1]*t.halfDepth]],e.coordinateScale);if(!a)continue;const r=ni(vc(a),i);Array.isArray(r)&&0!==r.length&&(s=s?si(s,r):r)}return s}function kc(t,e,i=2*(4*t.halfDepth+2*e.epsilon)){const s=function(t,e=hl){const i=new Set,s=Number.isFinite(e)&&e>=0?e:hl;for(let e=0;et-e)}(t);return s.length?bc(t,e,i,s):null}function xc(t,e,i,s,n){const o=function(t){let e=null;for(const i of t){const t=vc(i);try{e=e?si(e,t):t}catch{}}return e}(function(t,e,i=!1){if(!t)return[];const s=[];for(const n of t.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-a.u[1],a.u[0]],p=[-r.u[1],r.u[0]],u=[n.point[0]+d[0]*a.halfDepth,n.point[1]+d[1]*a.halfDepth],_=[n.point[0]-p[0]*r.halfDepth,n.point[1]-p[1]*r.halfDepth],m=Xl(u,a.u,_,r.u);if(!m)continue;const g=Math.hypot(m[0]-n.point[0],m[1]-n.point[1]);if(!Number.isFinite(g)||g<=n.limit)continue;const f=e?Math.sqrt(Math.max(0,n.limit*n.limit-a.halfDepth*a.halfDepth)):0,v=e?Math.sqrt(Math.max(0,n.limit*n.limit-r.halfDepth*r.halfDepth)):0,y=Sc([[u[0]+a.u[0]*f,u[1]+a.u[1]*f],[_[0]+r.u[0]*v,_[1]+r.u[1]*v],m],t.coordinateScale);if(y&&s.push(y),i){const e=m[0]-n.point[0],i=m[1]-n.point[1],o=Math.hypot(e,i),a=g-n.limit;if(o>t.epsilon&&a>t.epsilon){const r=Math.min(Math.max(8*t.epsilon,.05*n.halfDepth),.25*a),l=e/o,c=i/o,h=-c,d=l,p=Sc([[m[0]-l*r+h*r,m[1]-c*r+d*r],[m[0]-l*r-h*r,m[1]-c*r-d*r],[m[0]+l*r,m[1]+c*r]],t.coordinateScale);p&&s.push(p)}}}return s}({...e,nodes:[t]},i,s));return o&&n?oi(o,n):o}function $c(t,e,i,s){if(!t||!e.nodes.length)return t;let n=null;try{n=function(t){let e=null;for(const i of t.nodes){const s=kc(i,t);s&&(e=e?si(e,s):s)}return e}(e)}catch{return t}let o=t;for(const t of e.nodes){const a=4*t.halfDepth+2*e.epsilon,r=2*a,l=[[t.point[0]-a,t.point[1]-a],[t.point[0]+a,t.point[1]-a],[t.point[0]+a,t.point[1]+a],[t.point[0]-a,t.point[1]+a]];try{let a=o;const c=xc(t,e,!1,!0,n);c&&(a=oi(a,c));let h=bc(t,e,r);const d=xc(t,e,!0,!0,n);d&&(h=oi(h,d)),n&&(h=si(h,n));const p=.02*Math.min(...t.rays.map(t=>t.halfDepth));if(h=si(h,vc([[t.point[0]-p,t.point[1]-p],[t.point[0]+p,t.point[1]-p],[t.point[0]+p,t.point[1]+p],[t.point[0]-p,t.point[1]+p]])),!h)continue;let u=ni(h,vc(l));s?u=ni(u,s):i&&(u=ni(u,i));const _=vc(l),m=oi(a,_),g=i?oi(ni(a,_),i):null,f=wc(t,e,_);o=si(m,...g?[g]:[],...f?[f]:[],u)}catch{}}if(n)try{let t=n;s?t=ni(t,s):i&&(t=ni(t,i)),o=si(o,t)}catch{}return o}function Sc(t,e=1){if(!Array.isArray(t)||t.length<3)return null;const i=Number.isFinite(e)&&e>0?e:1,s=1e-12*Math.max(1,i),n=[];for(const e of t){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),i=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(i))return null;const o=Math.round(t/s)*s,a=Math.round(i/s)*s;if(!Number.isFinite(o)||!Number.isFinite(a))return null;n.push([Object.is(o,-0)?0:o,Object.is(a,-0)?0:a])}return Math.abs(Kl(n))>s*s?n:null}function Mc(t,e,i,s){if(mc(t[0],t[1],e[0],e[1],i[0],i[1])>s)return!1;const n=i[0]-e[0],o=i[1]-e[1],a=(t[0]-e[0])*n+(t[1]-e[1])*o,r=n*n+o*o,l=s*Math.sqrt(r);return a>=-l&&a<=r+l}function Cc(t,e,i){const s=[],n=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),p=[0,1];for(const t of e)for(const e of[t.a,t.b]){if(!Mc(e,a,r,i))continue;const t=((e[0]-a[0])*l+(e[1]-a[1])*c)/h;t>d&&t<1-d&&p.push(t)}p.sort((t,e)=>t-e);const u=p.filter((t,e)=>0===e||Math.abs(t-p[e-1])>d);for(let t=0;t=3&&n.length===s.length?{poly:s,offsets:n}:null}function Dc(t,e,i,s,n,o,a,r){const l=(t||[]).map(hi).filter(t=>!!t&&t.length>=3);if(!l.length)return null;let c=si(vc(l[0]));for(let t=1;t"outer"===t.kind&&t.half>0),p=4*Vl(s,a),u=r||ac(h,p,a);let _=null;for(const t of function(t){const e=[];for(const i of Array.isArray(t)?t:[])if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,-1).map(t=>[t[0],t[1]]);i.length>=3&&e.push(i)}return e}(c)){const e=Cc(t,d,p);if(!e||!e.offsets.some(t=>t>0))continue;const i=Fc(e.poly,e.offsets,u),s=Zl(e.poly,e.offsets,u);if(!i||!s)continue;const n=oi(vc(i),vc(s));_=_?si(_,n):n}return{centre:c,shell:_||[]}}function Pc(t,e,i,s,n,o,a=1){try{const r=Dc(t,e,i,s,n,o,a,cc(t,e,i,s,n,o,a));if(!r)return[];return r.shell?.length?si(r.centre,r.shell):r.centre}catch{return null}}function Tc(t){if(!t)return"";let e="";for(const i of t)if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,t.length-1);i.length<3||(e+=(e?" ":"")+Ql(i.map(t=>[t[0],t[1]])))}return e}function Rc(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return{status:"not-applicable",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:0,openingIndex:null,multiWallNodes:null,degradedExtraCount:0};const h=[],d=cc(t,e,i,n,o,a,r);let p=0;for(const s of t||[]){if(!s?.id)continue;const l=hc(t,s.id,e,i,n,o,a,r);if(!l||l.poly.length<3||!l.offsets.some(t=>t>0))continue;for(const t of l.offsets)t>0&&(p=Math.max(p,2*t));const c=Fc(l.poly,l.offsets,d),u=Zl(l.poly,l.offsets,d);c&&h.push({outset:c,inset:u})}for(const t of l){const e=t.map(t=>t[0]),i=t.map(t=>t[1]);if(e.length){const s=Math.min(Math.max(...e)-Math.min(...e),Math.max(...i)-Math.min(...i)),n=Math.min(...t.map((e,i)=>{const s=t[(i+1)%t.length];return Math.hypot(s[0]-e[0],s[1]-e[1])}));p=Math.max(p,t.length>16?s:n)}}const u=function(t,e,i,s,n,o,a,r){if(!e?.length||!i?.length)return[];const l=4*Vl(s,a),c=new Map;for(const r of dc(t,e,i,s,n,o,a))!r.open&&r.half>0&&!c.has(r.key)&&c.set(r.key,r);const h=[...c.values()];if(h.length<2)return[];const d=r||ac(h,l),p=[];for(const t of i)for(const e of[[t[0],t[1]],[t[2],t[3]]])p.some(t=>Math.hypot(t[0]-e[0],t[1]-e[1])<=l)||p.push(e);const u=[],_=(t,e)=>{let i=0,s=0;if(Math.hypot(t.a[0]-e[0],t.a[1]-e[1])<=l)i=t.b[0]-t.a[0],s=t.b[1]-t.a[1];else{if(!(Math.hypot(t.b[0]-e[0],t.b[1]-e[1])<=l))return null;i=t.a[0]-t.b[0],s=t.a[1]-t.b[1]}const n=Math.hypot(i,s);return n>l?[i/n,s/n]:null};for(const t of p){const e=h.map(e=>({iv:e,u:_(e,t)})).filter(t=>!!t.u);for(let i=0;i0?[t.slice(),p,m,_]:[t.slice(),_,m,p];else{if(!f)continue;{const e=[-n.u[1],n.u[0]],i=[-o.u[1],o.u[0]],s=a<0?1:-1,r=[t[0]+e[0]*n.iv.half*s,t[1]+e[1]*n.iv.half*s],l=[t[0]-i[0]*o.iv.half*s,t[1]-i[1]*o.iv.half*s];y=a>0?[t.slice(),r,l]:[t.slice(),l,r]}}Math.abs(Kl(y))>l*l&&u.push(y)}}return u}(t,e,i,n,o,a,r,d),_=s.length?Ec(t,e,i,n,o,a,r):null;let m="exterior";try{const v=Dc(t,e,i,n,o,a,r,d);m="paper";const y=v?v.shell?.length?si(v.centre,v.shell):v.centre:[],b=t=>{const e=vc(t.outset);return t.inset?oi(e,vc(t.inset)):e};m="room-rings";let w=null;for(const t of h)try{const e=b(t);w=w?si(w,e):e}catch{}if(m="edge-bodies",v)for(const s of zc(t,e,i,n,o,a,r))try{const t=ni(vc(s.quad),v.centre);w=w?si(w,t):t}catch{}m="junctions",w=function(t,e,i=1,s=si){let n=t;for(const t of e||[]){const e=Sc(t,i);if(e)try{const t=vc(e);n=n?s(n,t):t}catch{}}return n}(w,u,r),m="facade-clip",w&&v&&(w=ni(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const t=si(w,v.shell);if(!yc(t))throw new Error("invalid shell union");w=t}catch{if(!yc(w)||!yc(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const t=t=>t.rays.some(t=>t.supports.some(t=>t.length<2*t.halfDepth)),e=d.nodes.filter(t);if(e.length){w=$c(w,{...d,nodes:e},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const s=rc(d),l=function(t,e,i,s,n,o,a,r){try{const l=Dc(t,e,i,s,n,o,a,{epsilon:r.epsilon,coordinateScale:r.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?si(l.centre,l.shell):l.centre:null}catch{return null}}(t,e,i,n,o,a,r,d);for(const t of s.fans)try{let e=[vc(t)];if(l&&(e=ni(e,l)),!e?.length)continue;w=w?si(w,e):e}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(t=>{if(!Array.isArray(t)||!t.length)return t;const[e,...i]=t;return Math.abs(Kl(e||[]))<=f?null:[e,...i.filter(t=>Math.abs(Kl(t||[]))>f)]}).filter(t=>!!t):g}const $=w||[],S=[...yc($)?[{id:"room-primary",geom:$}]:[],...k.map((t,e)=>({id:`room-isolated-${e}`,geom:t.geom}))];m="openings";for(const t of s){if(!(t.length>0))continue;const e=Lc(_,t,!0);if(!e.negative&&!e.positive)continue;const i=t.angle*Math.PI/180,s=Math.cos(i),o=Math.sin(i),a=-o,l=s,c=t.length/2,h=1.25*Math.max(p,n*r),d=[[t.x-s*c-a*h,t.y-o*c-l*h],[t.x+s*c-a*h,t.y+o*c-l*h],[t.x+s*c+a*h,t.y+o*c+l*h],[t.x-s*c+a*h,t.y-o*c+l*h]];w&&(w=oi(w,vc(d)));for(const t of k)t.geom=oi(t.geom,vc(d))}m="extras";const M=[];let C=0;const D=c.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){C++;continue}const i=[vc(e)];try{const e=D(w,i,t);if(!yc(e))throw new Error("invalid extra union");w=e}catch{C++,yc(i)&&M.push({id:`extra-${t}`,geom:i})}}M.push(...k),M.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const P=w||[];return{status:C||x?"degraded-extra":"ok",geom:P,components:[...yc(P)?[{id:"primary",geom:P}]:[],...M.map((t,e)=>({...t,id:`isolated-${e}`}))],roomGeom:$,roomComponents:S,paperGeom:y,depthUnits:p,openingPadUnits:1.25*Math.max(p,n*r),openingIndex:_,multiWallNodes:d,degradedExtraCount:C+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:p,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ic(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return null;return Ac(Rc(t,e,i,s,n,o,a,r,l,c))}function Ac(t){if("failed-core"===t.status||"not-applicable"===t.status)return null;const e=t.components.map(t=>({id:t.id,d:Tc(t.geom),fillRule:"evenodd"})).filter(t=>!!t.d),i=e[0]?.d||"",s=Tc(t.paperGeom);if(e.length){const n={status:t.status,d:i,paths:e,components:t.components,roomGeom:t.roomGeom,multiWallNodes:t.multiWallNodes,paperD:s,depthUnits:t.depthUnits,fillRule:"evenodd"};return Object.defineProperties(n,{roomComponents:{value:t.roomComponents||[],enumerable:!1},openingIndex:{value:t.openingIndex,enumerable:!1},openingPadUnits:{value:t.openingPadUnits,enumerable:!1}}),n}return null}function zc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=new Set,l=[];for(const c of t||[]){if(!c?.id)continue;const h=hc(t,c.id,e,i,s,n,o,a);if(!h)continue;const d=h.poly;for(let t=0;t0))continue;const u=kl(e,i,s,a);if(r.has(u))continue;r.add(u);const _=gl(p,n,o),[m,g]=Yl(d,t),f=-m,v=-g,y=_/2,b=[[e[0]+f*y,e[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[e[0]+m*y,e[1]+g*y]];l.push({key:u,kind:c,cm:p,quad:b,a:[e[0],e[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Fc(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);tc(t),e.slice().reverse();const n=[];for(let o=0;o0||l>0)){n.push([t[o][0],t[o][1]]);continue}if(r>0!=l>0){const e=t[o],i=r>0?[e[0]-c*r,e[1]-h*r]:[e[0],e[1]],s=l>0?[e[0]-d*l,e[1]-p*l]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]-c*r,e[1]-h*r],s=[e[0]-d*l,e[1]-p*l];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(r,l,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}r>0&&n.push([t[o][0]-c*r,t[o][1]-h*r]),l>0&&n.push([t[o][0]-d*l,t[o][1]-p*l])}return n.length>=3?n:null}function Ec(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(!c)continue;const h=Math.abs(Ti(c.poly));for(let t=0;t[Math.max(e,t.x0),Math.min(i,t.x1)]).filter(t=>t[1]-t[0]>s).sort((t,e)=>t[0]-e[0]||t[1]-e[1]);if(!n.length)return{coverage:0,full:!1};let o=n[0][0],a=n[0][1],r=0,l=o<=e+s;for(let t=1;t=i-s,{coverage:r,full:l}}function Oc(t,e){return Number(e.full)-Number(t.full)||t.faceDistance-e.faceDistance||t.area-e.area||t.roomId.localeCompare(e.roomId)}function Lc(t,e,i=!1){const s=Number(e?.x),n=Number(e?.y),o=Number(e?.angle),a=Number(e?.length);if(!([s,n,o,a].every(Number.isFinite)&&a>0))return{negative:null,positive:null};const r=o*Math.PI/180,l=Math.cos(r),c=Math.sin(r),h=-c,d=l,p=a/2,u=Math.max(1e-9,t.adjacencyEps),_=new Map;let m=0;for(const e of t.edges){if(i&&!(e.half>0))continue;if(!Rl(e.a,e.b,o))continue;const[t,a]=bl(e.a,e.b);if(Math.abs((s-e.a[0])*a-(n-e.a[1])*t)>u)continue;const r=(e.a[0]-s)*l+(e.a[1]-n)*c,g=(e.b[0]-s)*l+(e.b[1]-n)*c,f=Math.max(-p,Math.min(r,g)),v=Math.min(p,Math.max(r,g));if(v-f<=u)continue;const y=e.inward[0]*h+e.inward[1]*d>=0?1:-1,b=((e.a[0]+e.b[0])/2-s)*h+((e.a[1]+e.b[1])/2-n)*d,w=Math.abs(b+y*e.half),k=`${y}|${e.roomId}`,x={x0:f,x1:v,half:e.half,cm:e.cm,key:e.key,axis:[t,a]},$=_.get(k);$?($.pieces.push(x),$.faceDistance=Math.min($.faceDistance,w)):_.set(k,{roomId:e.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:e.area,coverage:0,full:!1})}for(const t of _.values()){const e=Nc(t.pieces,-p,p,u);t.coverage=e.coverage,t.full=e.full}const g=t=>{const e=[..._.values()].filter(e=>e.side===t&&e.coverage>u);return e.sort(Oc),e[0]||null};return{negative:g(-1),positive:g(1)}}function Hc(t,e){const i=Lc(t,e),s=[i.negative,i.positive].filter(t=>!!t);if(!s.length)return{ox:0,oy:0,cm:0,side:-1};const n=i.negative&&i.positive?-1:s[0].side,o=e.flip_v?-n:n,a=(-1===o?i.negative:i.positive)||s[0],r=[...a.pieces].sort((t,e)=>(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))-(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))||e.x1-e.x0-(t.x1-t.x0)||t.key.localeCompare(e.key))[0];if(!(r.half>0&&r.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=e.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*r.half,oy:h*o*r.half,cm:r.cm,side:o}}function Bc(t,e){const i=1e-9,s=e.filter(t=>Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&Number.isFinite(t.half)&&t.x1>t.x0&&t.half>0);if(!s.length)return"";const n=s.flatMap(t=>[t.x0,t.x1]).sort((t,e)=>t-e),o=[];for(const t of n){const e=o[o.length-1];(void 0===e||t>e+i)&&o.push(t)}const a=[];for(let t=0;t+1e+i))continue;const r=(e+n)/2,l=s.reduce((t,e)=>r>=e.x0-i&&r<=e.x1+i?Math.max(t,e.half):t,0);if(!(l>0))continue;const c=a[a.length-1];c&&e<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=n:a.push({x0:e,x1:n,half:l})}const r=[];for(const t of a){const e=r[r.length-1],s=e?.[e.length-1];s&&t.x0<=s.x1+i?(t.x0=s.x1,e.push(t)):r.push([t])}return r.map(e=>{const i=e[0],s=e[e.length-1],n=Math.min(.25*Math.min(...e.map(t=>t.half)),.75),o=-t*n,a=[];if(1===t){a.push(`M ${i.x0} ${o} L ${s.x1} ${o}`);for(let t=e.length-1;t>=0;t--){const i=e[t];a.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{a.push(`M ${s.x1} ${o} L ${i.x0} ${o}`);for(const t of e)a.push(`L ${t.x0} ${-t.half} L ${t.x1} ${-t.half}`)}return a.push("Z"),a.join(" ")}).join(" ")}function qc(t,e,i,s){if(!s)return i;const n=t.angle*Math.PI/180,o=Math.cos(n),a=Math.sin(n),r=[],l=1e-9;for(const n of i){const[i,c]=n.axis,h=o*i+a*c;if(Math.abs(h)<=l)continue;const d=t.x*i+t.y*c,p=d+h*n.x0,u=d+h*n.x1,_=Math.min(p,u),m=Math.max(p,u),g=`${n.key}|${e}`,f=s.get(g)||[];let v=[[_,m]];for(const[t,e]of f){const i=[];for(const[s,n]of v)e<=s+l||t>=n-l?i.push([s,n]):(t>s+l&&i.push([s,Math.min(n,t)]),et[0]-e[0]||t[1]-e[1]),b=[];for(const t of y){const e=b[b.length-1];e&&t[0]<=e[1]+l?e[1]=Math.max(e[1],t[1]):b.push([t[0],t[1]])}s.set(g,b)}return r}function Wc(t,e){const i=new Map;return e.map(e=>function(t,e,i){const s=Lc(t,e,!0),n=s.negative,o=s.positive;if(!n&&!o)return null;let a;if(n&&o)a=[{candidate:n,side:-1},{candidate:o,side:1}];else{const t=n||o;a=[{candidate:t,side:-1},{candidate:t,side:1}]}const r=a.map(({candidate:t,side:s})=>({candidate:t,side:s,pieces:qc(e,s,t.pieces,i)})),l=r.map(({candidate:t,side:e,pieces:i})=>({side:e,roomId:t.roomId,d:Bc(e,i)})),c=r.flatMap(({pieces:t})=>t);if(!c.length)return null;const h=Math.max(...c.map(t=>t.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(t=>t.key))].sort().join("|")}}(t,e,i))}const jc=150,Uc=1e-6;function Gc(t){return Number.isFinite(t)?Math.max(1,Math.min(jc,t)):1}function Vc(t){return((Number.isFinite(Number(t))?Number(t):0)%90+90)%90}const Kc=t=>{const e=t.map(t=>[t[0],t[1]]);return!e.length||e[0][0]===e[e.length-1][0]&&e[0][1]===e[e.length-1][1]||e.push([...e[0]]),[e]},Yc=(t,e)=>t[0]===e[0]&&t[1]===e[1];function Jc(t,e=1e-6){const i=Number.isFinite(e)&&e>0?e:Uc,s=[];for(const e of t||[]){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(n))return null;const o=Math.round(t/i)*i,a=Math.round(n/i)*i;if(!Number.isFinite(o)||!Number.isFinite(a))return null;const r=[Object.is(o,-0)?0:o,Object.is(a,-0)?0:a];s.length&&Yc(s[s.length-1],r)||s.push(r)}return s.length>1&&Yc(s[0],s[s.length-1])&&s.pop(),s.length<3||new Set(s.map(t=>`${t[0]},${t[1]}`)).size<3?null:Ti(s)>i*i?s:null}function Xc(t){const e=[];for(const i of t||[])for(const t of i||[]){const i=(t||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||e.push(`M ${i.slice(0,-1).map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`)}return e.join(" ")}function Zc(t,e,i,s,n){return Ol({a:t,b:e,halfDepth:gl(i,s,n)/2})}function Qc(t,e,i){const s=Number(e)>0?Number(e):5,n=Gc(t.cm)/s*i,o=t.center[0],a=t.center[1];if("circle"===t.shape){const t=n/2;return Array.from({length:96},(e,i)=>{const s=i/96*Math.PI*2;return[o+Math.cos(s)*t,a+Math.sin(s)*t]})}const r=n/2,l=Vc(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-r,-r],[r,-r],[r,r],[-r,r]].map(([t,e])=>[o+t*c-e*h,a+t*h+e*c])}function th(t,e,i=1e-9){if(!e.length)return[t];let s=[Kc(t)];try{for(const t of e){const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(e,n);if(!(o>i))continue;const a=e/o,r=n/o,l=-r,c=a,h=1.25*Math.max(Number(t.depth)||0,4*i),d=Math.max(2*i,1e-9*o),p=[[t.a[0]-a*d-l*h,t.a[1]-r*d-c*h],[t.b[0]+a*d-l*h,t.b[1]+r*d-c*h],[t.b[0]+a*d+l*h,t.b[1]+r*d+c*h],[t.a[0]-a*d+l*h,t.a[1]-r*d+c*h]];s=oi(s,Kc(p))}return hh(s)}catch{return[t]}}function eh(t,e){try{const i=oi([[...t.map(t=>[t[0],t[1]]),[t[0][0],t[0][1]]]],[[...e.map(t=>[t[0],t[1]]),[e[0][0],e[0][1]]]]);let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Ti(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function ih(t,e,i,s=Math.max(2e-4*i,1e-9),n=[]){const o=[],a=[],r=new Map;for(const t of n){const e=r.get(t.hostId)||[];e.push(t),r.set(t.hostId,e)}const l=[],c=[],h=[];for(const s of t.room_drafts||[])for(let t=0;t+10))continue;const r={a:s.points[t],b:s.points[t+1],halfDepth:a},c=Ol(r);c&&(o.push(r),l.push(c))}const d=[];for(const s of t.partitions||[]){const t={a:s.a,b:s.b,halfDepth:gl(s.cm,e,i)/2};if(!(t.halfDepth>0))continue;const n=Ol(t);n&&(a.push(t),c.push(n),d.push({id:s.id,body:n}))}const p=[...o,...a];for(const{segmentIndex:t,wedge:e}of Wl(p,s)){const i=t=o.length&&(d[i.at].body=s))}for(const t of d)h.push(...th(t.body,r.get(t.id)||[],s));const u=(t.wall_columns||[]).map(t=>Qc(t,e,i)),_=jl([...o,...a],s).flatMap(t=>th(t,n,s));return{drafts:l,partitions:c,columns:u,patches:_,all:[...l,...h,..._,...u]}}function sh(t){try{const e=t.map(t=>Jc(t)).filter(t=>!!t).map(t=>Kc(t));return e.length?si(e[0],...e.slice(1)):null}catch{return null}}const nh=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`;function oh(t){const e=[];for(const i of t||[]){if(lh([i])<=1e-6)continue;const t=[];for(const e of i||[]){const i=(e||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||t.push(nh(i.slice(0,-1)))}t.length&&e.push(t.join(" "))}return e}function ah(t,e,i={}){const s=sh(t.filter(t=>t.length>=3)),n=e.some(t=>!Jc(t))?null:sh(e);if(!s)return[];if(n)try{return oh(ni(s,n))}catch{}return function(t,e,i){let s=null;for(let n=0;n=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]));return e}function hh(t){const e=[];for(const i of t||[]){const t=i?.[0];t?.length>=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]))}return e}function dh(t,e){let i=!1;for(let s=0,n=e.length-1;st[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a||1e-12)+o&&(i=!i)}return i}function ph(t,e,i){return function(t,e){for(const i of e||[]){const e=i?.[0];if(!e?.length||!dh(t,e))continue;let s=!1;for(let e=1;edh(t,e))}function uh(t,e,i){if(Math.hypot(t.center[0]-e.center[0],t.center[1]-e.center[1])>i)return!1;if(Math.abs(Gc(t.cm)-Gc(e.cm))>1e-6)return!1;if(t.shape!==e.shape)return!0;if("circle"===t.shape||"circle"===e.shape)return!0;const s=Math.abs(Vc(t.angle)-Vc(e.angle));return Math.min(s,90-s)<=1e-6}const _h=2.54;function mh(t){const e="number"==typeof t?t:NaN;return!Number.isFinite(e)||e<=0||5===e?1:5/e}function gh(t,e){return t*mh(e)}function fh(t){return t?_h:1}function vh(t,e){if(!e)return String(t);const i=t/_h;return String(Math.round(1e6*i)/1e6)}const yh=1e3;function bh(t,e){const i=Number(t),s=Number.isFinite(i)&&i>0?i:1,n=s>=1?e:e*s,o=s>=1?e/s:e;return{x:(e-n)/2,y:(e-o)/2,w:n,h:o}}const wh=.01,kh=100;function xh(t,e=1e3){const i=bh(t?.plan_aspect,e),s=Number(t?.plan_scale),n=Number.isFinite(s)&&s>0?Math.min(kh,Math.max(wh,s)):1,o=Number(t?.plan_scale_x),a=Number(t?.plan_scale_y),r=Number.isFinite(o)&&o>0?Math.min(kh,Math.max(wh,o)):n,l=Number.isFinite(a)&&a>0?Math.min(kh,Math.max(wh,a)):n,c=Number(t?.plan_x),h=Number(t?.plan_y),d=Ar(t?.plan_angle);return{x:i.x+(Number.isFinite(c)?zh(c):0)*e,y:i.y+(Number.isFinite(h)?zh(h):0)*e,w:i.w*r,h:i.h*l,...d?{angle:d}:{}}}function $h(t){if(null==t.x||null==t.y)return{x:t.x,y:t.y,w:t.w,h:t.h};const e=Number(t.w)||0,i=Number(t.h)||0;return{x:e<0?t.x+e:t.x,y:i<0?t.y+i:t.y,w:Math.abs(e),h:Math.abs(i)}}function Sh(t){return t&&Array.isArray(t.spaces)?t.spaces.map(t=>{const e=yh,i=function(t){return Array.isArray(t)&&4===t.length&&t.every(t=>Number.isFinite(t))&&t[2]>1e-6&&t[3]>1e-6?t:[0,0,1,1]}(t.view_box);return{id:t.id,title:t.title,cellCm:Number.isFinite(Number(t.cell_cm))&&Number(t.cell_cm)>0?Number(t.cell_cm):5,vb:[i[0]*yh,i[1]*e,i[2]*yh,i[3]*e],bg:t.plan_url?{href:As(t.plan_url),...xh(t,yh)}:null,rooms:(t.rooms||[]).map(t=>{const i={...t,...$h(t)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*yh:void 0,y:null!=i.y?i.y*e:void 0,w:null!=i.w?i.w*yh:void 0,h:null!=i.h?i.h*e:void 0,poly:i.poly?i.poly.map(t=>[t[0]*yh,t[1]*e]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(t.wall_segments||[]).map(t=>({...t,id:String(t.id),a:[Number(t.a?.[0])*yh,Number(t.a?.[1])*e],b:[Number(t.b?.[0])*yh,Number(t.b?.[1])*e],cm:Number(t.cm)})),room_drafts:(t.room_drafts||[]).map(t=>({id:t.id,points:(t.points||[]).map(t=>[t[0]*yh,t[1]*e]),segments:(t.segments||[]).map(t=>({..."string"==typeof t.id&&t.id?{id:t.id}:{},cm:Number(t.cm)}))})),partitions:(t.partitions||[]).map(t=>({id:t.id,a:[t.a[0]*yh,t.a[1]*e],b:[t.b[0]*yh,t.b[1]*e],cm:Number(t.cm)})),wall_columns:(t.wall_columns||[]).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[t.center[0]*yh,t.center[1]*e],cm:Number(t.cm),..."circle"===t.shape?{}:{angle:Vc(t.angle)}}))}}):[]}const Mh=5e3,Ch=Mh*yh,Dh=240,Ph=yh/Dh,Th=1/Dh;function Rh(t){if(!Number.isFinite(t))return t;const e=Math.round(t*Dh/yh)*yh/Dh;return Math.abs(e-t)<=1e-9*Ph?t:e}function Ih(t){return{x:Rh(t.x),y:Rh(t.y)}}function Ah(t){return Number.isFinite(t)?Math.min(Ch,Math.max(-Ch,t)):0}function zh(t){return Number.isFinite(t)?Math.min(Mh,Math.max(-Mh,t)):0}const Fh=1/3,Eh=200;function Nh(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t){const t=Number(o[0]),a=Number(o[1]);Number.isFinite(t)&&Number.isFinite(a)&&(ts&&(s=t),a>n&&(n=a))}return e>s?null:{minX:e,minY:i,maxX:s,maxY:n}}function Oh(t){return t.poly&&t.poly.length?Nh(t.poly):null==t.x||null==t.y?null:Nh([[t.x,t.y],[t.x+(t.w||0),t.y+(t.h||0)]])}function Lh(t,e){const i=[];for(const e of t.rooms||[]){const t=Oh(e);t&&i.push(t)}if(t.bg){const e=Nh(Lr(t.bg));e&&i.push(e)}for(const t of e||[])if(Array.isArray(t)){const e=Nh([t]);e&&i.push(e)}else i.push(t);return i}const Hh=t=>{if(!t.length)return 0;const e=[...t].sort((t,e)=>t-e),i=e.length>>1;return e.length%2?e[i]:(e[i-1]+e[i])/2},Bh=t=>{let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t)o.minXs&&(s=o.maxX),o.maxY>n&&(n=o.maxY);return e>s||i>n?null:{x:e,y:i,w:s-e,h:n-i}};function qh(t,e){let{x:i,y:s,w:n,h:o}=t;n<30&&(i=i+n/2-100,n=Eh),o<30&&(s=s+o/2-100,o=Eh);const a=Math.max(n,o)*e;return{x:i-a,y:s-a,w:n+2*a,h:o+2*a}}function Wh(t,e={}){const i=e.pad??.05,s=e.k??10,n=e.minSpread??50,o=t.filter(t=>Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&Math.abs(t.minX)<=Ch&&Math.abs(t.maxX)<=Ch&&Math.abs(t.minY)<=Ch&&Math.abs(t.maxY)<=Ch);if(!o.length)return{core:null,all:null,outliers:0};const a=Bh(o);if(o.length<4){const t=qh(a,i);return{core:t,all:t,outliers:0}}const r=o.map(t=>(t.minX+t.maxX)/2),l=o.map(t=>(t.minY+t.maxY)/2),c=Hh(r),h=Hh(l),d=o.map((t,e)=>Math.max(Math.abs(r[e]-c),Math.abs(l[e]-h))),p=Math.max(((t,e)=>t.length?t[Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))))]:0)([...d].sort((t,e)=>t-e),.75),n),u=d.map(t=>t>s*p),_=u.filter(Boolean).length,m=_&&_<=o.length*Fh?o.filter((t,e)=>!u[e]):o;return{core:qh(Bh(m)||a,i),all:qh(a,i),outliers:m===o?0:_}}function jh(t,e,i=.05){const s=Wh(Lh(t,e),{pad:i});if(s.core)return s.core;const n=t.vb&&4===t.vb.length&&t.vb[2]>0&&t.vb[3]>0?t.vb:[0,0,yh,yh];return{x:n[0],y:n[1],w:n[2],h:n[3]}}function Uh(t){const e=jh(t);return{x:e.x+e.w/2,y:e.y+e.h/2}}function Gh(t){const e=[];for(const i of t.rooms||[]){const t=Oh(i);t&&e.push(t)}const i=Wh(e,{pad:0}).core,s=yh*mh(t.cellCm??5);return i?Math.max(s,Math.min(Ch,Math.max(i.w,i.h))):s}function Vh(t,e,i,s=1){const n=Number(i),o=Number.isFinite(s)&&s>0?s:1;return!Number.isFinite(n)||n<=0?t*o:t*Gh(e)*o/n}const Kh=[1,2,5,10,20,50,100,200,500,1e3];function Yh(t){if(t.poly&&t.poly.length){const e=t.poly.map(t=>t[0]),i=t.poly.map(t=>t[1]),s=Math.min(...e),n=Math.min(...i);return{x:s,y:n,w:Math.max(...e)-s,h:Math.max(...i)-n}}return{x:t.x??0,y:t.y??0,w:t.w??0,h:t.h??0}}function Jh(t,e,i,s){const n=i["rl_"+(t.id||"")];if(n&&n.s===e)return{x:n.x*yh,y:n.y*yh};const o=function(t){if(t.poly){const e=t.poly.length;return[t.poly.reduce((t,e)=>t+e[0],0)/e,t.poly.reduce((t,e)=>t+e[1],0)/e]}return[t.x+t.w/2,t.y+.1*Math.min(t.w,t.h)]}(t);return Ih({x:o[0],y:o[1]})}const Xh=["furniture","appliance","sanitary","other"],Zh=[{id:"sofa",group:"furniture",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Qh=new Map(Zh.map(t=>[t.id,t]));function td(t){return t&&Qh.get(t)||null}function ed(t){return Zh.filter(e=>e.group===t)}function id(t,e,i=Ph,s=1e3){const n=Number(e)>0?Number(e):5;return(Number(t)||0)/n*i/s}const sd=5e-4,nd=Mh;function od(t){return Number.isFinite(t)?Math.max(sd,Math.min(nd,t)):sd}const ad=t=>{const e=Math.round(1e3*t)/1e3;return Object.is(e,-0)?"0":String(e)};function rd(t,e,i){const s=td(t);if(!(s&&e>0&&i>0))return"";const n=t=>ad(t*e),o=t=>ad(t*i),a=[];for(const t of s.g)if("r"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}H${n(e+s)}V${o(i+r)}H${n(e)}Z`)}else if("l"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}L${n(s)} ${o(r)}`)}else if("e"===t[0]){const[,s,r,l,c]=t;a.push(`M${n(s-l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s+l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s-l)} ${o(r)}Z`)}else{const e=t.slice(1);if(e.length<4)continue;let i=`M${n(e[0])} ${o(e[1])}`;for(let t=2;t+1{let e=(t%360+360)%360;return e>180&&(e-=360),e};function cd(t,e,i,s,n,o=0){let a=null,r=n;for(const n of s){const[s,l,c,h]=n,d=c-s,p=h-l,u=d*d+p*p;if(!u)continue;const _=Math.sqrt(u);let m=((t-s)*d+(e-l)*p)/u;m=Math.max(0,Math.min(1,m));let g=s+m*d,f=l+m*p;const v=Math.hypot(t-g,e-f);if(!(v0){const t=Math.round(m*_/o)*o;g=s+t/_*d,f=l+t/_*p}a={cx:g+y*(i/2),cy:f+b*(i/2),angle:ld(180*Math.atan2(-y,b)/Math.PI),dist:v}}return a}function hd(t,e,i){const s=i>0?i:1;return{a:[t[0]/s,t[1]/s],b:[e[0]/s,e[1]/s]}}function dd(t,e){const i=e>0?e:1;return[t.a[0]*i,t.a[1]*i,t.b[0]*i,t.b[1]*i]}function pd(t){return Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1]))}function ud(t){if(!Array.isArray(t))return[];const e=[];for(const i of t){if(!i||"object"!=typeof i)continue;const t=i;if(!pd(t.a)||!pd(t.b))continue;const s=[Number(t.a[0]),Number(t.a[1])],n=[Number(t.b[0]),Number(t.b[1])];Math.hypot(n[0]-s[0],n[1]-s[1])<.001||e.push({a:s,b:n})}return e}function _d(t,e,i,s,n=!0){const o=(t||[]).filter(t=>t?.id),a=ud(e);if(a.length)return function(t,e,i,s){const n=ud(t);if(!n.length)return[];const o=function(t,e){const i=[],s=(t||[]).filter(t=>t?.id);for(let t=0;t4*s||o>4*s)continue;const a=(t[0]-n)*p+(t[1]-l)*u,c=(t[2]-n)*p+(t[3]-l)*u,h=Math.max(0,Math.min(a,c)),m=Math.min(d,Math.max(a,c));if(m-ht.lo-e.lo||t.hi-e.hi);const i=[];for(const t of e){const e=i[i.length-1];e&&t.lo<=e.hi+r?e.hi=Math.max(e.hi,t.hi):i.push({...t})}for(const e of i){const i=[n+p*e.lo,l+u*e.lo],s=[n+p*e.hi,l+u*e.hi];Math.hypot(s[0]-i[0],s[1]-i[1])i.pair===t&&Math.abs(i.ux*a-i.uy*o)<=1e-6&&Math.abs((e[0]-i.origin[0])*i.uy-(e[1]-i.origin[1])*i.ux)<=c&&Math.abs((e[2]-i.origin[0])*i.uy-(e[3]-i.origin[1])*i.ux)<=c);h||(h={pair:t,origin:[e[0],e[1]],ux:o,uy:a,ranges:[]},l.push(h));const d=(e[0]-h.origin[0])*h.ux+(e[1]-h.origin[1])*h.uy,p=(e[2]-h.origin[0])*h.ux+(e[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,p),hi:Math.max(d,p)})}const h=[];for(const t of l){t.ranges.sort((t,e)=>t.lo-e.lo||t.hi-e.hi);const e=[];for(const i of t.ranges){const t=e[e.length-1];t&&i.lo<=t.hi+r?t.hi=Math.max(t.hi,i.hi):e.push({...i})}for(const s of e){const e=[t.origin[0]+t.ux*s.lo,t.origin[1]+t.uy*s.lo],n=[t.origin[0]+t.ux*s.hi,t.origin[1]+t.uy*s.hi];Math.hypot(n[0]-e[0],n[1]-e[1])>=r&&h.push(hd(e,n,i))}}return h}(a,t,i,s).map(t=>dd(t,i));if(!n)return[];const r=[],l=(t,e)=>(t.open_to||[]).includes(e.id)||(e.open_to||[]).includes(t.id);for(let t=0;t{const e=fd.get(t);if(!e)return;const i=Date.now();if("hidden"===t.visibilityState){e.hiddenAt||(e.hiddenAt=i);const t={kind:"hidden",token:e.token,at:i,hiddenFor:0,long:!1};for(const i of[...e.subscribers])i(t);return}const s=e.hiddenAt?Math.max(0,i-e.hiddenAt):0;e.hiddenAt=0,e.token++;const n={kind:"visible",token:e.token,at:i,hiddenFor:s,long:s>=md};for(const t of[...e.subscribers])t(n)},onPageShow:e=>{const i=fd.get(t);if(!i)return;const s=Date.now();i.token++;const n={kind:"pageshow",token:i.token,at:s,hiddenFor:0,long:!!e.persisted,persisted:!!e.persisted};for(const t of[...i.subscribers])t(n)}},fd.set(t,i),t.addEventListener("visibilitychange",i.onVisibility),t.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(e),()=>{const i=fd.get(t);i&&(i.subscribers.delete(e),i.subscribers.size||(t.removeEventListener("visibilitychange",i.onVisibility),t.defaultView?.removeEventListener("pageshow",i.onPageShow),fd.delete(t)))}}const yd={now:()=>Date.now(),setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),requestAnimationFrame:t=>window.requestAnimationFrame(t),cancelAnimationFrame:t=>window.cancelAnimationFrame(t)};class bd{constructor(t,e=yd){this.onChange=t,this.clock=e,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(t=>({...t,...t.stage?{stage:[...t.stage]}:{}}))}note(t,e={}){this.record(t,void 0,e)}record(t,e,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:t,state:this._state,...e?{reason:e}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(t){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&t&&t!==this._frameFingerprint&&(this._frameFingerprint=t,this.record("frame-refreshed"))}visibility(t){return"hidden"===t.kind?(this.record("visibility-hidden"),this._token):t.long||"visible"!==t.kind&&"pageshow"!==t.kind?this.beginCandidate("pageshow"===t.kind?"pageshow":"long-resume"):(this.record("pageshow"===t.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(t,e="plan"){return this._token++,this._recoveryReason=e,this._hasCompleteFrame?(this._state="connection"===e?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(e)),this.record("candidate-start",t),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(t){return!this._disposed&&t===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(t,e){if(this._disposed||t!==this._token)return!1;let i=!0;const s=(async()=>{for(await e.updateComplete();i&&!this._disposed&&t===this._token;)if(e.stageValid()&&e.assetsReady()){if(await this.nextFrame(),t!==this._token||!e.stageValid()||!e.assetsReady())continue;if(await this.nextFrame(),t===this._token&&e.stageValid()&&e.assetsReady())return!0}else await this.nextFrame();return!1})();let n=0;const o=new Promise(t=>{n=this.clock.setTimeout(()=>t({ready:!1,timedOut:!0}),gd)}),a=await Promise.race([s.then(t=>({ready:t,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(n),!this._disposed&&t===this._token&&(!(!a.ready&&!a.timedOut)&&(a.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=e.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(t=this._recoveryReason||"plan"){return this.beginCandidate("retry",t)}nextFrame(){return new Promise(t=>{const e=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(e),t()});this._barrierRafs.add(e)})}scheduleOverlay(t){this.clearOverlayTimer(),this._recoveryReason=t,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const t=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},t)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const t of this._barrierRafs)this.clock.cancelAnimationFrame(t);this._barrierRafs.clear()}}function wd(t){let e=2166136261,i=2654435769;const s=new WeakSet,n=t=>{for(let s=0;s>>0)+(i>>>2)}},o=t=>{if(null===t)return void n("n");const e=typeof t;if("string"===e)return void n(`s${t.length}:${t}`);if("number"===e)return void n(`d${Number.isNaN(t)?"NaN":String(t)}`);if("boolean"===e)return void n(t?"t":"f");if("undefined"===e)return void n("u");if("object"!==e)return void n(`${e}:${String(t)}`);const i=t;if(s.has(i))n("[cycle]");else{if(s.add(i),Array.isArray(t)){n("[");for(const e of t)o(e);return n("]"),void s.delete(i)}n("{");for(const e of Object.keys(t).sort())n(e),o(t[e]);n("}"),s.delete(i)}};return o(t),`${(e>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function kd(t){return wd(t)}const xd=new WeakMap;class $d{constructor(t,e=()=>Date.now()){this.onUpdate=t,this.now=e,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(t){const e=((t,e)=>{const i=t?.connection||t?.callWS||e;return!i||"object"!=typeof i&&"function"!=typeof i?e:i})(t,this.fallbackAuthority);return this.shared&&this.authority===e||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=e,this.shared=(t=>{let e=xd.get(t);return e||(e={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},xd.set(t,e)),e})(e),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(t,e){this.disposed=!1,this.referenced=new Set(e());const i=this.bind(t());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(t(),e()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const t of this.queued)this.shared.queued.delete(t)}this.queued.clear()}invalidate(t){const e=this.bind(t);clearTimeout(this.batchTimer),this.queued.clear(),e.queued.clear(),e.inFlight.clear(),e.retry.clear(),e.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return i;const s=this.bind(t);this.referenced.add(i),s.references.set(this.referenceOwner,new Set(this.referenced));const n=s.signed[i],o=n?this.now()-n.at:1/0;return o{const e=[...this.queued];this.queued.clear();for(const t of e)i.queued.delete(t);this.sign(t,e)},30))}sign(t,e){if(!e.length||!t?.callWS)return;const i=this.bind(t);for(const s of function(t,e){const i=Math.max(1,Math.floor(e)),s=[];for(let e=0;e{const s=i.inFlight.get(t);return!(void 0!==s&&e-s<15e3)&&(i.inFlight.set(t,e),!0)});n.length&&t.callWS({type:"houseplan/content/sign",paths:n}).then(t=>{const e=this.now();let s=0,o=!1;for(const a of n){const n=t?.urls?.[a];if("string"==typeof n&&n){const t=i.signed[a];t?.loaded&&t.url!==n?(t.pending={url:n,at:e},this.preloadReplacement(i,a,n,e)):(i.signed[a]={url:n,at:e,loaded:t?.url===n&&!!t.loaded},o=!0),i.retry.delete(a),s++}else this.backOff(i,a)}if(s&&(this.trimShared(i),o))for(const t of[...i.listeners])t()}).catch(()=>{for(const t of n)this.backOff(i,t)}).finally(()=>{for(const t of n)i.inFlight.get(t)===e&&i.inFlight.delete(t);for(const t of[...i.settlers])t()})}}preloadReplacement(t,e,i,s){const n=()=>{const n=t.signed[e];if(n?.pending?.url===i){t.signed[e]={url:i,at:s,loaded:!0},t.retry.delete(e),this.trimShared(t);for(const e of[...t.listeners])e()}},o=()=>{const s=t.signed[e];s?.pending?.url===i&&(delete s.pending,this.backOff(t,e))};if("undefined"==typeof Image)return void n();const a=new Image;a.onload=()=>{("function"==typeof a.decode?a.decode():Promise.resolve()).then(n).catch(o)},a.onerror=o,a.src=i}preloadCurrentImage(t,e,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const s=i.url;return i.preload=new Promise(n=>{const o=new Image;let a=!1;const r=o=>{if(a)return;a=!0,clearTimeout(l);const r=t.signed[e];if(r===i&&delete r.preload,o&&r===i&&r.url===s){r.loaded=!0;for(const e of[...t.listeners])e();n(!0)}else o||r!==i||this.backOff(t,e),n(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>r(!0)).catch(()=>r(!1))},o.onerror=()=>r(!1);const l=setTimeout(()=>r(!1),gd);o.src=s}),i.preload}prepareImage(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const s=this.bind(t),n=()=>{const e=s.signed[i];if(e&&this.now()-e.atthis.now()&&!s.inFlight.has(i)&&!s.queued.has(i)?Promise.resolve(!1):null},o=n();return o?(a=o,new Promise(t=>{let e=!1;const i=i=>{e||(e=!0,clearTimeout(s),t(i))},s=setTimeout(()=>i(!1),gd);a.then(i).catch(()=>i(!1))})):new Promise(t=>{let e=!1,i=null;const o=i=>{e||(e=!0,clearTimeout(r),s.settlers.delete(a),t(i))},a=()=>{e||i||(i=n(),i&&i.then(o).catch(()=>o(!1)))},r=setTimeout(()=>o(!1),gd);s.settlers.add(a),a()});var a}backOff(t,e){const i=t.retry.get(e)?.delay||0,s=Math.min(6e4,i?2*i:2e3);t.retry.set(e,{notBefore:this.now()+s,delay:s})}trimShared(t){const e=Object.entries(t.signed);if(e.length<=512)return;const i=new Set(t.inFlight.keys());for(const e of t.references.values())for(const t of e)i.add(t);for(const[t,s]of e)(s.pending||s.preload)&&i.add(t);e.sort((t,e)=>e[1].at-t[1].at);const s=e.filter(([t])=>i.has(t));for(const t of e){if(s.length>=512)break;i.has(t[0])||s.push(t)}t.signed=Object.fromEntries(s)}resign(t,e){const i=this.bind(t);this.referenced=new Set(e),i.references.set(this.referenceOwner,new Set(this.referenced));const s=this.now(),n=new Set;for(const t of i.references.values())for(const e of t)n.add(e);const o={};for(const[t,e]of Object.entries(i.signed))n.has(t)&&s-e.at!!o[t]&&!o[t].pending))}markLoaded(t,e,i){const s=As(e);if(!s.startsWith("/api/houseplan/content/"))return;const n=this.bind(t).signed[s];if(n&&(!i||n.url===i)&&!n.loaded){n.loaded=!0;for(const e of[...this.bind(t).listeners])e()}}isReady(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return!0;const s=this.bind(t).signed[i];return!!s&&this.now()-s.att.id===e)}function Md(t="file"){const e="draw"===t;return{source:t,showBorders:e,showNames:e,displayTouched:!1}}function Cd(t,e){if(t.displayTouched)return{...t,source:e};const i="draw"===e;return{...t,source:e,showBorders:i,showNames:i}}function Dd(t,e,i){return{...t,[e]:i,displayTouched:!0}}function Pd(t,e,i){return[t[0]*e+t[1]*i+t[2],t[3]*e+t[4]*i+t[5]]}function Td(t,e){let i=0;for(const[s,n]of e){const e=Pd(t,s[0],s[1]);i=Math.max(i,Math.hypot(e[0]-n[0],e[1]-n[1]))}return i}const Rd=t=>{if(null==t||""===t)return null;const e=Number(t);return Number.isFinite(e)?e:null},Id=t=>{const e=t,i=Rd(Array.isArray(e)?e[0]:e?.x),s=Rd(Array.isArray(e)?e[1]:e?.y);return null==i||null==s?null:[i,s]};function Ad(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}if(e.length<3)return null;let i=0,s=0,n=0;for(let t=0;tt+e[0],0)/e.length,e.reduce((t,e)=>t+e[1],0)/e.length]:[s/(3*i),n/(3*i)]}function zd(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}const i=Ad(e);if(!i)return null;const s=e.map(t=>t[0]),n=e.map(t=>t[1]);return{centroid:i,bbox:[Math.min(...s),Math.min(...n),Math.max(...s),Math.max(...n)]}}function Fd(t){let e=t;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;e=t.path??t.points??e}if(!Array.isArray(e)||!e.length)return[];let i=(e.some(t=>(t=>Array.isArray(t)?t.length>=2&&!Array.isArray(t[0])&&("object"!=typeof t[0]||null==t[0]):!!t&&"object"==typeof t&&("x"in t||"y"in t))(t))?[e]:e.filter(Array.isArray)).map(t=>t.map(Id).filter(t=>null!=t)).filter(t=>t.length>=2);i.length>64&&(i=i.slice(-64));const s=i.reduce((t,e)=>t+e.length,0);if(s<=4e3)return i.map(t=>t.slice());const n=4e3-2*i.length,o=i.map(t=>t.length-2),a=o.reduce((t,e)=>t+e,0),r=o.map(t=>n*t/a),l=r.map(Math.floor);let c=n-l.reduce((t,e)=>t+e,0);const h=r.map((t,e)=>({index:e,fraction:t-Math.floor(t)})).sort((t,e)=>e.fraction-t.fraction||t.index-e.index);for(let t=0;tfunction(t,e){if(e>=t.length)return t.slice();if(e<=2)return[t[0],t[t.length-1]];const i=[];for(let s=0;st.slice()),i=e[e.length-1];return i?(i.length>2?i.pop():e.pop(),e):[]}function Od(t){if(!t)return null;const e=t.vacuum_position||t.robot_position||null,i=e&&null!=Rd(e.x)&&null!=Rd(e.y)?{x:Rd(e.x),y:Rd(e.y),a:Rd(e.a??e.angle??e.theta)}:null,s=Fd(t.path?.path??t.path?.points??t.path),n=[],o=t.rooms,a=Array.isArray(o)?o.map((t,e)=>[String(t?.id??e),t]):o&&"object"==typeof o?Object.entries(o):[];for(const[t,e]of a){if(!e||"object"!=typeof e)continue;const i=String(e.name??e.label??"").trim(),s=[[Rd(e.cx),Rd(e.cy)],[Rd(e.center?.x),Rd(e.center?.y)],[Rd(e.x),Rd(e.y)]].find(([t,e])=>null!=t&&null!=e);let o=s?.[0]??null,a=s?.[1]??null;const r=zd(e.outline),l=Rd(e.x0),c=Rd(e.y0),h=Rd(e.x1),d=Rd(e.y1),p=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||r?.bbox||null;if(null!=o&&null!=a||!r||([o,a]=r.centroid),null!=o&&null!=a||!p||(o=(p[0]+p[2])/2,a=(p[1]+p[3])/2),i&&null!=o&&null!=a){const e={id:t,name:i,cx:o,cy:a};p&&([e.x0,e.y0,e.x1,e.y1]=p),n.push(e)}}const r=function(t){return String(t.map_name??t.current_map??t.map_index??t.selected_map??"default")}(t);return i||n.length||s.length?{pos:i,path:s,rooms:n,mapId:r}:null}function Ld(t,e,i){if(!t||!e)return null;const s=e.attributes||{},n=t.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,a=!!Id(s.vacuum_position??s.robot_position),r=!(!s.rooms||"object"!=typeof s.rooms),l=Fd(s.path?.path??s.path?.points??s.path).length>0,c=[s.map_name,s.current_map,s.map_index,s.selected_map].some(t=>null!=t),h="xiaomi_cloud_map_extractor"===o,d=r||l||c;let p=null;if(a?p="compatible":h?p="known_xcme_incomplete":d?p="partial":"camera"===n&&(p="camera"),!p)return null;const u=a?"camera"===n?300:200:h?100:d?50:0;return{entityId:t,name:String(s.friendly_name||t),platform:o,category:p,hasPosition:a,hasRooms:r,hasPath:l,hasMapId:c,score:u}}const Hd=t=>t.toLowerCase().replace(/[\s_\-.,]+/g,"");function Bd(t,e){const i=new Map(e.map(t=>[Hd(t.name),t])),s=[],n=[];for(const e of t){const t=i.get(Hd(e.name));t&&(s.push([[e.cx,e.cy],[t.cx,t.cy]]),n.push(e.name))}if(s.length<3)return null;const o=function(t){if(t.length<3)return null;let e=0,i=0,s=0,n=0,o=0,a=0,r=0,l=0,c=0,h=0,d=0,p=0;for(const[[u,_],[m,g]]of t){if(![u,_,m,g].every(Number.isFinite))return null;e+=u*u,i+=u*_,s+=u,n+=_*_,o+=_,a+=1,r+=u*m,l+=_*m,c+=m,h+=u*g,d+=_*g,p+=g}const u=[e,i,s,i,n,o,s,o,a],_=t=>{const[e,i,s,n,o,a,r,l,c]=u,h=e*(o*c-a*l)-i*(n*c-a*r)+s*(n*l-o*r);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-a*l)/h,(s*l-i*c)/h,(i*a-s*o)/h,(a*r-n*c)/h,(e*c-s*r)/h,(s*n-e*a)/h,(n*l-o*r)/h,(i*r-e*l)/h,(e*o-i*n)/h];return[d[0]*t[0]+d[1]*t[1]+d[2]*t[2],d[3]*t[0]+d[4]*t[1]+d[5]*t[2],d[6]*t[0]+d[7]*t[1]+d[8]*t[2]]},m=_([r,l,c]),g=_([h,d,p]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(s);return o?{matrix:o,matched:n,residual:Td(o,s)}:null}function qd(t,e,i){const s=t[t.length-1];if(s&&s[0]===e[0]&&s[1]===e[1])return t;if(t.push(e),t.length<=600)return t;let n=function(t,e){if(t.length<3)return t.slice();const i=new Uint8Array(t.length);i[0]=i[t.length-1]=1;const s=[[0,t.length-1]];for(;s.length;){const[n,o]=s.pop(),[a,r]=t[n],[l,c]=t[o],h=l-a,d=c-r,p=Math.hypot(h,d)||1e-9;let u=0,_=-1;for(let e=n+1;eu&&(u=i,_=e)}_>0&&u>e&&(i[_]=1,s.push([n,_],[_,o]))}const n=[];for(let e=0;e600&&(n=n.filter((t,e)=>e%2==0||e===n.length-1)),n}function Wd(t){return"cleaning"===t||"returning"===t||"on"===t}const jd={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Ud(t){const[e,i]=jd[t.rot]||[1,0],s=t.mir?-1:1;return[t.s*e*s,-t.s*i,t.ox,t.s*i*s,t.s*e,t.oy]}function Gd(t){const e=t[0]*t[4]-t[1]*t[3];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;const i=e<0,s=Math.sqrt(Math.abs(e));let n=180*Math.atan2(-t[1],t[4])/Math.PI;return n=(90*Math.round(n/90)%360+360)%360,{ox:t[2],oy:t[5],s:s,rot:n,mir:i}}function Vd(t,e,i,s){const[n,o]=Pd(Ud(e),i,s),a=Ud({...t,ox:0,oy:0}),[r,l]=Pd(a,i,s);return{...t,ox:n-r,oy:o-l}}function Kd(t){const e=t?.trail_mode;return"never"===e||"cleaning"===e||"always"===e?e:!1===t?.trail?"never":"cleaning"}const Yd={offStates:["off"],unknownUsesToggle:!0},Jd={light:Yd,switch:Yd,fan:Yd,humidifier:Yd,input_boolean:Yd,automation:Yd,remote:Yd,group:Yd,climate:{...Yd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Yd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Yd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Yd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function Xd(t){return t.slice(0,t.indexOf("."))}function Zd(t,e,i){if(!t?.services||"object"!=typeof t.services)return!1;const s=t.services?.[e];return!!s&&Object.prototype.hasOwnProperty.call(s,i)}function Qd(t,e,i){return Zd(t,e,i)?{domain:e,service:i}:Zd(t,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function tp(t,e){return t?.entities?.[e]||null}function ep(t,e,i){const s=t?.states?.[i],n=tp(e,i);return s?.attributes?.friendly_name||n?.name||n?.original_name||i}function ip(t,e){const i=tp(t,e);if(null!=i?.disabled_by)return!0;const s=i?.device_id?t?.devices?.[i.device_id]:null;return null!=s?.disabled_by}function sp(t,e){const i=t?.attributes?.supported_features;if(null==i||""===i)return!1;const s=Number(i);return Number.isFinite(s)&&(s&e)===e}function np(t,e,i){const s=Xd(i);if("lock"===s||"alarm_control_panel"===s)return!0;if("cover"!==s)return!1;const n=t?.states?.[i],o=tp(e,i),a=String(n?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Ui.has(a)}function op(t,e,i,s,n){return{ref:i,entityId:s,name:s?ep(t,e,s):null,reason:n}}function ap(t,e,i,s,n,o=null){return{target:null,skipped:op(t,e,i,s,n),semantics:o,nextEffect:null,command:null}}function rp(t,e,i,s,n=i){const o=Xd(i);if("cover"!==o&&"valve"!==o)return function(t,e,i,s,n=i){const o=Xd(i),a=t?.states?.[i];if(ip(e,i))return ap(t,e,n,i,"ha-disabled","power");if(np(t,e,i))return ap(t,e,n,i,"secure");if(!a)return ap(t,e,n,i,"missing","power");if("unavailable"===a.state)return ap(t,e,n,i,"unavailable","power");const r=Jd[o];if(!r)return ap(t,e,n,i,"unsupported");let l,c;if("unknown"===a.state||""===a.state){if(!r.unknownUsesToggle)return ap(t,e,n,i,"unsupported","power");l="toggle",c="toggle"}else r.offStates.includes(String(a.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=r.featureMasks?.[c];if(h&&!sp(a,h))return ap(t,e,n,i,"unsupported","power");const d=Qd(t,o,c);return d?{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:ap(t,e,n,i,"unsupported","power")}(t,e,i,s,n);if(ip(e,i))return ap(t,e,n,i,"ha-disabled",o);if(np(t,e,i))return ap(t,e,n,i,"secure",o);const a=t?.states?.[i];if(!a)return ap(t,e,n,i,"missing",o);if("unavailable"===a.state)return ap(t,e,n,i,"unavailable",o);const r=function(t,e,i){const s=String(i?.state||""),n="closed"===s?{service:`open_${e}`,effect:"open",feature:1}:"open"===s?{service:`close_${e}`,effect:"close",feature:2}:"opening"===s||"closing"===s?{service:`stop_${e}`,effect:"stop",feature:8}:null;return n&&sp(i,n.feature)&&Zd(t,e,n.service)?n:sp(i,3)&&Zd(t,e,"toggle")?{service:"toggle",effect:"toggle"}:null}(t,o,a);if(!r)return ap(t,e,n,i,"unsupported",o);return{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:o,nextEffect:r.effect,command:{domain:o,service:r.service,data:{entity_id:i}}}}function lp(t){return"entity"===t.bindingKind?t.bindingRef&&Ms(t.bindingRef)?[t.bindingRef]:[]:"virtual"===t.bindingKind?[]:to(t)}function cp(t){const e=t.marker?.toggle_entity;return e&&lp(t).includes(e)?e:null}function hp(t,e,i){const s=function(t,e){if("entity"===t.bindingKind&&t.bindingRef){const e=t.marker?.light_entity?eo(t):null;return[...new Set([e,t.bindingRef].filter(t=>!!t))]}const i=t.entities.length?t.entities:t.allEntities||[],s=t.marker?.light_entity||t.primary&&Ms(t.primary)?eo(t):null;return[...new Set([s,...Yn(e,i)].filter(t=>!!t))]}(i,e);if(!s.length)return null;const n="entity"===i.bindingKind?"binding":"device-role";if("binding"===n)return rp(t,e,s[0],n);let o=null,a=null;for(const i of s){const s=rp(t,e,i,n);if(s.command)return s;const r=s.skipped?.reason;if("missing"===r||"unavailable"===r||"secure"===r)return s;"ha-disabled"!==r?o||=s:a||=s}return o||a}function dp(t){const e=t.skipped?.reason;return"missing"===e?"unavailable":e||"unsupported"}function pp(t,e){return{origin:t,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:e,nextEffect:null,command:null}}function up(t,e){return"cover"===t||"toggle"===t?"toggle":"more-info"===t||"run"===t||"info"===t?t:(null==t||""===t)&&"light"===e?"toggle":"info"}function _p(t,e){return{origin:t,kind:"single",semantics:e.semantics,targets:e.target?[e.target]:[],skippedTargets:e.skipped?[e.skipped]:[],noneReason:e.command?null:dp(e),nextEffect:e.nextEffect,command:e.command}}function mp(t,e,i,s=[]){const n=new Map,o=[],a=new Set,r=t=>{const e=`${t.ref}\n${t.entityId||""}\n${t.reason}`;a.has(e)||(a.add(e),o.push(t))};for(const t of s)r(t);for(const s of i){const i=rp(t,e,s.entityId,s.via,s.ref);i.target?n.set(s.entityId,n.get(s.entityId)||i.target):i.skipped&&r(i.skipped)}const l=[...n.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(t=>"secure"===t.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(t=>"on"===t.state)?"turn_off":"turn_on",h=Qd(t,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(t=>t.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>op(t,e,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function gp(t){return String(t.marker?.id||t.id||"")}function fp(t){const{hass:e,device:i}=t,s=t.registryHass||e,n=function(t){return"toggle"===t.tapAction?"explicit-toggle":"cover"===t.tapAction?"legacy-cover":!t.tapAction&&t.primary?.startsWith("light.")?"default-light":null}(i);if(!n)return null;const o=i.marker;if("explicit-toggle"===n&&yn(o)){const e=String(o?.id||i.id||""),s=ro(t.devices).get(e);if(s)return function(t,e){const i=t.registryHass||t.hass;return mp(t.hass,i,e.driverEids.map(t=>({entityId:t,via:"control-marker-driver",ref:`marker:${e.markerId}`})))}(t,s);const a=bn(o,t.virtualLights);return{origin:n,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:a?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:a?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===n){if(Zn(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(t,e=null){const{hass:i,device:s,devices:n}=t,o=t.registryHass||i,a=Zn(s.marker?.binding,s.marker?.controls??s.controls,s.entities),r=t.lightSources||ho(i,n,null,t.virtualLights),l=new Map;for(const t of r){if(!t.key.startsWith("marker:"))continue;const e=l.get(t.key)||[];e.push(t),l.set(t.key,e)}const c=ro(n),h=new Map;for(const t of n){const e=String(t.marker?.id||t.id||"");e&&h.set(e,t)}const d=[],p=[];e&&d.push({entityId:e,via:"entity"===s.bindingKind?"binding":"device-role",ref:e});for(const t of a){if(!t.startsWith("marker:")){Ms(t)?d.push({entityId:t,via:"control-entity",ref:t}):p.push(op(i,o,t,t.includes(".")?t:null,"unsupported"));continue}const e=l.get(t)||[];if(!e.length){const e=h.get(t.slice(7));if("ha_disabled"===e?.bindingStatus?.kind){const s=e.bindingStatus.allEntityIds[0]||null;p.push({ref:t,entityId:s,name:e.name||(s?ep(i,o,s):null),reason:"ha-disabled"})}else p.push(op(i,o,t,null,"missing"));continue}const n=[...new Set(e.flatMap(t=>t.serviceEids))];if(n.length){for(const e of n)d.push({entityId:e,via:"control-entity",ref:t});continue}const a=e.some(t=>t.passive),r=t.slice(7),u=gp(s),_=c.get(r)?.controllers.find(t=>gp(t.device)===u);if(a&&_?.driverEids.length)for(const e of _.driverEids)d.push({entityId:e,via:"control-marker-driver",ref:t});else p.push(op(i,o,t,null,a?"missing":"unsupported"))}return mp(i,o,d,p)}(t,cp(i))}if("legacy-cover"===n){const t=i.entities.find(t=>t.startsWith("cover."))||i.allEntities?.find(t=>t.startsWith("cover."));return t?_p(n,rp(e,s,t,"device-role")):pp(n,"no-actionable-entity")}const a=cp(i),r=a?rp(e,s,a,"entity"===i.bindingKind?"binding":"device-role"):hp(e,s,i);return r?_p(n,r):pp(n,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function vp(t){if(!t)return[];const e=Array.isArray(t.data.entity_id)?t.data.entity_id:[t.data.entity_id];return[...new Set(e)].sort()}function yp(t){return t?t.operation?t.operation:t.command?{kind:"ha-service",command:t.command}:null:null}const bp=new Set(["missing","ha-disabled","unavailable"]);function wp(t,e){const i=yp(t),s=yp(e);return!(!i||!s||i.kind!==s.kind)&&("virtual-light"===i.kind&&"virtual-light"===s.kind?i.markerId===s.markerId:"ha-service"===i.kind&&"ha-service"===s.kind&&function(t,e){const i=vp(t),s=vp(e);return i.length===s.length&&i.every((t,e)=>t===s[e])}(i.command,s.command))}const kp=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]);function xp(t,e=5,i=5){return gl(t.cm,e,i)/2}function $p(t,e,i=1,s=5,n=5,o=0){const a=t.host;if(!a||"partition"!==a.kind||"string"!=typeof a.id||!a.id)return{resolved:null,reason:"invalid-host"};const r=e.find(t=>t.id===a.id);if(!r)return{resolved:null,reason:"missing-partition"};if(!kp(r.a)||!kp(r.b)||!Number.isFinite(a.t)||a.t<0||a.t>1)return{resolved:null,reason:"invalid-position"};const l=r.b[0]-r.a[0],c=r.b[1]-r.a[1],h=Math.hypot(l,c),d=Number(t.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const p=a.t*h;if(p-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const u=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:t,host:a,partition:r,center:[r.a[0]+l*a.t,r.a[1]+c*a.t],angle:m,length:d,depth:gl(r.cm,s,n),t:a.t,axis:{a:[r.a[0],r.a[1]],b:[r.b[0],r.b[1]],ux:u,uy:_,length:h}}}}function Sp(t,e,i=1,s=5,n=5){return $p(t,e,i,s,n,0)}function Mp(t,e,i=1,s=5,n=5){const o=t.host,a="partition"===o?.kind?e.find(t=>t.id===o.id):void 0;if(!a)return Sp(t,e,i,s,n);const r=$p(t,e,i,s,n,xp(a,s,n));return"does-not-fit"===r.reason?{resolved:null,reason:"does-not-fit-jamb"}:r}function Cp(t,e){return!t||(t.length!==e.length||t.host?.kind!==e.host?.kind||t.host?.id!==e.host?.id||t.host?.t!==e.host?.t)}function Dp(t){const{center:e,length:i,axis:s,host:n}=t,o=i/2;return{hostId:n.id,a:[e[0]-s.ux*o,e[1]-s.uy*o],b:[e[0]+s.ux*o,e[1]+s.uy*o],depth:t.depth}}function Pp(t,e=!1){const i=e?1:-1,s=t.depth/2;return{ox:-t.axis.uy*i*s,oy:t.axis.ux*i*s,cm:t.partition.cm,side:i}}function Tp(t,e,i){return t.flatMap(t=>!kp(t.a)||!kp(t.b)||Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])<=1e-9?[]:[{roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`partition:${t.id}`,kind:"outer",cm:t.cm,open:!1,half:gl(t.cm,e,i)/2,partitionHost:{kind:"partition",id:t.id}}])}function Rp(t,e,i){const{center:s,length:n,axis:o}=t,a=n/2,r=e.flatMap(t=>{if(!t.kind||t.open)return[];const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(e,n);if(!(r>i))return[];const l=e/r,c=n/r;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((s[0]-t.a[0])*c-(s[1]-t.a[1])*l)>i)return[];const h=t=>(t[0]-s[0])*o.ux+(t[1]-s[1])*o.uy,d=h(t.a),p=h(t.b),u=Math.max(-a,Math.min(d,p)),_=Math.min(a,Math.max(d,p));return _>=u-i?[[u,_]]:[]});if(!r.length)return!1;r.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let l=-a;for(const[t,e]of r){if(t>l+i)return!1;if(l=Math.max(l,e),l>=a-i)return!0}return!1}function Ip(t,e,i){return{...t,x:e.center[0]/i,y:e.center[1]/i,angle:e.angle}}const Ap=.001;function zp(t){return!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function Fp(t){return`${t[0].toFixed(6)},${t[1].toFixed(6)}`}function Ep(t,e,i){return Math.abs(t[0]-e[0])"room"!==t.kind&&i.some(i=>i!==t&&function(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>i))return!1;const a=s/o,r=n/o,l=e=>Math.abs((e[0]-t.a[0])*r-(e[1]-t.a[1])*a);if(l(e.a)>i||l(e.b)>i)return!1;const c=(e.a[0]-t.a[0])*a+(e.a[1]-t.a[1])*r,h=(e.b[0]-t.a[0])*a+(e.b[1]-t.a[1])*r;return Math.min(o,Math.max(c,h))-Math.max(0,Math.min(c,h))>i}(t,i,e))),n=s.map(t=>{const[e,i]=Np(t.a,t.b);return{a:e,b:i,key:`hidden|${Lp(t,e,i)}`,sourceKind:t.kind,sourceId:t.id}}).sort((t,e)=>t.key.localeCompare(e.key)),o=s.flatMap(t=>[t.a,t.b].map((e,i)=>({point:[e[0],e[1]],key:`hidden|${Op(t)}|endpoint-${i}`,sourceKind:t.kind,sourceId:t.id}))).sort((t,e)=>t.key.localeCompare(e.key));return{segments:n,endpoints:o}}function Wp(t){const e=t.epsilon??Ap,i=t.roomCuts||[],s=new Map;for(const e of t.partitionCuts||[]){if("string"!=typeof e.hostId||!e.hostId||!zp(e.a)||!zp(e.b))continue;const t=s.get(e.hostId)||[];t.push([e.a[0],e.a[1],e.b[0],e.b[1]]),s.set(e.hostId,t)}const n=[];for(const[e,s]of pi(t.space.rooms).entries())s.length<4||n.push({a:[s[0],s[1]],b:[s[2],s[3]],kind:"room",id:`room-edge-${e}`,cuts:i});for(const e of t.space.room_drafts||[])if(e.id!==t.activeDraftId)for(let t=0;t+1Bp(s,t,e)))continue;const t=Fp(s);a.has(t)||a.set(t,{point:[s[0],s[1]],key:t})}}}return{segments:[...o.values()].sort((t,e)=>t.key.localeCompare(e.key)),endpoints:[...a.values()].sort((t,e)=>t.key.localeCompare(e.key))}}function jp(t,e,i){return e.some(e=>zp(e)&&Ep(t,e,i))}function Up(t,e,i){if(!i)return!0;const s=t-i.distance;return s<-1e-9||Math.abs(s)<=1e-9&&e.localeCompare(i.key)<0}function Gp(t,e,i){const s=i.epsilon??Ap,n=i.excludePoints||[],o=[...t.endpoints,...(i.extraEndpoints||[]).filter(t=>zp(t.point)).map(t=>({point:[t.point[0],t.point[1]],key:t.key}))],a=new Map;for(const t of o){if(jp(t.point,n,s))continue;const e=Fp(t.point),i=a.get(e);(!i||t.key.localeCompare(i.key)<0)&&a.set(e,t)}return[...a.values()].map(t=>({kind:"endpoint",point:[...t.point],key:t.key,distance:Math.hypot(e[0]-t.point[0],e[1]-t.point[1])})).filter(t=>t.distance<=i.tolerance).sort((t,e)=>t.distance-e.distance||t.key.localeCompare(e.key))}function Vp(t,e){if(!t.length)return null;if(e>0){const i=new Set;for(let s=0;s1)return{kind:"ambiguous",candidate:null,conflicts:t.filter(t=>i.has(t.key)).map(t=>({point:[...t.point],key:t.key}))}}return{kind:"resolved",candidate:t[0],conflicts:[]}}function Kp(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>0))return[...t.a];const a=s/o,r=n/o,l=Math.max(0,Math.min(o,(e[0]-t.a[0])*a+(e[1]-t.a[1])*r)),c=i>0?Math.max(0,Math.min(o,Math.round(l/i)*i)):l;return[t.a[0]+a*c,t.a[1]+r*c]}function Yp(t,e,i){if(!(zp(e)&&zp(i.anchor)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=function(t,e){const i=e[0]-t[0],s=e[1]-t[1];if(!(Math.hypot(i,s)>Number.EPSILON))return null;const n=Math.round(Math.atan2(s,i)/(Math.PI/4))*(Math.PI/4);return[Math.cos(n),Math.sin(n)]}(i.anchor,e);if(!n)return{kind:"none",candidate:null,conflicts:[]};const o=Gp(t,e,i).filter(t=>function(t,e,i,s){const n=t[0]-e[0],o=t[1]-e[1];return n*i[0]+o*i[1]>s&&Math.abs(n*i[1]-o*i[0])<=s*Math.max(Math.hypot(n,o),1)}(t.point,i.anchor,n,s)),a=Vp(o,i.distinguishTolerance||0);if(a)return a;let r=null;for(const o of t.segments){const t=o.b[0]-o.a[0],a=o.b[1]-o.a[1],l=o.a[0]-i.anchor[0],c=o.a[1]-i.anchor[1],h=n[0]*a-n[1]*t;let d=null;if(Math.abs(h)<=s*Math.max(Math.hypot(t,a),1)){if(Math.abs(l*n[1]-c*n[0])>s*Math.max(Math.hypot(l,c),1))continue;const t=[o.a,o.b].map(t=>({point:t,along:(t[0]-i.anchor[0])*n[0]+(t[1]-i.anchor[1])*n[1]})).filter(t=>t.along>s).sort((t,e)=>t.along-e.along);t.length&&(d=[...t[0].point])}else{const e=(l*a-c*t)/h,o=(l*n[1]-c*n[0])/h;e>s&&o>=-s&&o<=1+s&&(d=[i.anchor[0]+n[0]*e,i.anchor[1]+n[1]*e])}if(!d)continue;const p=Math.hypot(e[0]-d[0],e[1]-d[1]);p>i.tolerance||jp(d,i.excludePoints||[],s)||!Up(p,o.key,r)||(r={kind:"line",point:d,key:o.key,distance:p,segment:o})}return r?{kind:"resolved",candidate:r,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}const Jp=.001;function Xp(t,e,i,s){const n=Number.isFinite(t)&&t>0?Math.floor(t):0,o=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null,a=o(i),r=o(s)??0,l=[];let c=null;for(let t=0;t=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function tu(t,e,i,s){return t*s-e*i}function eu(t){let e=0;for(let i=0;it.localeCompare(e)),e[0]}function au(t,e,i){const s=[...t];for(let t=!0;t&&s.length>=3;){t=!1;for(let n=0;n=0){s.splice(n,1),t=!0;break}}}return s}function ru(t,e){const i=t.map(t=>Math.max(0,Math.min(1,t))).sort((t,e)=>t-e),s=[];for(const t of i)(!s.length||Math.abs(t-s[s.length-1])>e)&&s.push(t);return s}function lu(t,e){return[t.a[0]+(t.b[0]-t.a[0])*e,t.a[1]+(t.b[1]-t.a[1])*e]}function cu(t,e,i){const s=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n:0}(t,e);if(s<-i||s>1+i)return null;const n=lu(e,s);return Math.hypot(n[0]-t[0],n[1]-t[1])<=i?Math.max(0,Math.min(1,s)):null}function hu(t,e,i,s,n){const o=t.b[0]-t.a[0],a=t.b[1]-t.a[1],r=e.b[0]-e.a[0],l=e.b[1]-e.a[1],c=e.a[0]-t.a[0],h=e.a[1]-t.a[1],d=tu(o,a,r,l),p=Math.max(Math.hypot(o,a),Math.hypot(r,l),1);if(Math.abs(d)>n*p){const t=tu(c,h,r,l)/d,e=tu(c,h,o,a)/d;return void(t>=-n&&t<=1+n&&e>=-n&&e<=1+n&&(i.push(Math.max(0,Math.min(1,t))),s.push(Math.max(0,Math.min(1,e)))))}if(!(Math.abs(tu(c,h,o,a))>n*p)){for(const s of[e.a,e.b]){const e=cu(s,t,n);null!=e&&i.push(e)}for(const i of[t.a,t.b]){const t=cu(i,e,n);null!=t&&s.push(t)}}}function du(t){let e=t+1|0;return e^=e<<13,e^=e>>>17,e^=e<<5,e>>>0}function pu(t,e){return t.minY-e.minY||t.index-e.index}function uu(t){return t.subtreeMaxY=Math.max(t.item.maxY,t.left?.subtreeMaxY??-1/0,t.right?.subtreeMaxY??-1/0),t}function _u(t){const e=t.right;return t.right=e.left,e.left=uu(t),uu(e)}function mu(t){const e=t.left;return t.left=e.right,e.right=uu(t),uu(e)}function gu(t,e){return t?(pu(e,t.item)<0?(t.left=gu(t.left,e),t.left.priority0)t.right=fu(t.right,e);else{if(!t.left)return t.right;if(!t.right)return t.left;t.left.priority=e&&vu(t.left,e,i,s),t.item.minY<=i&&t.item.maxY>=e&&s.push(t.item),t.item.minY<=i&&vu(t.right,e,i,s))}function yu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=t.filter(t=>Qp(t.a)&&Qp(t.b)&&"string"==typeof t.key&&t.key.length>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>i),n=s.map(()=>[0,1]);!function(t,e,i){const s=t.map((t,e)=>({index:e,minX:Math.min(t.a[0],t.b[0])-i,maxX:Math.max(t.a[0],t.b[0])+i,minY:Math.min(t.a[1],t.b[1])-i,maxY:Math.max(t.a[1],t.b[1])+i})),n=[...s].sort((t,e)=>t.minX-e.minX||t.minY-e.minY||t.index-e.index),o=[...s].sort((t,e)=>t.maxX-e.maxX||t.index-e.index),a=new Set;let r=null,l=0;for(const s of n){for(;lt.index-e.index);for(const o of n)hu(t[o.index],t[s.index],e[o.index],e[s.index],i);a.add(s.index),r=gu(r,s)}}(s,n,i);const o=new Map;for(let t=0;t({key:t,a:e.a,b:e.b,sourceKeys:[...e.sourceKeys].sort((t,e)=>t.localeCompare(e))})).sort((t,e)=>t.key.localeCompare(e.key))}function bu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=yu(t,i),n=new Map,o=new Map,a=new Map(s.map(t=>[t.key,t]));for(const t of s){const e=su(t.a,i),s=su(t.b,i);n.set(e,t.a),n.set(s,t.b),o.has(e)||o.set(e,new Set),o.has(s)||o.set(s,new Set),o.get(e).add(s),o.get(s).add(e)}const r=new Map;for(const[t,e]of o){const i=n.get(t);r.set(t,[...e].sort((t,e)=>{const s=n.get(t),o=n.get(e);return Math.atan2(s[1]-i[1],s[0]-i[0])-Math.atan2(o[1]-i[1],o[0]-i[0])||t.localeCompare(e)}))}const l=new Set,c=new Map,h=(t,e)=>`${t}>${e}`;for(const t of s){const e=[su(t.a,i),su(t.b,i)];for(const[t,o]of[e,[e[1],e[0]]]){if(l.has(h(t,o)))continue;const e=[],d=[];let p=t,u=o,_=!1;for(let i=0;i<=2*s.length+2;i++){const i=h(p,u);if(l.has(i)){_=p===t&&u===o;break}l.add(i),e.push(p),d.push(nu(p,u));const s=r.get(u)||[],n=s.indexOf(p);if(n<0||!s.length)break;if(p=u,u=s[(n-1+s.length)%s.length],p===t&&u===o){_=!0;break}}if(!_||new Set(e).size<3||new Set(e).size!==e.length)continue;const m=e.map(t=>n.get(t)),g=eu(m);if(!(g>i*i))continue;const f=ou(au(e,n,i)),v=new Set;for(const t of d)for(const e of a.get(t)?.sourceKeys||[])v.add(e);const y={ring:m,key:f,area:g,atomKeys:[...d],sourceKeys:[...v].sort((t,e)=>t.localeCompare(e))};c.has(f)||c.set(f,y)}}return{atoms:s,faces:[...c.values()].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))}}function wu(t,e,i=.001){if(!Qp(e))return null;const s=t.faces.filter(t=>{if(t.ring.some((s,n)=>function(t,e,i,s){const n=i[0]-e[0],o=i[1]-e[1],a=n*n+o*o;if(!(a>0))return Math.hypot(t[0]-e[0],t[1]-e[1])<=s;const r=((t[0]-e[0])*n+(t[1]-e[1])*o)/a;return!(r<0||r>1)&&Math.hypot(e[0]+n*r-t[0],e[1]+o*r-t[1])<=s}(e,s,t.ring[(n+1)%t.ring.length],i)))return!1;let s=!1;for(let i=0,n=t.ring.length-1;ie[1]!=a[1]>e[1]&&e[0]<(a[0]-o[0])*(e[1]-o[1])/(a[1]-o[1])+o[0]&&(s=!s)}return s});return[...s].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))[0]||null}function ku(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n,a=o>0?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o)):0;return Math.hypot(e[0]+s*a-t[0],e[1]+n*a-t[1])}function xu(t,e,i=.5){let s=Math.abs(t-e)%180;return s>90&&(s=180-s),s<=i}function $u(t,e,i,s){const n=t.filter(t=>"outer"===t.kind&&!t.open&&t.cm>0).map(t=>({interval:t,reusePartitionId:e.find(e=>function(t,e,i){return!(Math.abs(t.cm-e.cm)>1e-6)&&(xu(180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI,180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI,.001)&&ku(e.a,t.a,t.b)<=i&&ku(e.b,t.a,t.b)<=i)}(e,t,s))?.id||null})),o=new Map;for(const e of i){if("partition"===e.host?.kind)continue;const i=t.map(t=>{const i=180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI;return{interval:t,distance:xu(e.angle,i)?ku([e.x,e.y],t.a,t.b):1/0}}).filter(t=>t.distance<=s).sort((t,e)=>t.distance-e.distance||t.interval.key.localeCompare(e.interval.key)),n=i[0]?.interval;"outer"===n?.kind&&!n.open&&n.cm>0&&o.set(e.id,n.key)}return{materialize:n,openingIntervals:o,removeOpeningIds:[...o.keys()].sort((t,e)=>t.localeCompare(e))}}function Su(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?Math.max(0,Math.min(1,((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n)):0}const Mu=t=>!t.key.startsWith("static:room|");function Cu(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;if(!(n>0))return null;const o=((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n,a=[e.a[0]+i*o,e.a[1]+s*o];return{point:a,t:o,distance:Math.hypot(a[0]-t[0],a[1]-t[1])}}function Du(t,e){return e>0?Math.hypot(t[0]-Math.round(t[0]/e)*e,t[1]-Math.round(t[1]/e)*e):0}function Pu(t,e,i){if(Mu(t.source)!==Mu(e.source))return Mu(t.source)?t:e;const s=Du(t.point,i),n=Du(e.point,i);return Math.abs(s-n)>1e-9?s>n?t:e:function(t,e){return t[0]-e[0]||t[1]-e[1]}(t.point,e.point)>0?t:e}function Tu(t){return[t.from[0],t.from[1],t.to[0],t.to[1],t.targetKind].map(t=>"number"==typeof t?t.toFixed(6):t).join("|")}function Ru(t,e){return t.map(t=>t.key!==e.sourceKey?t:{...t,[e.endpoint]:[...e.to]})}function Iu(t,e){const i=e.epsilon??.001;if(!(e.maxDistance>=0)||!e.point&&!e.requiredSourceKey)return{kind:"none"};const s=new Map,n=t.flatMap(t=>[{source:t,endpoint:"a",point:t.a},{source:t,endpoint:"b",point:t.b}]);for(let t=0;ti)||l>e.maxDistance)continue;const c=Pu(a,r,e.gridStep||0),h=c===a?r:a;if(!Mu(c.source))continue;const d={sourceKey:c.source.key,endpoint:c.endpoint,from:[c.point[0],c.point[1]],to:[h.point[0],h.point[1]],targetSourceKey:h.source.key,targetKind:"endpoint",distance:l};s.set(Tu(d),d)}for(const o of n)if(Mu(o.source))for(const n of t){if(n===o.source)continue;const t=Cu(o.point,n);if(!t||t.t<=i||t.t>=1-i||!(t.distance>i)||t.distance>e.maxDistance)continue;const a={sourceKey:o.source.key,endpoint:o.endpoint,from:[o.point[0],o.point[1]],to:t.point,targetSourceKey:n.key,targetKind:"line",distance:t.distance};s.set(Tu(a),a)}const o=[];for(const n of s.values()){const s=bu(Ru(t,n),i),a=e.point?wu(s,e.point,i):s.faces.find(t=>!e.requiredSourceKey||t.sourceKeys.includes(e.requiredSourceKey))||null;a&&o.push({proposal:n,face:a})}if(o.sort((t,e)=>t.proposal.distance-e.proposal.distance||Tu(t.proposal).localeCompare(Tu(e.proposal))),!o.length)return{kind:"none"};return new Set(o.map(t=>`${Tu(t.proposal)}|${t.face.key}`)).size>1?{kind:"ambiguous",proposals:o.map(t=>t.proposal)}:{kind:"repair",...o[0]}}const Au=1e-5;function zu(t){const e=t.map(()=>[]);for(let i=0;i=1-1e-9||p<=1e-9||p>=1-1e-9||(e[i].push(d),e[a].push(p))}}const i=[];for(let s=0;st-e),1];for(let t=1;t{const i=e[2]-e[0],s=e[3]-e[1],n=i*i+s*s;if(!(n>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const o=Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/n));return Math.hypot(t[0]-(e[0]+o*i),t[1]-(e[1]+o*s))},Nu=(t,e,i,s)=>{const n=s[2]-s[0],o=s[3]-s[1],a=e*o-i*n;if(Math.abs(a)<1e-12)return 1/0;const r=s[0]-t[0],l=s[1]-t[1],c=(r*o-l*n)/a;if(!(c>1e-9))return 1/0;const h=(r*i-l*e)/a;return h<-1e-9||h>1+1e-9?1/0:c};function Ou(t,e,i,s=96){if(!(e>0&&Number.isFinite(t[0])&&Number.isFinite(t[1])))return[];const n=[];for(const s of i){if(!s||s.length<4)continue;if(![s[0],s[1],s[2],s[3]].every(Number.isFinite))continue;const i=Eu(t,s);if(i<1e-7)return[];i>e||n.push(s)}const o=[],a=Math.max(12,Math.round(s));for(let t=0;tt-e);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const s=Math.cos(i),o=Math.sin(i);let a=e;for(const e of n){const i=Nu(t,s,o,e);i=3?l:[]}class Lu extends ht{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(t){this._config=t}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const t=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(t?.config?.spaces||[]).map(t=>({value:t.id,label:t.title||t.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return ra(this.hass,this._config?.language)}get _floorToken(){const t=this._config?.floor;return"number"==typeof t?`__houseplan_yaml_floor_index__:${String(t)}`:null}get _formData(){const t={...this._config},e=this._floorToken;return e?t.floor=e:Object.prototype.hasOwnProperty.call(t,"floor")||(t.floor=""),t}get _schema(){const t=this._spaces||[],e=this._lang,i=[{value:"",label:la(e,"editor.floor_none")}],s=this._floorToken;s&&i.push({value:s,label:la(e,"editor.floor_index",{index:String(this._config?.floor)})});const n="string"==typeof this._config?.floor?this._config.floor:"";n&&!t.some(t=>t.value===n)&&i.push({value:n,label:n}),i.push(...t);const o="string"==typeof this._config?.default_floor?this._config.default_floor:"",a=[...t];return o&&!t.some(t=>t.value===o)&&a.unshift({value:o,label:o}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:i}}},t.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:a}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:[{value:"",label:la(e,"editor.lang_auto")},{value:"en",label:la(e,"editor.lang_en")},{value:"ru",label:la(e,"editor.lang_ru")}]}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return G;this._loadSpaces();const t=this._lang,e={title:la(t,"editor.title"),floor:la(t,"editor.floor"),default_floor:la(t,"editor.default_floor"),language:la(t,"editor.language"),icon_size:la(t,"editor.icon_size"),show_temperature:la(t,"editor.show_temperature"),live_states:la(t,"editor.live_states"),show_signal:la(t,"editor.show_signal"),kiosk:la(t,"editor.kiosk"),cycle:la(t,"editor.cycle")},i=this._schema,s=function(t,e,i){if(!i||null===e)return null;const s="string"==typeof t?.default_floor?t.default_floor:"";return!s||e.some(t=>t.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),n=t=>W`${t.visibleLabel}`:G}
${t?.content||G}
- `}afterRender(){const t=this.host.root();this._blocked&&(this._openGroupId?this.closeGroup(!1):"palette"===this._currentModel?.kind&&this._currentModel.dismiss?.()),this._syncGlobalDismissListener();const e=t.querySelector(".editor-secondary"),i=this._renderedContext,s=e?.dataset.contextId||"";if(s&&i&&s!==i&&!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches&&(this._contentAnimation?.cancel(),this._contentAnimation=e?.querySelector(".editor-secondary-content")?.animate([{opacity:.35,transform:"translateY(-4px)"},{opacity:1,transform:"translateY(0)"}],{duration:100,easing:"ease-out"})),this._renderedContext=s,i&&s!==i&&this._focusOwned){const i=s?e?.querySelector('[tabindex="0"], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'):t.querySelector(".editbar-tools");i?.focus?.(),this._focusOwned=!!s}if("palette"===this._currentModel?.kind&&this._currentModel.launcherId){const e=[...t.querySelectorAll("[data-editor-palette]")].find(t=>t.dataset.editorPalette===this._currentModel?.launcherId);e&&null!==e.offsetParent||this._currentModel.dismiss?.()}if(!this._openGroupId)return;const n=[...t.querySelectorAll("[data-editor-group]")].find(t=>t.dataset.editorGroup===this._openGroupId);n&&null!==n.offsetParent||this.closeGroup(!0)}handleOutsideDismiss(t){if(q_(t,t=>t.hasAttribute("data-editor-navigation")))return"pointerdown"===t.type?this.closeForNavigation():"click"===t.type&&this._dismissPointerTarget&&this._clearDismissClick(),!1;if("click"===t.type&&this._dismissPointerTarget){return!!(t.composedPath?.()||[t.target]).includes(this._dismissPointerTarget)&&(this._clearDismissClick(),t.preventDefault(),t.stopImmediatePropagation(),!0)}const e=this._openGroupId||this._blocked||"palette"!==this._currentModel?.kind?null:this._currentModel;if("pointerdown"===t.type&&(this._openGroupId||e)){const i=q_(t,t=>t.classList.contains("editor-secondary")),s=q_(t,t=>!!t.dataset.editorGroup),n=q_(t,t=>!!t.dataset.editorPalette),o=q_(t,t=>t.classList.contains("stage"));if(!(i||s||n||"stay-open-on-canvas"===e?.dismissPolicy&&o))return t.preventDefault(),t.stopImmediatePropagation(),this._dismissPointerTarget=t.target,clearTimeout(this._dismissTimer),this._dismissTimer=window.setTimeout(()=>{this._clearDismissClick()},800),this._openGroupId?this.closeGroup(!1):e?.dismiss?.(),this._syncGlobalDismissListener(),!0}return!1}_activateGroupItem(t,e,i){if(t.id!==this._openGroupId)return;const s=t.items.find(t=>t.id===e);if(!s||s.disabled)return;const n="toggle"===s.role&&"stay-open"===s.closePolicy,o=0===i.detail;n||(this._openGroupId=null,this.host.requestUpdate(),this._syncGlobalDismissListener()),s.invoke(),!n&&o&&this.host.updateComplete().then(()=>{const e=[...this.host.root().querySelectorAll("[data-editor-group]")].find(e=>e.dataset.editorGroup===t.id&&null!==e.offsetParent);e?.focus()})}_groupKeydown(t){if(!["ArrowLeft","ArrowRight","Home","End"].includes(t.key))return;const e=[...t.currentTarget.querySelectorAll(".editor-group-item:not([disabled])")];if(!e.length)return;t.preventDefault();const i=e.indexOf(this.host.root().activeElement),s="Home"===t.key?0:"End"===t.key?e.length-1:"ArrowLeft"===t.key?i<=0?e.length-1:i-1:(i+1)%e.length;e[s]?.focus()}_clearDismissClick(){this._dismissPointerTarget=null,clearTimeout(this._dismissTimer),this._dismissTimer=void 0,this._syncGlobalDismissListener()}_syncGlobalDismissListener(){const t=!this._blocked&&"palette"===this._currentModel?.kind,e=!!this._openGroupId||t||!!this._dismissPointerTarget;e!==this._globalDismissListening&&(this._globalDismissListening=e,e?(window.addEventListener("pointerdown",this._globalDismissGuard,!0),window.addEventListener("click",this._globalDismissGuard,!0)):(window.removeEventListener("pointerdown",this._globalDismissGuard,!0),window.removeEventListener("click",this._globalDismissGuard,!0)))}}const j_=t=>t.stopPropagation(),U_=4.166666666666667e-9;function G_(t){return Number.isFinite(t)?Math.round(t/Th)*Th:t}const V_=(t,e,i,s)=>Math.hypot(i-t,s-e),K_=(t,e,i,s,n,o,a,r)=>Math.hypot(Math.max(Math.abs(n-t),Math.abs(n+a-(t+i))),Math.max(Math.abs(o-e),Math.abs(o+r-(e+s)))),Y_=(t,e,i,s,n,o,a)=>{const r=Math.max(Number(s)||0,0)/2,l=Math.PI/180,c=Math.cos(i*l)*r,h=Math.sin(i*l)*r,d=Math.cos(a*l)*r,p=Math.sin(a*l)*r,u=Math.max(V_(t+c,e+h,n+d,o+p),V_(t-c,e-h,n-d,o-p)),_=Math.max(V_(t+c,e+h,n-d,o-p),V_(t-c,e-h,n+d,o+p));return Math.min(u,_)},J_=t=>{const e=Number(t?.cell_cm);return e>0?e:5};function X_(t,e){const i=JSON.parse(JSON.stringify(t||[])),s=JSON.parse(JSON.stringify(e||{}));let n=0,o=0,a=0,r=0,l="",c=0,h=0,d=0;const p=(t,e)=>{Number.isFinite(t)&&Number.isFinite(e)&&t!==e&&Math.abs(e-t)<=U_&&h++},u=(t,e)=>{p(t[0],e[0]),p(t[1],e[1])},_={};let m=5;for(const t of i){const e=J_(t);null!=t?.id&&(_[String(t.id)]=e),e>m&&(m=e)}const g=(t,e,i,s=!1)=>{if(!(t>U_||s))return;n++,t>a&&(a=t);const o=t*Dh*e;o>r&&(r=o,l=i)};for(const t of i){const e=J_(t),i=null!=t?.id?String(t.id):"";for(const s of t.rooms||[]){o++;let t=0;if(s.poly?.length)s.poly=s.poly.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),u(e,i),i});else if(null!=s.x&&null!=s.y){const e=s.x,i=s.y,n=s.w||0,o=s.h||0,a=G_(e+n),r=G_(i+o),l=G_(e),c=G_(i),h=Math.max(Th,a-l),d=Math.max(Th,r-c);t=K_(e,i,n,o,l,c,h,d),s.x=l,s.y=c,s.w=h,s.h=d,p(e,l),p(i,c),p(e+n,l+h),p(i+o,c+d)}g(t,e,i)}for(const s of t.room_drafts||[]){o++;let t=0;const n=s.points||[],a=n.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),i}),r=a.length?[a[0]]:[],l=a.length?[[n[0],a[0]]]:[],c=[];for(let t=0;t+1=2)for(const[t,e]of l)u(t,e);g(t,e,i)}if(Array.isArray(t.room_drafts)){const e=t.room_drafts.length;t.room_drafts=t.room_drafts.filter(t=>t.points?.length>=2),d+=e-t.room_drafts.length,t.room_drafts.length||delete t.room_drafts}for(const s of t.partitions||[]){o++;const n=[s.a[0],s.a[1]],a=[s.b[0],s.b[1]],r=[G_(n[0]),G_(n[1])],l=[G_(a[0]),G_(a[1])];let c=Math.max(V_(n[0],n[1],r[0],r[1]),V_(a[0],a[1],l[0],l[1]));const h=V_(r[0],r[1],l[0],l[1]),d=(t.openings||[]).filter(t=>"partition"===t.host?.kind&&t.host.id===s.id).every(t=>{const e=Number(t.length),i=Number(t.host.t),s=i*h;return Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>=0&&i<=1&&s-e/2>=-U_&&s+e/2<=h+U_});h>U_&&d?(s.a=r,s.b=l,u(n,r),u(a,l)):c=0,g(c,e,i)}for(const s of t.wall_columns||[]){o++;const t=[s.center[0],s.center[1]],n=[G_(t[0]),G_(t[1])],a=V_(t[0],t[1],n[0],n[1]);s.center=n,u(t,n),g(a,e,i)}for(const s of t.decor||[]){o++;let t=0;if("line"===s.kind){const e=[s.x1,s.y1],i=[s.x2,s.y2],n=[G_(e[0]),G_(e[1])],o=[G_(i[0]),G_(i[1])];t=Math.max(V_(e[0],e[1],n[0],n[1]),V_(i[0],i[1],o[0],o[1])),s.x1=n[0],s.y1=n[1],s.x2=o[0],s.y2=o[1],u(e,n),u(i,o)}else{const e=s.x,i=s.y,n=s.w,o=s.h,a=G_(e),r=G_(i);if(null!=s.w&&null!=s.h){const l=G_(e+n),c=G_(i+o),h=Math.max(Th,l-a),d=Math.max(Th,c-r);t=K_(e,i,n,o,a,r,h,d),s.w=h,s.h=d,p(e+n,a+h),p(i+o,r+d)}else t=V_(e,i,a,r);s.x=a,s.y=r,p(e,a),p(i,r)}g(t,e,i)}for(const s of t.openings||[]){if(o++,"partition"===s.host?.kind){const n=(t.partitions||[]).find(t=>t.id===s.host.id),o=Number(s.host.t);if(!n||!Number.isFinite(o)||o<0||o>1)continue;const a=n.b[0]-n.a[0],r=n.b[1]-n.a[1];if(Math.hypot(a,r)<=U_)continue;const l=n.a[0]+a*o,h=n.a[1]+r*o;let d=180*Math.atan2(r,a)/Math.PI;d>=90?d-=180:d<-90&&(d+=180);const p=Number(s.angle),u=!(Number.isFinite(p)&&p===d),_=Y_(s.x,s.y,Number.isFinite(p)?p:d,Number(s.length)||0,l,h,d);s.x=l,s.y=h,s.angle=d,u&&c++,g(_,e,i,u);continue}const n=ui([s.x,s.y],t.rooms||[],.025,{step:Th,length:Number(s.length)||0});if(!n)continue;const a=Number(s.angle),r=!(Number.isFinite(a)&&a===n.angle),l=Y_(s.x,s.y,Number.isFinite(a)?a:n.angle,Number(s.length)||0,n.x,n.y,n.angle);s.x=n.x,s.y=n.y,s.angle=n.angle,r&&c++,g(l,e,i,r)}}for(const[t,e]of Object.entries(s)){if(!e||"object"!=typeof e)continue;const i=e;if("number"!=typeof i.x||"number"!=typeof i.y)continue;o++;const n=G_(i.x),a=G_(i.y),r=V_(i.x,i.y,n,a);s[t]={...i,x:n,y:a},p(i.x,n),p(i.y,a);const l="string"==typeof i.s?i.s:"";g(r,_[l]??m,l)}return{spaces:i,layout:s,report:{moved:n,coordsCanonicalized:h,total:o,maxShift:a,maxShiftCm:r,maxSpace:l,rotated:c,removedDrafts:d},changed:n>0||h>0}}function Z_(t,e){const i=e.base+t*e.span;return Math.min(1,Math.max(0,i))}const Q_=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),tm=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1]);function em(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<=0)return tm(t,e);let a=((t[0]-e[0])*s+(t[1]-e[1])*n)/o;return a=Math.max(0,Math.min(1,a)),Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))}function im(t,e,i,s,n){for(const s of e)if(s&&!i.has(s.id)&&Q_(s.a)&&Q_(s.b)&&(tm(t,s.a)<=n||tm(t,s.b)<=n))return!0;for(const e of s?.roomPolygons||[])for(let i=0;i0&&r>0))return null;if(Math.abs(n[0]/a*(o[1]/r)-n[1]/a*(o[0]/r))>i)return null;for(const[i,n]of[[t.a,e.a],[t.a,e.b],[t.b,e.a],[t.b,e.b]])if(tm(i,n)<=s)return[(i[0]+n[0])/2,(i[1]+n[1])/2];return null}function nm(t,e){const i=.05*(Number(e.pitch)>0?Number(e.pitch):1),s=new Map;let n=(t||[]).filter(t=>!!t&&"string"==typeof t.id&&Q_(t.a)&&Q_(t.b));if(n.length<2)return{partitions:[...t||[]],merged:0,openingMoves:[]};const o=e.seedIds&&e.seedIds.length?new Set(e.seedIds):null;let a=0;for(let t=0;ttm(e,t.at)>i);let h=c[0]??r.a,d=c[c.length-1]??l.b;if(c.length<2&&(h=r.a,d=l.b),d[0]0?(d[0]-h[0])/u:0,m=u>0?(d[1]-h[1])/u:0,g=t=>u>0?((t[0]-h[0])*_+(t[1]-h[1])*m)/u:0;for(const t of[r,l]){const e=g(t.a),i=g(t.b)-e;for(const[n,o]of s)o.toId===t.id&&s.set(n,{fromId:o.fromId,toId:p.id,base:e+o.base*i,span:o.span*i});s.set(t.id,{fromId:t.id,toId:p.id,base:e,span:i})}o&&o.add(p.id),n=n.filter((e,i)=>i!==t.i&&i!==t.j),n.splice(t.i,0,p),a++}return{partitions:n,merged:a,openingMoves:[...s.values()]}}function om(t,e,i,s){if(!t?.length||!i.length)return 0;const n=new Map(i.map(t=>[t.fromId,t]));let o=0;for(const i of t){const t=i?.host;if(!t||"partition"!==t.kind)continue;const a=n.get(t.id);if(!a)continue;i.host={...t,id:a.toId,t:Z_(t.t,a)},o++;const r=Sp(i,e,s.coordScale,s.cellCm,s.gridPitch).resolved;r&&Object.assign(i,Ip(i,r,s.coordScale))}return o}function am(t,e){const i=e?.excludeDraftId||null;return{roomPolygons:(t?.rooms||[]).map(t=>hi(t)).filter(t=>!!t),columns:t?.wall_columns||[],draftEnds:(t?.room_drafts||[]).flatMap(t=>{if(i&&t?.id===i)return[];const e=t?.points||[];return e.length?[e[0],e[e.length-1]]:[]})}}const rm=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),lm=(t,e)=>t[0]-e[0]||t[1]-e[1],cm=(t,e,i,s)=>[t[0]+e*s,t[1]+i*s],hm=(t,e,i,s)=>(t[0]-e[0])*i+(t[1]-e[1])*s,dm=(t,e,i,s,n)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n))return null;const l=o/r,c=a/r,h=e=>Math.abs((e[0]-t[0])*c-(e[1]-t[1])*l);if(h(i)>n||h(s)>n)return null;const d=hm(i,t,l,c),p=hm(s,t,l,c),u=Math.max(0,Math.min(d,p)),_=Math.min(r,Math.max(d,p));return _-u>n?{lo:u,hi:_}:null},pm=(t,e,i)=>Math.min(t.hi,e.hi)-Math.max(t.lo,e.lo)>i,um=t=>{const e=new Set(["id","a","b","cm"]);return Object.keys(t||{}).every(t=>e.has(t))},_m=(t,e,i,s)=>{const n=t.b[0]-t.a[0],o=t.b[1]-t.a[1],a=Math.hypot(n,o);if(!(a>s))return!0;const r=n/a,l=o/a,c=gl(t.cm,i.cellCm,i.gridPitch)/2;return e.some(e=>{const n=e?.center;if(!rm(n))return!0;const o=hm(n,t.a,r,l),h=Math.abs((n[0]-t.a[0])*l-(n[1]-t.a[1])*r),d=gl(Number(e.cm),i.cellCm,i.gridPitch)*("square"===e.shape?Math.SQRT1_2:.5);return!(Number.isFinite(d)&&d>0)||o>=-d-s&&o<=a+d+s&&h<=c+d+s})},mm=(t,e,i)=>{if(t.host){const s=Sp(t,e,i.coordScale,i.cellCm,i.gridPitch).resolved;return s?{center:s.center,angle:s.angle,length:s.length}:null}const s=Number(t.x)*i.coordScale,n=Number(t.y)*i.coordScale,o=Number(t.angle),a=Number(t.length)*i.coordScale;return[s,n,o,a].every(Number.isFinite)&&a>0?{center:[s,n],angle:o,length:a}:null},gm=(t,e,i)=>{const s=t.angle*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=e.angle*Math.PI/180,r=Math.cos(a),l=Math.sin(a);if(Math.abs(n*l-o*r)>1e-6)return!1;const c=e.center[0]-t.center[0],h=e.center[1]-t.center[1];if(Math.abs(c*o-h*n)>i)return!1;const d=c*n+h*o;return Math.max(-t.length/2,d-e.length/2)({...t,a:[t.a[0]*e,t.a[1]*e],b:[t.b[0]*e,t.b[1]*e]}),vm=(t,e,i,s)=>{const n=`~r-${(t=>{let e=2166136261;for(let i=0;i>>0;return e.toString(36)})(`${t}|${e[0].toFixed(9)},${e[1].toFixed(9)}|${i[0].toFixed(9)},${i[1].toFixed(9)}`)}`,o=`${t.slice(0,Math.max(1,64-n.length))}${n}`;let a=o;for(let t=2;s.has(a);t++){const e=`-${t}`;a=`${o.slice(0,64-e.length)}${e}`}return s.add(a),a},ym=(t,e)=>{const i=[];for(const s of t){const t=i[i.length-1];!(t&&Math.abs(t.hi-s.lo)<=e&&t.safe===s.safe)||s.safe&&t.signature!==s.signature?i.push({lo:s.lo,hi:s.hi,a:s.a,b:s.b,safe:s.safe,signature:s.signature,roomIds:s.roomIds,finalCm:s.finalCm}):(t.hi=s.hi,t.b=s.b)}return i};function bm(t,e,i,s,n){const o=i||[],a=Array.isArray(t?.partitions)?t.partitions:[],r=Array.isArray(t?.openings)?t.openings:[],l=Array.isArray(t?.room_drafts)?t.room_drafts:[],c={walls:o,partitions:a,openings:r,roomDrafts:l,partitionsReconciled:0,openingsRehosted:0,removedDrafts:0};if(!a.length&&!l.length)return c;const h=Math.max(2e-4*n.gridPitch,1e-9);let d=o,p=a,u=r;const _=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),m=((t,e,i,s)=>{const n=new Map(t.map(t=>[t.id,t])),o=new Set;for(const t of e){if(!n.get(t.id)||!Array.isArray(t.points)||t.points.length<2||t.segments.length!==t.points.length-1)continue;let e=!0;for(let n=0;n+10)){e=!1;break}const l=Math.hypot(a[0]-o[0],a[1]-o[1]);if(!(l>s)){e=!1;break}const c=i.flatMap(t=>{const e=t.cm>0?t.cm:ll;if(t.open||"outer"!==t.kind&&"shared"!==t.kind||e+st.lo-e.lo||t.hi-e.hi);let h=0;for(const t of c){if(t.lo>h+s)break;if(h=Math.max(h,t.hi),h>=l-s)break}h!m.has(t.id));let f=0,v=0;const y=new Map(e.partitions.map(t=>[t.id,t]));for(const t of[...a].sort((t,e)=>t.id.localeCompare(e.id))){if(!p.some(e=>e.id===t.id))continue;if(!um(t))continue;const i=y.get(t.id);if(!(i&&rm(i.a)&&rm(i.b)&&Number.isFinite(i.cm)&&i.cm>0))continue;const[o,a]=lm(i.a,i.b)<=0?[[i.a[0],i.a[1]],[i.b[0],i.b[1]]]:[[i.b[0],i.b[1]],[i.a[0],i.a[1]]],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>h))continue;const _=r/c,g=l/c,b=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),w=b.flatMap(t=>{if(t.open||"outer"!==t.kind&&"shared"!==t.kind)return[];const e=dm(o,a,t.a,t.b,h);return e?[{interval:t,range:e}]:[]});if(!w.length)continue;const k=u.filter(t=>"partition"===t.host?.kind&&t.host.id===i.id).map(t=>({opening:t,resolved:Sp(t,e.partitions,n.coordScale,n.cellCm,n.gridPitch).resolved}));if(k.some(t=>!t.resolved))continue;const x=[0,c];for(const{range:t}of w)x.push(t.lo,t.hi);const $=x.slice(),S=new Map;for(const{opening:t,resolved:e}of k){const i=hm(e.center,o,_,g),s={lo:i-e.length/2,hi:i+e.length/2};S.set(t.id,s),$.push(Math.max(0,s.lo),Math.min(c,s.hi))}const M=[...new Set($.filter(t=>Number.isFinite(t)&&t>=-h&&t<=c+h).map(t=>Math.max(0,Math.min(c,t)).toFixed(9)))].map(Number).sort((t,e)=>t-e),C=p.map(t=>fm(t,n.coordScale)).filter(t=>t.id!==i.id),D=e.room_drafts.filter(t=>!m.has(t.id)),P=[];for(let t=0;t+1h))continue;const r=cm(o,_,g,s),l=cm(o,_,g,a),c=w.filter(({range:t})=>t.lo<=s+h&&t.hi>=a-h).map(({interval:t})=>t),d=new Map;for(const t of c)d.set(t.roomId,t);const p=[...d.values()],u=new Set(p.map(t=>t.kind)),m=new Set(p.map(t=>t.cm>0?t.cm:ll)),f=p[0]?.kind,v=[...d.keys()].sort(),y=1===u.size&&1===m.size&&("outer"===f&&1===v.length||"shared"===f&&2===v.length),b={id:i.id,a:r,b:l,cm:i.cm},k=C.some(t=>!!dm(r,l,t.a,t.b,h)),x=D.some(t=>t.points.some((e,i)=>i+10?p[0].cm:ll:0,T=y?Math.max(S,i.cm):i.cm;P.push({lo:s,hi:a,a:r,b:l,safe:$,signature:$?`${f}|${v.join(",")}|${T}`:"",roomIds:v,roomCm:S,finalCm:T})}if(!P.some(t=>t.safe))continue;const T=new Map;for(const{opening:t,resolved:e}of k){const s=S.get(t.id),o=x.some(t=>t>s.lo+h&&tpm(t,s,h)),r=new Set(a.filter(t=>t.safe).map(t=>t.signature));if(!o&&a.length>0&&a.every(t=>t.safe)&&1===r.size&&Rp(e,b,h)){T.set(t.id,{resolved:e,signature:[...r][0]});continue}const l=xp(i,n.cellCm,n.gridPitch),c={lo:s.lo-l,hi:s.hi+l};for(const t of P)pm(t,c,h)&&(t.safe=!1,t.signature="")}let R=!0;for(;R;){R=!1;for(const[t,e]of[...T.entries()]){const s=S.get(t),o=P.filter(t=>pm(t,s,h));if(o.length>0&&o.every(t=>t.safe)&&o.every(t=>t.signature===e.signature))continue;T.delete(t);const a=xp(i,n.cellCm,n.gridPitch),r={lo:s.lo-a,hi:s.hi+a};for(const t of P)pm(t,r,h)&&(t.safe=!1,t.signature="");R=!0}}const I=ym(P,h),A=I.filter(t=>t.safe),z=I.filter(t=>!t.safe);if(!A.length)continue;if(p.length-1+z.length>2e3)continue;let F=d;for(const t of A){const[e,s]=lm(i.a,i.b)<=0?[t.a,t.b]:[t.b,t.a];F=Fl(F,e,s,t.finalCm,n.pitch,n.coordScale)}if(F=uc(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),F.length>500)continue;const E=new Set(p.map(t=>t.id));E.delete(i.id);const N=z.map((t,e)=>{const s=[t.a[0]/n.coordScale,t.a[1]/n.coordScale],o=[t.b[0]/n.coordScale,t.b[1]/n.coordScale],a=0===e?i.id:vm(i.id,s,o,E);return E.add(a),{id:a,a:s,b:o,cm:i.cm}}),O=p.findIndex(t=>t.id===i.id),L=p.slice();L.splice(O,1,...N);const H=L.map(t=>fm(t,n.coordScale)),B=new Map;let q=!0;for(const{opening:t,resolved:e}of k){const i=T.get(t.id);if(i){const e=Ip(t,i.resolved,n.coordScale),{host:s,...o}=e;B.set(t.id,o);continue}const s=S.get(t.id),o=N[z.findIndex(t=>t.lo<=s.lo+h&&t.hi>=s.hi-h)],a=o&&H.find(t=>t.id===o.id);if(!o||!a){q=!1;break}const r=a.b[0]-a.a[0],l=a.b[1]-a.a[1],c=Math.hypot(r,l),d=hm(e.center,a.a,r/c,l/c),p={...Ip(t,e,n.coordScale),host:{kind:"partition",id:o.id,t:d/c}};if(!Mp(p,H,n.coordScale,n.cellCm,n.gridPitch).resolved){q=!1;break}B.set(t.id,p)}if(!q)continue;const W=u.map(t=>B.get(t.id)||t),j=[...T.keys()].map(t=>B.get(t)),U=j.map(t=>mm(t,H,n));if(U.some(t=>!t))continue;let G=!1;for(let t=0;tt.id));for(const t of W){if(V.has(t.id))continue;const e=mm(t,H,n);e&&U.some(t=>gm(t,e,h))&&(G=!0)}if(G)continue;const K=Ec(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale);[...T.entries()].every(([t,e])=>{const i=B.get(t),s=Lc(K,{x:i.x*n.coordScale,y:i.y*n.coordScale,angle:i.angle,length:i.length*n.coordScale},!0),o=[s.negative,s.positive].filter(t=>!!t?.full),a=e.signature.split("|")[1].split(","),r=new Set(o.map(t=>t.roomId));return o.length===a.length&&r.size===a.length&&a.every(t=>r.has(t))})&&(d=F,p=L,u=W,f+=A.length,v+=T.size)}return{walls:d,partitions:p,openings:u,roomDrafts:g,partitionsReconciled:f,openingsRehosted:v,removedDrafts:m.size}}const wm=t=>JSON.parse(JSON.stringify(t)),km=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),xm=(t,e)=>e.length>0&&e.length<=35&&("space"===t?/^[a-z0-9_-]+$/.test(e):/^[A-Za-z0-9_-]+$/.test(e));function $m(t,e){let i=String(e??"");const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s}_(.+)_([0-9a-f]{8})$`);let o=0;for(;o<16;o++){const t=n.exec(i);if(!t)return{root:i,layers:o,bounded:!1};i=t[1]}return{root:i,layers:o,bounded:n.test(i)}}const Sm=(t,e,i)=>{const s=t.get(e)||[];s.push(i),t.set(e,s)};const Mm=1e-9;class Cm extends Error{constructor(t,e=""){super(e?`${t}: ${e}`:t),this.reason=t,this.name="WallSegmentModelError"}}const Dm=t=>JSON.parse(JSON.stringify(t)),Pm=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1])),Tm=t=>[Number(t[0]),Number(t[1])],Rm=t=>`${Number(t[0]).toFixed(12)},${Number(t[1]).toFixed(12)}`,Im=(t,e)=>{const i=Rm(t),s=Rm(e);return iRm(t)<=Rm(e)?[Tm(t),Tm(e)]:[Tm(e),Tm(t)],zm=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Fm=t=>{const e=[[Number(t.points[0][0]),Number(t.points[0][1])]],i=[];for(let s=1;s{const i=new Set,s=t=>{const e=Number(t);if(!Number.isFinite(e))return;const s=e/Th;Math.abs(s-Math.round(s))>=Ur&&i.add(e.toFixed(12))};for(const e of Array.isArray(t?.rooms)?t.rooms:[])for(const t of hi(e)||[])s(t[0]),s(t[1]);for(const e of[t?.wall_segments,t?.walls])for(const t of Array.isArray(e)?e:[])s(t?.a?.[0]),s(t?.a?.[1]),s(t?.b?.[0]),s(t?.b?.[1]);for(const t of e)s(t?.[0]),s(t?.[1]);return i.size},Nm=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;return o>1e-18?((t[0]-e[0])*s+(t[1]-e[1])*n)/o:0},Om=(t,e,i)=>{const s=Math.max(0,Math.min(1,Nm(t,e,i)));return Math.hypot(t[0]-(e[0]+(i[0]-e[0])*s),t[1]-(e[1]+(i[1]-e[1])*s))},Lm=(t,e,i,s,n=Mm)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(r<=n)return 0;const l=e=>Math.abs((e[0]-t[0])*a-(e[1]-t[1])*o)/r;if(l(i)>n||l(s)>n)return 0;const c=Nm(i,t,e),h=Nm(s,t,e);return Math.max(0,Math.min(1,Math.max(c,h))-Math.max(0,Math.min(c,h)))*r},Hm=t=>{const e=(new TextEncoder).encode(t),i=8*e.length,s=64*Math.ceil((e.length+9)/64),n=new Uint8Array(s);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(s-8,Math.floor(i/4294967296),!1),o.setUint32(s-4,i>>>0,!1);const a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(t,e)=>t>>>e|t<<32-e;for(let t=0;t>>3,n=c(i,17)^c(i,19)^i>>>10;l[t]=l[t-16]+s+l[t-7]+n>>>0}let[e,i,s,n,h,d,p,u]=r;for(let t=0;t<64;t++){const o=u+(c(h,6)^c(h,11)^c(h,25))+(h&d^~h&p)+a[t]+l[t]>>>0,r=e&i^e&s^i&s;u=p,p=d,d=h,h=n+o>>>0,n=s,s=i,i=e,e=o+((c(e,2)^c(e,13)^c(e,22))+r>>>0)>>>0}r[0]=r[0]+e>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+s>>>0,r[3]=r[3]+n>>>0,r[4]=r[4]+h>>>0,r[5]=r[5]+d>>>0,r[6]=r[6]+p>>>0,r[7]=r[7]+u>>>0}const h=new Uint8Array(32),d=new DataView(h.buffer);for(let t=0;t{const e="abcdefghijklmnopqrstuvwxyz234567";let i=0,s=0,n="";for(const o of t)for(s=s<<8|o,i+=8;i>=5;)n+=e[s>>>i-5&31],i-=5;return i&&(n+=e[s<<5-i&31]),n},qm=(t,e,i,s,n="")=>{const[o,a]=Am(e,i),r=`${t}|${Rm(o)}|${Rm(a)}|${[...s].sort().join(",")}${n}`;return`wall-${Bm(Hm(r)).slice(0,20)}`};let Wm=0;const jm=t=>{for(let e=0;e<1e3;e++){const e=globalThis.crypto?.randomUUID?.(),i=`wall-${e||Bm(Hm(`${Date.now()}|${Wm++}|${Math.random()}`)).slice(0,26)}`;if(!t.has(i))return i}throw new Cm("duplicate-id","id factory exhausted")},Um=t=>{const e=new Map;for(const i of Array.isArray(t?.wall_segments)?t.wall_segments:[])if(i&&"string"==typeof i.id&&Pm(i.a)&&Pm(i.b)){if(e.has(i.id))throw new Cm("duplicate-id",i.id);e.set(i.id,i)}return e},Gm=(t,e,i)=>{const s=(i,s)=>{const n=t[0]-i[0],o=t[1]-i[1];return Math.abs(e[0]-s[0]-n)<=Mm&&Math.abs(e[1]-s[1]-o)<=Mm?[n,o]:null};return s(i.a,i.b)||s(i.b,i.a)},Vm=(t,e)=>{const i=Array.isArray(t.rooms)?t.rooms:[],s=ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]),n=s.length?s:_d(i,null,1,.04*Th,!0),o=[];for(const t of i){const i=hi(t),s=Array.isArray(t?.wall_ids)?t.wall_ids:[];if(i&&s.length===i.length)for(let t=0;t"partition"!==t.host?.kind&&[Number(t.x),Number(t.y)].every(Number.isFinite)&&Number.isFinite(Number(t.angle))&&Number(t.length)>0&&n.some(e=>Om([Number(t.x),Number(t.y)],[e[0],e[1]],[e[2],e[3]])<=.04*Th)):[],l=r.map(t=>{const e=Number(t.angle)*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Number(t.length)/2,n=[Number(t.x),Number(t.y)];return{a:[n[0]-i[0]*s,n[1]-i[1]*s],b:[n[0]+i[0]*s,n[1]+i[1]*s]}}),c=(t,e)=>r.some(i=>{const s=[Number(i.x),Number(i.y)];if(!Rl(t,e,Number(i.angle)))return!1;if(Om(s,t,e)>.02*Th)return!1;const n=zm(t,e),o=Nm(s,t,e)*n,a=Number(i.length)/2;return o+a>=-Mm&&o-a<=n+Mm}),h=new Map,d=[];for(const s of i){const r=String(s?.id||""),p=hi(s);if(!r||!p||p.length<3)throw new Cm("invalid-room",r);const u=ec(i,r,a,Th,1,[...t.walls||[],...l]);if(!u||u.poly.length<3)throw new Cm("invalid-room",r);const _=Array.isArray(s.wall_ids)?s.wall_ids:[],m=_.length===p.length;let g=null,f=m;if(f)for(let t=0;tMm||Math.abs(s[1]-g[1])>Mm)){f=!1;break}g=s}const v=[];for(let t=0;t2)throw new Cm("third-owner",a);const d=m?_[u.parent[t]]:void 0;if("string"==typeof d&&d){const n=e.get(d);f||!n||Lm(i,s,n.a,n.b)>Mm?l.preferredIds.add(d):l.positionalIds.add(d),l.preferredCarriers.set(d,{a:Tm(p[u.parent[t]]),b:Tm(p[(u.parent[t]+1)%p.length])})}const g=u.parent[t];l.parentKeys.add(wl(p[g],p[(g+1)%p.length],Th));const y=[(i[0]+s[0])/2,(i[1]+s[1])/2],b=t=>t.some(t=>Om(y,[t[0],t[1]],[t[2],t[3]])<=.04*Th);l.zeroWall||=b(o)||b(n)&&!c(i,s),v.push(a)}const y={...s};delete y.wall_ids,d.push({...y,poly:u.poly.map(t=>[t[0],t[1]]),wall_ids:v})}return{atoms:[...h.values()].sort((t,e)=>t.key.localeCompare(e.key)),rooms:d}},Km=(t,e,i,s,n)=>{const o=new Map([...i.values()].map(t=>[Im(t.a,t.b),t])),a=(t=>{const e=new Map;for(const i of t)"wall"===i.host?.kind&&e.set(i.host.id,(e.get(i.host.id)||0)+1);return e})(t.openings||[]),r=new Map;for(const t of e){const e=n?.get(t.key);if(e){const s=i.get(e);if(!s)throw new Cm("duplicate-id",e);r.set(t,s);continue}if(t.preferredIds.size>1)throw new Cm("duplicate-id",[...t.preferredIds].sort().join(","));const s=[...t.preferredIds][0],l=s?i.get(s):void 0;if(l){r.set(t,l);continue}const c=s?t.preferredCarriers.get(s):void 0;if(s&&c){r.set(t,{id:s,a:c.a,b:c.b,cm:0});continue}const h=o.get(t.key);if(h){r.set(t,h);continue}const d=[...i.values()].filter(e=>Lm(t.a,t.b,e.a,e.b)>Mm),p=[...new Map(d.map(t=>[t.id,t])).values()];if(p.sort((t,e)=>(a.get(e.id)||0)-(a.get(t.id)||0)||zm(e.a,e.b)-zm(t.a,t.b)||t.id.localeCompare(e.id)),p[0])r.set(t,p[0]);else if(1===t.positionalIds.size){const e=i.get([...t.positionalIds][0]);e&&r.set(t,e)}}const l=new Map;for(const[t,e]of r){const i=l.get(e.id)||[];i.push(t),l.set(e.id,i)}for(const[t,e]of l){const s=i.get(t)||r.get(e[0]);if(!s)throw new Cm("duplicate-id",t);const n=[(s.a[0]+s.b[0])/2,(s.a[1]+s.b[1])/2];e.sort((t,e)=>{const i=Om(n,t.a,t.b)<=Mm?0:1,o=Om(n,e.a,e.b)<=Mm?0:1;if(i!==o)return i-o;return(Om(s.a,t.a,t.b)<=Mm?0:1)-(Om(s.a,e.a,e.b)<=Mm?0:1)||t.key.localeCompare(e.key)}),e[0].id=t}const c=(t=>{const e=new Set;for(const i of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns])for(const t of Array.isArray(i)?i:[])"string"==typeof t?.id&&t.id&&e.add(t.id);for(const i of Array.isArray(t.room_drafts)?t.room_drafts:[])for(const t of Array.isArray(i?.segments)?i.segments:[])"string"==typeof t?.id&&t.id&&e.add(t.id);return e})(t);for(const t of e)if(t.id){if(c.has(t.id))throw new Cm("duplicate-id",t.id);c.add(t.id)}const h=e.filter(t=>!t.id);if(s){const e=h.map(e=>{const[i,s]=Am(e.a,e.b),n=`${String(t.id||"")}|${Rm(i)}|${Rm(s)}|${[...e.owners].sort().join(",")}`,o=Bm(Hm(n));return{atom:e,seed:n,digest:o,base:`wall-${o.slice(0,20)}`}}).sort((t,e)=>t.digest.localeCompare(e.digest)||t.atom.key.localeCompare(e.atom.key)),i=new Map;for(const t of e){const e=i.get(t.digest);if(e&&e!==t.seed)throw new Cm("duplicate-id",t.digest);i.set(t.digest,t.seed);let s=1,n=t.base;for(;c.has(n);)n=`${t.base}-${++s}`;t.atom.id=n,c.add(n)}}else for(const t of h)t.id=jm(c),c.add(t.id)},Ym=(t,e)=>{if("partition"===t.host?.kind)return null;const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=e=>{if(!(Number(e.cm)>0))return!1;const s=Nm(i,e.a,e.b),n=zm(e.a,e.b),o=Number(t.length)/2;return s>=-Mm&&s<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(o)&&o>=0&&s*n-o>=-Mm&&s*n+o<=n+Mm},n="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null,o=n&&s(n)?[n]:e.filter(s);if(1!==o.length)return null;const a=o[0];return{kind:"wall",id:a.id,t:Math.max(0,Math.min(1,Nm(i,a.a,a.b)))}},Jm=(t,e)=>{const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=Number(t.length)/2,n=e.filter(e=>{if(!(Number(e.cm)>0))return!1;const n=Nm(i,e.a,e.b),o=zm(e.a,e.b);return n>=-Mm&&n<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(s)&&s>=0&&n*o-s>=-Mm&&n*o+s<=o+Mm}),o=(e=>{if(!e.length)return null;const s="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null;return s||[...e].sort((t,e)=>Om(i,t.a,t.b)-Om(i,e.a,e.b)||Number(e.cm)-Number(t.cm)||(t.ide.id?1:0))[0]})(n);return o?{kind:"wall",id:o.id,t:Math.max(0,Math.min(1,Nm(i,o.a,o.b)))}:null},Xm=(t,e,i)=>{const s=Um(t),{atoms:n,rooms:o}=Vm(t,s);Km(t,n,s,e,i);const a=n.map(e=>{const i=e.id?s.get(e.id):void 0,n=((t,e,i)=>{if(e.zeroWall)return 0;const s=Array.isArray(t.walls)?t.walls:[],n=wl(e.a,e.b,Th),o=s.filter(t=>Number(t.cm)>0&&(!(t.key!==n&&!e.parentKeys.has(t.key))||!(!Pm(t.a)||!Pm(t.b))&&Lm(e.a,e.b,t.a,t.b)>=zm(e.a,e.b)-Mm)).map(t=>Math.max(1,Math.min(100,Number(t.cm))));if(new Set(o.map(t=>t.toFixed(9))).size>1)throw new Cm("thickness-conflict",e.key);if(o.length)return o[0];const a=Pl(s,e.a,e.b,Th,1);return a>0?a:Number(i?.cm)>0?Number(i.cm):0})(t,e,i);return{...i||{},id:e.id,a:[...e.a],b:[...e.b],cm:n}}),r=new Map(n.map(t=>[t.key,t.id]));for(const t of o)t.wall_ids=t.wall_ids.map(t=>r.get(t));t.rooms=o,t.wall_segments=a,t.walls=a.filter(t=>t.cm>0).map(t=>({key:wl(t.a,t.b,Th),cm:t.cm,a:[...t.a],b:[...t.b]})),t.walls.length||delete t.walls,delete t.open_spans;for(const e of t.rooms)delete e.open_to;return((t,e)=>{const i=new Set;for(const e of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns,t.wall_segments])for(const t of Array.isArray(e)?e:[])"string"==typeof t?.id&&t.id&&i.add(t.id);for(const s of Array.isArray(t.room_drafts)?t.room_drafts:[]){const n=Array.isArray(s.segments)?s.segments:[];for(let o=0;o{const s=Array.isArray(t.openings)?t.openings:[];for(const t of s){if("partition"===t.host?.kind)continue;if(!t.host&&!i){const i=Ym(t,e);i&&(t.host=i);continue}const s=Ym(t,e)??(i?Jm(t,e):null);if(s)t.host=s;else{if(!i)throw new Cm("opening-host",t.id);delete t.host}}})(t,a,e),a.reduce((t,e)=>t+(s.has(e.id)?0:1),0)};function Zm(t,e={}){const i=JSON.stringify(t),s=Dm(t);rl(s);let n=0;const o=Number(s?.model_version||0)<9;for(const t of Array.isArray(s?.spaces)?s.spaces:[]){const i=e.lineageSpaceId===String(t?.id||"")?e.lineageHints:void 0;n+=Xm(t,o,i)}return s.model_version=9,rl(s),{config:s,changed:i!==JSON.stringify(s),migratedSegments:n}}const Qm=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tg(t,e){const i=(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){const s=new Map;for(const e of t)Qm(e)&&"string"==typeof e.id&&e.id&&s.set(e.id,e);const n=e.map((e,n)=>{if(Qm(e)&&"string"==typeof e.id&&e.id){const t=s.get(e.id);return t?i(t,e):Dm(e)}return n[e,e in t?i(t[e],s):Dm(s)]);for(const e of Object.keys(t))delete t[e];for(const[e,i]of s)t[e]=i;return t}return Dm(e)};return i(t,e)}const eg=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ig=(t,e,i)=>Math.min(i,Math.max(e,t)),sg=t=>Sh({spaces:[t]})[0],ng=(t,e,i)=>{const s=i>0?i:1,n=t=>`${(t[0]/s).toFixed(12)},${(t[1]/s).toFixed(12)}`,o=n(t),a=n(e);return o0?a:1,l=Math.max(s*r*.02,1e-9),c=[];for(const e of t||[])for(const t of hi(e)||[])c.push([t[0],t[1]]);const h=[];for(const t of i||[])Array.isArray(t)&&t.length>=4&&t.slice(0,4).every(Number.isFinite)&&h.push([t[0],t[1]],[t[2],t[3]]);const d=(t,e)=>e.some(e=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l),p=new Map;for(const a of t||[]){if(!a?.id)continue;const u=hc(t,a.id,e,i,s,n,o,r);if(u)for(let t=0;t0&&_>0&&a===m&&_!==a))continue;const g=u.poly[s],f=u.poly[(s+1)%u.poly.length],v=Math.hypot(f[0]-g[0],f[1]-g[1]);if(!(v>l&&v<.5*o-1e-9*o))continue;if(d(g,h)||d(f,h))continue;if(d(g,c)&&d(f,c))continue;const y=ng(g,f,r),b=p.get(y);b?b.targets.add(a):p.set(y,{a:[g[0],g[1]],b:[f[0],f[1]],targets:new Set([a])})}}}let u=e.slice();const _=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l,m=(t,e)=>{if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return!1;const i=[Number(t.a[0])*r,Number(t.a[1])*r],s=[Number(t.b[0])*r,Number(t.b[1])*r];return!![...i,...s].every(Number.isFinite)&&(_(i,e.a)&&_(s,e.b)||_(i,e.b)&&_(s,e.a))};for(const t of[...p.values()].filter(t=>1===t.targets.size).sort((t,e)=>ng(t.a,t.b,r).localeCompare(ng(e.a,e.b,r)))){const e=[...t.targets][0],i=u.filter(e=>m(e,t));if(new Set(i.map(t=>t.cm)).size>1)continue;let n=!1;u=u.map(i=>m(i,t)?(n=!0,i.cm===e?i:{...i,cm:e}):i),n||(u=Fl(u,t.a,t.b,e,s,r))}return u}const ag=t=>{const e=[];for(const i of t||[]){const t=hi(i);if(t?.length)for(let i=0;i"string"==typeof t?.id?t.id:"").filter(Boolean),h=new Set(c),d=new Map;for(const t of c){const e=$m("space",t);e.layers>0&&xm("space",e.root)&&Sm(d,e.root,t)}const p=new Map,u=new Map,_=new Map,m=new Map;for(const t of r){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i=new Map;for(const s of Array.isArray(t.rooms)?t.rooms:[]){const t="string"==typeof s?.id?s.id:"";if(!t)continue;const n=$m("room",t);n.layers>0&&xm("room",n.root)&&Sm(i,n.root,t),u.has(t)||u.set(t,e),_.has(t)||_.set(t,String(s.name||""));const o="string"==typeof s.area?s.area:"";if(o){const i=m.get(o)||[];i.push({spaceId:e,roomId:t}),m.set(o,i)}}p.set(e,i)}const g=new Set(u.keys()),f=new Map,v=new Map;for(const t of l)"string"==typeof t?.id&&t.id&&(!0===t.removed?v.set(t.id,t):f.set(t.id,t));const y={spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,positionsUnresolved:0,nestedRefsUnresolved:0,deadSpaceIds:[],orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0,removedPositions:[],liveMissingPositions:[],unverifiedPositions:[]},b=new Set,w=t=>h.has(t)?null:(()=>{const e=$m("space",t).root;if(!xm("space",e))return null;const i=d.get(e)||[];return 1===i.length?i[0]:null})(),k=(t,e)=>{const i=$m("room",t).root;if(!xm("room",i))return null;const s=p.get(e)?.get(i)||[];return 1===s.length?s[0]:null},x=t=>{const e=i.effectiveAreaByMarker?.[t]||"",s=e&&m.get(e)||[];return 1===s.length?s[0]:null},$=(t,e,i)=>{if("string"==typeof t.room_id&&t.room_id&&!g.has(t.room_id)){const s=e?k(t.room_id,e):null;s?(t.room_id=s,y.roomRefsRemapped++):i?(t.room_id=i.roomId,y.roomRefsRemapped++):!0!==t.removed&&delete t.room_id}const s=t.vacuum?.segment_map;if(s&&"object"==typeof s&&!Array.isArray(s))for(const t of Object.keys(s)){const i=s[t];if("string"!=typeof i||!i||g.has(i))continue;const n=e?k(i,e):null;n?(s[t]=n,y.roomRefsRemapped++):y.nestedRefsUnresolved++}};for(const t of l){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i="string"==typeof t.space?t.space:"",s=i&&!h.has(i),o=n[e],a="string"==typeof o?.s?o.s:"",r=a&&!h.has(a),l=!0===t.removed;let c=i&&h.has(i)?i:null,d=null,p=!1;if(s){const s=w(i);s?(t.space=s,c=s,p=!0,y.spaceRefsRemapped++):l||"virtual"===t.binding?l||(delete t.space,c=null,y.markersDetached++):(d=x(e),d?(t.space=d.spaceId,c=d.spaceId,y.spaceRefsRemapped++):(delete t.space,c=null,y.markersDetached++))}l&&!p||$(t,c,d),r&&p&&a===i&&c&&(n[e]={...o,s:c},y.positionsRemapped++,b.add(e))}for(const t of Object.keys(n)){if(b.has(t))continue;const e=n[t],i="string"==typeof e?.s?e.s:"";if(!i||h.has(i))continue;const s=w(i);if(s){if(t.startsWith("rl_")){const i=t.slice(3),o=k(i,s);if(o){const i=`rl_${o}`;km(n,i)||(n[i]={...e,s:s}),delete n[t],y.roomRefsRemapped++,y.positionsRemapped++;continue}}n[t]={...e,s:s},y.positionsRemapped++}}const S=i.ownerRoster,M=!0===S?.authoritative,C=new Set(S?.deviceIds||[]),D=new Set(S?.entityIds||[]),P=new Set(Array.isArray(s.settings?.known_devices)?s.settings.known_devices.filter(t=>"string"==typeof t):[]),T=(t,e="")=>{const i=String(S?.names?.[t]||e||"").trim();return i&&i!==t?i:""},R=(t,e,i,s="",n)=>({id:t,spaceId:e,kind:i,name:T(t,s),...n?{reason:n}:{}}),I=t=>{"room_label"===t?y.orphanRoomLabelsRemoved++:"group"===t?y.orphanGroupPositionsRemoved++:y.orphanDevicePositionsRemoved++},A=new Set;for(const[t,e]of Object.entries(n)){const s="string"==typeof e?.s?e.s:"";if(!s||h.has(s))continue;let o,a;const r=f.get(t),l=v.get(t);if(r)o=R(t,s,"device",String(r.name||"")),a="live";else if(l)o=R(t,s,"device",String(l.name||"")),a="absent";else if(t.startsWith("rl_")){const e=t.slice(3);o=R(t,s,"room_label",_.get(e)||""),a=g.has(e)?"live":"absent"}else if(t.startsWith("lg_")){const e=t.slice(3);o=R(t,s,"group"),a=D.has(e)?"live":M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")}else C.has(t)?(o=R(t,s,"device"),a="live"):P.has(t)?(o=R(t,s,"device"),a=M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")):(o=R(t,s,"unknown","","unknown_owner"),a="unverified");if("absent"!==a){if("live"===a){if(y.liveMissingPositions.push(o),!0===i.removeLiveMissingPositions){delete n[t],y.liveMissingPositionsRemoved++,I(o.kind),y.removedPositions.push(o);continue}}else y.unverifiedPositions.push(o);y.positionsUnresolved++,A.add(s)}else delete n[t],I(o.kind),y.removedPositions.push(o)}return y.deadSpaceIds=[...A].sort((t,e)=>t.localeCompare(e)),{config:s,layout:n,report:y,changed:JSON.stringify(s)!==o||JSON.stringify(n)!==a}}(t,e,i),a=o.config,r=nl(a,o.layout);rl(a),al(o.layout);const l=JSON.stringify(t||{}),c=JSON.stringify(e||{}),h=Number.isInteger(Number(a.model_version))?Number(a.model_version):0,d=(t=>{let e=0,i=0,s=0;for(const i of t.markers||[]){if("ripple"===i.display&&(i.display="icon_ripple",e++),Array.isArray(i.controls)){const t="string"==typeof i.binding&&i.binding.startsWith("entity:")?i.binding.slice(7):"",s=t?i.controls.filter(e=>e!==t):i.controls;JSON.stringify(s)!==JSON.stringify(i.controls)&&(i.controls=s.length?s:null,e++)}const t=i.vacuum;t&&eg(t,"trail")&&(["never","cleaning","always"].includes(t.trail_mode)||(t.trail_mode=!1===t.trail?"never":"cleaning"),delete t.trail,e++)}for(const n of t.spaces||[]){const t=n.settings;"glow"===t?.fill_mode&&("boolean"!=typeof t.glow_enabled&&(t.glow_enabled=!0),t.fill_mode="none",e++,i++);for(const t of n.rooms||[]){const i=t.settings;"glow"===i?.fill_mode&&("boolean"!=typeof i.glow&&(i.glow=!0),delete i.fill_mode,e++,s++)}if(eg(n,"segments")&&(delete n.segments,e++),eg(n,"plan_scale")){const t=Number(n.plan_scale);Number.isFinite(t)&&t>=wh&&t<=kh&&(eg(n,"plan_scale_x")||(n.plan_scale_x=t),eg(n,"plan_scale_y")||(n.plan_scale_y=t),delete n.plan_scale,e++)}const o=Number(n.cell_cm);eg(n,"cell_cm")&&(!Number.isFinite(o)||o<.1||o>1e3)&&(n.cell_cm=Number.isFinite(o)&&o>0?ig(o,.1,1e3):5,e++);const a=Number(n.cell_cm),r=Number.isFinite(a)&&a>0?a:5;for(const t of n.wall_columns||[])if("circle"===t.shape)eg(t,"angle")&&(delete t.angle,e++);else if("square"===t.shape&&eg(t,"angle")){const i=((Number(t.angle)||0)%90+90)%90;t.angle!==i&&(t.angle=i,e++)}for(const t of n.decor||[]){if(eg(t,"width")){const i=Number(t.width);(eg(t,"width_cm")||Number.isFinite(i))&&(eg(t,"width_cm")||(t.width_cm=Number(ig(i/Ph*r,.1,100).toFixed(6))),delete t.width,e++)}if("rect"!==t?.kind&&"ellipse"!==t?.kind||!0!==t.fill||(eg(t,"fill_color")||(t.fill_color=t.color||"#607d8b",e++),eg(t,"fill_opacity")||(t.fill_opacity=.25,e++)),"text"!==t?.kind)continue;void 0===t.size_cm?(t.size_cm=Number(ig(es*is(t)/Ph*r,.1,2e3).toFixed(6)),delete t.scale,delete t.size,e++):(eg(t,"scale")||eg(t,"size"))&&(delete t.scale,delete t.size,e++);let i=String(t.text??"");const s=[...i.matchAll(/\{([^{}\r\n]+)\}/g)].some(t=>!!Yi(t[1]));if(!(eg(t,"entity")||eg(t,"attr")||eg(t,"unit")))continue;const n=String(t.unit??"").trim(),o="state"===String(t.attr??"").trim().toLowerCase()?null:t.attr,a=s||n?"":Ji(t.entity,o);if(s||a){if(a){const e=i.indexOf("{}");i=e>=0?i.slice(0,e)+a+i.slice(e+2):`${i}${i?" ":""}${a}`,t.text=i}delete t.entity,delete t.attr,delete t.unit,e++}}}return{total:e,glowSpaces:i,glowRooms:s}})(a);let p=d.total;const u=(_=a.spaces||[],JSON.parse(JSON.stringify(_)));var _;const m=X_(a.spaces||[],o.layout);let g=0,f=0,v=0,y="";const b=m.spaces.map(t=>{const e=function(t){const e=JSON.parse(JSON.stringify(t||{}));let i=Array.isArray(e.rooms)?e.rooms:[];const s=new Map;for(const t of i){const e=hi(t);if(e)for(let t=0;tt.key.localeCompare(e.key))){let e=null;for(const s of $a(t,i)){const t=r.get(_a(s.from));if(t&&t!==_a(s.to))continue;const n=wa(i,s);if(ka(i,n,s)){e=s,i=n;break}}e?(r.set(_a(e.from),_a(e.to)),n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}e.rooms=i;for(const t of e.room_drafts||[]){if(!Array.isArray(t?.points)||t.points.length<2)continue;const e=t.points.map(t=>[...t]),i=e.slice(0,-1).flatMap((i,s)=>{const n=e[s+1],o=pa(i,n);return o?[{key:`${String(t.id||"")}:${s}`,a:[...i],b:[...n],axis:o.axis}]:[]});let s=e;for(const t of i){let e=null;for(const i of $a(t,[{poly:s}])){const t=s.map(t=>ba(t,i)),n=t.length>=4&&ma(t[0],t[t.length-1]),o=n?t.slice(0,-1):t;if(n?va(o):ya(o)){e=i,s=t;break}}e?(n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}t.points=s}for(const t of e.partitions||[]){if(!Array.isArray(t?.a)||!Array.isArray(t?.b))continue;const i=pa(t.a,t.b);if(!i)continue;const s={key:String(t.id||ga(t.a,t.b)),a:[...t.a],b:[...t.b],axis:i.axis};let r=null;for(const i of $a(s,[{poly:[t.a,t.b]}])){const s=ba(t.a,i),n=ba(t.b,i),o=Math.hypot(n[0]-s[0],n[1]-s[1]);if(!(o>0))continue;const a=(e.openings||[]).filter(e=>"partition"===e?.host?.kind&&e.host.id===t.id).every(t=>{const e=Number(t.host.t),i=Number(t.length);return Number.isFinite(e)&&e>=0&&e<=1&&Number.isFinite(i)&&i>0&&e*o-i/2>=-1e-12&&e*o+i/2<=o+1e-12});if(a){r=i,t.a=s,t.b=n;break}}r?(n++,a=Math.max(a,Math.hypot(r.to[0]-r.from[0],r.to[1]-r.from[1]))):o++}return{space:e,report:{wallsStraightened:n,wallsStraightenSkipped:o,maxStraightenShift:a},changed:n>0}}(t);g+=e.report.wallsStraightened,f+=e.report.wallsStraightenSkipped;const i=Number(t?.cell_cm)>0?Number(t.cell_cm):5,s=e.report.maxStraightenShift/Th*i;return s>v&&(v=s,y=String(t?.id||"")),e.space}),w=g?X_(b,m.layout):{...m,spaces:b};a.spaces=w.spaces;const k=g?{...m.report,moved:m.report.moved+w.report.moved,coordsCanonicalized:m.report.coordsCanonicalized+w.report.coordsCanonicalized,maxShift:Math.max(m.report.maxShift,w.report.maxShift),maxShiftCm:Math.max(m.report.maxShiftCm,w.report.maxShiftCm),maxSpace:w.report.maxShiftCm>m.report.maxShiftCm?w.report.maxSpace:m.report.maxSpace,rotated:m.report.rotated+w.report.rotated,removedDrafts:m.report.removedDrafts+w.report.removedDrafts}:{...m.report};let x=0,$=0,S=0,M=0,C=0,D=0,P=0,T=0;for(let t=0;t0===Number(t.cm)),walls:e.walls||[]}),o=sg(e),r=sg(i);if(!o||!r)continue;const l=ag(o.rooms),c=ag(r.rooms),h=.02*Ph,d=(e.wall_segments||[]).filter(t=>0===Number(t.cm)).map(t=>({...t,key:wl(t.a,t.b,Th),cm:0})),p=new Set(d.map(t=>t.key)),_=m_(e,o.rooms,yh,h);$+=_.length;for(const t of _){const e=[t[0]/yh,t[1]/yh],i=[t[2]/yh,t[3]/yh],s=wl(e,i,Th);p.has(s)||(p.add(s),d.push({key:s,a:e,b:i,cm:0}))}const m=d.length,g=Al(d,l,c,Th,yh),f=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(!(o>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))},v=g.filter(t=>{if(!Array.isArray(t.a)||!Array.isArray(t.b))return!1;const e=t.a.map(t=>t*yh),i=t.b.map(t=>t*yh);return c.some(([t,s])=>f(e,t,s)<=4*h&&f(i,t,s)<=4*h)});S+=Math.max(0,m-v.length);const y=(i.wall_segments||[]).filter(t=>Number(t.cm)>0);i.wall_segments=[...y,...v.map(({key:t,...e})=>e)];const b=v.map(t=>[t.a[0]*yh,t.a[1]*yh,t.b[0]*yh,t.b[1]*yh]),w=Array.isArray(e.walls)?e.walls.length:0;let k=Al(e.walls,l,c,Th,yh);k=og(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=uc(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=Tl(k,i.rooms||[],Th,1,b.map(t=>[t[0]/yh,t[1]/yh,t[2]/yh,t[3]/yh])),x+=Math.max(0,w-k.length),k.length?i.walls=k:delete i.walls;const R=nm(i.partitions||[],{pitch:Th,geometry:am(i)});R.merged&&(M+=R.merged,i.partitions=R.partitions,om(i.openings,i.partitions,R.openingMoves,{coordScale:yh,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph}));const I=sg(i);if(I){const t=n(i,I,i.walls||[],b,{pitch:Th,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph,coordScale:yh});t.partitionsReconciled&&(C+=t.partitionsReconciled,D+=t.openingsRehosted,t.partitions.length?i.partitions=t.partitions:delete i.partitions,t.openings.length?i.openings=t.openings:delete i.openings,t.walls.length?i.walls=t.walls:delete i.walls),t.removedDrafts&&(P+=t.removedDrafts,t.roomDrafts.length?i.room_drafts=t.roomDrafts:delete i.room_drafts)}JSON.stringify({zero:(i.wall_segments||[]).filter(t=>0===Number(t.cm)),walls:i.walls||[]})!==s&&T++}let R=0;h<=9&&(R=function(t){const e=Zm(t);return tg(t,e.config),{...e,config:t}}(a).migratedSegments);const I=rl(a),A=al(w.layout),z=JSON.stringify(I)!==l||JSON.stringify(A)!==c;h<9&&z&&(I.model_version=9);const F=JSON.stringify(I)!==l||JSON.stringify(A)!==c,E=Number.isInteger(Number(I.model_version))?Number(I.model_version):h,N=F?k:{...k,moved:0,coordsCanonicalized:0,maxShift:0,maxShiftCm:0,maxSpace:"",rotated:0,removedDrafts:0},O=F?o.report:{...o.report,spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0};return{config:I,layout:A,report:{...N,modelFrom:h,modelTo:E,migrated:F?p:0,glowSpacesMigrated:F?d.glowSpaces:0,glowRoomsMigrated:F?d.glowRooms:0,canonicalized:F?T:0,wallSegmentsMigrated:F?R:0,legacyZeroWallsMigrated:F?$:0,wallsMerged:F?x:0,spansMerged:F?S:0,partitionsMerged:F?M:0,partitionsReconciled:F?C:0,openingsRehosted:F?D:0,redundantDraftsRemoved:F?P:0,wallsStraightened:F?g:0,wallsStraightenSkipped:f,maxStraightenShiftCm:F?v:0,maxStraightenSpace:F?y:"",latticeCoordinatesCanonicalized:F?r.canonicalized:0,latticeCoordinatesFar:F?r.far:0,latticeMaxShift:F?r.maxShift:0,latticeMaxShiftCm:F?r.maxShiftCm:0,latticeSpaces:F?r.spaces:[],...O},changed:F}}function lg(t,e,i){const s=(t?.spaces||[]).find(t=>t?.id===i),n=new Set((s?.rooms||[]).map(t=>String(t?.id||"")).filter(Boolean)),o=[...new Set((t?.markers||[]).filter(t=>!0!==t?.removed&&"string"==typeof t?.id).filter(t=>t.space===i||"string"==typeof t.room_id&&n.has(t.room_id)||e?.[t.id]?.s===i).map(t=>t.id))].sort((t,e)=>t.localeCompare(e));return{markerIds:o,count:o.length}}function cg(t){return t instanceof Error?t.name||"Error":typeof t}function hg(t){return wd({id:t?.id??"",cell_cm:t?.cell_cm,rooms:t?.rooms||[],walls:t?.walls||[],wall_segments:t?.wall_segments||[],open_spans:t?.open_spans||[],openings:t?.openings||[],partitions:t?.partitions||[],room_drafts:t?.room_drafts||[],wall_columns:t?.wall_columns||[]})}function dg(t,e,i,s=Ph,n=1e3){return(Array.isArray(t?.openings)?t.openings:[]).flatMap(t=>{const o={...t,rx:Number(t.x)*n,ry:Number(t.y)*n,rlen:Number(t.length)*n};if(!t.host||"wall"===t.host.kind)return[o];const a=Sp(t,e.partitions,n,i,s);return a.resolved?[{...t,rx:a.resolved.center[0],ry:a.resolved.center[1],rlen:a.resolved.length,angle:a.resolved.angle,partitionHost:a.resolved}]:[]})}function pg(t,e=()=>!0){return t.flatMap(t=>t.host&&t.partitionHost&&e(t)?[Dp(t.partitionHost)]:[])}function ug(t,e,i,s,n,o,a=Ph,r=1e3){const l=dc(e.rooms,[...i],s,n,o,a,r);return t.flatMap(t=>{const e={x:t.rx,y:t.ry,angle:Number(t.angle)||0,length:t.rlen};return t.host&&"wall"!==t.host.kind?t.partitionHost&&Rp(t.partitionHost,l,2e-4*a)?[e]:[]:[e]})}function _g(t,e){const i=Th,s=Ph,n=yh,o=Number.isFinite(Number(e.cellCm))&&Number(e.cellCm)>0?Number(e.cellCm):5,a=Array.isArray(t?.walls)?t.walls:[],r=function(t,e,i=Ph,s=1e3){return _d(e.rooms,t?.open_spans,s,.02*i)}(t,e,s,n),l=function(t,e,i=Ph){if(!e.length)return[];const s=t.filter(t=>t?.id),n=.02*i,o=[];for(let t=0;t{const e=[(t[0]+t[2])/2,(t[1]+t[3])/2];return h.some(t=>Ls(e,t)<4*n)}).map(t=>[...t]);d.length&&o.push({a:a,b:r,segs:d})}return o}(e.rooms,r,s).flatMap(t=>t.segs),c=dg(t,e,o,s,n),h=pg(c),d=ih(e,o,s,2e-4*s,h).all;return{space:e,walls:a,openCuts:l,openings:c,roomOpenings:ug(c,e,a,l,i,o,s,n),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:s,coordScale:n}}function mg(t,e,i){const s="string"==typeof t?.title?t.title.trim():"",n=null==t?.id?"":String(t.id).trim();return{spaceId:n,displayName:s||n||i(e+1)}}function gg(t,e={}){const i=(e.fingerprint||wd)(t),s=Array.isArray(t?.spaces)?t.spaces:[],n=e.fallbackSpaceName||(t=>`Space ${t}`),o=e.prepareSpace||_g,a=e.wallPass||Rc,r=e.floorPass||Pc,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!p){l.push({...h,status:"not-applicable"});continue}let u=null;if(p){try{u=a(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(t){l.push({...h,status:"failed",reason:"wall-exception",detail:cg(t)});continue}if(null==u){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===u.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===u.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}e.captureWallGeometry?.(d,u)}if(d.space.rooms.length&&null==u?.paperGeom){let t;try{t=r(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(t){l.push({...h,status:"failed",reason:"floor-exception",detail:cg(t)});continue}if(null==t){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(t=>"failed"===t.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}class fg{constructor(t=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(t))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(t){this._undo.push(t),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const t=this._undo.pop()??null;return t&&this._redo.push(t),t}redo(){const t=this._redo.pop()??null;return t&&this._undo.push(t),t}clear(){this._undo=[],this._redo=[]}}const vg=new WeakMap;const yg=(t,e,i)=>255===t[i+3]&&e.every((e,s)=>Math.abs(t[i+s]-e)<=2);async function bg(t){const e=t.defaultView;if(!e||!e.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],s=[16,64,128],n=[9,19,29],o=`\n \n \n \n \n \n `,a=e.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((t,i)=>{const s=new e.Image,n=e.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);s.onload=()=>{e.clearTimeout(n),t(s)},s.onerror=()=>{e.clearTimeout(n),i(new Error("SVG blend probe failed"))},s.src=a}),r=t.createElement("canvas");r.width=4,r.height=1;const l=r.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return yg(c,i,0)&&yg(c,function(t,e){return[0,1,2].map(i=>Math.round(255-(255-t[i])*(255-e[i])/255))}(i,s),4)&&yg(c,s,8)&&yg(c,n,12)}catch{return!1}finally{e.URL.revokeObjectURL(a)}}const wg={now:()=>performance.now(),requestFrame:t=>requestAnimationFrame(t),cancelFrame:t=>cancelAnimationFrame(t)},kg=t=>Math.max(0,Math.min(1,t)),xg=(t,e,i)=>t+(e-t)*i,$g=(t,e,i)=>{const s=1-t;return 3*s*s*t*e+3*s*t*t*i+t*t*t};function Sg(t,e){return{centerX:t.x+t.w/2,centerY:t.y+t.h/2,pixelsPerUnit:e>0&&t.w>0?e/t.w:1,viewBox:{...t}}}function Mg(t,e,i){const s=Math.max(1e-9,t.pixelsPerUnit),n=Math.max(1e-9,e/s),o=Math.max(1e-9,i/s);return{x:t.centerX-n/2,y:t.centerY-o/2,w:n,h:o}}function Cg(t){const e=t.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(e);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const s=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(e)?.[1];return s?[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16),8===s.length?parseInt(s.slice(6,8),16)/255:1]:null}function Dg(t,e,i){const s=Cg(t),n=Cg(e);if(!s||!n)return i<.5?t:e;const o=kg(i);return`rgba(${Math.round(xg(s[0],n[0],o))}, ${Math.round(xg(s[1],n[1],o))}, ${Math.round(xg(s[2],n[2],o))}, ${xg(s[3],n[3],o).toFixed(3)})`}function Pg(t,e,i){const s=(t=>{const e=kg(t);if(0===e||1===e)return e;let i=0,s=1,n=e;for(let t=0;t<12;t++)n=(i+s)/2,$g(n,.2,.2){const e=this._state;if(!e||e.token!==n)return;const i=kg((t-e.startedAt)/e.duration);e.presented=i>=1?e.to:Pg(e.from,e.to,i),e.phase=i>=1?"settling":"running",this._hooks.frame(e),i<1?this._raf=this._clock.requestFrame(a):(this._raf=0,this._hooks.settled(e),this._state?.token===n&&(this._state=null))};return this._raf=this._clock.requestFrame(a),n}cancel(t=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const e=this._state;this._state=null,this._token++,e&&t&&(e.phase="settling",e.presented=e.to,this._hooks.frame(e),this._hooks.settled(e))}dispose(){this.cancel(!1)}}const Rg="houseplan_card_labs_v1",Ig=Object.freeze([Object.freeze({id:"iso",issue:89,since:"1.62.0",expires:"1.65.0",summary:"Volumetric plan renderer"})]);function Ag(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(String(t||"").trim());if(!e)return null;const i=e.slice(1).map(Number);return i.every(t=>Number.isSafeInteger(t))?i:null}function zg(t,e){for(let i=0;i<3;i++)if(t[i]!==e[i])return t[i]t.split(",")).map(t=>t.trim()).filter(Boolean)}function Hg(t,e,i,s=Ig){const n=function(t,e=Ig){const i=Ag(t),s=new Map;if(!i||!Eg(e))return s;for(const t of e){const e=Ag(t.since),n=Ag(t.expires);zg(i,e)>=0&&zg(i,n)<0&&s.set(t.id,t)}return s}(i,s),o=new Set(Eg(s)?s.map(t=>t.id):[]),a=new Set(function(t){if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}catch{return[]}}(e).filter(t=>n.has(t)));let r=!1;const l=t=>{if("off"===t)return a.clear(),void(r=!0);const e=t.startsWith("-"),i=e?t.slice(1):t;o.has(i)&&(r=!0,e||!n.has(i)?a.delete(i):a.add(i))};for(const e of Lg(new URLSearchParams(String(t.search||"").replace(/^\?/,""))))l(e);for(const e of Lg(Ng(t.hash)))l(e);const c=Object.freeze([...a].sort());return{active:c,space:Og(t.hash),persist:r?JSON.stringify(c):void 0,knownUrlOperation:r}}let Bg={active:Object.freeze([]),space:""},qg="",Wg=!1,jg="";const Ug=new Set;function Gg(){if("undefined"==typeof window)return Bg;const t=Hg(window.location,function(){try{return window.localStorage.getItem(Rg)}catch{return null}}(),qg);void 0!==t.persist&&function(t){try{window.localStorage.setItem(Rg,t)}catch{}}(t.persist),Bg={active:t.active,space:t.space},window.__hpLabs=t.active;for(const t of Ug)t(Bg);return Bg}function Vg(){Gg()}function Kg(t){return qg=t,"undefined"==typeof window?Bg:(Wg||(Wg=!0,window.addEventListener("hashchange",Vg),window.addEventListener("popstate",Vg)),Gg())}const Yg=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])});function Jg(t){return[t.rotDeg,t.tiltDeg,t.xyScale,t.zScale,t.origin[0],t.origin[1]].every(Number.isFinite)&&Math.abs(t.xyScale)>1e-12&&Math.abs(Math.cos(t.tiltDeg*Math.PI/180))>1e-12}function Xg(t,e,i=Yg){if(!(Jg(i)&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(e)))throw new Error("invalid isometric projection input");const s=i.rotDeg*Math.PI/180,n=i.tiltDeg*Math.PI/180,o=t[0]-i.origin[0],a=t[1]-i.origin[1],r=(o*Math.cos(s)-a*Math.sin(s))*i.xyScale,l=(o*Math.sin(s)+a*Math.cos(s))*i.xyScale;return[i.origin[0]+r,i.origin[1]+l*Math.cos(n)-e*i.zScale*Math.sin(n)]}function Zg(t,e=Yg){if(!Jg(e)||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new Error("invalid isometric projection input");const i=e.rotDeg*Math.PI/180,s=e.tiltDeg*Math.PI/180,n=(t[0]-e.origin[0])/e.xyScale,o=(t[1]-e.origin[1])/(e.xyScale*Math.cos(s));return[e.origin[0]+n*Math.cos(i)+o*Math.sin(i),e.origin[1]-n*Math.sin(i)+o*Math.cos(i)]}function Qg(t=Yg){return`matrix(${function(t=Yg){if(!Jg(t))throw new Error("invalid isometric camera");const e=t.rotDeg*Math.PI/180,i=t.tiltDeg*Math.PI/180,s=t.xyScale*Math.cos(e),n=-t.xyScale*Math.sin(e),o=t.xyScale*Math.sin(e)*Math.cos(i),a=t.xyScale*Math.cos(e)*Math.cos(i);return[s,o,n,a,t.origin[0]-s*t.origin[0]-n*t.origin[1],t.origin[1]-o*t.origin[0]-a*t.origin[1]]}(t).map(t=>Number(t.toFixed(12))).join(" ")})`}function tf(t,e=Yg){const{rect:i,wallHeight:s}=t,n=t.openingHeight??s,o=t.floorDepth??0;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(o)||s<0||n<0||o<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],r=Math.max(s,n),l=a.flatMap(t=>[Xg(t,-o,e),Xg(t,r,e)]),c=l.map(t=>t[0]),h=l.map(t=>t[1]),d=Math.min(...c),p=Math.min(...h);return{x:d,y:p,w:Math.max(...c)-d,h:Math.max(...h)-p}}const ef=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function sf(t){let e=0;for(let i=0;iArray.isArray(t)&&Number.isFinite(t[0])&&Number.isFinite(t[1])).map(t=>[Number(t[0]),Number(t[1])]),i=e[e.length-1];return e.length>1&&e[0][0]===i[0]&&e[0][1]===i[1]&&e.pop(),e}(t);if(i.length<3)return[];const s=!e;return sf(i)>0===s?i:[...i].reverse()}function of(t,e,i){return t.length?`M ${t.map(t=>ef(Xg(t,i,e))).join(" L ")} Z`:""}function af(t,e,i){const s=e[1]-t[1],n=-(e[0]-t[0]),o=i.rotDeg*Math.PI/180;return s*Math.sin(o)+n*Math.cos(o)}function rf(t,e,i=Yg){if(!Number.isFinite(e)||e<0)throw new Error("invalid floor edge height");const s=(t||[]).map(t=>(t||[]).map((t,e)=>function(t,e){const i=nf(t,e);if(!i.length)return i;let s=0;for(let t=1;t0)).filter(t=>t.length>=3&&Math.abs(sf(t))>=1e-9)).filter(t=>t.length&&sf(t[0])>0);s.sort((t,e)=>{const i=t[0][0],s=e[0][0];return i[0]-s[0]||i[1]-s[1]||Math.abs(sf(e[0]))-Math.abs(sf(t[0]))});const n=[],o=[];let a=0;for(let t=0;tt.depth-e.depth||t.component-e.component||t.edge-e.edge),{footprintPath:n.join(" "),sides:o,componentCount:s.length,edgeCount:a}}function lf(t,e){return t^=Math.round(64*(Number.isFinite(e)?e:0)),Math.imul(t,16777619)>>>0}const cf=t=>t.every(Number.isFinite);function hf(t,e,i,s){const n=t[0]*i,o=t[1]*s,a=e*Math.PI/180;return[n*Math.cos(a)-o*Math.sin(a),n*Math.sin(a)+o*Math.cos(a)]}function df(t,e,i,s,n,o,a){const r=t.flipH?-1:1,l="gate"===t.type?1:t.flipV?-1:1,c=(t.type,t.flipV,t.angle,t.face,{ox:0,oy:0}),h=function(t,e){return[t[0]+e[0],t[1]+e[1]]}([t.x+c.ox,t.y+c.oy],hf(i,t.angle,r,l));return{leaf:e,hinge:h,closedVector:hf(s,t.angle,r,l),quarterVector:hf([-s[1],s[0]],t.angle,r,l),turnDeg:n,bottom:o,top:a}}const pf=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function uf(t,e,i=Yg){const s=Math.max(0,Math.min(1,Number.isFinite(e)?e:0));return t.leaves.map(e=>{const n=function(t,e){const i=t.turnDeg*e*Math.PI/180;return[t.hinge[0]+t.closedVector[0]*Math.cos(i)+t.quarterVector[0]*Math.sin(i),t.hinge[1]+t.closedVector[1]*Math.cos(i)+t.quarterVector[1]*Math.sin(i)]}(e,s),o=Xg(e.hinge,e.bottom,i),a=Xg(n,e.bottom,i),r=Xg(n,e.top,i),l=Xg(e.hinge,e.top,i);return{id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${pf(o)} L ${pf(a)} L ${pf(r)} L ${pf(l)} Z`,shadowD:`M ${pf(Xg(e.hinge,0,i))} L ${pf(Xg(n,0,i))}`,depth:Math.max(o[1],a[1])}})}const _f={window:120,door:90,passage:90,gate:300};function mf(t){return _f[t]}function gf(t,e){const i=[t[0],t[1]],s=[e[0],e[1]];return function(t,e){return t[0]-e[0]||t[1]-e[1]}(i,s)<=0?{a:i,b:s}:{a:s,b:i}}function ff(t){const e=new Map;return t.forEach((t,i)=>{if(!t.kind||t.open)return;const s=gf(t.a,t.b);if(Math.hypot(s.b[0]-s.a[0],s.b[1]-s.a[1])<=1e-9)return;const n=function(t,e){const i=t=>(Math.abs(t)<=5e-10?0:Math.round(1e6*t)/1e6).toFixed(6);return`${i(t[0])},${i(t[1])}>${i(e[0])},${i(e[1])}`}(s.a,s.b),o=e.get(n);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,t.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(t.partitionHost&&(o.partitionHost&&o.partitionHost.id!==t.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=t.partitionHost));e.set(n,{segmentKey:n,a:s.a,b:s.b,physicalHalfWidth:Math.max(0,t.half||0),sourceOrder:i,...t.partitionHost?{partitionHost:t.partitionHost}:{}})}),[...e.values()]}function vf(t,e){if(Math.abs(t.distance-e.distance)>1e-9)return t.distance-e.distance;if(Math.abs(t.perpendicular-e.perpendicular)>1e-9)return t.perpendicular-e.perpendicular;return(t.target.segmentKeye.target.segmentKey?1:0)||t.target.sourceOrder-e.target.sourceOrder}function yf(t){const e=ff(t.intervals).map(e=>{const i=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,r=(t[0]-e.a[0])*o+(t[1]-e.a[1])*a,l=Math.max(0,Math.min(n,r)),c=e.a[0]+l*o,h=e.a[1]+l*a;return{along:l,length:n,x:c,y:h,distance:Math.hypot(t[0]-c,t[1]-h),perpendicular:Math.abs((t[0]-e.a[0])*a-(t[1]-e.a[1])*o)}}(t.pointer,e);return{target:e,...i,envelope:Math.max(t.baseTolerance,e.physicalHalfWidth+t.bodyPointerPadding)}}).filter(t=>t.distance<=t.envelope+1e-9).filter(e=>!function(t,e,i,s,n){const o=e.b[0]-e.a[0],a=e.b[1]-e.a[1],r=Math.hypot(o,a);if(!(r>1e-9))return!1;const l=o/r,c=a/r;for(const o of i){if(!o.open&&o.kind)continue;const i=gf(o.a,o.b),a=i.b[0]-i.a[0],r=i.b[1]-i.a[1],h=Math.hypot(a,r);if(!(h>1e-9))continue;const d=a/h,p=r/h;if(Math.abs(l*p-c*d)>1e-6)continue;if(Math.abs((i.a[0]-e.a[0])*c-(i.a[1]-e.a[1])*l)>n)continue;const u=(t[0]-i.a[0])*d+(t[1]-i.a[1])*p,_=1e-9;if(!(u<=_||u>=h-_)&&Math.abs((t[0]-i.a[0])*p-(t[1]-i.a[1])*d)<=s+1e-9)return!0}return!1}(t.pointer,e.target,t.intervals,e.envelope,Math.max(1e-9,Math.min(t.baseTolerance,.04*t.gridStep)))),i=e.filter(e=>!!e.target.partitionHost&&t.renderedLength+2*e.target.physicalHalfWidth>e.length+1e-9).sort(vf),s=e.filter(e=>!e.target.partitionHost||t.renderedLength+2*e.target.physicalHalfWidth<=e.length+1e-9).sort(vf);let n=s[0];if(!n)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=s.filter(t=>Math.abs(t.distance-n.distance)<=1e-9&&Math.abs(t.perpendicular-n.perpendicular)<=1e-9),a=o.filter(t=>t.target.partitionHost);if(a.length){if(1!==new Set(a.map(t=>t.target.partitionHost.id)).size||a.some(t=>t.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const t=a[0],e=t.target.b[0]-t.target.a[0],i=t.target.b[1]-t.target.a[1],s=Math.hypot(e,i),r=e/s,l=i/s,c=o.every(e=>{const i=e.target.b[0]-e.target.a[0],s=e.target.b[1]-e.target.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,c=Math.abs(r*a-l*o)<=1e-6,h=Math.abs((e.target.a[0]-t.target.a[0])*l-(e.target.a[1]-t.target.a[1])*r);return c&&h<=1e-9});if(!c)return{candidate:null,jambBlockedTarget:null};n=t}if(n.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:r,length:l}=n,c=r.b[0]-r.a[0],h=r.b[1]-r.a[1],d=c/l,p=h/l,u=r.partitionHost?r.physicalHalfWidth:0,_=Math.min(Math.max(0,t.renderedLength)/2+u,l/2);let m=n.along;const g=Math.max(t.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=r.a[0]+d*m,y=r.a[1]+p*m,b=Math.max(0,t.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),$=Math.max(0,l-k),S=[r.a[0]+d*(w-x/2),r.a[1]+p*(w-x/2)],M=[r.a[0]+d*(k+$/2),r.a[1]+p*(k+$/2)];let C=180*Math.atan2(h,c)/Math.PI;C>=90?C-=180:C<-90&&(C+=180);const D=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:t.preset.revision,geometryRevision:t.geometryRevision,pointer:[t.pointer[0],t.pointer[1]],type:t.preset.type,lengthCm:t.preset.lengthCm,flipH:t.preset.flipH,flipV:t.preset.flipV,x:v,y:y,angle:C,renderedLength:t.renderedLength,target:r,...r.partitionHost?{host:{...r.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:S},{distance:$,midpoint:M}],guide:D?{x:v,y:y,angle:C}:null}},jambBlockedTarget:null}}function bf(t,e,i,s,n=1e-6){return t.presetRevision===i&&t.geometryRevision===s&&Math.hypot(t.pointer[0]-e[0],t.pointer[1]-e[1])<=n}const wf=(t,e)=>t[0]*e[1]-t[1]*e[0],kf=(t,e)=>t[0]*e[0]+t[1]*e[1],xf=(t,e)=>[t[0]-e[0],t[1]-e[1]],$f=(t,e,i)=>[t[0]+e[0]*i,t[1]+e[1]*i];function Sf(t,e,i){return Math.abs(wf(t,e))<=i}function Mf(t,e,i){return Math.abs(wf(xf(t,e),i))}function Cf(t,e,i,s,n){const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n&&i>0))return[];const l=[o/r,a/r];return function(t,e,i){const s=e.map(([e,i])=>[Math.max(0,Math.min(e,i)),Math.min(t,Math.max(e,i))]).filter(([t,e])=>e>t+i).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),n=[];for(const t of s){const e=n[n.length-1];!e||t[0]>e[1]+i?n.push([...t]):e[1]=Math.max(e[1],t[1])}const o=[];let a=0;for(const[t,e]of n)t>a+i&&o.push([a,t]),a=Math.max(a,e);return t>a+i&&o.push([a,t]),o}(r,s.flatMap(e=>{const s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=Math.hypot(s,o);if(!(a>n&&Sf(l,[s/a,o/a],1e-6)))return[];if(Mf(e.a,t,l)>1.1*Math.max(i,n)||Mf(e.b,t,l)>1.1*Math.max(i,n))return[];return[[kf(xf(e.a,t),l),kf(xf(e.b,t),l)]]}),n).flatMap(([e,s])=>{const n=Ol({a:$f(t,l,e),b:$f(t,l,s),halfDepth:i});return n?[n]:[]})}function Df(t){const e=t.coordScale??1,i=Math.max(t.epsilon??2e-4*t.gridPitch,1e-9),s=[];for(const i of t.rooms||[]){if(!i?.id)continue;const n=hc(t.rooms,i.id,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e);if(!n||n.poly.length<3)continue;const o=Zl(n.poly,n.offsets);!o||o.length<3||s.push({roomId:i.id,profile:n,inner:o})}s.sort((t,e)=>t.roomId.localeCompare(e.roomId));const n=(t.roomOpenings||[]).map(t=>{const e=t.angle*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Math.max(0,t.length)/2;return{a:$f([t.x,t.y],i,-s),b:$f([t.x,t.y],i,s)}}),o=[];for(const s of zc(t.rooms,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e))for(const t of Cf(s.a,s.b,s.depthUnits/2,n,i))o.push({body:t});const a=new Map;for(const e of t.partitionCuts||[]){const t=a.get(e.hostId)||[];t.push(e),a.set(e.hostId,t)}for(const e of t.partitions||[]){const s=gl(e.cm,t.cellCm,t.gridPitch)/2;for(const t of Cf(e.a,e.b,s,a.get(e.id)||[],i))o.push({body:t,partitionId:e.id})}return{rooms:s,boundaries:o,epsilon:i}}function Pf(t,e,i,s){const n=t.profile.offsets[e];if(!(n>0))return null;const o=function(t,e){const i=t[e],s=t[(e+1)%t.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return function(t){let e=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t.profile.poly,e),a=$f(i.center,o,n),r=[];for(let e=0;es&&Sf(i.axis,[l[0]/c,l[1]/c],1e-6)))continue;if(Mf(n,a,i.axis)>s||Mf(o,a,i.axis)>s)continue;const h=kf(xf(n,a),i.axis),d=kf(xf(o,a),i.axis);r.push([Math.min(h,d),Math.max(h,d)])}const l=function(t,e){t.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);const i=[];for(const s of t){const t=i[i.length-1];!t||s[0]>t[1]+e?i.push([...s]):t[1]=Math.max(t[1],s[1])}return i}(r,s).find(([t,e])=>t<=s&&e>=-s);if(!l)return null;const[c,h]=l,d=$f(a,i.axis,-i.half),p=$f(a,i.axis,i.half),u=Math.max(0,-i.half-c),_=Math.max(0,h-i.half),m=u>0?$f(a,i.axis,c):d,g=_>0?$f(a,i.axis,h):p,f=kf(o,i.normal)>=0?1:-1,v=(e,s,n)=>({from:e,to:s,label:[(e[0]+s[0])/2,(e[1]+s[1])/2],axis:i.axis,labelNormal:o,distance:n,roomId:t.roomId,roomSide:f,source:"room-face"});return{left:v(d,m,u),right:v(p,g,_)}}function Tf(t){const e=$f(t.center,t.axis,-t.half),i=$f(t.center,t.axis,t.half),s=$f(t.center,t.axis,Math.min(-t.half,t.targetLo)),n=$f(t.center,t.axis,Math.max(t.half,t.targetHi)),o=(e,i)=>({from:e,to:i,label:[(e[0]+i[0])/2,(e[1]+i[1])/2],axis:t.axis,labelNormal:t.normal,distance:Math.hypot(i[0]-e[0],i[1]-e[1]),source:"host-end"});return[o(e,s),o(i,n)]}function Rf(t,e,i,s){const n=xf(i,e),o=kf(n,n);if(!(o>s*s))return Math.hypot(...xf(t,e))<=s;const a=kf(xf(t,e),n)/o;if(a<-s||a>1+s)return!1;const r=$f(e,n,Math.max(0,Math.min(1,a)));return Math.hypot(...xf(t,r))<=s}function If(t,e,i){let s=!1;for(let n=0,o=e.length-1;nt[1]!=c>t[1]&&t[0]<(l-a)*(t[1]-r)/(c-r)+a&&(s=!s)}return s}function Af(t,e,i,s,n,o){const a=xf(s,i),r=wf(e,a);if(Math.abs(r)<=o)return null;const l=xf(i,t),c=wf(l,a)/r,h=wf(l,e)/r;return c<-o||c>n+o||h<-o||h>1+o?null:Math.max(0,Math.min(n,c))}function zf(t,e,i){const s=Tf(i),n="partition"===t.host?.kind?t.host.id:void 0;return[{base:s[0],direction:[-i.axis[0],-i.axis[1]]},{base:s[1],direction:i.axis}].map(({base:t,direction:i})=>{const s=t.distance,o=function(t,e,i,s,n,o){let a=null;for(const r of s)if(!n||r.partitionId!==n){if(If(t,r.body,o))return 0;for(let s=0;skf(xf(t,n),i));return{center:n,axis:i,normal:s,half:Math.max(0,t.renderedLength)/2,targetLo:Math.min(...o),targetHi:Math.max(...o)}}(t),s=e.rooms.flatMap(t=>{const s=function(t,e,i){const{profile:s}=t;let n=null;for(let t=0;t0))continue;const o=s.poly[t],a=s.poly[(t+1)%s.poly.length],r=xf(a,o),l=Math.hypot(r[0],r[1]);if(!(l>i&&Sf(e.axis,[r[0]/l,r[1]/l],1e-6)))continue;if(Mf(o,e.center,e.axis)>i||Mf(a,e.center,e.axis)>i)continue;const c=kf(xf(o,e.center),e.axis),h=kf(xf(a,e.center),e.axis),d=Math.min(c,h),p=Math.max(c,h);if(d>-e.half+i||p0?d:p<0?-p:0);(!n||u2)return Tf(i);if(s.length){const t=s.map(({room:t,edge:s})=>Pf(t,s,i,e.epsilon));if(t.some(t=>!t))return Tf(i);const n=t;return[...n.map(t=>t.left),...n.map(t=>t.right)]}return zf(t,e,i)}function Ef(t){return!(!t.canEdit||t.kiosk||t.fixedFloor)&&("view"!==t.mode&&("mouse"===t.pointerType&&t.spaceCount>1))}const Nf="1.68.0",Of={badge:"display.badge",icon_ripple:"display.icon_ripple",value:"display.value",static_icon:"display.static_icon"},Lf={badge:"marker.display_hint_badge",icon_ripple:"marker.display_hint_icon_ripple",value:"marker.display_hint_value",static_icon:"marker.display_hint_static_icon"},Hf=2e3,Bf=1e3,qf=1500,Wf=t=>{const e=String(t??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return null;const i=Number(e);return Number.isFinite(i)?i:null},jf=(t,e)=>{if(!t.has(e))return{hit:!1};const i=t.get(e);return t.delete(e),t.set(e,i),{hit:!0,value:i}},Uf=(t,e,i,s)=>{for(t.delete(e),t.set(e,i);t.size>s;){const e=t.keys().next().value;if(void 0===e)break;t.delete(e)}},Gf=new Map;let Vf=0;const Kf=t=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(t??{})}`;let Yf=1e4;const Jf="houseplan_card_layout_v1",Xf="houseplan_card_cfg_v1",Zf="houseplan_card_zoom_v1",Qf="houseplan_card_nav_v1",tv="houseplan_card_kiosk_v1",ev="houseplan_card_view_v1",iv="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",sv=1e3,nv=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]],ov=(t,e)=>{const i=Math.min(t.x,e.x),s=Math.min(t.y,e.y);return{x:i,y:s,w:Math.max(t.x+t.w,e.x+e.w)-i,h:Math.max(t.y+t.h,e.y+e.h)-s}},av=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),rv=2e3,lv=(t,e,i)=>{const s=new Event(e,{bubbles:!0,composed:!0});s.detail=i??{},t.dispatchEvent(s)},cv=t=>{history.pushState(null,"",t),lv(window,"location-changed",{replace:!1})},hv=(t,e)=>{let i,s=null;const n=(...n)=>{clearTimeout(i),s=n,i=window.setTimeout(()=>{i=void 0;const e=s;s=null,e&&t(...e)},e)};return n.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const e=s;s=null,e&&t(...e)},n.cancel=()=>{clearTimeout(i),i=void 0,s=null},n.pending=()=>void 0!==i,n},dv=t=>{try{t.target?.setPointerCapture?.(t.pointerId)}catch{}};class pv extends ht{constructor(){super(...arguments),this._space="f1",this._layout={},this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._serverCfg=null,this._cfgRev=0,this._cfgContentFingerprint="",this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._layoutRev=0,this._layoutContentFingerprint="",this._virtualLights=mn(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._tip=null,this._hoverRoom=null,this._pointerModality=new N_(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...Rr},this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=t=>{this._reducedMotion=t.matches,this._cancelDevicePressFeedback(),t.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:t.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Tg({frame:t=>this._applyModeTransitionFrame(t),settled:t=>this._settleModeTransition(t)}),this._editorSecondary=new W_({root:()=>this.renderRoot,requestUpdate:()=>this.requestUpdate(),updateComplete:()=>this.updateComplete,clearTip:()=>{this._tip=null}}),this._editorSecondaryCopy={groupActive:(t,e)=>this._t("editor.group_active",{group:t,item:e}),openGroup:t=>this._t("editor.open_group",{group:t}),disabledAction:(t,e)=>this._t("editor.disabled_action",{action:t,reason:e})},this._tool="draw",this._geometryHistory=new fg(50),this._wallDialog=null,this._drawWallField=null,this._activeDraftId=null,this._resumeDraftBySpace={},this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowClipCache=new Map,this._glowGeometryWarnings=new Set,this._lightBarrierCache=null,this._glowFeatherUnits=null,this._glowRenderedSources=new Map,this._glowLastAppearance=new Map,this._glowEnteringSources=new Set,this._glowEnterRafs=new Map,this._glowFadeTimers=new Map,this._glowFeatherSuspendUntil=0,this._glowFeatherResumeTimer=0,this._glowSourceSeq=0,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszSel=null,this._rszDrag=null,this._rszEligibilityCache=null,this._rszPreview=null,this._rszLive=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._touchContacts=new Map,this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:t=>this._guardTouchGesture(t)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._alignDialog=null,this._settingsDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=t=>this._onKey(t),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++Vf,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=t=>{if(this._continuity.visibility(t),this._dayCycleVisibility(t),"hidden"===t.kind)return this._clearTransientHover(!0),this._cancelDevicePressFeedback(),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,!t.long){const t=Date.now();let e=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+I_)>t||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,e=!0);return void(e&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._lastTap=0,this._onLabsSnapshot=t=>{const e=this._effectiveProjection();this._labs=t;const i=this._effectiveProjection();this._convertProjectionView(e,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const t=this._hashSpace();if(t&&this._model.find(e=>e.id===t)&&t!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._onHaRegistryUpdate=()=>{const t=An(this.hass);t.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=t.revision,this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,function(t){const e=Cn(t);e&&(Tn(t,e),Rn(t,e))}(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new $d(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=hv(()=>{if(this._serverStorage){const t=[...this._dirtyPos];this._dirtyPos.clear();for(const e of t){const t=ol(this._layout[e]);t&&(this._layout={...this._layout,[e]:t},this._sentPos.set(e,t),this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t}).then(t=>this._noteLayoutRev(t)).catch(t=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))).finally(()=>{this._sentPos.get(e)===t&&this._sentPos.delete(e)}))}this._cacheSnapshot()}else this._layout=al(Gr(this._layout)),localStorage.setItem(Jf,JSON.stringify(this._layout))},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.undo();t&&(this._applyGeometryState(t.before,!0)?this._showToast(this._t("history.undone",{name:t.name})):this._geometryHistory.clear())},this._redoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.redo();t&&(this._applyGeometryState(t.after,!0)?this._showToast(this._t("history.redone",{name:t.name})):this._geometryHistory.clear())},this._saveConfigDebounced=hv(()=>{this._serverCfg&&this._writeConfig().catch(t=>{const e=!0===t?.physicalGeometryRolledBack;"geometry-unsafe"!==t?.code&&("wall_model_client_outdated"===t?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===t?.code?(this._showToast(this._t("toast.conflict")),e||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(t)})),e&&this._reloadRejectedPhysicalWrite())})},500),this._draftSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>{const t=this._physicalDialog,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=Wf(t.cm);if(null==s)return void this._showPhysicalRange("column"===t.kind?jc:100,"column"===t.kind?1:0);const n=this._imperial?2.54*s:s,o="column"===t.kind?jc:100,a="column"===t.kind?1:0;if(!Number.isFinite(n)||no)return void this._showPhysicalRange(o,a);if("column"===t.kind){const e=i.wall_columns.find(e=>e.id===t.id);if(!e)return;const s=Wf(t.angle||"0");if("circle"!==t.shape&&(null==s||s<0||s>=90))return void this._showToast(this._t("toast.physical_angle"));const o="circle"===t.shape?{id:t.id,shape:"circle",center:e.center,cm:n}:{id:t.id,shape:"square",center:e.center,cm:n,angle:s};if(i.wall_columns.some(e=>e.id!==t.id&&uh(e,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"))}const r=this._geometrySnapshot();if("partition"===t.kind){const i=(e.partitions||[]).find(e=>e.id===t.id);if(i&&0===n&&f_(e.openings,{kind:"partition",id:t.id}))return void this._showToast(this._t("toast.zero_wall_opening_conflict"));i&&(i.cm=n)}else if("column"===t.kind){const i=(e.wall_columns||[]).find(e=>e.id===t.id);i&&(i.cm=Gc(n),i.shape="circle"===t.shape?"circle":"square","square"===i.shape?i.angle=Wf(t.angle||"0"):delete i.angle)}else{const i=(e.room_drafts||[]).find(e=>e.id===t.id);i?.segments?.[t.segment||0]&&(i.segments[t.segment||0].cm=n)}const l=this._commitPhysicalGeometry(this._t("history.physical_edit"),r);this._physicalDialog=null,l||this.requestUpdate()},this._deletePhysicalSelection=()=>{const t=this._physicalSel,e=this._curSpaceCfg;if(!t||!e)return;if("draft"===t.kind)return void this._deleteDraftWhole();const i=this._geometrySnapshot();if("partition"===t.kind){const i=(e.openings||[]).filter(e=>"partition"===e.host?.kind&&e.host.id===t.id).sort((t,e)=>(t.host?.t||0)-(e.host?.t||0));if(i.length)return void(this._partitionDeleteDialog={id:t.id,openings:i.map(t=>JSON.parse(JSON.stringify(t)))})}const s="partition"===t.kind?"partitions":"column"===t.kind?"wall_columns":"room_drafts";e[s]=(e[s]||[]).filter(e=>e.id!==t.id),e[s].length||delete e[s],this._activeDraftId===t.id&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._confirmPartitionDelete=()=>{const t=this._partitionDeleteDialog,e=this._curSpaceCfg;if(!t||!e)return;const i=this._geometrySnapshot();e.partitions=(e.partitions||[]).filter(e=>e.id!==t.id),e.partitions.length||delete e.partitions,e.openings=(e.openings||[]).filter(e=>"partition"!==e.host?.kind||e.host.id!==t.id),e.openings.length||delete e.openings,this._partitionDeleteDialog=null,this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftWhole=()=>{const t="draft"===this._physicalDialog?.kind?this._physicalDialog.id:"draft"===this._physicalSel?.kind?this._physicalSel.id:null,e=this._curSpaceCfg;if(!t||!e||!confirm(this._t("confirm.delete_draft")))return;const i=this._geometrySnapshot();e.room_drafts=(e.room_drafts||[]).filter(e=>e.id!==t),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===t&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftSegment=()=>{const t=this._physicalDialog,e=this._curSpaceCfg;if(!t||"draft"!==t.kind||!e)return;if(!confirm(this._t("confirm.delete_draft_segment")))return;const i=(e.room_drafts||[]).findIndex(e=>e.id===t.id);if(i<0)return;const s=e.room_drafts[i],n=Math.max(0,Math.min(s.segments.length-1,t.segment||0)),o=[],a=s.points.slice(0,n+1),r=s.points.slice(n+1);if(a.length>=2&&o.push({id:s.id,points:a,segments:s.segments.slice(0,n)}),r.length>=2&&o.push({id:o.length?`${s.id}-${Date.now().toString(36)}`:s.id,points:r,segments:s.segments.slice(n+1)}),2===o.length&&e.room_drafts.length>=200)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot();e.room_drafts.splice(i,1,...o),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===s.id&&this._cancelPath(),this._physicalDialog=null,this._physicalSel=o.length?{kind:"draft",id:o[0].id}:null,this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),l)},this._confirmRoomDelete=t=>{const e=this._roomDeleteDialog,i=this._curSpaceCfg,s=this._spaceModel();if(!e||!i||!s)return;const n=s.rooms.find(t=>t.id===e.roomId);if(!n)return void(this._roomDeleteDialog=null);const o=this._openCuts(),a=$u(dc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv).filter(t=>t.roomId===n.id),s.partitions,this._openingsR.map(t=>({...t,x:t.rx,y:t.ry})),.02*this._gridPitch),r=new Set(a.materialize.filter(t=>!t.reusePartitionId).map(t=>t.interval.key)).size;if(t&&(i.partitions||[]).length+r>rv)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot(),c=pc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv);if(t){i.partitions||=[];const t=new Map,e=new Map,s=t=>{const e=(i.wall_segments||[]).find(e=>{const i=[Number(e.a?.[0])*sv,Number(e.a?.[1])*sv],s=[Number(e.b?.[0])*sv,Number(e.b?.[1])*sv];return this._samePt(t.a,i)&&this._samePt(t.b,s)||this._samePt(t.a,s)&&this._samePt(t.b,i)});return"string"==typeof e?.id&&e.id?e.id:null},n=Date.now().toString(36);for(const o of a.materialize){let a=o.reusePartitionId?i.partitions.find(t=>t.id===o.reusePartitionId):e.get(o.interval.key);a||(a={id:s(o.interval)||`partition-room-${n}-${e.size}`,a:[o.interval.a[0]/sv,o.interval.a[1]/sv],b:[o.interval.b[0]/sv,o.interval.b[1]/sv],cm:o.interval.cm},i.partitions.push(a),e.set(o.interval.key,a)),t.set(o.interval.key,a)}for(const e of i.openings||[]){const i=a.openingIntervals.get(e.id),s=i?t.get(i):null,n=this._openingsR.find(t=>t.id===e.id);if(!s||!n)continue;const o={a:[s.a[0]*sv,s.a[1]*sv],b:[s.b[0]*sv,s.b[1]*sv]};e.host={kind:"partition",id:s.id,t:Su([n.rx,n.ry],o)}}}else if(a.removeOpeningIds.length){const t=new Set(a.removeOpeningIds);i.openings=(i.openings||[]).filter(e=>!t.has(e.id)),i.openings.length||delete i.openings}i.rooms=i.rooms.filter(t=>t.id!==n.id),this._cfgEpoch++;const h=this._normalizeWalls(c,this._openCuts());h.length?i.walls=h:delete i.walls,this._roomDeleteDialog=null,this._commitPhysicalGeometry(this._t(t?"history.delete_room_keep_walls":"history.delete_room_with_walls"),l),this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate()},this._rebindPartitionOpening=()=>{const t=this._openingDialog;if(!t?.id)return;const e=t.id;this._activateMarkupTool("opening"),"opening"===this._tool&&(this._openingRebindId=e,this._openingPreset={type:t.type,lengthCm:t.lengthCm,flipH:t.flipH,flipV:t.flipV,revision:++this._openingPresetRevision},this._openingDialog=null,this._openingHoverCandidate=null)},this._keepClosedAsPartitions=()=>{if(this._wallFaceBatch)return void this._decideWallFace(!1);if(!this._contourClosed||this._pendingSplit||!this._curSpaceCfg)return;const t=this._curSpaceCfg,e=this._path.slice(0,-1);if((t.partitions||[]).length+e.length>rv)return void this._showToast(this._t("toast.physical_limit"));const i=this._geometrySnapshot(),s=Xp(e.length,[...this._draftSegmentCms,this._closingWallCm??void 0],this._drawWallCm,ll);t.partitions||=[];const n=Date.now().toString(36),o=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,a=this._draftSegmentsForPath(this._path,o,s);for(let i=0;it.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.contour_to_partitions"),i),this._roomDialog=!1,this._path=[],delete this._resumeDraftBySpace[this._space],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null},this._toggleServerPlans=async()=>{const t=this._spaceDialog;if(t)if(t.pickSaved)this._spaceDialog={...t,pickSaved:!1};else{this._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.hass.callWS({type:"houseplan/plans/list"}),e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:t?.plans||[],savedBusy:!1})}catch(t){const e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:[],savedBusy:!1}),this._showToast(this._t("toast.plans_list_failed",{err:this._errText(t)}))}}},this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const t=this._dayCycleState();if(!t)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const e=mr(t);e!==this._dayCycleClockKey&&(this._dayCycleClockKey=e,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(!this._norm)return;const t=this._glowRadiusCm,e=this._imperial?Math.round(t/30.48*10)/10:Math.round(t)/100;this._settingsDialog={colors:JSON.parse(JSON.stringify(this._fillColors)),glowRadius:e,bgColor:hs(this._settings,{bgColor:null})||null,northDeg:$r(this._settings,{}),bgMode:Sr(this._settings,{}),sunRays:Mr(this._settings,{}),busy:!1}},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._previewAlignDialog(!1),this._toggleOptimizeLivePositions=()=>{const t=this._alignDialog;t&&!t.busy&&t.report.liveMissingPositions.length&&this._previewAlignDialog(!t.removeLiveMissingPositions)},this._optimizeUndoBusy=!1,this._openBackupExport=()=>{this._settingsDialog=null,this._backupExportDialog={kind:"full",planOnly:!1,busy:!1,error:""}},this._openRulesDialog=()=>{if(!this._norm)return;const t=this._settings.icon_rules,e=(t&&t.length?t:Jt).map(t=>({...t}));this._rulesDialog={rules:e,test:"",busy:!1}},this._climateCache=null,this._gearPtCache=new WeakMap}get _canEdit(){return!!this._norm&&(!0===this._serverCanWrite||!1!==this._serverCanWrite&&!0===this.hass?.user?.is_admin)}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}_cssColor(t,e){const i=String(t||"").trim();if(!i)return e;const s=document.createElement("span");s.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(s);const n=getComputedStyle(s).color||e;return s.remove(),n}_currentModeVisual(t=this._mode){const e=this._modeTransition.presented||this._modeTransitionVisual;if(e)return{...e,viewport:{...e.viewport,viewBox:{...e.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const s=this.renderRoot.querySelector(".editorchrome"),n=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),a=this.renderRoot.querySelector(".hp-backdrop"),r=this.renderRoot.querySelector(".zoomwrap"),l=r?getComputedStyle(r).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:t,editorChromeHeight:"view"===t?0:s?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:Sg(n,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===t?.35:1,backdropOpacity:a&&Number(getComputedStyle(a).opacity)||1,viewWeight:"view"===t?1:0,editorWeight:"view"===t?0:1,toolbarContentOpacity:"view"===t?0:1}}_viewForModeTarget(t,e,i,s,n){const o=Ni(this._baseVb(),s/Math.max(1,n)),a=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),r=o.w/a,l=o.h/a,c=e??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-r/2,y:h-l/2,w:r,h:l},o)}_targetStageColor(t){return"view"!==t?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(t){return"view"===t&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(t){return 1}_applyModeTransitionFrame(t){t.targetMode===this._mode&&(this._modeTransitionVisual=t.presented,this._view={...t.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(t){if(t.targetMode!==this._mode)return;const e=this._modeTransitionRequest;this._view={...t.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[t.to.stageWidth,t.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._modeTransitionBusy||t.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-t.to.stageWidth)>.5||Math.abs(i.clientHeight-t.to.stageHeight)>.5)){const t=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,t?t.x+t.w/2:void 0,t?t.y+t.h/2:void 0),this.requestUpdate()}const s=this.renderRoot.activeElement;(!s||!s.isConnected||!!s.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(t=!0){const e=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(t),t&&e||(this._modeTransitionVisual=null)}_adoptMode(t){this._cancelModeTransition(!1),this._mode=t,"view"!==t&&(this._editorChromeMode=t)}_commitViewModeAtomic(t,e,i,s){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=e,t){const n=this._stageEl?.clientWidth||t.stageWidth,o=Math.max(1,t.stageHeight+t.editorChromeHeight);this._view=this._viewForModeTarget(e,i,s,n,o),this._lastValidStageSize=[n,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(t,e,i,s,n,o){this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._mode!==i)return void(t===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const a=this.renderRoot.querySelector(".editorchrome"),r=a?.querySelector(".editorchrome-inner"),l="view"===i?0:r?.scrollHeight||r?.getBoundingClientRect().height||0,c=Math.max(1,e.stageHeight+e.editorChromeHeight),h=Math.max(1,c-l),d=this._stageEl?.clientWidth||e.stageWidth;if(d<=0||h<=0)return this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._applyView(s,n,o),void this.requestUpdate();const p=this._viewForModeTarget(s,n,o,d,h),u={presentedMode:i,editorChromeHeight:l,stageWidth:d,stageHeight:h,viewport:Sg(p,d),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const _=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(e,u,i,this._reducedMotion||_?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(t=this._model,e=this._loadOk){const i=this._config?.floor,s=function(t){if(!t.hasFloor)return{kind:"absent"};const e=t.floor;if("string"==typeof e)return e.length?t.spaceIds.includes(e)?{kind:"valid",id:e,source:"id"}:{kind:"invalid",reason:"unknown-id",value:e}:{kind:"invalid",reason:"empty-id",value:e};if("number"==typeof e){if(!Number.isFinite(e))return{kind:"invalid",reason:"non-finite-index",value:e};if(!Number.isInteger(e))return{kind:"invalid",reason:"fractional-index",value:e};if(e<0)return{kind:"invalid",reason:"negative-index",value:e};const i=t.spaceIds[e];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:e}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:e}}({spaceIds:t.map(t=>t.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||e?s:"number"==typeof i?"valid"===s.kind||"invalid"===s.kind&&"out-of-range-index"===s.reason?{kind:"pending",value:i}:s:"valid"===s.kind||"invalid"===s.kind&&"unknown-id"!==s.reason?s:{kind:"pending",value:i}}_canCommitSpace(t,e=!1){if(e||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===t}_commitSpace(t,e=!1){return!!this._canCommitSpace(t,e)&&(t!==this._space&&(this._clearTransientHover(!0),this._cancelDevicePressFeedback()),this._space=t,!0)}_slideTo(t,e){if(t===this._space)return!0;if(!this._canCommitSpace(t))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),i||(this._slide=e,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(t,e){Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:t.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(dv(t),this._tabDragRelease=t=>this._tabPointerUp(t),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:e,pointerId:t.pointerId,x:t.clientX,y:t.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(t,e,i){const s=this._model.map(t=>t.id),n=s.indexOf(i);if(n<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const a of o){const o=a.dataset.id||"";if(!o||o===i)continue;const r=a.getBoundingClientRect();if(tr.right||er.bottom)continue;const l=s.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,s;const n=this._tabDropTargetAt(t.clientX,t.clientY,e.id);e.moved&&e.targetId===n?.targetId&&e.placement===n?.placement||(this._tabDrag={...e,moved:!0,targetId:n?.targetId||null,placement:n?.placement||null})}_tabPointerUp(t){const e=this._tabDrag;if(e&&e.pointerId!==t.pointerId)return;const i="pointerup"===t.type&&e?.moved?this._tabDropTargetAt(t.clientX,t.clientY,e.id):null;"pointerup"===t.type&&e?.moved&&this._suppressNextTabClick(),this._endTabDrag(),e?.moved&&i&&this._commitTabOrder(e.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(t){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(t)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(t,e){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const s=this._model.map(t=>t.id),n=function(t,e,i){const s=t.indexOf(e),n=t.indexOf(i);if(s<0||n<0||s===n)return t;const o=t.slice();return o.splice(s,1),o.splice(n,0,e),o}(s,t,e);if(n===s)return;const o=new Map(this._devices.map(t=>[String(t.id),String(t.area||"")])),a=function(t,e,i,s=()=>""){if(!i)return[];const n=[];for(const o of t){if(!o||!0===o.removed)continue;const t="string"==typeof o.id?o.id:"";if(!t)continue;if("string"==typeof o.space&&o.space)continue;const a=("string"==typeof o.area?o.area:"")||s(t)||"";a&&e[a]||n.push({id:t,space:i})}return n}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([t,e])=>[t,e.space])),s[0]||"",t=>o.get(t)||"");if(a.length){const t=new Map(a.map(t=>[t.id,t.space]));for(const e of i.markers||[]){const i=t.get(String(e.id));i&&(e.space=i)}}i.spaces=function(t,e){const i=new Map(e.map((t,e)=>[t,e]));return t.map((t,e)=>({space:t,index:e})).sort((t,e)=>(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)||t.index-e.index).map(t=>t.space)}(i.spaces||[],n),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(t){if(this._endTabDrag(),t===this._space)return;const e=this._model.map(t=>t.id),i=e.indexOf(this._space),s=e.indexOf(t);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(t,i>=0&&s0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const t=this._model.map(t=>t.id),e=t.indexOf(this._space);this._slideTo(t[(e+1)%t.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(t){this._wallUnionCacheValue=t,null===t&&this._wallUnionPool.clear()}_newContinuityController(){return new bd(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(ev,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(t){const e=this._view;if(!e)return null;const i=[e.x+e.w/2,e.y+e.h/2],s="iso"===t?Zg(i):i;return{x:s[0],y:s[1]}}_convertProjectionView(t,e){if(t===e)return;const i=this._logicalViewCenter(t);this._view=null;const s=i?"iso"===e?Xg([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,s?.[0],s?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(t){if(!this._labsIso||"view"!==this._mode)return;const e=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:t},"iso"===t){const t=this._isoSceneKey();t&&this._isoFallback.delete(t)}this._saveViewPreference();const i=this._effectiveProjection();this._convertProjectionView(e,i)}_hashSpace(){return Og(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const t=(e=this.ownerDocument,vg.get(e)?.resolved);var e;void 0!==t&&(this._glowScreenBlend=t),this._continuityUnsub?.(),this._continuityUnsub=vd(this.ownerDocument,this._pageVisibility),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(t=>{for(const e of t)for(const t of e.addedNodes)this._syncPointerHoverSubtree(t)}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),function(t){const e=vg.get(t);if(e)return e.promise;const i={promise:Promise.resolve(!1)};return i.promise=bg(t).catch(()=>!1).then(t=>(i.resolved=t,t)),vg.set(t,i),i.promise}(this.ownerDocument).then(t=>{t!==this._glowScreenBlend&&(this._glowScreenBlend=t,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>Is(this._serverCfg)),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(t,e){Ug.add(e);const i=Kg(t);return"undefined"==typeof window&&e(i),()=>{Ug.delete(e)}}(Nf,this._onLabsSnapshot),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const t of this._activityRt.values())clearTimeout(t.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),this._modeTransition.dispose(),this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer);for(const t of this._glowFadeTimers.values())clearTimeout(t);for(const t of this._glowEnterRafs.values())cancelAnimationFrame(t);clearTimeout(this._glowFeatherResumeTimer),this._glowFeatherResumeTimer=0,this._glowFeatherSuspendUntil=0,this._glowFadeTimers.clear(),this._glowEnterRafs.clear(),this._glowEnteringSources.clear(),this._glowRenderedSources.clear(),this._glowLastAppearance.clear(),this._glowSourceSeq=0,this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._touchContacts.clear(),this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(t){if("Escape"===t.key&&this._vacFit)return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void t.stopPropagation();if("Escape"===t.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm=null);if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._settingsDialog)return void(this._settingsDialog=null);if(this._markerDialog)return void(this._markerDialog=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary.hasOpenGroup)return t.preventDefault(),void this._editorSecondary.closeGroup(!0)}const e=t.composedPath?.()||[t.target],i=e.some(t=>t?.matches?.('input, textarea, select, [contenteditable="true"]')),s=e.some(t=>t?.classList?.contains?.("editor-secondary")),n=t.ctrlKey||t.metaKey,o=t.key.toLowerCase(),a=/^[a-z]$/.test(o),r="z"===o||!a&&"KeyZ"===t.code,l="y"===o||!a&&"KeyY"===t.code,c=n&&(r&&t.shiftKey||l),h=n&&r&&!t.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;return c?(t.preventDefault(),void this._redoGeometry()):h?(t.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry()):"Delete"!==t.key&&"Backspace"!==t.key||!this._decorSel||i||s?void("Escape"===t.key&&(t.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._furnPalette=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(t.preventDefault(),void this._decorDeleteSel())}if(this._markup&&(!h&&!c||!i)){if(("Delete"===t.key||"Backspace"===t.key)&&this._physicalSel&&!i&&!s)return t.preventDefault(),void this._deletePhysicalSelection();if(c)return t.preventDefault(),void this._redoGeometry();if(h)return t.preventDefault(),this._rszDrag?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===t.key)return this._physicalDrag||this._physicalRotate?(t.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(t.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(t.preventDefault(),void this._finishWallChain()):this._physicalSel?(t.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(t.preventDefault(),this._rszDrag?void this._rszCancelDrag():void(this._rszSel?this._rszSel=null:this._tool="draw")):"split"===this._tool?(t.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(t.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(t.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(t.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length){if(this._contourClosed)return this._path=this._path.slice(0,-1),void(this._closingWallCm=null);if(this._activeDraftId&&this._path.length>1&&this._curSpaceCfg){const t=this._geometrySnapshot();this._path=this._path.slice(0,-1),this._draftSegmentCms=this._draftSegmentCms.slice(0,-1);const e=this._curSpaceCfg,i=(e.room_drafts||[]).findIndex(t=>t.id===this._activeDraftId);if(i>=0){const s=Array.isArray(e.room_drafts[i]?.segments)?e.room_drafts[i].segments:[];this._path.length<2?(e.room_drafts.splice(i,1),e.room_drafts.length||delete e.room_drafts,this._activeDraftId=null):e.room_drafts[i]={id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentCms.map((t,e)=>({...s[e]||{},cm:t}))},this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),t)}return}this._path=this._path.slice(0,-1)}}_undoActiveDraftPoint(){const t=this._activeDraftId,e=this._path[0]?[...this._path[0]]:null,i=this._geometryHistory.undo();if(!i)return void this._undoPoint();if(!this._applyGeometryState(i.before,!0))return void this._geometryHistory.clear();const s=t?this._spaceModel()?.room_drafts.find(e=>e.id===t):null;s?(this._activeDraftId=s.id,this._path=s.points.map(t=>[...t]),this._draftSegmentCms=this._adoptDraftCms(this._path,s.segments.map(t=>t.cm),s.id),this._resumeDraftBySpace[this._space]=s.id):(this._activeDraftId=null,this._path=e?[e]:[],this._draftSegmentCms=[],t&&this._resumeDraftBySpace[this._space]===t&&delete this._resumeDraftBySpace[this._space]),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:i.name}))}static getConfigElement(){return document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(t){for(const t of Gf.values())for(const e of t)clearTimeout(e.evict);Gf.clear(),Yf=t&&t>0?t:1e4}static _warmBootStats(){let t=0,e=0;const i=[];for(const s of Gf.values())for(const n of s)t++,n.dlg&&(e++,i.push(n.dlg.kind));return{keys:Gf.size,slots:t,dlgs:e,drafts:i}}setConfig(t){const e=this._config,i=!!e&&Object.prototype.hasOwnProperty.call(e,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...t};(i!==this._hasFixedFloor||e?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&t.default_floor&&this._commitSpace(t.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(Zf)||"{}")||{}}catch{this._zoomBySpace={}}try{const t=JSON.parse(localStorage.getItem(ev)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(t).filter(t=>"flat"===t[1]||"iso"===t[1]))}catch{this._viewPreference={}}this._labs=Kg(Nf);try{const t=JSON.parse(localStorage.getItem(tv)||"null");this._kioskScale={icon:Es(t?.icon),font:Es(t?.font)}}catch{}try{const t=JSON.parse(localStorage.getItem(Xf)||"null");t&&t.config&&Array.isArray(t.config.spaces)&&(this._serverCfg=t.config,this._cfgEpoch++,this._cfgRev=t.rev||0,this._cfgContentFingerprint=t.config_fingerprint||wd(t.config),this._layout=t.layout||{},this._layoutRev=t.layout_rev||0,this._layoutContentFingerprint=t.layout_fingerprint||wd(this._layout),this._virtualLights=mn(t.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1)}_warmAdopt(){if(this._config?.kiosk)return;const t=Kf(this._config);if(this._warmKey===t&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const e=this.parentNode,i=this._warmIdx(e),s=Gf.get(t);if(!s||!s.length)return;const n=s.find(t=>t.owner===this._warmGen);if(n)return this._warmLongReturn=!!n.freed&&Date.now()-n.freed>=md,clearTimeout(n.evict),n.evict=0,n.freed=0,n.live=!0,this._warmSlot=n,this._warmKey=t,n.frameFingerprint&&this._continuity.adoptCompleteFrame(n.frameFingerprint),void(!this._devices.length&&n.devices?.length&&(this._devices=[...n.devices]));const{slot:o,sure:a}=((t,e,i,s)=>{const n=t=>{const e=!!i&&t.place?.deref()===i;return e&&t.idx===s?4:t.live?0:e?3:2};let o=null,a=0,r=0,l=null;for(const i of t){if(i.owner===e)continue;l=i;const t=n(i);t<=0||(t>a?(o=i,a=t,r=1):t===a&&r++)}return!o||r>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(s,this._warmGen,e,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=md,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),this._warmKey=t,a?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=e?new WeakRef(e):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},s.push(this._warmSlot),this._warmTrim(s)))}_warmIdx(t){const e=t?.children;if(!e)return-1;for(let t=0;t4;){const e=t.findIndex(t=>!t.live);if(e<0)break;clearTimeout(t[e].evict),t.splice(e,1)}}_warmScheduleEvict(t,e){if(clearTimeout(t.evict),!(t.dlg||t.vp&&"view"!==t.vp.mode))return;const i=t.freed,s=t.owner;t.evict=window.setTimeout(()=>{if(t.evict=0,t.freed!==i||t.owner!==s)return;var n;t.dlg=null,t.vp=(n=t.vp)&&"view"!==n.mode?{...n,mode:"view",zoom:n.snap?.space===n.space?n.snap.zoom:n.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:n,t.frameFingerprint="";const o=Gf.get(e);if(!t.live&&o&&o.length>1){const e=o.indexOf(t);e>=0&&o.splice(e,1)}},Yf+250)}_warmAdoptViewport(t){const e=this._warmVp;if(!e||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(t=>t.id===e.space)||"valid"===i.kind&&i.id!==e.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(e.space,!0),this._navApplied=!0,this._adoptMode("view"!==e.mode&&this._canEdit&&!t.kiosk?e.mode:"view"),this._pendingNavMode="view"===e.mode||this._canEdit||t.kiosk?null:e.mode,this._zoom=e.zoom;const s=this._effectiveProjection(),n=s===e.projection&&this._labsIso===e.activeLabsIso;if(this._view=n&&e.view?{...e.view}:null,this._viewModeSnap=n&&e.snap?{...e.snap}:null,!n&&e.logicalCenter){const t="iso"===s?Xg([e.logicalCenter.x,e.logicalCenter.y],0):[e.logicalCenter.x,e.logicalCenter.y];this._applyView(e.zoom,t[0],t[1])}var o;this._tool="opening"===(o=function(t){return"partition"===t?"draw":t}(o=e.tool))?"draw":"string"==typeof o&&av.has(o)?o:"draw",this._decorTool=e.decorTool,this._showHidden=e.showHidden,this._showFar!==e.showFar&&(this._showFar=e.showFar,this._frame=null),this._selId=e.selId,this._rszSel=e.rszSel,this._decorSel=e.decorSel,this._warmVpArmed=!0}_warmPatch(t,e=!1){if(this._config?.kiosk)return;const i=Kf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!e)return;const t=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:this._warmIdx(t),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const s=Gf.get(i)||[];for(s.push(this._warmSlot),Gf.set(i,s),this._warmTrim(s);Gf.size>8;){const t=Gf.keys().next().value;if(void 0===t||t===i)break;for(const e of Gf.get(t)||[])clearTimeout(e.evict);Gf.delete(t)}}Object.assign(this._warmSlot,t)}}_warmViewportState(){const t=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:t,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(t),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._rszSel,decorSel:this._decorSel}}_warmDialogState(){const t=(t,e)=>({kind:t,space:this._space,mode:this._mode,data:e});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?t("openingInfo",this._openingInfo.id):this._infoCard?t("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:t("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:t("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:t("marker",this._markerDialog):this._openingDialog?t("opening",this._openingDialog):this._backdropDialog?t("backdrop",this._backdropDialog):this._decorShapeDialog?t("decorShape",this._decorShapeDialog):this._decorTextDialog?t("decorText",this._decorTextDialog):this._roomDialog?t("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:t("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const t={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices};if(this._warmRevivePending||(t.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const e=this.parentNode;t.place=e?new WeakRef(e):null,t.idx=this._warmIdx(e)}this._warmPatch(t)}_warmReviveDialog(){this._warmRevivePending=!1;const t=this._warmSlot;if(this._warmReviveTimer=void 0,!t||!t.dlg)return;const e=t.dlg,i=t.freed;if(t.dlg=null,t.freed=0,clearTimeout(t.evict),t.evict=0,i&&!(Date.now()-i>Yf)&&e.space===this._space&&e.mode===this._mode){switch(e.kind){case"space":this._spaceDialog={...e.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...e.data,busy:!1};break;case"settings":this._settingsDialog={...e.data,busy:!1};break;case"rules":this._rulesDialog={...e.data,busy:!1};break;case"opening":this._openingDialog={...e.data};break;case"backdrop":this._backdropDialog={...e.data};break;case"decorShape":this._decorShapeDialog={...e.data};break;case"decorText":{this._decorTextDialog={...e.data};const t=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:t,end:t};break}case"room":{const t=e.data;this._roomEditId=t.editId,this._roomFill=t.fill,this._roomCustomFill=t.customFill||null,this._roomTempSrc=t.tempSrc,this._roomHumSrc=t.humSrc,this._roomSrcOpen=t.srcOpen,this._roomSrcFilter=t.srcFilter,this._roomNameScale=t.nameScale,this._roomLabelScale=t.labelScale,this._areaSel=t.areaSel,this._nameSel=t.nameSel,this._pendingSplit=t.pendingSplit,this._wallFaceBatch=t.wallFaceBatch||null,this._path=t.path,this._wallFaceBatch&&(this._activeDraftId=this._wallFaceBatch.activeDraftId,this._draftSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const t=this._devices.find(t=>t.id===e.data);t&&(this._infoCard=t);break}case"openingInfo":{const t=(this._curSpaceCfg?.openings||[]).find(t=>t.id===e.data);t&&(this._openingInfo=t);break}}this.requestUpdate()}}_cacheSnapshot(){if(this._serverCfg)try{this._cfgContentFingerprint=wd(this._serverCfg),this._layoutContentFingerprint=wd(this._layout),this._virtualLights=function(t,e,i){if(t.configRev===i)return t;const s=new Set((Array.isArray(e?.markers)?e.markers:[]).filter(yn).map(t=>t.id));return{...t,configRev:i,off:new Set([...t.off].filter(t=>s.has(t)))}}(this._virtualLights,this._serverCfg,this._cfgRev),localStorage.setItem(Xf,JSON.stringify({config:this._serverCfg,rev:this._cfgRev,config_fingerprint:this._cfgContentFingerprint,layout:this._layout,layout_rev:this._layoutRev,layout_fingerprint:this._layoutContentFingerprint,virtual_lights:fn(this._virtualLights)}))}catch{}}_beginContinuityCandidate(t,e,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=e,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(t,i))}_continuityStageValid(){const t=this._stageEl;return!!t&&t.clientWidth>0&&t.clientHeight>0}_continuityAssetsReady(){if(!this._model.length)return!1;const t=this._model.length?this._spaceModel():null;return!t?.bg?.href||this._signer.isReady(this.hass,t.bg.href)}_initialSpaceSelection(t,e=this._loadOk){const i=this._fixedFloorState(t,e);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(t){const e=new Set(t.spaceIds.filter(t=>!!t));if(!e.size)return{id:null,source:"none"};const i=[["hash",!1===t.acceptHash?null:t.hashSpace],["current",t.preserveCurrent?t.currentSpace:null],["saved",t.savedSpace],["default",t.defaultSpace],["first",t.spaceIds[0]]];for(const[t,s]of i)if(s&&e.has(s))return{id:s,source:t};return{id:null,source:"none"}}({spaceIds:t.map(t=>t.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(t,e=this._loadOk){const i=this._initialSpaceSelection(t,e);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(t,e=this._space){const i=Sh(t),s=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==s.kind)return"";const n=this._initialSpaceSelection(i,!0).id||(i.some(t=>t.id===e)?e:i[0]?.id);return i.find(t=>t.id===n)?.bg?.href||""}_visualFrameFingerprint(){const t=this._stageEl,e=t?[t.clientWidth,t.clientHeight]:[0,0];return kd([this._cfgRev,this._cfgContentFingerprint||wd(this._serverCfg),this._layoutRev,this._layoutContentFingerprint||wd(this._layout),this._space,this._mode,this._view,e,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const t=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==t)return this._stagedDeviceSnapshotToken=t,void this.requestUpdate();this._continuityPaintToken!==t&&(this._continuityPaintToken=t,this._continuity.candidateReady(t)&&this._continuity.commitAfterPaint(t,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(e=>{e&&t===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):t===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(t,e){this._signer.markLoaded(this.hass,t,e),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const t="connection"===this._continuity.recoveryReason;return W`
`}afterRender(){const t=this.host.root();this._blocked&&(this._openGroupId?this.closeGroup(!1):"palette"===this._currentModel?.kind&&this._currentModel.dismiss?.()),this._syncGlobalDismissListener();const e=t.querySelector(".editor-secondary"),i=this._renderedContext,s=e?.dataset.contextId||"";if(s&&i&&s!==i&&!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches&&(this._contentAnimation?.cancel(),this._contentAnimation=e?.querySelector(".editor-secondary-content")?.animate([{opacity:.35,transform:"translateY(-4px)"},{opacity:1,transform:"translateY(0)"}],{duration:100,easing:"ease-out"})),this._renderedContext=s,i&&s!==i&&this._focusOwned){const i=s?e?.querySelector('[tabindex="0"], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'):t.querySelector(".editbar-tools");i?.focus?.(),this._focusOwned=!!s}if("palette"===this._currentModel?.kind&&this._currentModel.launcherId){const e=[...t.querySelectorAll("[data-editor-palette]")].find(t=>t.dataset.editorPalette===this._currentModel?.launcherId);e&&null!==e.offsetParent||this._currentModel.dismiss?.()}if(!this._openGroupId)return;const n=[...t.querySelectorAll("[data-editor-group]")].find(t=>t.dataset.editorGroup===this._openGroupId);n&&null!==n.offsetParent||this.closeGroup(!0)}handleOutsideDismiss(t){if(q_(t,t=>t.hasAttribute("data-editor-navigation")))return"pointerdown"===t.type?this.closeForNavigation():"click"===t.type&&this._dismissPointerTarget&&this._clearDismissClick(),!1;if("click"===t.type&&this._dismissPointerTarget){return!!(t.composedPath?.()||[t.target]).includes(this._dismissPointerTarget)&&(this._clearDismissClick(),t.preventDefault(),t.stopImmediatePropagation(),!0)}const e=this._openGroupId||this._blocked||"palette"!==this._currentModel?.kind?null:this._currentModel;if("pointerdown"===t.type&&(this._openGroupId||e)){const i=q_(t,t=>t.classList.contains("editor-secondary")),s=q_(t,t=>!!t.dataset.editorGroup),n=q_(t,t=>!!t.dataset.editorPalette),o=q_(t,t=>t.classList.contains("stage"));if(!(i||s||n||"stay-open-on-canvas"===e?.dismissPolicy&&o))return t.preventDefault(),t.stopImmediatePropagation(),this._dismissPointerTarget=t.target,clearTimeout(this._dismissTimer),this._dismissTimer=window.setTimeout(()=>{this._clearDismissClick()},800),this._openGroupId?this.closeGroup(!1):e?.dismiss?.(),this._syncGlobalDismissListener(),!0}return!1}_activateGroupItem(t,e,i){if(t.id!==this._openGroupId)return;const s=t.items.find(t=>t.id===e);if(!s||s.disabled)return;const n="toggle"===s.role&&"stay-open"===s.closePolicy,o=0===i.detail;n||(this._openGroupId=null,this.host.requestUpdate(),this._syncGlobalDismissListener()),s.invoke(),!n&&o&&this.host.updateComplete().then(()=>{const e=[...this.host.root().querySelectorAll("[data-editor-group]")].find(e=>e.dataset.editorGroup===t.id&&null!==e.offsetParent);e?.focus()})}_groupKeydown(t){if(!["ArrowLeft","ArrowRight","Home","End"].includes(t.key))return;const e=[...t.currentTarget.querySelectorAll(".editor-group-item:not([disabled])")];if(!e.length)return;t.preventDefault();const i=e.indexOf(this.host.root().activeElement),s="Home"===t.key?0:"End"===t.key?e.length-1:"ArrowLeft"===t.key?i<=0?e.length-1:i-1:(i+1)%e.length;e[s]?.focus()}_clearDismissClick(){this._dismissPointerTarget=null,clearTimeout(this._dismissTimer),this._dismissTimer=void 0,this._syncGlobalDismissListener()}_syncGlobalDismissListener(){const t=!this._blocked&&"palette"===this._currentModel?.kind,e=!!this._openGroupId||t||!!this._dismissPointerTarget;e!==this._globalDismissListening&&(this._globalDismissListening=e,e?(window.addEventListener("pointerdown",this._globalDismissGuard,!0),window.addEventListener("click",this._globalDismissGuard,!0)):(window.removeEventListener("pointerdown",this._globalDismissGuard,!0),window.removeEventListener("click",this._globalDismissGuard,!0)))}}const j_=t=>t.stopPropagation(),U_=4.166666666666667e-9;function G_(t){return Number.isFinite(t)?Math.round(t/Th)*Th:t}const V_=(t,e,i,s)=>Math.hypot(i-t,s-e),K_=(t,e,i,s,n,o,a,r)=>Math.hypot(Math.max(Math.abs(n-t),Math.abs(n+a-(t+i))),Math.max(Math.abs(o-e),Math.abs(o+r-(e+s)))),Y_=(t,e,i,s,n,o,a)=>{const r=Math.max(Number(s)||0,0)/2,l=Math.PI/180,c=Math.cos(i*l)*r,h=Math.sin(i*l)*r,d=Math.cos(a*l)*r,p=Math.sin(a*l)*r,u=Math.max(V_(t+c,e+h,n+d,o+p),V_(t-c,e-h,n-d,o-p)),_=Math.max(V_(t+c,e+h,n-d,o-p),V_(t-c,e-h,n+d,o+p));return Math.min(u,_)},J_=t=>{const e=Number(t?.cell_cm);return e>0?e:5};function X_(t,e){const i=JSON.parse(JSON.stringify(t||[])),s=JSON.parse(JSON.stringify(e||{}));let n=0,o=0,a=0,r=0,l="",c=0,h=0,d=0;const p=(t,e)=>{Number.isFinite(t)&&Number.isFinite(e)&&t!==e&&Math.abs(e-t)<=U_&&h++},u=(t,e)=>{p(t[0],e[0]),p(t[1],e[1])},_={};let m=5;for(const t of i){const e=J_(t);null!=t?.id&&(_[String(t.id)]=e),e>m&&(m=e)}const g=(t,e,i,s=!1)=>{if(!(t>U_||s))return;n++,t>a&&(a=t);const o=t*Dh*e;o>r&&(r=o,l=i)};for(const t of i){const e=J_(t),i=null!=t?.id?String(t.id):"";for(const s of t.rooms||[]){o++;let t=0;if(s.poly?.length)s.poly=s.poly.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),u(e,i),i});else if(null!=s.x&&null!=s.y){const e=s.x,i=s.y,n=s.w||0,o=s.h||0,a=G_(e+n),r=G_(i+o),l=G_(e),c=G_(i),h=Math.max(Th,a-l),d=Math.max(Th,r-c);t=K_(e,i,n,o,l,c,h,d),s.x=l,s.y=c,s.w=h,s.h=d,p(e,l),p(i,c),p(e+n,l+h),p(i+o,c+d)}g(t,e,i)}for(const s of t.room_drafts||[]){o++;let t=0;const n=s.points||[],a=n.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),i}),r=a.length?[a[0]]:[],l=a.length?[[n[0],a[0]]]:[],c=[];for(let t=0;t+1=2)for(const[t,e]of l)u(t,e);g(t,e,i)}if(Array.isArray(t.room_drafts)){const e=t.room_drafts.length;t.room_drafts=t.room_drafts.filter(t=>t.points?.length>=2),d+=e-t.room_drafts.length,t.room_drafts.length||delete t.room_drafts}for(const s of t.partitions||[]){o++;const n=[s.a[0],s.a[1]],a=[s.b[0],s.b[1]],r=[G_(n[0]),G_(n[1])],l=[G_(a[0]),G_(a[1])];let c=Math.max(V_(n[0],n[1],r[0],r[1]),V_(a[0],a[1],l[0],l[1]));const h=V_(r[0],r[1],l[0],l[1]),d=(t.openings||[]).filter(t=>"partition"===t.host?.kind&&t.host.id===s.id).every(t=>{const e=Number(t.length),i=Number(t.host.t),s=i*h;return Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>=0&&i<=1&&s-e/2>=-U_&&s+e/2<=h+U_});h>U_&&d?(s.a=r,s.b=l,u(n,r),u(a,l)):c=0,g(c,e,i)}for(const s of t.wall_columns||[]){o++;const t=[s.center[0],s.center[1]],n=[G_(t[0]),G_(t[1])],a=V_(t[0],t[1],n[0],n[1]);s.center=n,u(t,n),g(a,e,i)}for(const s of t.decor||[]){o++;let t=0;if("line"===s.kind){const e=[s.x1,s.y1],i=[s.x2,s.y2],n=[G_(e[0]),G_(e[1])],o=[G_(i[0]),G_(i[1])];t=Math.max(V_(e[0],e[1],n[0],n[1]),V_(i[0],i[1],o[0],o[1])),s.x1=n[0],s.y1=n[1],s.x2=o[0],s.y2=o[1],u(e,n),u(i,o)}else{const e=s.x,i=s.y,n=s.w,o=s.h,a=G_(e),r=G_(i);if(null!=s.w&&null!=s.h){const l=G_(e+n),c=G_(i+o),h=Math.max(Th,l-a),d=Math.max(Th,c-r);t=K_(e,i,n,o,a,r,h,d),s.w=h,s.h=d,p(e+n,a+h),p(i+o,r+d)}else t=V_(e,i,a,r);s.x=a,s.y=r,p(e,a),p(i,r)}g(t,e,i)}for(const s of t.openings||[]){if(o++,"partition"===s.host?.kind){const n=(t.partitions||[]).find(t=>t.id===s.host.id),o=Number(s.host.t);if(!n||!Number.isFinite(o)||o<0||o>1)continue;const a=n.b[0]-n.a[0],r=n.b[1]-n.a[1];if(Math.hypot(a,r)<=U_)continue;const l=n.a[0]+a*o,h=n.a[1]+r*o;let d=180*Math.atan2(r,a)/Math.PI;d>=90?d-=180:d<-90&&(d+=180);const p=Number(s.angle),u=!(Number.isFinite(p)&&p===d),_=Y_(s.x,s.y,Number.isFinite(p)?p:d,Number(s.length)||0,l,h,d);s.x=l,s.y=h,s.angle=d,u&&c++,g(_,e,i,u);continue}const n=ui([s.x,s.y],t.rooms||[],.025,{step:Th,length:Number(s.length)||0});if(!n)continue;const a=Number(s.angle),r=!(Number.isFinite(a)&&a===n.angle),l=Y_(s.x,s.y,Number.isFinite(a)?a:n.angle,Number(s.length)||0,n.x,n.y,n.angle);s.x=n.x,s.y=n.y,s.angle=n.angle,r&&c++,g(l,e,i,r)}}for(const[t,e]of Object.entries(s)){if(!e||"object"!=typeof e)continue;const i=e;if("number"!=typeof i.x||"number"!=typeof i.y)continue;o++;const n=G_(i.x),a=G_(i.y),r=V_(i.x,i.y,n,a);s[t]={...i,x:n,y:a},p(i.x,n),p(i.y,a);const l="string"==typeof i.s?i.s:"";g(r,_[l]??m,l)}return{spaces:i,layout:s,report:{moved:n,coordsCanonicalized:h,total:o,maxShift:a,maxShiftCm:r,maxSpace:l,rotated:c,removedDrafts:d},changed:n>0||h>0}}function Z_(t,e){const i=e.base+t*e.span;return Math.min(1,Math.max(0,i))}const Q_=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),tm=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1]);function em(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<=0)return tm(t,e);let a=((t[0]-e[0])*s+(t[1]-e[1])*n)/o;return a=Math.max(0,Math.min(1,a)),Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))}function im(t,e,i,s,n){for(const s of e)if(s&&!i.has(s.id)&&Q_(s.a)&&Q_(s.b)&&(tm(t,s.a)<=n||tm(t,s.b)<=n))return!0;for(const e of s?.roomPolygons||[])for(let i=0;i0&&r>0))return null;if(Math.abs(n[0]/a*(o[1]/r)-n[1]/a*(o[0]/r))>i)return null;for(const[i,n]of[[t.a,e.a],[t.a,e.b],[t.b,e.a],[t.b,e.b]])if(tm(i,n)<=s)return[(i[0]+n[0])/2,(i[1]+n[1])/2];return null}function nm(t,e){const i=.05*(Number(e.pitch)>0?Number(e.pitch):1),s=new Map;let n=(t||[]).filter(t=>!!t&&"string"==typeof t.id&&Q_(t.a)&&Q_(t.b));if(n.length<2)return{partitions:[...t||[]],merged:0,openingMoves:[]};const o=e.seedIds&&e.seedIds.length?new Set(e.seedIds):null;let a=0;for(let t=0;ttm(e,t.at)>i);let h=c[0]??r.a,d=c[c.length-1]??l.b;if(c.length<2&&(h=r.a,d=l.b),d[0]0?(d[0]-h[0])/u:0,m=u>0?(d[1]-h[1])/u:0,g=t=>u>0?((t[0]-h[0])*_+(t[1]-h[1])*m)/u:0;for(const t of[r,l]){const e=g(t.a),i=g(t.b)-e;for(const[n,o]of s)o.toId===t.id&&s.set(n,{fromId:o.fromId,toId:p.id,base:e+o.base*i,span:o.span*i});s.set(t.id,{fromId:t.id,toId:p.id,base:e,span:i})}o&&o.add(p.id),n=n.filter((e,i)=>i!==t.i&&i!==t.j),n.splice(t.i,0,p),a++}return{partitions:n,merged:a,openingMoves:[...s.values()]}}function om(t,e,i,s){if(!t?.length||!i.length)return 0;const n=new Map(i.map(t=>[t.fromId,t]));let o=0;for(const i of t){const t=i?.host;if(!t||"partition"!==t.kind)continue;const a=n.get(t.id);if(!a)continue;i.host={...t,id:a.toId,t:Z_(t.t,a)},o++;const r=Sp(i,e,s.coordScale,s.cellCm,s.gridPitch).resolved;r&&Object.assign(i,Ip(i,r,s.coordScale))}return o}function am(t,e){const i=e?.excludeDraftId||null;return{roomPolygons:(t?.rooms||[]).map(t=>hi(t)).filter(t=>!!t),columns:t?.wall_columns||[],draftEnds:(t?.room_drafts||[]).flatMap(t=>{if(i&&t?.id===i)return[];const e=t?.points||[];return e.length?[e[0],e[e.length-1]]:[]})}}const rm=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),lm=(t,e)=>t[0]-e[0]||t[1]-e[1],cm=(t,e,i,s)=>[t[0]+e*s,t[1]+i*s],hm=(t,e,i,s)=>(t[0]-e[0])*i+(t[1]-e[1])*s,dm=(t,e,i,s,n)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n))return null;const l=o/r,c=a/r,h=e=>Math.abs((e[0]-t[0])*c-(e[1]-t[1])*l);if(h(i)>n||h(s)>n)return null;const d=hm(i,t,l,c),p=hm(s,t,l,c),u=Math.max(0,Math.min(d,p)),_=Math.min(r,Math.max(d,p));return _-u>n?{lo:u,hi:_}:null},pm=(t,e,i)=>Math.min(t.hi,e.hi)-Math.max(t.lo,e.lo)>i,um=t=>{const e=new Set(["id","a","b","cm"]);return Object.keys(t||{}).every(t=>e.has(t))},_m=(t,e,i,s)=>{const n=t.b[0]-t.a[0],o=t.b[1]-t.a[1],a=Math.hypot(n,o);if(!(a>s))return!0;const r=n/a,l=o/a,c=gl(t.cm,i.cellCm,i.gridPitch)/2;return e.some(e=>{const n=e?.center;if(!rm(n))return!0;const o=hm(n,t.a,r,l),h=Math.abs((n[0]-t.a[0])*l-(n[1]-t.a[1])*r),d=gl(Number(e.cm),i.cellCm,i.gridPitch)*("square"===e.shape?Math.SQRT1_2:.5);return!(Number.isFinite(d)&&d>0)||o>=-d-s&&o<=a+d+s&&h<=c+d+s})},mm=(t,e,i)=>{if(t.host){const s=Sp(t,e,i.coordScale,i.cellCm,i.gridPitch).resolved;return s?{center:s.center,angle:s.angle,length:s.length}:null}const s=Number(t.x)*i.coordScale,n=Number(t.y)*i.coordScale,o=Number(t.angle),a=Number(t.length)*i.coordScale;return[s,n,o,a].every(Number.isFinite)&&a>0?{center:[s,n],angle:o,length:a}:null},gm=(t,e,i)=>{const s=t.angle*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=e.angle*Math.PI/180,r=Math.cos(a),l=Math.sin(a);if(Math.abs(n*l-o*r)>1e-6)return!1;const c=e.center[0]-t.center[0],h=e.center[1]-t.center[1];if(Math.abs(c*o-h*n)>i)return!1;const d=c*n+h*o;return Math.max(-t.length/2,d-e.length/2)({...t,a:[t.a[0]*e,t.a[1]*e],b:[t.b[0]*e,t.b[1]*e]}),vm=(t,e,i,s)=>{const n=`~r-${(t=>{let e=2166136261;for(let i=0;i>>0;return e.toString(36)})(`${t}|${e[0].toFixed(9)},${e[1].toFixed(9)}|${i[0].toFixed(9)},${i[1].toFixed(9)}`)}`,o=`${t.slice(0,Math.max(1,64-n.length))}${n}`;let a=o;for(let t=2;s.has(a);t++){const e=`-${t}`;a=`${o.slice(0,64-e.length)}${e}`}return s.add(a),a},ym=(t,e)=>{const i=[];for(const s of t){const t=i[i.length-1];!(t&&Math.abs(t.hi-s.lo)<=e&&t.safe===s.safe)||s.safe&&t.signature!==s.signature?i.push({lo:s.lo,hi:s.hi,a:s.a,b:s.b,safe:s.safe,signature:s.signature,roomIds:s.roomIds,finalCm:s.finalCm}):(t.hi=s.hi,t.b=s.b)}return i};function bm(t,e,i,s,n){const o=i||[],a=Array.isArray(t?.partitions)?t.partitions:[],r=Array.isArray(t?.openings)?t.openings:[],l=Array.isArray(t?.room_drafts)?t.room_drafts:[],c={walls:o,partitions:a,openings:r,roomDrafts:l,partitionsReconciled:0,openingsRehosted:0,removedDrafts:0};if(!a.length&&!l.length)return c;const h=Math.max(2e-4*n.gridPitch,1e-9);let d=o,p=a,u=r;const _=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),m=((t,e,i,s)=>{const n=new Map(t.map(t=>[t.id,t])),o=new Set;for(const t of e){if(!n.get(t.id)||!Array.isArray(t.points)||t.points.length<2||t.segments.length!==t.points.length-1)continue;let e=!0;for(let n=0;n+10)){e=!1;break}const l=Math.hypot(a[0]-o[0],a[1]-o[1]);if(!(l>s)){e=!1;break}const c=i.flatMap(t=>{const e=t.cm>0?t.cm:ll;if(t.open||"outer"!==t.kind&&"shared"!==t.kind||e+st.lo-e.lo||t.hi-e.hi);let h=0;for(const t of c){if(t.lo>h+s)break;if(h=Math.max(h,t.hi),h>=l-s)break}h!m.has(t.id));let f=0,v=0;const y=new Map(e.partitions.map(t=>[t.id,t]));for(const t of[...a].sort((t,e)=>t.id.localeCompare(e.id))){if(!p.some(e=>e.id===t.id))continue;if(!um(t))continue;const i=y.get(t.id);if(!(i&&rm(i.a)&&rm(i.b)&&Number.isFinite(i.cm)&&i.cm>0))continue;const[o,a]=lm(i.a,i.b)<=0?[[i.a[0],i.a[1]],[i.b[0],i.b[1]]]:[[i.b[0],i.b[1]],[i.a[0],i.a[1]]],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>h))continue;const _=r/c,g=l/c,b=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),w=b.flatMap(t=>{if(t.open||"outer"!==t.kind&&"shared"!==t.kind)return[];const e=dm(o,a,t.a,t.b,h);return e?[{interval:t,range:e}]:[]});if(!w.length)continue;const k=u.filter(t=>"partition"===t.host?.kind&&t.host.id===i.id).map(t=>({opening:t,resolved:Sp(t,e.partitions,n.coordScale,n.cellCm,n.gridPitch).resolved}));if(k.some(t=>!t.resolved))continue;const x=[0,c];for(const{range:t}of w)x.push(t.lo,t.hi);const $=x.slice(),S=new Map;for(const{opening:t,resolved:e}of k){const i=hm(e.center,o,_,g),s={lo:i-e.length/2,hi:i+e.length/2};S.set(t.id,s),$.push(Math.max(0,s.lo),Math.min(c,s.hi))}const M=[...new Set($.filter(t=>Number.isFinite(t)&&t>=-h&&t<=c+h).map(t=>Math.max(0,Math.min(c,t)).toFixed(9)))].map(Number).sort((t,e)=>t-e),C=p.map(t=>fm(t,n.coordScale)).filter(t=>t.id!==i.id),D=e.room_drafts.filter(t=>!m.has(t.id)),P=[];for(let t=0;t+1h))continue;const r=cm(o,_,g,s),l=cm(o,_,g,a),c=w.filter(({range:t})=>t.lo<=s+h&&t.hi>=a-h).map(({interval:t})=>t),d=new Map;for(const t of c)d.set(t.roomId,t);const p=[...d.values()],u=new Set(p.map(t=>t.kind)),m=new Set(p.map(t=>t.cm>0?t.cm:ll)),f=p[0]?.kind,v=[...d.keys()].sort(),y=1===u.size&&1===m.size&&("outer"===f&&1===v.length||"shared"===f&&2===v.length),b={id:i.id,a:r,b:l,cm:i.cm},k=C.some(t=>!!dm(r,l,t.a,t.b,h)),x=D.some(t=>t.points.some((e,i)=>i+10?p[0].cm:ll:0,T=y?Math.max(S,i.cm):i.cm;P.push({lo:s,hi:a,a:r,b:l,safe:$,signature:$?`${f}|${v.join(",")}|${T}`:"",roomIds:v,roomCm:S,finalCm:T})}if(!P.some(t=>t.safe))continue;const T=new Map;for(const{opening:t,resolved:e}of k){const s=S.get(t.id),o=x.some(t=>t>s.lo+h&&tpm(t,s,h)),r=new Set(a.filter(t=>t.safe).map(t=>t.signature));if(!o&&a.length>0&&a.every(t=>t.safe)&&1===r.size&&Rp(e,b,h)){T.set(t.id,{resolved:e,signature:[...r][0]});continue}const l=xp(i,n.cellCm,n.gridPitch),c={lo:s.lo-l,hi:s.hi+l};for(const t of P)pm(t,c,h)&&(t.safe=!1,t.signature="")}let R=!0;for(;R;){R=!1;for(const[t,e]of[...T.entries()]){const s=S.get(t),o=P.filter(t=>pm(t,s,h));if(o.length>0&&o.every(t=>t.safe)&&o.every(t=>t.signature===e.signature))continue;T.delete(t);const a=xp(i,n.cellCm,n.gridPitch),r={lo:s.lo-a,hi:s.hi+a};for(const t of P)pm(t,r,h)&&(t.safe=!1,t.signature="");R=!0}}const I=ym(P,h),A=I.filter(t=>t.safe),z=I.filter(t=>!t.safe);if(!A.length)continue;if(p.length-1+z.length>2e3)continue;let F=d;for(const t of A){const[e,s]=lm(i.a,i.b)<=0?[t.a,t.b]:[t.b,t.a];F=Fl(F,e,s,t.finalCm,n.pitch,n.coordScale)}if(F=uc(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),F.length>500)continue;const E=new Set(p.map(t=>t.id));E.delete(i.id);const N=z.map((t,e)=>{const s=[t.a[0]/n.coordScale,t.a[1]/n.coordScale],o=[t.b[0]/n.coordScale,t.b[1]/n.coordScale],a=0===e?i.id:vm(i.id,s,o,E);return E.add(a),{id:a,a:s,b:o,cm:i.cm}}),O=p.findIndex(t=>t.id===i.id),L=p.slice();L.splice(O,1,...N);const H=L.map(t=>fm(t,n.coordScale)),B=new Map;let q=!0;for(const{opening:t,resolved:e}of k){const i=T.get(t.id);if(i){const e=Ip(t,i.resolved,n.coordScale),{host:s,...o}=e;B.set(t.id,o);continue}const s=S.get(t.id),o=N[z.findIndex(t=>t.lo<=s.lo+h&&t.hi>=s.hi-h)],a=o&&H.find(t=>t.id===o.id);if(!o||!a){q=!1;break}const r=a.b[0]-a.a[0],l=a.b[1]-a.a[1],c=Math.hypot(r,l),d=hm(e.center,a.a,r/c,l/c),p={...Ip(t,e,n.coordScale),host:{kind:"partition",id:o.id,t:d/c}};if(!Mp(p,H,n.coordScale,n.cellCm,n.gridPitch).resolved){q=!1;break}B.set(t.id,p)}if(!q)continue;const W=u.map(t=>B.get(t.id)||t),j=[...T.keys()].map(t=>B.get(t)),U=j.map(t=>mm(t,H,n));if(U.some(t=>!t))continue;let G=!1;for(let t=0;tt.id));for(const t of W){if(V.has(t.id))continue;const e=mm(t,H,n);e&&U.some(t=>gm(t,e,h))&&(G=!0)}if(G)continue;const K=Ec(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale);[...T.entries()].every(([t,e])=>{const i=B.get(t),s=Lc(K,{x:i.x*n.coordScale,y:i.y*n.coordScale,angle:i.angle,length:i.length*n.coordScale},!0),o=[s.negative,s.positive].filter(t=>!!t?.full),a=e.signature.split("|")[1].split(","),r=new Set(o.map(t=>t.roomId));return o.length===a.length&&r.size===a.length&&a.every(t=>r.has(t))})&&(d=F,p=L,u=W,f+=A.length,v+=T.size)}return{walls:d,partitions:p,openings:u,roomDrafts:g,partitionsReconciled:f,openingsRehosted:v,removedDrafts:m.size}}const wm=t=>JSON.parse(JSON.stringify(t)),km=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),xm=(t,e)=>e.length>0&&e.length<=35&&("space"===t?/^[a-z0-9_-]+$/.test(e):/^[A-Za-z0-9_-]+$/.test(e));function $m(t,e){let i=String(e??"");const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s}_(.+)_([0-9a-f]{8})$`);let o=0;for(;o<16;o++){const t=n.exec(i);if(!t)return{root:i,layers:o,bounded:!1};i=t[1]}return{root:i,layers:o,bounded:n.test(i)}}const Sm=(t,e,i)=>{const s=t.get(e)||[];s.push(i),t.set(e,s)};const Mm=1e-9;class Cm extends Error{constructor(t,e=""){super(e?`${t}: ${e}`:t),this.reason=t,this.name="WallSegmentModelError"}}const Dm=t=>JSON.parse(JSON.stringify(t)),Pm=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1])),Tm=t=>[Number(t[0]),Number(t[1])],Rm=t=>`${Number(t[0]).toFixed(12)},${Number(t[1]).toFixed(12)}`,Im=(t,e)=>{const i=Rm(t),s=Rm(e);return iRm(t)<=Rm(e)?[Tm(t),Tm(e)]:[Tm(e),Tm(t)],zm=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Fm=t=>{const e=[[Number(t.points[0][0]),Number(t.points[0][1])]],i=[];for(let s=1;s{const i=new Set,s=t=>{const e=Number(t);if(!Number.isFinite(e))return;const s=e/Th;Math.abs(s-Math.round(s))>=Ur&&i.add(e.toFixed(12))};for(const e of Array.isArray(t?.rooms)?t.rooms:[])for(const t of hi(e)||[])s(t[0]),s(t[1]);for(const e of[t?.wall_segments,t?.walls])for(const t of Array.isArray(e)?e:[])s(t?.a?.[0]),s(t?.a?.[1]),s(t?.b?.[0]),s(t?.b?.[1]);for(const t of e)s(t?.[0]),s(t?.[1]);return i.size},Nm=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;return o>1e-18?((t[0]-e[0])*s+(t[1]-e[1])*n)/o:0},Om=(t,e,i)=>{const s=Math.max(0,Math.min(1,Nm(t,e,i)));return Math.hypot(t[0]-(e[0]+(i[0]-e[0])*s),t[1]-(e[1]+(i[1]-e[1])*s))},Lm=(t,e,i,s,n=Mm)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(r<=n)return 0;const l=e=>Math.abs((e[0]-t[0])*a-(e[1]-t[1])*o)/r;if(l(i)>n||l(s)>n)return 0;const c=Nm(i,t,e),h=Nm(s,t,e);return Math.max(0,Math.min(1,Math.max(c,h))-Math.max(0,Math.min(c,h)))*r},Hm=t=>{const e=(new TextEncoder).encode(t),i=8*e.length,s=64*Math.ceil((e.length+9)/64),n=new Uint8Array(s);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(s-8,Math.floor(i/4294967296),!1),o.setUint32(s-4,i>>>0,!1);const a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(t,e)=>t>>>e|t<<32-e;for(let t=0;t>>3,n=c(i,17)^c(i,19)^i>>>10;l[t]=l[t-16]+s+l[t-7]+n>>>0}let[e,i,s,n,h,d,p,u]=r;for(let t=0;t<64;t++){const o=u+(c(h,6)^c(h,11)^c(h,25))+(h&d^~h&p)+a[t]+l[t]>>>0,r=e&i^e&s^i&s;u=p,p=d,d=h,h=n+o>>>0,n=s,s=i,i=e,e=o+((c(e,2)^c(e,13)^c(e,22))+r>>>0)>>>0}r[0]=r[0]+e>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+s>>>0,r[3]=r[3]+n>>>0,r[4]=r[4]+h>>>0,r[5]=r[5]+d>>>0,r[6]=r[6]+p>>>0,r[7]=r[7]+u>>>0}const h=new Uint8Array(32),d=new DataView(h.buffer);for(let t=0;t{const e="abcdefghijklmnopqrstuvwxyz234567";let i=0,s=0,n="";for(const o of t)for(s=s<<8|o,i+=8;i>=5;)n+=e[s>>>i-5&31],i-=5;return i&&(n+=e[s<<5-i&31]),n},qm=(t,e,i,s,n="")=>{const[o,a]=Am(e,i),r=`${t}|${Rm(o)}|${Rm(a)}|${[...s].sort().join(",")}${n}`;return`wall-${Bm(Hm(r)).slice(0,20)}`};let Wm=0;const jm=t=>{for(let e=0;e<1e3;e++){const e=globalThis.crypto?.randomUUID?.(),i=`wall-${e||Bm(Hm(`${Date.now()}|${Wm++}|${Math.random()}`)).slice(0,26)}`;if(!t.has(i))return i}throw new Cm("duplicate-id","id factory exhausted")},Um=t=>{const e=new Map;for(const i of Array.isArray(t?.wall_segments)?t.wall_segments:[])if(i&&"string"==typeof i.id&&Pm(i.a)&&Pm(i.b)){if(e.has(i.id))throw new Cm("duplicate-id",i.id);e.set(i.id,i)}return e},Gm=(t,e,i)=>{const s=(i,s)=>{const n=t[0]-i[0],o=t[1]-i[1];return Math.abs(e[0]-s[0]-n)<=Mm&&Math.abs(e[1]-s[1]-o)<=Mm?[n,o]:null};return s(i.a,i.b)||s(i.b,i.a)},Vm=(t,e)=>{const i=Array.isArray(t.rooms)?t.rooms:[],s=ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]),n=s.length?s:_d(i,null,1,.04*Th,!0),o=[];for(const t of i){const i=hi(t),s=Array.isArray(t?.wall_ids)?t.wall_ids:[];if(i&&s.length===i.length)for(let t=0;t"partition"!==t.host?.kind&&[Number(t.x),Number(t.y)].every(Number.isFinite)&&Number.isFinite(Number(t.angle))&&Number(t.length)>0&&n.some(e=>Om([Number(t.x),Number(t.y)],[e[0],e[1]],[e[2],e[3]])<=.04*Th)):[],l=r.map(t=>{const e=Number(t.angle)*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Number(t.length)/2,n=[Number(t.x),Number(t.y)];return{a:[n[0]-i[0]*s,n[1]-i[1]*s],b:[n[0]+i[0]*s,n[1]+i[1]*s]}}),c=(t,e)=>r.some(i=>{const s=[Number(i.x),Number(i.y)];if(!Rl(t,e,Number(i.angle)))return!1;if(Om(s,t,e)>.02*Th)return!1;const n=zm(t,e),o=Nm(s,t,e)*n,a=Number(i.length)/2;return o+a>=-Mm&&o-a<=n+Mm}),h=new Map,d=[];for(const s of i){const r=String(s?.id||""),p=hi(s);if(!r||!p||p.length<3)throw new Cm("invalid-room",r);const u=ec(i,r,a,Th,1,[...t.walls||[],...l]);if(!u||u.poly.length<3)throw new Cm("invalid-room",r);const _=Array.isArray(s.wall_ids)?s.wall_ids:[],m=_.length===p.length;let g=null,f=m;if(f)for(let t=0;tMm||Math.abs(s[1]-g[1])>Mm)){f=!1;break}g=s}const v=[];for(let t=0;t2)throw new Cm("third-owner",a);const d=m?_[u.parent[t]]:void 0;if("string"==typeof d&&d){const n=e.get(d);f||!n||Lm(i,s,n.a,n.b)>Mm?l.preferredIds.add(d):l.positionalIds.add(d),l.preferredCarriers.set(d,{a:Tm(p[u.parent[t]]),b:Tm(p[(u.parent[t]+1)%p.length])})}const g=u.parent[t];l.parentKeys.add(wl(p[g],p[(g+1)%p.length],Th));const y=[(i[0]+s[0])/2,(i[1]+s[1])/2],b=t=>t.some(t=>Om(y,[t[0],t[1]],[t[2],t[3]])<=.04*Th);l.zeroWall||=b(o)||b(n)&&!c(i,s),v.push(a)}const y={...s};delete y.wall_ids,d.push({...y,poly:u.poly.map(t=>[t[0],t[1]]),wall_ids:v})}return{atoms:[...h.values()].sort((t,e)=>t.key.localeCompare(e.key)),rooms:d}},Km=(t,e,i,s,n)=>{const o=new Map([...i.values()].map(t=>[Im(t.a,t.b),t])),a=(t=>{const e=new Map;for(const i of t)"wall"===i.host?.kind&&e.set(i.host.id,(e.get(i.host.id)||0)+1);return e})(t.openings||[]),r=new Map;for(const t of e){const e=n?.get(t.key);if(e){const s=i.get(e);if(!s)throw new Cm("duplicate-id",e);r.set(t,s);continue}if(t.preferredIds.size>1)throw new Cm("duplicate-id",[...t.preferredIds].sort().join(","));const s=[...t.preferredIds][0],l=s?i.get(s):void 0;if(l){r.set(t,l);continue}const c=s?t.preferredCarriers.get(s):void 0;if(s&&c){r.set(t,{id:s,a:c.a,b:c.b,cm:0});continue}const h=o.get(t.key);if(h){r.set(t,h);continue}const d=[...i.values()].filter(e=>Lm(t.a,t.b,e.a,e.b)>Mm),p=[...new Map(d.map(t=>[t.id,t])).values()];if(p.sort((t,e)=>(a.get(e.id)||0)-(a.get(t.id)||0)||zm(e.a,e.b)-zm(t.a,t.b)||t.id.localeCompare(e.id)),p[0])r.set(t,p[0]);else if(1===t.positionalIds.size){const e=i.get([...t.positionalIds][0]);e&&r.set(t,e)}}const l=new Map;for(const[t,e]of r){const i=l.get(e.id)||[];i.push(t),l.set(e.id,i)}for(const[t,e]of l){const s=i.get(t)||r.get(e[0]);if(!s)throw new Cm("duplicate-id",t);const n=[(s.a[0]+s.b[0])/2,(s.a[1]+s.b[1])/2];e.sort((t,e)=>{const i=Om(n,t.a,t.b)<=Mm?0:1,o=Om(n,e.a,e.b)<=Mm?0:1;if(i!==o)return i-o;return(Om(s.a,t.a,t.b)<=Mm?0:1)-(Om(s.a,e.a,e.b)<=Mm?0:1)||t.key.localeCompare(e.key)}),e[0].id=t}const c=(t=>{const e=new Set;for(const i of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns])for(const t of Array.isArray(i)?i:[])"string"==typeof t?.id&&t.id&&e.add(t.id);for(const i of Array.isArray(t.room_drafts)?t.room_drafts:[])for(const t of Array.isArray(i?.segments)?i.segments:[])"string"==typeof t?.id&&t.id&&e.add(t.id);return e})(t);for(const t of e)if(t.id){if(c.has(t.id))throw new Cm("duplicate-id",t.id);c.add(t.id)}const h=e.filter(t=>!t.id);if(s){const e=h.map(e=>{const[i,s]=Am(e.a,e.b),n=`${String(t.id||"")}|${Rm(i)}|${Rm(s)}|${[...e.owners].sort().join(",")}`,o=Bm(Hm(n));return{atom:e,seed:n,digest:o,base:`wall-${o.slice(0,20)}`}}).sort((t,e)=>t.digest.localeCompare(e.digest)||t.atom.key.localeCompare(e.atom.key)),i=new Map;for(const t of e){const e=i.get(t.digest);if(e&&e!==t.seed)throw new Cm("duplicate-id",t.digest);i.set(t.digest,t.seed);let s=1,n=t.base;for(;c.has(n);)n=`${t.base}-${++s}`;t.atom.id=n,c.add(n)}}else for(const t of h)t.id=jm(c),c.add(t.id)},Ym=(t,e)=>{if("partition"===t.host?.kind)return null;const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=e=>{if(!(Number(e.cm)>0))return!1;const s=Nm(i,e.a,e.b),n=zm(e.a,e.b),o=Number(t.length)/2;return s>=-Mm&&s<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(o)&&o>=0&&s*n-o>=-Mm&&s*n+o<=n+Mm},n="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null,o=n&&s(n)?[n]:e.filter(s);if(1!==o.length)return null;const a=o[0];return{kind:"wall",id:a.id,t:Math.max(0,Math.min(1,Nm(i,a.a,a.b)))}},Jm=(t,e)=>{const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=Number(t.length)/2,n=e.filter(e=>{if(!(Number(e.cm)>0))return!1;const n=Nm(i,e.a,e.b),o=zm(e.a,e.b);return n>=-Mm&&n<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(s)&&s>=0&&n*o-s>=-Mm&&n*o+s<=o+Mm}),o=(e=>{if(!e.length)return null;const s="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null;return s||[...e].sort((t,e)=>Om(i,t.a,t.b)-Om(i,e.a,e.b)||Number(e.cm)-Number(t.cm)||(t.ide.id?1:0))[0]})(n);return o?{kind:"wall",id:o.id,t:Math.max(0,Math.min(1,Nm(i,o.a,o.b)))}:null},Xm=(t,e,i)=>{const s=Um(t),{atoms:n,rooms:o}=Vm(t,s);Km(t,n,s,e,i);const a=n.map(e=>{const i=e.id?s.get(e.id):void 0,n=((t,e,i)=>{if(e.zeroWall)return 0;const s=Array.isArray(t.walls)?t.walls:[],n=wl(e.a,e.b,Th),o=s.filter(t=>Number(t.cm)>0&&(!(t.key!==n&&!e.parentKeys.has(t.key))||!(!Pm(t.a)||!Pm(t.b))&&Lm(e.a,e.b,t.a,t.b)>=zm(e.a,e.b)-Mm)).map(t=>Math.max(1,Math.min(100,Number(t.cm))));if(new Set(o.map(t=>t.toFixed(9))).size>1)throw new Cm("thickness-conflict",e.key);if(o.length)return o[0];const a=Pl(s,e.a,e.b,Th,1);return a>0?a:Number(i?.cm)>0?Number(i.cm):0})(t,e,i);return{...i||{},id:e.id,a:[...e.a],b:[...e.b],cm:n}}),r=new Map(n.map(t=>[t.key,t.id]));for(const t of o)t.wall_ids=t.wall_ids.map(t=>r.get(t));t.rooms=o,t.wall_segments=a,t.walls=a.filter(t=>t.cm>0).map(t=>({key:wl(t.a,t.b,Th),cm:t.cm,a:[...t.a],b:[...t.b]})),t.walls.length||delete t.walls,delete t.open_spans;for(const e of t.rooms)delete e.open_to;return((t,e)=>{const i=new Set;for(const e of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns,t.wall_segments])for(const t of Array.isArray(e)?e:[])"string"==typeof t?.id&&t.id&&i.add(t.id);for(const s of Array.isArray(t.room_drafts)?t.room_drafts:[]){const n=Array.isArray(s.segments)?s.segments:[];for(let o=0;o{const s=Array.isArray(t.openings)?t.openings:[];for(const t of s){if("partition"===t.host?.kind)continue;if(!t.host&&!i){const i=Ym(t,e);i&&(t.host=i);continue}const s=Ym(t,e)??(i?Jm(t,e):null);if(s)t.host=s;else{if(!i)throw new Cm("opening-host",t.id);delete t.host}}})(t,a,e),a.reduce((t,e)=>t+(s.has(e.id)?0:1),0)};function Zm(t,e={}){const i=JSON.stringify(t),s=Dm(t);rl(s);let n=0;const o=Number(s?.model_version||0)<9;for(const t of Array.isArray(s?.spaces)?s.spaces:[]){const i=e.lineageSpaceId===String(t?.id||"")?e.lineageHints:void 0;n+=Xm(t,o,i)}return s.model_version=9,rl(s),{config:s,changed:i!==JSON.stringify(s),migratedSegments:n}}const Qm=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tg(t,e){const i=(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){const s=new Map;for(const e of t)Qm(e)&&"string"==typeof e.id&&e.id&&s.set(e.id,e);const n=e.map((e,n)=>{if(Qm(e)&&"string"==typeof e.id&&e.id){const t=s.get(e.id);return t?i(t,e):Dm(e)}return n[e,e in t?i(t[e],s):Dm(s)]);for(const e of Object.keys(t))delete t[e];for(const[e,i]of s)t[e]=i;return t}return Dm(e)};return i(t,e)}const eg=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ig=(t,e,i)=>Math.min(i,Math.max(e,t)),sg=t=>Sh({spaces:[t]})[0],ng=(t,e,i)=>{const s=i>0?i:1,n=t=>`${(t[0]/s).toFixed(12)},${(t[1]/s).toFixed(12)}`,o=n(t),a=n(e);return o0?a:1,l=Math.max(s*r*.02,1e-9),c=[];for(const e of t||[])for(const t of hi(e)||[])c.push([t[0],t[1]]);const h=[];for(const t of i||[])Array.isArray(t)&&t.length>=4&&t.slice(0,4).every(Number.isFinite)&&h.push([t[0],t[1]],[t[2],t[3]]);const d=(t,e)=>e.some(e=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l),p=new Map;for(const a of t||[]){if(!a?.id)continue;const u=hc(t,a.id,e,i,s,n,o,r);if(u)for(let t=0;t0&&_>0&&a===m&&_!==a))continue;const g=u.poly[s],f=u.poly[(s+1)%u.poly.length],v=Math.hypot(f[0]-g[0],f[1]-g[1]);if(!(v>l&&v<.5*o-1e-9*o))continue;if(d(g,h)||d(f,h))continue;if(d(g,c)&&d(f,c))continue;const y=ng(g,f,r),b=p.get(y);b?b.targets.add(a):p.set(y,{a:[g[0],g[1]],b:[f[0],f[1]],targets:new Set([a])})}}}let u=e.slice();const _=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l,m=(t,e)=>{if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return!1;const i=[Number(t.a[0])*r,Number(t.a[1])*r],s=[Number(t.b[0])*r,Number(t.b[1])*r];return!![...i,...s].every(Number.isFinite)&&(_(i,e.a)&&_(s,e.b)||_(i,e.b)&&_(s,e.a))};for(const t of[...p.values()].filter(t=>1===t.targets.size).sort((t,e)=>ng(t.a,t.b,r).localeCompare(ng(e.a,e.b,r)))){const e=[...t.targets][0],i=u.filter(e=>m(e,t));if(new Set(i.map(t=>t.cm)).size>1)continue;let n=!1;u=u.map(i=>m(i,t)?(n=!0,i.cm===e?i:{...i,cm:e}):i),n||(u=Fl(u,t.a,t.b,e,s,r))}return u}const ag=t=>{const e=[];for(const i of t||[]){const t=hi(i);if(t?.length)for(let i=0;i"string"==typeof t?.id?t.id:"").filter(Boolean),h=new Set(c),d=new Map;for(const t of c){const e=$m("space",t);e.layers>0&&xm("space",e.root)&&Sm(d,e.root,t)}const p=new Map,u=new Map,_=new Map,m=new Map;for(const t of r){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i=new Map;for(const s of Array.isArray(t.rooms)?t.rooms:[]){const t="string"==typeof s?.id?s.id:"";if(!t)continue;const n=$m("room",t);n.layers>0&&xm("room",n.root)&&Sm(i,n.root,t),u.has(t)||u.set(t,e),_.has(t)||_.set(t,String(s.name||""));const o="string"==typeof s.area?s.area:"";if(o){const i=m.get(o)||[];i.push({spaceId:e,roomId:t}),m.set(o,i)}}p.set(e,i)}const g=new Set(u.keys()),f=new Map,v=new Map;for(const t of l)"string"==typeof t?.id&&t.id&&(!0===t.removed?v.set(t.id,t):f.set(t.id,t));const y={spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,positionsUnresolved:0,nestedRefsUnresolved:0,deadSpaceIds:[],orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0,removedPositions:[],liveMissingPositions:[],unverifiedPositions:[]},b=new Set,w=t=>h.has(t)?null:(()=>{const e=$m("space",t).root;if(!xm("space",e))return null;const i=d.get(e)||[];return 1===i.length?i[0]:null})(),k=(t,e)=>{const i=$m("room",t).root;if(!xm("room",i))return null;const s=p.get(e)?.get(i)||[];return 1===s.length?s[0]:null},x=t=>{const e=i.effectiveAreaByMarker?.[t]||"",s=e&&m.get(e)||[];return 1===s.length?s[0]:null},$=(t,e,i)=>{if("string"==typeof t.room_id&&t.room_id&&!g.has(t.room_id)){const s=e?k(t.room_id,e):null;s?(t.room_id=s,y.roomRefsRemapped++):i?(t.room_id=i.roomId,y.roomRefsRemapped++):!0!==t.removed&&delete t.room_id}const s=t.vacuum?.segment_map;if(s&&"object"==typeof s&&!Array.isArray(s))for(const t of Object.keys(s)){const i=s[t];if("string"!=typeof i||!i||g.has(i))continue;const n=e?k(i,e):null;n?(s[t]=n,y.roomRefsRemapped++):y.nestedRefsUnresolved++}};for(const t of l){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i="string"==typeof t.space?t.space:"",s=i&&!h.has(i),o=n[e],a="string"==typeof o?.s?o.s:"",r=a&&!h.has(a),l=!0===t.removed;let c=i&&h.has(i)?i:null,d=null,p=!1;if(s){const s=w(i);s?(t.space=s,c=s,p=!0,y.spaceRefsRemapped++):l||"virtual"===t.binding?l||(delete t.space,c=null,y.markersDetached++):(d=x(e),d?(t.space=d.spaceId,c=d.spaceId,y.spaceRefsRemapped++):(delete t.space,c=null,y.markersDetached++))}l&&!p||$(t,c,d),r&&p&&a===i&&c&&(n[e]={...o,s:c},y.positionsRemapped++,b.add(e))}for(const t of Object.keys(n)){if(b.has(t))continue;const e=n[t],i="string"==typeof e?.s?e.s:"";if(!i||h.has(i))continue;const s=w(i);if(s){if(t.startsWith("rl_")){const i=t.slice(3),o=k(i,s);if(o){const i=`rl_${o}`;km(n,i)||(n[i]={...e,s:s}),delete n[t],y.roomRefsRemapped++,y.positionsRemapped++;continue}}n[t]={...e,s:s},y.positionsRemapped++}}const S=i.ownerRoster,M=!0===S?.authoritative,C=new Set(S?.deviceIds||[]),D=new Set(S?.entityIds||[]),P=new Set(Array.isArray(s.settings?.known_devices)?s.settings.known_devices.filter(t=>"string"==typeof t):[]),T=(t,e="")=>{const i=String(S?.names?.[t]||e||"").trim();return i&&i!==t?i:""},R=(t,e,i,s="",n)=>({id:t,spaceId:e,kind:i,name:T(t,s),...n?{reason:n}:{}}),I=t=>{"room_label"===t?y.orphanRoomLabelsRemoved++:"group"===t?y.orphanGroupPositionsRemoved++:y.orphanDevicePositionsRemoved++},A=new Set;for(const[t,e]of Object.entries(n)){const s="string"==typeof e?.s?e.s:"";if(!s||h.has(s))continue;let o,a;const r=f.get(t),l=v.get(t);if(r)o=R(t,s,"device",String(r.name||"")),a="live";else if(l)o=R(t,s,"device",String(l.name||"")),a="absent";else if(t.startsWith("rl_")){const e=t.slice(3);o=R(t,s,"room_label",_.get(e)||""),a=g.has(e)?"live":"absent"}else if(t.startsWith("lg_")){const e=t.slice(3);o=R(t,s,"group"),a=D.has(e)?"live":M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")}else C.has(t)?(o=R(t,s,"device"),a="live"):P.has(t)?(o=R(t,s,"device"),a=M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")):(o=R(t,s,"unknown","","unknown_owner"),a="unverified");if("absent"!==a){if("live"===a){if(y.liveMissingPositions.push(o),!0===i.removeLiveMissingPositions){delete n[t],y.liveMissingPositionsRemoved++,I(o.kind),y.removedPositions.push(o);continue}}else y.unverifiedPositions.push(o);y.positionsUnresolved++,A.add(s)}else delete n[t],I(o.kind),y.removedPositions.push(o)}return y.deadSpaceIds=[...A].sort((t,e)=>t.localeCompare(e)),{config:s,layout:n,report:y,changed:JSON.stringify(s)!==o||JSON.stringify(n)!==a}}(t,e,i),a=o.config,r=nl(a,o.layout);rl(a),al(o.layout);const l=JSON.stringify(t||{}),c=JSON.stringify(e||{}),h=Number.isInteger(Number(a.model_version))?Number(a.model_version):0,d=(t=>{let e=0,i=0,s=0;for(const i of t.markers||[]){if("ripple"===i.display&&(i.display="icon_ripple",e++),Array.isArray(i.controls)){const t="string"==typeof i.binding&&i.binding.startsWith("entity:")?i.binding.slice(7):"",s=t?i.controls.filter(e=>e!==t):i.controls;JSON.stringify(s)!==JSON.stringify(i.controls)&&(i.controls=s.length?s:null,e++)}const t=i.vacuum;t&&eg(t,"trail")&&(["never","cleaning","always"].includes(t.trail_mode)||(t.trail_mode=!1===t.trail?"never":"cleaning"),delete t.trail,e++)}for(const n of t.spaces||[]){const t=n.settings;"glow"===t?.fill_mode&&("boolean"!=typeof t.glow_enabled&&(t.glow_enabled=!0),t.fill_mode="none",e++,i++);for(const t of n.rooms||[]){const i=t.settings;"glow"===i?.fill_mode&&("boolean"!=typeof i.glow&&(i.glow=!0),delete i.fill_mode,e++,s++)}if(eg(n,"segments")&&(delete n.segments,e++),eg(n,"plan_scale")){const t=Number(n.plan_scale);Number.isFinite(t)&&t>=wh&&t<=kh&&(eg(n,"plan_scale_x")||(n.plan_scale_x=t),eg(n,"plan_scale_y")||(n.plan_scale_y=t),delete n.plan_scale,e++)}const o=Number(n.cell_cm);eg(n,"cell_cm")&&(!Number.isFinite(o)||o<.1||o>1e3)&&(n.cell_cm=Number.isFinite(o)&&o>0?ig(o,.1,1e3):5,e++);const a=Number(n.cell_cm),r=Number.isFinite(a)&&a>0?a:5;for(const t of n.wall_columns||[])if("circle"===t.shape)eg(t,"angle")&&(delete t.angle,e++);else if("square"===t.shape&&eg(t,"angle")){const i=((Number(t.angle)||0)%90+90)%90;t.angle!==i&&(t.angle=i,e++)}for(const t of n.decor||[]){if(eg(t,"width")){const i=Number(t.width);(eg(t,"width_cm")||Number.isFinite(i))&&(eg(t,"width_cm")||(t.width_cm=Number(ig(i/Ph*r,.1,100).toFixed(6))),delete t.width,e++)}if("rect"!==t?.kind&&"ellipse"!==t?.kind||!0!==t.fill||(eg(t,"fill_color")||(t.fill_color=t.color||"#607d8b",e++),eg(t,"fill_opacity")||(t.fill_opacity=.25,e++)),"text"!==t?.kind)continue;void 0===t.size_cm?(t.size_cm=Number(ig(es*is(t)/Ph*r,.1,2e3).toFixed(6)),delete t.scale,delete t.size,e++):(eg(t,"scale")||eg(t,"size"))&&(delete t.scale,delete t.size,e++);let i=String(t.text??"");const s=[...i.matchAll(/\{([^{}\r\n]+)\}/g)].some(t=>!!Yi(t[1]));if(!(eg(t,"entity")||eg(t,"attr")||eg(t,"unit")))continue;const n=String(t.unit??"").trim(),o="state"===String(t.attr??"").trim().toLowerCase()?null:t.attr,a=s||n?"":Ji(t.entity,o);if(s||a){if(a){const e=i.indexOf("{}");i=e>=0?i.slice(0,e)+a+i.slice(e+2):`${i}${i?" ":""}${a}`,t.text=i}delete t.entity,delete t.attr,delete t.unit,e++}}}return{total:e,glowSpaces:i,glowRooms:s}})(a);let p=d.total;const u=(_=a.spaces||[],JSON.parse(JSON.stringify(_)));var _;const m=X_(a.spaces||[],o.layout);let g=0,f=0,v=0,y="";const b=m.spaces.map(t=>{const e=function(t){const e=JSON.parse(JSON.stringify(t||{}));let i=Array.isArray(e.rooms)?e.rooms:[];const s=new Map;for(const t of i){const e=hi(t);if(e)for(let t=0;tt.key.localeCompare(e.key))){let e=null;for(const s of $a(t,i)){const t=r.get(_a(s.from));if(t&&t!==_a(s.to))continue;const n=wa(i,s);if(ka(i,n,s)){e=s,i=n;break}}e?(r.set(_a(e.from),_a(e.to)),n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}e.rooms=i;for(const t of e.room_drafts||[]){if(!Array.isArray(t?.points)||t.points.length<2)continue;const e=t.points.map(t=>[...t]),i=e.slice(0,-1).flatMap((i,s)=>{const n=e[s+1],o=pa(i,n);return o?[{key:`${String(t.id||"")}:${s}`,a:[...i],b:[...n],axis:o.axis}]:[]});let s=e;for(const t of i){let e=null;for(const i of $a(t,[{poly:s}])){const t=s.map(t=>ba(t,i)),n=t.length>=4&&ma(t[0],t[t.length-1]),o=n?t.slice(0,-1):t;if(n?va(o):ya(o)){e=i,s=t;break}}e?(n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}t.points=s}for(const t of e.partitions||[]){if(!Array.isArray(t?.a)||!Array.isArray(t?.b))continue;const i=pa(t.a,t.b);if(!i)continue;const s={key:String(t.id||ga(t.a,t.b)),a:[...t.a],b:[...t.b],axis:i.axis};let r=null;for(const i of $a(s,[{poly:[t.a,t.b]}])){const s=ba(t.a,i),n=ba(t.b,i),o=Math.hypot(n[0]-s[0],n[1]-s[1]);if(!(o>0))continue;const a=(e.openings||[]).filter(e=>"partition"===e?.host?.kind&&e.host.id===t.id).every(t=>{const e=Number(t.host.t),i=Number(t.length);return Number.isFinite(e)&&e>=0&&e<=1&&Number.isFinite(i)&&i>0&&e*o-i/2>=-1e-12&&e*o+i/2<=o+1e-12});if(a){r=i,t.a=s,t.b=n;break}}r?(n++,a=Math.max(a,Math.hypot(r.to[0]-r.from[0],r.to[1]-r.from[1]))):o++}return{space:e,report:{wallsStraightened:n,wallsStraightenSkipped:o,maxStraightenShift:a},changed:n>0}}(t);g+=e.report.wallsStraightened,f+=e.report.wallsStraightenSkipped;const i=Number(t?.cell_cm)>0?Number(t.cell_cm):5,s=e.report.maxStraightenShift/Th*i;return s>v&&(v=s,y=String(t?.id||"")),e.space}),w=g?X_(b,m.layout):{...m,spaces:b};a.spaces=w.spaces;const k=g?{...m.report,moved:m.report.moved+w.report.moved,coordsCanonicalized:m.report.coordsCanonicalized+w.report.coordsCanonicalized,maxShift:Math.max(m.report.maxShift,w.report.maxShift),maxShiftCm:Math.max(m.report.maxShiftCm,w.report.maxShiftCm),maxSpace:w.report.maxShiftCm>m.report.maxShiftCm?w.report.maxSpace:m.report.maxSpace,rotated:m.report.rotated+w.report.rotated,removedDrafts:m.report.removedDrafts+w.report.removedDrafts}:{...m.report};let x=0,$=0,S=0,M=0,C=0,D=0,P=0,T=0;for(let t=0;t0===Number(t.cm)),walls:e.walls||[]}),o=sg(e),r=sg(i);if(!o||!r)continue;const l=ag(o.rooms),c=ag(r.rooms),h=.02*Ph,d=(e.wall_segments||[]).filter(t=>0===Number(t.cm)).map(t=>({...t,key:wl(t.a,t.b,Th),cm:0})),p=new Set(d.map(t=>t.key)),_=m_(e,o.rooms,yh,h);$+=_.length;for(const t of _){const e=[t[0]/yh,t[1]/yh],i=[t[2]/yh,t[3]/yh],s=wl(e,i,Th);p.has(s)||(p.add(s),d.push({key:s,a:e,b:i,cm:0}))}const m=d.length,g=Al(d,l,c,Th,yh),f=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(!(o>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))},v=g.filter(t=>{if(!Array.isArray(t.a)||!Array.isArray(t.b))return!1;const e=t.a.map(t=>t*yh),i=t.b.map(t=>t*yh);return c.some(([t,s])=>f(e,t,s)<=4*h&&f(i,t,s)<=4*h)});S+=Math.max(0,m-v.length);const y=(i.wall_segments||[]).filter(t=>Number(t.cm)>0);i.wall_segments=[...y,...v.map(({key:t,...e})=>e)];const b=v.map(t=>[t.a[0]*yh,t.a[1]*yh,t.b[0]*yh,t.b[1]*yh]),w=Array.isArray(e.walls)?e.walls.length:0;let k=Al(e.walls,l,c,Th,yh);k=og(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=uc(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=Tl(k,i.rooms||[],Th,1,b.map(t=>[t[0]/yh,t[1]/yh,t[2]/yh,t[3]/yh])),x+=Math.max(0,w-k.length),k.length?i.walls=k:delete i.walls;const R=nm(i.partitions||[],{pitch:Th,geometry:am(i)});R.merged&&(M+=R.merged,i.partitions=R.partitions,om(i.openings,i.partitions,R.openingMoves,{coordScale:yh,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph}));const I=sg(i);if(I){const t=n(i,I,i.walls||[],b,{pitch:Th,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph,coordScale:yh});t.partitionsReconciled&&(C+=t.partitionsReconciled,D+=t.openingsRehosted,t.partitions.length?i.partitions=t.partitions:delete i.partitions,t.openings.length?i.openings=t.openings:delete i.openings,t.walls.length?i.walls=t.walls:delete i.walls),t.removedDrafts&&(P+=t.removedDrafts,t.roomDrafts.length?i.room_drafts=t.roomDrafts:delete i.room_drafts)}JSON.stringify({zero:(i.wall_segments||[]).filter(t=>0===Number(t.cm)),walls:i.walls||[]})!==s&&T++}let R=0;h<=9&&(R=function(t){const e=Zm(t);return tg(t,e.config),{...e,config:t}}(a).migratedSegments);const I=rl(a),A=al(w.layout),z=JSON.stringify(I)!==l||JSON.stringify(A)!==c;h<9&&z&&(I.model_version=9);const F=JSON.stringify(I)!==l||JSON.stringify(A)!==c,E=Number.isInteger(Number(I.model_version))?Number(I.model_version):h,N=F?k:{...k,moved:0,coordsCanonicalized:0,maxShift:0,maxShiftCm:0,maxSpace:"",rotated:0,removedDrafts:0},O=F?o.report:{...o.report,spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0};return{config:I,layout:A,report:{...N,modelFrom:h,modelTo:E,migrated:F?p:0,glowSpacesMigrated:F?d.glowSpaces:0,glowRoomsMigrated:F?d.glowRooms:0,canonicalized:F?T:0,wallSegmentsMigrated:F?R:0,legacyZeroWallsMigrated:F?$:0,wallsMerged:F?x:0,spansMerged:F?S:0,partitionsMerged:F?M:0,partitionsReconciled:F?C:0,openingsRehosted:F?D:0,redundantDraftsRemoved:F?P:0,wallsStraightened:F?g:0,wallsStraightenSkipped:f,maxStraightenShiftCm:F?v:0,maxStraightenSpace:F?y:"",latticeCoordinatesCanonicalized:F?r.canonicalized:0,latticeCoordinatesFar:F?r.far:0,latticeMaxShift:F?r.maxShift:0,latticeMaxShiftCm:F?r.maxShiftCm:0,latticeSpaces:F?r.spaces:[],...O},changed:F}}function lg(t,e,i){const s=(t?.spaces||[]).find(t=>t?.id===i),n=new Set((s?.rooms||[]).map(t=>String(t?.id||"")).filter(Boolean)),o=[...new Set((t?.markers||[]).filter(t=>!0!==t?.removed&&"string"==typeof t?.id).filter(t=>t.space===i||"string"==typeof t.room_id&&n.has(t.room_id)||e?.[t.id]?.s===i).map(t=>t.id))].sort((t,e)=>t.localeCompare(e));return{markerIds:o,count:o.length}}function cg(t){return t instanceof Error?t.name||"Error":typeof t}function hg(t){return wd({id:t?.id??"",cell_cm:t?.cell_cm,rooms:t?.rooms||[],walls:t?.walls||[],wall_segments:t?.wall_segments||[],open_spans:t?.open_spans||[],openings:t?.openings||[],partitions:t?.partitions||[],room_drafts:t?.room_drafts||[],wall_columns:t?.wall_columns||[]})}function dg(t,e,i,s=Ph,n=1e3){return(Array.isArray(t?.openings)?t.openings:[]).flatMap(t=>{const o={...t,rx:Number(t.x)*n,ry:Number(t.y)*n,rlen:Number(t.length)*n};if(!t.host||"wall"===t.host.kind)return[o];const a=Sp(t,e.partitions,n,i,s);return a.resolved?[{...t,rx:a.resolved.center[0],ry:a.resolved.center[1],rlen:a.resolved.length,angle:a.resolved.angle,partitionHost:a.resolved}]:[]})}function pg(t,e=()=>!0){return t.flatMap(t=>t.host&&t.partitionHost&&e(t)?[Dp(t.partitionHost)]:[])}function ug(t,e,i,s,n,o,a=Ph,r=1e3){const l=dc(e.rooms,[...i],s,n,o,a,r);return t.flatMap(t=>{const e={x:t.rx,y:t.ry,angle:Number(t.angle)||0,length:t.rlen};return t.host&&"wall"!==t.host.kind?t.partitionHost&&Rp(t.partitionHost,l,2e-4*a)?[e]:[]:[e]})}function _g(t,e){const i=Th,s=Ph,n=yh,o=Number.isFinite(Number(e.cellCm))&&Number(e.cellCm)>0?Number(e.cellCm):5,a=Array.isArray(t?.walls)?t.walls:[],r=function(t,e,i=Ph,s=1e3){return _d(e.rooms,t?.open_spans,s,.02*i)}(t,e,s,n),l=function(t,e,i=Ph){if(!e.length)return[];const s=t.filter(t=>t?.id),n=.02*i,o=[];for(let t=0;t{const e=[(t[0]+t[2])/2,(t[1]+t[3])/2];return h.some(t=>Ls(e,t)<4*n)}).map(t=>[...t]);d.length&&o.push({a:a,b:r,segs:d})}return o}(e.rooms,r,s).flatMap(t=>t.segs),c=dg(t,e,o,s,n),h=pg(c),d=ih(e,o,s,2e-4*s,h).all;return{space:e,walls:a,openCuts:l,openings:c,roomOpenings:ug(c,e,a,l,i,o,s,n),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:s,coordScale:n}}function mg(t,e,i){const s="string"==typeof t?.title?t.title.trim():"",n=null==t?.id?"":String(t.id).trim();return{spaceId:n,displayName:s||n||i(e+1)}}function gg(t,e={}){const i=(e.fingerprint||wd)(t),s=Array.isArray(t?.spaces)?t.spaces:[],n=e.fallbackSpaceName||(t=>`Space ${t}`),o=e.prepareSpace||_g,a=e.wallPass||Rc,r=e.floorPass||Pc,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!p){l.push({...h,status:"not-applicable"});continue}let u=null;if(p){try{u=a(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(t){l.push({...h,status:"failed",reason:"wall-exception",detail:cg(t)});continue}if(null==u){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===u.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===u.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}e.captureWallGeometry?.(d,u)}if(d.space.rooms.length&&null==u?.paperGeom){let t;try{t=r(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(t){l.push({...h,status:"failed",reason:"floor-exception",detail:cg(t)});continue}if(null==t){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(t=>"failed"===t.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}class fg{constructor(t=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(t))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(t){this._undo.push(t),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const t=this._undo.pop()??null;return t&&this._redo.push(t),t}redo(){const t=this._redo.pop()??null;return t&&this._undo.push(t),t}clear(){this._undo=[],this._redo=[]}}const vg=new WeakMap;const yg=(t,e,i)=>255===t[i+3]&&e.every((e,s)=>Math.abs(t[i+s]-e)<=2);async function bg(t){const e=t.defaultView;if(!e||!e.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],s=[16,64,128],n=[9,19,29],o=`\n \n \n \n \n \n `,a=e.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((t,i)=>{const s=new e.Image,n=e.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);s.onload=()=>{e.clearTimeout(n),t(s)},s.onerror=()=>{e.clearTimeout(n),i(new Error("SVG blend probe failed"))},s.src=a}),r=t.createElement("canvas");r.width=4,r.height=1;const l=r.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return yg(c,i,0)&&yg(c,function(t,e){return[0,1,2].map(i=>Math.round(255-(255-t[i])*(255-e[i])/255))}(i,s),4)&&yg(c,s,8)&&yg(c,n,12)}catch{return!1}finally{e.URL.revokeObjectURL(a)}}const wg={now:()=>performance.now(),requestFrame:t=>requestAnimationFrame(t),cancelFrame:t=>cancelAnimationFrame(t)},kg=t=>Math.max(0,Math.min(1,t)),xg=(t,e,i)=>t+(e-t)*i,$g=(t,e,i)=>{const s=1-t;return 3*s*s*t*e+3*s*t*t*i+t*t*t};function Sg(t,e){return{centerX:t.x+t.w/2,centerY:t.y+t.h/2,pixelsPerUnit:e>0&&t.w>0?e/t.w:1,viewBox:{...t}}}function Mg(t,e,i){const s=Math.max(1e-9,t.pixelsPerUnit),n=Math.max(1e-9,e/s),o=Math.max(1e-9,i/s);return{x:t.centerX-n/2,y:t.centerY-o/2,w:n,h:o}}function Cg(t){const e=t.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(e);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const s=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(e)?.[1];return s?[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16),8===s.length?parseInt(s.slice(6,8),16)/255:1]:null}function Dg(t,e,i){const s=Cg(t),n=Cg(e);if(!s||!n)return i<.5?t:e;const o=kg(i);return`rgba(${Math.round(xg(s[0],n[0],o))}, ${Math.round(xg(s[1],n[1],o))}, ${Math.round(xg(s[2],n[2],o))}, ${xg(s[3],n[3],o).toFixed(3)})`}function Pg(t,e,i){const s=(t=>{const e=kg(t);if(0===e||1===e)return e;let i=0,s=1,n=e;for(let t=0;t<12;t++)n=(i+s)/2,$g(n,.2,.2){const e=this._state;if(!e||e.token!==n)return;const i=kg((t-e.startedAt)/e.duration);e.presented=i>=1?e.to:Pg(e.from,e.to,i),e.phase=i>=1?"settling":"running",this._hooks.frame(e),i<1?this._raf=this._clock.requestFrame(a):(this._raf=0,this._hooks.settled(e),this._state?.token===n&&(this._state=null))};return this._raf=this._clock.requestFrame(a),n}cancel(t=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const e=this._state;this._state=null,this._token++,e&&t&&(e.phase="settling",e.presented=e.to,this._hooks.frame(e),this._hooks.settled(e))}dispose(){this.cancel(!1)}}const Rg="houseplan_card_labs_v1",Ig=Object.freeze([Object.freeze({id:"iso",issue:89,since:"1.62.0",expires:"1.65.0",summary:"Volumetric plan renderer"})]);function Ag(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(String(t||"").trim());if(!e)return null;const i=e.slice(1).map(Number);return i.every(t=>Number.isSafeInteger(t))?i:null}function zg(t,e){for(let i=0;i<3;i++)if(t[i]!==e[i])return t[i]t.split(",")).map(t=>t.trim()).filter(Boolean)}function Hg(t,e,i,s=Ig){const n=function(t,e=Ig){const i=Ag(t),s=new Map;if(!i||!Eg(e))return s;for(const t of e){const e=Ag(t.since),n=Ag(t.expires);zg(i,e)>=0&&zg(i,n)<0&&s.set(t.id,t)}return s}(i,s),o=new Set(Eg(s)?s.map(t=>t.id):[]),a=new Set(function(t){if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}catch{return[]}}(e).filter(t=>n.has(t)));let r=!1;const l=t=>{if("off"===t)return a.clear(),void(r=!0);const e=t.startsWith("-"),i=e?t.slice(1):t;o.has(i)&&(r=!0,e||!n.has(i)?a.delete(i):a.add(i))};for(const e of Lg(new URLSearchParams(String(t.search||"").replace(/^\?/,""))))l(e);for(const e of Lg(Ng(t.hash)))l(e);const c=Object.freeze([...a].sort());return{active:c,space:Og(t.hash),persist:r?JSON.stringify(c):void 0,knownUrlOperation:r}}let Bg={active:Object.freeze([]),space:""},qg="",Wg=!1,jg="";const Ug=new Set;function Gg(){if("undefined"==typeof window)return Bg;const t=Hg(window.location,function(){try{return window.localStorage.getItem(Rg)}catch{return null}}(),qg);void 0!==t.persist&&function(t){try{window.localStorage.setItem(Rg,t)}catch{}}(t.persist),Bg={active:t.active,space:t.space},window.__hpLabs=t.active;for(const t of Ug)t(Bg);return Bg}function Vg(){Gg()}function Kg(t){return qg=t,"undefined"==typeof window?Bg:(Wg||(Wg=!0,window.addEventListener("hashchange",Vg),window.addEventListener("popstate",Vg)),Gg())}const Yg=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])});function Jg(t){return[t.rotDeg,t.tiltDeg,t.xyScale,t.zScale,t.origin[0],t.origin[1]].every(Number.isFinite)&&Math.abs(t.xyScale)>1e-12&&Math.abs(Math.cos(t.tiltDeg*Math.PI/180))>1e-12}function Xg(t,e,i=Yg){if(!(Jg(i)&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(e)))throw new Error("invalid isometric projection input");const s=i.rotDeg*Math.PI/180,n=i.tiltDeg*Math.PI/180,o=t[0]-i.origin[0],a=t[1]-i.origin[1],r=(o*Math.cos(s)-a*Math.sin(s))*i.xyScale,l=(o*Math.sin(s)+a*Math.cos(s))*i.xyScale;return[i.origin[0]+r,i.origin[1]+l*Math.cos(n)-e*i.zScale*Math.sin(n)]}function Zg(t,e=Yg){if(!Jg(e)||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new Error("invalid isometric projection input");const i=e.rotDeg*Math.PI/180,s=e.tiltDeg*Math.PI/180,n=(t[0]-e.origin[0])/e.xyScale,o=(t[1]-e.origin[1])/(e.xyScale*Math.cos(s));return[e.origin[0]+n*Math.cos(i)+o*Math.sin(i),e.origin[1]-n*Math.sin(i)+o*Math.cos(i)]}function Qg(t=Yg){return`matrix(${function(t=Yg){if(!Jg(t))throw new Error("invalid isometric camera");const e=t.rotDeg*Math.PI/180,i=t.tiltDeg*Math.PI/180,s=t.xyScale*Math.cos(e),n=-t.xyScale*Math.sin(e),o=t.xyScale*Math.sin(e)*Math.cos(i),a=t.xyScale*Math.cos(e)*Math.cos(i);return[s,o,n,a,t.origin[0]-s*t.origin[0]-n*t.origin[1],t.origin[1]-o*t.origin[0]-a*t.origin[1]]}(t).map(t=>Number(t.toFixed(12))).join(" ")})`}function tf(t,e=Yg){const{rect:i,wallHeight:s}=t,n=t.openingHeight??s,o=t.floorDepth??0;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(o)||s<0||n<0||o<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],r=Math.max(s,n),l=a.flatMap(t=>[Xg(t,-o,e),Xg(t,r,e)]),c=l.map(t=>t[0]),h=l.map(t=>t[1]),d=Math.min(...c),p=Math.min(...h);return{x:d,y:p,w:Math.max(...c)-d,h:Math.max(...h)-p}}const ef=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function sf(t){let e=0;for(let i=0;iArray.isArray(t)&&Number.isFinite(t[0])&&Number.isFinite(t[1])).map(t=>[Number(t[0]),Number(t[1])]),i=e[e.length-1];return e.length>1&&e[0][0]===i[0]&&e[0][1]===i[1]&&e.pop(),e}(t);if(i.length<3)return[];const s=!e;return sf(i)>0===s?i:[...i].reverse()}function of(t,e,i){return t.length?`M ${t.map(t=>ef(Xg(t,i,e))).join(" L ")} Z`:""}function af(t,e,i){const s=e[1]-t[1],n=-(e[0]-t[0]),o=i.rotDeg*Math.PI/180;return s*Math.sin(o)+n*Math.cos(o)}function rf(t,e,i=Yg){if(!Number.isFinite(e)||e<0)throw new Error("invalid floor edge height");const s=(t||[]).map(t=>(t||[]).map((t,e)=>function(t,e){const i=nf(t,e);if(!i.length)return i;let s=0;for(let t=1;t0)).filter(t=>t.length>=3&&Math.abs(sf(t))>=1e-9)).filter(t=>t.length&&sf(t[0])>0);s.sort((t,e)=>{const i=t[0][0],s=e[0][0];return i[0]-s[0]||i[1]-s[1]||Math.abs(sf(e[0]))-Math.abs(sf(t[0]))});const n=[],o=[];let a=0;for(let t=0;tt.depth-e.depth||t.component-e.component||t.edge-e.edge),{footprintPath:n.join(" "),sides:o,componentCount:s.length,edgeCount:a}}function lf(t,e){return t^=Math.round(64*(Number.isFinite(e)?e:0)),Math.imul(t,16777619)>>>0}const cf=t=>t.every(Number.isFinite);function hf(t,e,i,s){const n=t[0]*i,o=t[1]*s,a=e*Math.PI/180;return[n*Math.cos(a)-o*Math.sin(a),n*Math.sin(a)+o*Math.cos(a)]}function df(t,e,i,s,n,o,a){const r=t.flipH?-1:1,l="gate"===t.type?1:t.flipV?-1:1,c=(t.type,t.flipV,t.angle,t.face,{ox:0,oy:0}),h=function(t,e){return[t[0]+e[0],t[1]+e[1]]}([t.x+c.ox,t.y+c.oy],hf(i,t.angle,r,l));return{leaf:e,hinge:h,closedVector:hf(s,t.angle,r,l),quarterVector:hf([-s[1],s[0]],t.angle,r,l),turnDeg:n,bottom:o,top:a}}const pf=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function uf(t,e,i=Yg){const s=Math.max(0,Math.min(1,Number.isFinite(e)?e:0));return t.leaves.map(e=>{const n=function(t,e){const i=t.turnDeg*e*Math.PI/180;return[t.hinge[0]+t.closedVector[0]*Math.cos(i)+t.quarterVector[0]*Math.sin(i),t.hinge[1]+t.closedVector[1]*Math.cos(i)+t.quarterVector[1]*Math.sin(i)]}(e,s),o=Xg(e.hinge,e.bottom,i),a=Xg(n,e.bottom,i),r=Xg(n,e.top,i),l=Xg(e.hinge,e.top,i);return{id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${pf(o)} L ${pf(a)} L ${pf(r)} L ${pf(l)} Z`,shadowD:`M ${pf(Xg(e.hinge,0,i))} L ${pf(Xg(n,0,i))}`,depth:Math.max(o[1],a[1])}})}const _f={window:120,door:90,passage:90,gate:300};function mf(t){return _f[t]}function gf(t,e){const i=[t[0],t[1]],s=[e[0],e[1]];return function(t,e){return t[0]-e[0]||t[1]-e[1]}(i,s)<=0?{a:i,b:s}:{a:s,b:i}}function ff(t){const e=new Map;return t.forEach((t,i)=>{if(!t.kind||t.open)return;const s=gf(t.a,t.b);if(Math.hypot(s.b[0]-s.a[0],s.b[1]-s.a[1])<=1e-9)return;const n=function(t,e){const i=t=>(Math.abs(t)<=5e-10?0:Math.round(1e6*t)/1e6).toFixed(6);return`${i(t[0])},${i(t[1])}>${i(e[0])},${i(e[1])}`}(s.a,s.b),o=e.get(n);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,t.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(t.partitionHost&&(o.partitionHost&&o.partitionHost.id!==t.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=t.partitionHost));e.set(n,{segmentKey:n,a:s.a,b:s.b,physicalHalfWidth:Math.max(0,t.half||0),sourceOrder:i,...t.partitionHost?{partitionHost:t.partitionHost}:{}})}),[...e.values()]}function vf(t,e){if(Math.abs(t.distance-e.distance)>1e-9)return t.distance-e.distance;if(Math.abs(t.perpendicular-e.perpendicular)>1e-9)return t.perpendicular-e.perpendicular;return(t.target.segmentKeye.target.segmentKey?1:0)||t.target.sourceOrder-e.target.sourceOrder}function yf(t){const e=ff(t.intervals).map(e=>{const i=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,r=(t[0]-e.a[0])*o+(t[1]-e.a[1])*a,l=Math.max(0,Math.min(n,r)),c=e.a[0]+l*o,h=e.a[1]+l*a;return{along:l,length:n,x:c,y:h,distance:Math.hypot(t[0]-c,t[1]-h),perpendicular:Math.abs((t[0]-e.a[0])*a-(t[1]-e.a[1])*o)}}(t.pointer,e);return{target:e,...i,envelope:Math.max(t.baseTolerance,e.physicalHalfWidth+t.bodyPointerPadding)}}).filter(t=>t.distance<=t.envelope+1e-9).filter(e=>!function(t,e,i,s,n){const o=e.b[0]-e.a[0],a=e.b[1]-e.a[1],r=Math.hypot(o,a);if(!(r>1e-9))return!1;const l=o/r,c=a/r;for(const o of i){if(!o.open&&o.kind)continue;const i=gf(o.a,o.b),a=i.b[0]-i.a[0],r=i.b[1]-i.a[1],h=Math.hypot(a,r);if(!(h>1e-9))continue;const d=a/h,p=r/h;if(Math.abs(l*p-c*d)>1e-6)continue;if(Math.abs((i.a[0]-e.a[0])*c-(i.a[1]-e.a[1])*l)>n)continue;const u=(t[0]-i.a[0])*d+(t[1]-i.a[1])*p,_=1e-9;if(!(u<=_||u>=h-_)&&Math.abs((t[0]-i.a[0])*p-(t[1]-i.a[1])*d)<=s+1e-9)return!0}return!1}(t.pointer,e.target,t.intervals,e.envelope,Math.max(1e-9,Math.min(t.baseTolerance,.04*t.gridStep)))),i=e.filter(e=>!!e.target.partitionHost&&t.renderedLength+2*e.target.physicalHalfWidth>e.length+1e-9).sort(vf),s=e.filter(e=>!e.target.partitionHost||t.renderedLength+2*e.target.physicalHalfWidth<=e.length+1e-9).sort(vf);let n=s[0];if(!n)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=s.filter(t=>Math.abs(t.distance-n.distance)<=1e-9&&Math.abs(t.perpendicular-n.perpendicular)<=1e-9),a=o.filter(t=>t.target.partitionHost);if(a.length){if(1!==new Set(a.map(t=>t.target.partitionHost.id)).size||a.some(t=>t.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const t=a[0],e=t.target.b[0]-t.target.a[0],i=t.target.b[1]-t.target.a[1],s=Math.hypot(e,i),r=e/s,l=i/s,c=o.every(e=>{const i=e.target.b[0]-e.target.a[0],s=e.target.b[1]-e.target.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,c=Math.abs(r*a-l*o)<=1e-6,h=Math.abs((e.target.a[0]-t.target.a[0])*l-(e.target.a[1]-t.target.a[1])*r);return c&&h<=1e-9});if(!c)return{candidate:null,jambBlockedTarget:null};n=t}if(n.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:r,length:l}=n,c=r.b[0]-r.a[0],h=r.b[1]-r.a[1],d=c/l,p=h/l,u=r.partitionHost?r.physicalHalfWidth:0,_=Math.min(Math.max(0,t.renderedLength)/2+u,l/2);let m=n.along;const g=Math.max(t.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=r.a[0]+d*m,y=r.a[1]+p*m,b=Math.max(0,t.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),$=Math.max(0,l-k),S=[r.a[0]+d*(w-x/2),r.a[1]+p*(w-x/2)],M=[r.a[0]+d*(k+$/2),r.a[1]+p*(k+$/2)];let C=180*Math.atan2(h,c)/Math.PI;C>=90?C-=180:C<-90&&(C+=180);const D=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:t.preset.revision,geometryRevision:t.geometryRevision,pointer:[t.pointer[0],t.pointer[1]],type:t.preset.type,lengthCm:t.preset.lengthCm,flipH:t.preset.flipH,flipV:t.preset.flipV,x:v,y:y,angle:C,renderedLength:t.renderedLength,target:r,...r.partitionHost?{host:{...r.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:S},{distance:$,midpoint:M}],guide:D?{x:v,y:y,angle:C}:null}},jambBlockedTarget:null}}function bf(t,e,i,s,n=1e-6){return t.presetRevision===i&&t.geometryRevision===s&&Math.hypot(t.pointer[0]-e[0],t.pointer[1]-e[1])<=n}const wf=(t,e)=>t[0]*e[1]-t[1]*e[0],kf=(t,e)=>t[0]*e[0]+t[1]*e[1],xf=(t,e)=>[t[0]-e[0],t[1]-e[1]],$f=(t,e,i)=>[t[0]+e[0]*i,t[1]+e[1]*i];function Sf(t,e,i){return Math.abs(wf(t,e))<=i}function Mf(t,e,i){return Math.abs(wf(xf(t,e),i))}function Cf(t,e,i,s,n){const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n&&i>0))return[];const l=[o/r,a/r];return function(t,e,i){const s=e.map(([e,i])=>[Math.max(0,Math.min(e,i)),Math.min(t,Math.max(e,i))]).filter(([t,e])=>e>t+i).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),n=[];for(const t of s){const e=n[n.length-1];!e||t[0]>e[1]+i?n.push([...t]):e[1]=Math.max(e[1],t[1])}const o=[];let a=0;for(const[t,e]of n)t>a+i&&o.push([a,t]),a=Math.max(a,e);return t>a+i&&o.push([a,t]),o}(r,s.flatMap(e=>{const s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=Math.hypot(s,o);if(!(a>n&&Sf(l,[s/a,o/a],1e-6)))return[];if(Mf(e.a,t,l)>1.1*Math.max(i,n)||Mf(e.b,t,l)>1.1*Math.max(i,n))return[];return[[kf(xf(e.a,t),l),kf(xf(e.b,t),l)]]}),n).flatMap(([e,s])=>{const n=Ol({a:$f(t,l,e),b:$f(t,l,s),halfDepth:i});return n?[n]:[]})}function Df(t){const e=t.coordScale??1,i=Math.max(t.epsilon??2e-4*t.gridPitch,1e-9),s=[];for(const i of t.rooms||[]){if(!i?.id)continue;const n=hc(t.rooms,i.id,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e);if(!n||n.poly.length<3)continue;const o=Zl(n.poly,n.offsets);!o||o.length<3||s.push({roomId:i.id,profile:n,inner:o})}s.sort((t,e)=>t.roomId.localeCompare(e.roomId));const n=(t.roomOpenings||[]).map(t=>{const e=t.angle*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Math.max(0,t.length)/2;return{a:$f([t.x,t.y],i,-s),b:$f([t.x,t.y],i,s)}}),o=[];for(const s of zc(t.rooms,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e))for(const t of Cf(s.a,s.b,s.depthUnits/2,n,i))o.push({body:t});const a=new Map;for(const e of t.partitionCuts||[]){const t=a.get(e.hostId)||[];t.push(e),a.set(e.hostId,t)}for(const e of t.partitions||[]){const s=gl(e.cm,t.cellCm,t.gridPitch)/2;for(const t of Cf(e.a,e.b,s,a.get(e.id)||[],i))o.push({body:t,partitionId:e.id})}return{rooms:s,boundaries:o,epsilon:i}}function Pf(t,e,i,s){const n=t.profile.offsets[e];if(!(n>0))return null;const o=function(t,e){const i=t[e],s=t[(e+1)%t.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return function(t){let e=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t.profile.poly,e),a=$f(i.center,o,n),r=[];for(let e=0;es&&Sf(i.axis,[l[0]/c,l[1]/c],1e-6)))continue;if(Mf(n,a,i.axis)>s||Mf(o,a,i.axis)>s)continue;const h=kf(xf(n,a),i.axis),d=kf(xf(o,a),i.axis);r.push([Math.min(h,d),Math.max(h,d)])}const l=function(t,e){t.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);const i=[];for(const s of t){const t=i[i.length-1];!t||s[0]>t[1]+e?i.push([...s]):t[1]=Math.max(t[1],s[1])}return i}(r,s).find(([t,e])=>t<=s&&e>=-s);if(!l)return null;const[c,h]=l,d=$f(a,i.axis,-i.half),p=$f(a,i.axis,i.half),u=Math.max(0,-i.half-c),_=Math.max(0,h-i.half),m=u>0?$f(a,i.axis,c):d,g=_>0?$f(a,i.axis,h):p,f=kf(o,i.normal)>=0?1:-1,v=(e,s,n)=>({from:e,to:s,label:[(e[0]+s[0])/2,(e[1]+s[1])/2],axis:i.axis,labelNormal:o,distance:n,roomId:t.roomId,roomSide:f,source:"room-face"});return{left:v(d,m,u),right:v(p,g,_)}}function Tf(t){const e=$f(t.center,t.axis,-t.half),i=$f(t.center,t.axis,t.half),s=$f(t.center,t.axis,Math.min(-t.half,t.targetLo)),n=$f(t.center,t.axis,Math.max(t.half,t.targetHi)),o=(e,i)=>({from:e,to:i,label:[(e[0]+i[0])/2,(e[1]+i[1])/2],axis:t.axis,labelNormal:t.normal,distance:Math.hypot(i[0]-e[0],i[1]-e[1]),source:"host-end"});return[o(e,s),o(i,n)]}function Rf(t,e,i,s){const n=xf(i,e),o=kf(n,n);if(!(o>s*s))return Math.hypot(...xf(t,e))<=s;const a=kf(xf(t,e),n)/o;if(a<-s||a>1+s)return!1;const r=$f(e,n,Math.max(0,Math.min(1,a)));return Math.hypot(...xf(t,r))<=s}function If(t,e,i){let s=!1;for(let n=0,o=e.length-1;nt[1]!=c>t[1]&&t[0]<(l-a)*(t[1]-r)/(c-r)+a&&(s=!s)}return s}function Af(t,e,i,s,n,o){const a=xf(s,i),r=wf(e,a);if(Math.abs(r)<=o)return null;const l=xf(i,t),c=wf(l,a)/r,h=wf(l,e)/r;return c<-o||c>n+o||h<-o||h>1+o?null:Math.max(0,Math.min(n,c))}function zf(t,e,i){const s=Tf(i),n="partition"===t.host?.kind?t.host.id:void 0;return[{base:s[0],direction:[-i.axis[0],-i.axis[1]]},{base:s[1],direction:i.axis}].map(({base:t,direction:i})=>{const s=t.distance,o=function(t,e,i,s,n,o){let a=null;for(const r of s)if(!n||r.partitionId!==n){if(If(t,r.body,o))return 0;for(let s=0;skf(xf(t,n),i));return{center:n,axis:i,normal:s,half:Math.max(0,t.renderedLength)/2,targetLo:Math.min(...o),targetHi:Math.max(...o)}}(t),s=e.rooms.flatMap(t=>{const s=function(t,e,i){const{profile:s}=t;let n=null;for(let t=0;t0))continue;const o=s.poly[t],a=s.poly[(t+1)%s.poly.length],r=xf(a,o),l=Math.hypot(r[0],r[1]);if(!(l>i&&Sf(e.axis,[r[0]/l,r[1]/l],1e-6)))continue;if(Mf(o,e.center,e.axis)>i||Mf(a,e.center,e.axis)>i)continue;const c=kf(xf(o,e.center),e.axis),h=kf(xf(a,e.center),e.axis),d=Math.min(c,h),p=Math.max(c,h);if(d>-e.half+i||p0?d:p<0?-p:0);(!n||u2)return Tf(i);if(s.length){const t=s.map(({room:t,edge:s})=>Pf(t,s,i,e.epsilon));if(t.some(t=>!t))return Tf(i);const n=t;return[...n.map(t=>t.left),...n.map(t=>t.right)]}return zf(t,e,i)}function Ef(t){return!(!t.canEdit||t.kiosk||t.fixedFloor)&&("view"!==t.mode&&("mouse"===t.pointerType&&t.spaceCount>1))}const Nf="1.68.0",Of={badge:"display.badge",icon_ripple:"display.icon_ripple",value:"display.value",static_icon:"display.static_icon"},Lf={badge:"marker.display_hint_badge",icon_ripple:"marker.display_hint_icon_ripple",value:"marker.display_hint_value",static_icon:"marker.display_hint_static_icon"},Hf=2e3,Bf=1e3,qf=1500,Wf=t=>{const e=String(t??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return null;const i=Number(e);return Number.isFinite(i)?i:null},jf=(t,e)=>{if(!t.has(e))return{hit:!1};const i=t.get(e);return t.delete(e),t.set(e,i),{hit:!0,value:i}},Uf=(t,e,i,s)=>{for(t.delete(e),t.set(e,i);t.size>s;){const e=t.keys().next().value;if(void 0===e)break;t.delete(e)}},Gf=new Map;let Vf=0;const Kf=t=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(t??{})}`;let Yf=1e4;const Jf="houseplan_card_layout_v1",Xf="houseplan_card_cfg_v1",Zf="houseplan_card_zoom_v1",Qf="houseplan_card_nav_v1",tv="houseplan_card_kiosk_v1",ev="houseplan_card_view_v1",iv="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",sv=1e3,nv=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]],ov=(t,e)=>{const i=Math.min(t.x,e.x),s=Math.min(t.y,e.y);return{x:i,y:s,w:Math.max(t.x+t.w,e.x+e.w)-i,h:Math.max(t.y+t.h,e.y+e.h)-s}},av=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),rv=2e3,lv=(t,e,i)=>{const s=new Event(e,{bubbles:!0,composed:!0});s.detail=i??{},t.dispatchEvent(s)},cv=t=>{history.pushState(null,"",t),lv(window,"location-changed",{replace:!1})},hv=(t,e)=>{let i,s=null;const n=(...n)=>{clearTimeout(i),s=n,i=window.setTimeout(()=>{i=void 0;const e=s;s=null,e&&t(...e)},e)};return n.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const e=s;s=null,e&&t(...e)},n.cancel=()=>{clearTimeout(i),i=void 0,s=null},n.pending=()=>void 0!==i,n},dv=t=>{try{t.target?.setPointerCapture?.(t.pointerId)}catch{}};class pv extends ht{constructor(){super(...arguments),this._space="f1",this._layout={},this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._serverCfg=null,this._cfgRev=0,this._cfgContentFingerprint="",this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._layoutRev=0,this._layoutContentFingerprint="",this._virtualLights=mn(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._tip=null,this._hoverRoom=null,this._pointerModality=new N_(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...Rr},this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=t=>{this._reducedMotion=t.matches,this._cancelDevicePressFeedback(),t.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:t.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Tg({frame:t=>this._applyModeTransitionFrame(t),settled:t=>this._settleModeTransition(t)}),this._editorSecondary=new W_({root:()=>this.renderRoot,requestUpdate:()=>this.requestUpdate(),updateComplete:()=>this.updateComplete,clearTip:()=>{this._tip=null}}),this._editorSecondaryCopy={groupActive:(t,e)=>this._t("editor.group_active",{group:t,item:e}),openGroup:t=>this._t("editor.open_group",{group:t}),disabledAction:(t,e)=>this._t("editor.disabled_action",{action:t,reason:e})},this._tool="draw",this._geometryHistory=new fg(50),this._wallDialog=null,this._drawWallField=null,this._activeDraftId=null,this._resumeDraftBySpace={},this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowClipCache=new Map,this._glowGeometryWarnings=new Set,this._lightBarrierCache=null,this._lightBarrierPool=new Map,this._glowFeatherUnits=null,this._glowRenderedSources=new Map,this._glowLastAppearance=new Map,this._glowEnteringSources=new Set,this._glowEnterRafs=new Map,this._glowFadeTimers=new Map,this._glowFeatherSuspendUntil=0,this._glowFeatherResumeTimer=0,this._glowSourceSeq=0,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszSel=null,this._rszDrag=null,this._rszEligibilityCache=null,this._rszPreview=null,this._rszLive=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._touchContacts=new Map,this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:t=>this._guardTouchGesture(t)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._alignDialog=null,this._settingsDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=t=>this._onKey(t),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++Vf,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=t=>{if(this._continuity.visibility(t),this._dayCycleVisibility(t),"hidden"===t.kind)return this._clearTransientHover(!0),this._cancelDevicePressFeedback(),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,!t.long){const t=Date.now();let e=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+I_)>t||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,e=!0);return void(e&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._lastTap=0,this._onLabsSnapshot=t=>{const e=this._effectiveProjection();this._labs=t;const i=this._effectiveProjection();this._convertProjectionView(e,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const t=this._hashSpace();if(t&&this._model.find(e=>e.id===t)&&t!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._onHaRegistryUpdate=()=>{const t=An(this.hass);t.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=t.revision,this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,function(t){const e=Cn(t);e&&(Tn(t,e),Rn(t,e))}(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new $d(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=hv(()=>{if(this._serverStorage){const t=[...this._dirtyPos];this._dirtyPos.clear();for(const e of t){const t=ol(this._layout[e]);t&&(this._layout={...this._layout,[e]:t},this._sentPos.set(e,t),this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t}).then(t=>this._noteLayoutRev(t)).catch(t=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))).finally(()=>{this._sentPos.get(e)===t&&this._sentPos.delete(e)}))}this._cacheSnapshot()}else this._layout=al(Gr(this._layout)),localStorage.setItem(Jf,JSON.stringify(this._layout))},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.undo();t&&(this._applyGeometryState(t.before,!0)?this._showToast(this._t("history.undone",{name:t.name})):this._geometryHistory.clear())},this._redoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.redo();t&&(this._applyGeometryState(t.after,!0)?this._showToast(this._t("history.redone",{name:t.name})):this._geometryHistory.clear())},this._saveConfigDebounced=hv(()=>{this._serverCfg&&this._writeConfig().catch(t=>{const e=!0===t?.physicalGeometryRolledBack;"geometry-unsafe"!==t?.code&&("wall_model_client_outdated"===t?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===t?.code?(this._showToast(this._t("toast.conflict")),e||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(t)})),e&&this._reloadRejectedPhysicalWrite())})},500),this._draftSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>{const t=this._physicalDialog,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=Wf(t.cm);if(null==s)return void this._showPhysicalRange("column"===t.kind?jc:100,"column"===t.kind?1:0);const n=this._imperial?2.54*s:s,o="column"===t.kind?jc:100,a="column"===t.kind?1:0;if(!Number.isFinite(n)||no)return void this._showPhysicalRange(o,a);if("column"===t.kind){const e=i.wall_columns.find(e=>e.id===t.id);if(!e)return;const s=Wf(t.angle||"0");if("circle"!==t.shape&&(null==s||s<0||s>=90))return void this._showToast(this._t("toast.physical_angle"));const o="circle"===t.shape?{id:t.id,shape:"circle",center:e.center,cm:n}:{id:t.id,shape:"square",center:e.center,cm:n,angle:s};if(i.wall_columns.some(e=>e.id!==t.id&&uh(e,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"))}const r=this._geometrySnapshot();if("partition"===t.kind){const i=(e.partitions||[]).find(e=>e.id===t.id);if(i&&0===n&&f_(e.openings,{kind:"partition",id:t.id}))return void this._showToast(this._t("toast.zero_wall_opening_conflict"));i&&(i.cm=n)}else if("column"===t.kind){const i=(e.wall_columns||[]).find(e=>e.id===t.id);i&&(i.cm=Gc(n),i.shape="circle"===t.shape?"circle":"square","square"===i.shape?i.angle=Wf(t.angle||"0"):delete i.angle)}else{const i=(e.room_drafts||[]).find(e=>e.id===t.id);i?.segments?.[t.segment||0]&&(i.segments[t.segment||0].cm=n)}const l=this._commitPhysicalGeometry(this._t("history.physical_edit"),r);this._physicalDialog=null,l||this.requestUpdate()},this._deletePhysicalSelection=()=>{const t=this._physicalSel,e=this._curSpaceCfg;if(!t||!e)return;if("draft"===t.kind)return void this._deleteDraftWhole();const i=this._geometrySnapshot();if("partition"===t.kind){const i=(e.openings||[]).filter(e=>"partition"===e.host?.kind&&e.host.id===t.id).sort((t,e)=>(t.host?.t||0)-(e.host?.t||0));if(i.length)return void(this._partitionDeleteDialog={id:t.id,openings:i.map(t=>JSON.parse(JSON.stringify(t)))})}const s="partition"===t.kind?"partitions":"column"===t.kind?"wall_columns":"room_drafts";e[s]=(e[s]||[]).filter(e=>e.id!==t.id),e[s].length||delete e[s],this._activeDraftId===t.id&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._confirmPartitionDelete=()=>{const t=this._partitionDeleteDialog,e=this._curSpaceCfg;if(!t||!e)return;const i=this._geometrySnapshot();e.partitions=(e.partitions||[]).filter(e=>e.id!==t.id),e.partitions.length||delete e.partitions,e.openings=(e.openings||[]).filter(e=>"partition"!==e.host?.kind||e.host.id!==t.id),e.openings.length||delete e.openings,this._partitionDeleteDialog=null,this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftWhole=()=>{const t="draft"===this._physicalDialog?.kind?this._physicalDialog.id:"draft"===this._physicalSel?.kind?this._physicalSel.id:null,e=this._curSpaceCfg;if(!t||!e||!confirm(this._t("confirm.delete_draft")))return;const i=this._geometrySnapshot();e.room_drafts=(e.room_drafts||[]).filter(e=>e.id!==t),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===t&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftSegment=()=>{const t=this._physicalDialog,e=this._curSpaceCfg;if(!t||"draft"!==t.kind||!e)return;if(!confirm(this._t("confirm.delete_draft_segment")))return;const i=(e.room_drafts||[]).findIndex(e=>e.id===t.id);if(i<0)return;const s=e.room_drafts[i],n=Math.max(0,Math.min(s.segments.length-1,t.segment||0)),o=[],a=s.points.slice(0,n+1),r=s.points.slice(n+1);if(a.length>=2&&o.push({id:s.id,points:a,segments:s.segments.slice(0,n)}),r.length>=2&&o.push({id:o.length?`${s.id}-${Date.now().toString(36)}`:s.id,points:r,segments:s.segments.slice(n+1)}),2===o.length&&e.room_drafts.length>=200)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot();e.room_drafts.splice(i,1,...o),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===s.id&&this._cancelPath(),this._physicalDialog=null,this._physicalSel=o.length?{kind:"draft",id:o[0].id}:null,this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),l)},this._confirmRoomDelete=t=>{const e=this._roomDeleteDialog,i=this._curSpaceCfg,s=this._spaceModel();if(!e||!i||!s)return;const n=s.rooms.find(t=>t.id===e.roomId);if(!n)return void(this._roomDeleteDialog=null);const o=this._openCuts(),a=$u(dc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv).filter(t=>t.roomId===n.id),s.partitions,this._openingsR.map(t=>({...t,x:t.rx,y:t.ry})),.02*this._gridPitch),r=new Set(a.materialize.filter(t=>!t.reusePartitionId).map(t=>t.interval.key)).size;if(t&&(i.partitions||[]).length+r>rv)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot(),c=pc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv);if(t){i.partitions||=[];const t=new Map,e=new Map,s=t=>{const e=(i.wall_segments||[]).find(e=>{const i=[Number(e.a?.[0])*sv,Number(e.a?.[1])*sv],s=[Number(e.b?.[0])*sv,Number(e.b?.[1])*sv];return this._samePt(t.a,i)&&this._samePt(t.b,s)||this._samePt(t.a,s)&&this._samePt(t.b,i)});return"string"==typeof e?.id&&e.id?e.id:null},n=Date.now().toString(36);for(const o of a.materialize){let a=o.reusePartitionId?i.partitions.find(t=>t.id===o.reusePartitionId):e.get(o.interval.key);a||(a={id:s(o.interval)||`partition-room-${n}-${e.size}`,a:[o.interval.a[0]/sv,o.interval.a[1]/sv],b:[o.interval.b[0]/sv,o.interval.b[1]/sv],cm:o.interval.cm},i.partitions.push(a),e.set(o.interval.key,a)),t.set(o.interval.key,a)}for(const e of i.openings||[]){const i=a.openingIntervals.get(e.id),s=i?t.get(i):null,n=this._openingsR.find(t=>t.id===e.id);if(!s||!n)continue;const o={a:[s.a[0]*sv,s.a[1]*sv],b:[s.b[0]*sv,s.b[1]*sv]};e.host={kind:"partition",id:s.id,t:Su([n.rx,n.ry],o)}}}else if(a.removeOpeningIds.length){const t=new Set(a.removeOpeningIds);i.openings=(i.openings||[]).filter(e=>!t.has(e.id)),i.openings.length||delete i.openings}i.rooms=i.rooms.filter(t=>t.id!==n.id),this._cfgEpoch++;const h=this._normalizeWalls(c,this._openCuts());h.length?i.walls=h:delete i.walls,this._roomDeleteDialog=null,this._commitPhysicalGeometry(this._t(t?"history.delete_room_keep_walls":"history.delete_room_with_walls"),l),this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate()},this._rebindPartitionOpening=()=>{const t=this._openingDialog;if(!t?.id)return;const e=t.id;this._activateMarkupTool("opening"),"opening"===this._tool&&(this._openingRebindId=e,this._openingPreset={type:t.type,lengthCm:t.lengthCm,flipH:t.flipH,flipV:t.flipV,revision:++this._openingPresetRevision},this._openingDialog=null,this._openingHoverCandidate=null)},this._keepClosedAsPartitions=()=>{if(this._wallFaceBatch)return void this._decideWallFace(!1);if(!this._contourClosed||this._pendingSplit||!this._curSpaceCfg)return;const t=this._curSpaceCfg,e=this._path.slice(0,-1);if((t.partitions||[]).length+e.length>rv)return void this._showToast(this._t("toast.physical_limit"));const i=this._geometrySnapshot(),s=Xp(e.length,[...this._draftSegmentCms,this._closingWallCm??void 0],this._drawWallCm,ll);t.partitions||=[];const n=Date.now().toString(36),o=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,a=this._draftSegmentsForPath(this._path,o,s);for(let i=0;it.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.contour_to_partitions"),i),this._roomDialog=!1,this._path=[],delete this._resumeDraftBySpace[this._space],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null},this._toggleServerPlans=async()=>{const t=this._spaceDialog;if(t)if(t.pickSaved)this._spaceDialog={...t,pickSaved:!1};else{this._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.hass.callWS({type:"houseplan/plans/list"}),e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:t?.plans||[],savedBusy:!1})}catch(t){const e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:[],savedBusy:!1}),this._showToast(this._t("toast.plans_list_failed",{err:this._errText(t)}))}}},this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const t=this._dayCycleState();if(!t)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const e=mr(t);e!==this._dayCycleClockKey&&(this._dayCycleClockKey=e,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(!this._norm)return;const t=this._glowRadiusCm,e=this._imperial?Math.round(t/30.48*10)/10:Math.round(t)/100;this._settingsDialog={colors:JSON.parse(JSON.stringify(this._fillColors)),glowRadius:e,bgColor:hs(this._settings,{bgColor:null})||null,northDeg:$r(this._settings,{}),bgMode:Sr(this._settings,{}),sunRays:Mr(this._settings,{}),busy:!1}},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._previewAlignDialog(!1),this._toggleOptimizeLivePositions=()=>{const t=this._alignDialog;t&&!t.busy&&t.report.liveMissingPositions.length&&this._previewAlignDialog(!t.removeLiveMissingPositions)},this._optimizeUndoBusy=!1,this._openBackupExport=()=>{this._settingsDialog=null,this._backupExportDialog={kind:"full",planOnly:!1,busy:!1,error:""}},this._openRulesDialog=()=>{if(!this._norm)return;const t=this._settings.icon_rules,e=(t&&t.length?t:Jt).map(t=>({...t}));this._rulesDialog={rules:e,test:"",busy:!1}},this._climateCache=null,this._gearPtCache=new WeakMap}get _canEdit(){return!!this._norm&&(!0===this._serverCanWrite||!1!==this._serverCanWrite&&!0===this.hass?.user?.is_admin)}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}_cssColor(t,e){const i=String(t||"").trim();if(!i)return e;const s=document.createElement("span");s.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(s);const n=getComputedStyle(s).color||e;return s.remove(),n}_currentModeVisual(t=this._mode){const e=this._modeTransition.presented||this._modeTransitionVisual;if(e)return{...e,viewport:{...e.viewport,viewBox:{...e.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const s=this.renderRoot.querySelector(".editorchrome"),n=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),a=this.renderRoot.querySelector(".hp-backdrop"),r=this.renderRoot.querySelector(".zoomwrap"),l=r?getComputedStyle(r).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:t,editorChromeHeight:"view"===t?0:s?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:Sg(n,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===t?.35:1,backdropOpacity:a&&Number(getComputedStyle(a).opacity)||1,viewWeight:"view"===t?1:0,editorWeight:"view"===t?0:1,toolbarContentOpacity:"view"===t?0:1}}_viewForModeTarget(t,e,i,s,n){const o=Ni(this._baseVb(),s/Math.max(1,n)),a=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),r=o.w/a,l=o.h/a,c=e??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-r/2,y:h-l/2,w:r,h:l},o)}_targetStageColor(t){return"view"!==t?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(t){return"view"===t&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(t){return 1}_applyModeTransitionFrame(t){t.targetMode===this._mode&&(this._modeTransitionVisual=t.presented,this._view={...t.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(t){if(t.targetMode!==this._mode)return;const e=this._modeTransitionRequest;this._view={...t.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[t.to.stageWidth,t.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._modeTransitionBusy||t.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-t.to.stageWidth)>.5||Math.abs(i.clientHeight-t.to.stageHeight)>.5)){const t=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,t?t.x+t.w/2:void 0,t?t.y+t.h/2:void 0),this.requestUpdate()}const s=this.renderRoot.activeElement;(!s||!s.isConnected||!!s.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(t=!0){const e=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(t),t&&e||(this._modeTransitionVisual=null)}_adoptMode(t){this._cancelModeTransition(!1),this._mode=t,"view"!==t&&(this._editorChromeMode=t)}_commitViewModeAtomic(t,e,i,s){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=e,t){const n=this._stageEl?.clientWidth||t.stageWidth,o=Math.max(1,t.stageHeight+t.editorChromeHeight);this._view=this._viewForModeTarget(e,i,s,n,o),this._lastValidStageSize=[n,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(t,e,i,s,n,o){this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._mode!==i)return void(t===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const a=this.renderRoot.querySelector(".editorchrome"),r=a?.querySelector(".editorchrome-inner"),l="view"===i?0:r?.scrollHeight||r?.getBoundingClientRect().height||0,c=Math.max(1,e.stageHeight+e.editorChromeHeight),h=Math.max(1,c-l),d=this._stageEl?.clientWidth||e.stageWidth;if(d<=0||h<=0)return this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._applyView(s,n,o),void this.requestUpdate();const p=this._viewForModeTarget(s,n,o,d,h),u={presentedMode:i,editorChromeHeight:l,stageWidth:d,stageHeight:h,viewport:Sg(p,d),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const _=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(e,u,i,this._reducedMotion||_?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(t=this._model,e=this._loadOk){const i=this._config?.floor,s=function(t){if(!t.hasFloor)return{kind:"absent"};const e=t.floor;if("string"==typeof e)return e.length?t.spaceIds.includes(e)?{kind:"valid",id:e,source:"id"}:{kind:"invalid",reason:"unknown-id",value:e}:{kind:"invalid",reason:"empty-id",value:e};if("number"==typeof e){if(!Number.isFinite(e))return{kind:"invalid",reason:"non-finite-index",value:e};if(!Number.isInteger(e))return{kind:"invalid",reason:"fractional-index",value:e};if(e<0)return{kind:"invalid",reason:"negative-index",value:e};const i=t.spaceIds[e];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:e}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:e}}({spaceIds:t.map(t=>t.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||e?s:"number"==typeof i?"valid"===s.kind||"invalid"===s.kind&&"out-of-range-index"===s.reason?{kind:"pending",value:i}:s:"valid"===s.kind||"invalid"===s.kind&&"unknown-id"!==s.reason?s:{kind:"pending",value:i}}_canCommitSpace(t,e=!1){if(e||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===t}_commitSpace(t,e=!1){return!!this._canCommitSpace(t,e)&&(t!==this._space&&(this._clearTransientHover(!0),this._cancelDevicePressFeedback()),this._space=t,!0)}_slideTo(t,e){if(t===this._space)return!0;if(!this._canCommitSpace(t))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),i||(this._slide=e,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(t,e){Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:t.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(dv(t),this._tabDragRelease=t=>this._tabPointerUp(t),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:e,pointerId:t.pointerId,x:t.clientX,y:t.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(t,e,i){const s=this._model.map(t=>t.id),n=s.indexOf(i);if(n<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const a of o){const o=a.dataset.id||"";if(!o||o===i)continue;const r=a.getBoundingClientRect();if(tr.right||er.bottom)continue;const l=s.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,s;const n=this._tabDropTargetAt(t.clientX,t.clientY,e.id);e.moved&&e.targetId===n?.targetId&&e.placement===n?.placement||(this._tabDrag={...e,moved:!0,targetId:n?.targetId||null,placement:n?.placement||null})}_tabPointerUp(t){const e=this._tabDrag;if(e&&e.pointerId!==t.pointerId)return;const i="pointerup"===t.type&&e?.moved?this._tabDropTargetAt(t.clientX,t.clientY,e.id):null;"pointerup"===t.type&&e?.moved&&this._suppressNextTabClick(),this._endTabDrag(),e?.moved&&i&&this._commitTabOrder(e.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(t){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(t)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(t,e){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const s=this._model.map(t=>t.id),n=function(t,e,i){const s=t.indexOf(e),n=t.indexOf(i);if(s<0||n<0||s===n)return t;const o=t.slice();return o.splice(s,1),o.splice(n,0,e),o}(s,t,e);if(n===s)return;const o=new Map(this._devices.map(t=>[String(t.id),String(t.area||"")])),a=function(t,e,i,s=()=>""){if(!i)return[];const n=[];for(const o of t){if(!o||!0===o.removed)continue;const t="string"==typeof o.id?o.id:"";if(!t)continue;if("string"==typeof o.space&&o.space)continue;const a=("string"==typeof o.area?o.area:"")||s(t)||"";a&&e[a]||n.push({id:t,space:i})}return n}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([t,e])=>[t,e.space])),s[0]||"",t=>o.get(t)||"");if(a.length){const t=new Map(a.map(t=>[t.id,t.space]));for(const e of i.markers||[]){const i=t.get(String(e.id));i&&(e.space=i)}}i.spaces=function(t,e){const i=new Map(e.map((t,e)=>[t,e]));return t.map((t,e)=>({space:t,index:e})).sort((t,e)=>(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)||t.index-e.index).map(t=>t.space)}(i.spaces||[],n),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(t){if(this._endTabDrag(),t===this._space)return;const e=this._model.map(t=>t.id),i=e.indexOf(this._space),s=e.indexOf(t);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(t,i>=0&&s0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const t=this._model.map(t=>t.id),e=t.indexOf(this._space);this._slideTo(t[(e+1)%t.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(t){this._wallUnionCacheValue=t,null===t&&this._wallUnionPool.clear()}_newContinuityController(){return new bd(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(ev,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(t){const e=this._view;if(!e)return null;const i=[e.x+e.w/2,e.y+e.h/2],s="iso"===t?Zg(i):i;return{x:s[0],y:s[1]}}_convertProjectionView(t,e){if(t===e)return;const i=this._logicalViewCenter(t);this._view=null;const s=i?"iso"===e?Xg([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,s?.[0],s?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(t){if(!this._labsIso||"view"!==this._mode)return;const e=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:t},"iso"===t){const t=this._isoSceneKey();t&&this._isoFallback.delete(t)}this._saveViewPreference();const i=this._effectiveProjection();this._convertProjectionView(e,i)}_hashSpace(){return Og(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const t=(e=this.ownerDocument,vg.get(e)?.resolved);var e;void 0!==t&&(this._glowScreenBlend=t),this._continuityUnsub?.(),this._continuityUnsub=vd(this.ownerDocument,this._pageVisibility),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(t=>{for(const e of t)for(const t of e.addedNodes)this._syncPointerHoverSubtree(t)}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),function(t){const e=vg.get(t);if(e)return e.promise;const i={promise:Promise.resolve(!1)};return i.promise=bg(t).catch(()=>!1).then(t=>(i.resolved=t,t)),vg.set(t,i),i.promise}(this.ownerDocument).then(t=>{t!==this._glowScreenBlend&&(this._glowScreenBlend=t,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>Is(this._serverCfg)),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(t,e){Ug.add(e);const i=Kg(t);return"undefined"==typeof window&&e(i),()=>{Ug.delete(e)}}(Nf,this._onLabsSnapshot),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const t of this._activityRt.values())clearTimeout(t.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),this._modeTransition.dispose(),this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer);for(const t of this._glowFadeTimers.values())clearTimeout(t);for(const t of this._glowEnterRafs.values())cancelAnimationFrame(t);clearTimeout(this._glowFeatherResumeTimer),this._glowFeatherResumeTimer=0,this._glowFeatherSuspendUntil=0,this._glowFadeTimers.clear(),this._glowEnterRafs.clear(),this._glowEnteringSources.clear(),this._glowRenderedSources.clear(),this._glowLastAppearance.clear(),this._glowSourceSeq=0,this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._touchContacts.clear(),this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(t){if("Escape"===t.key&&this._vacFit)return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void t.stopPropagation();if("Escape"===t.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm=null);if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._settingsDialog)return void(this._settingsDialog=null);if(this._markerDialog)return void(this._markerDialog=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary.hasOpenGroup)return t.preventDefault(),void this._editorSecondary.closeGroup(!0)}const e=t.composedPath?.()||[t.target],i=e.some(t=>t?.matches?.('input, textarea, select, [contenteditable="true"]')),s=e.some(t=>t?.classList?.contains?.("editor-secondary")),n=t.ctrlKey||t.metaKey,o=t.key.toLowerCase(),a=/^[a-z]$/.test(o),r="z"===o||!a&&"KeyZ"===t.code,l="y"===o||!a&&"KeyY"===t.code,c=n&&(r&&t.shiftKey||l),h=n&&r&&!t.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;return c?(t.preventDefault(),void this._redoGeometry()):h?(t.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry()):"Delete"!==t.key&&"Backspace"!==t.key||!this._decorSel||i||s?void("Escape"===t.key&&(t.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._furnPalette=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(t.preventDefault(),void this._decorDeleteSel())}if(this._markup&&(!h&&!c||!i)){if(("Delete"===t.key||"Backspace"===t.key)&&this._physicalSel&&!i&&!s)return t.preventDefault(),void this._deletePhysicalSelection();if(c)return t.preventDefault(),void this._redoGeometry();if(h)return t.preventDefault(),this._rszDrag?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===t.key)return this._physicalDrag||this._physicalRotate?(t.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(t.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(t.preventDefault(),void this._finishWallChain()):this._physicalSel?(t.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(t.preventDefault(),this._rszDrag?void this._rszCancelDrag():void(this._rszSel?this._rszSel=null:this._tool="draw")):"split"===this._tool?(t.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(t.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(t.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(t.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length){if(this._contourClosed)return this._path=this._path.slice(0,-1),void(this._closingWallCm=null);if(this._activeDraftId&&this._path.length>1&&this._curSpaceCfg){const t=this._geometrySnapshot();this._path=this._path.slice(0,-1),this._draftSegmentCms=this._draftSegmentCms.slice(0,-1);const e=this._curSpaceCfg,i=(e.room_drafts||[]).findIndex(t=>t.id===this._activeDraftId);if(i>=0){const s=Array.isArray(e.room_drafts[i]?.segments)?e.room_drafts[i].segments:[];this._path.length<2?(e.room_drafts.splice(i,1),e.room_drafts.length||delete e.room_drafts,this._activeDraftId=null):e.room_drafts[i]={id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentCms.map((t,e)=>({...s[e]||{},cm:t}))},this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),t)}return}this._path=this._path.slice(0,-1)}}_undoActiveDraftPoint(){const t=this._activeDraftId,e=this._path[0]?[...this._path[0]]:null,i=this._geometryHistory.undo();if(!i)return void this._undoPoint();if(!this._applyGeometryState(i.before,!0))return void this._geometryHistory.clear();const s=t?this._spaceModel()?.room_drafts.find(e=>e.id===t):null;s?(this._activeDraftId=s.id,this._path=s.points.map(t=>[...t]),this._draftSegmentCms=this._adoptDraftCms(this._path,s.segments.map(t=>t.cm),s.id),this._resumeDraftBySpace[this._space]=s.id):(this._activeDraftId=null,this._path=e?[e]:[],this._draftSegmentCms=[],t&&this._resumeDraftBySpace[this._space]===t&&delete this._resumeDraftBySpace[this._space]),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:i.name}))}static getConfigElement(){return document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(t){for(const t of Gf.values())for(const e of t)clearTimeout(e.evict);Gf.clear(),Yf=t&&t>0?t:1e4}static _warmBootStats(){let t=0,e=0;const i=[];for(const s of Gf.values())for(const n of s)t++,n.dlg&&(e++,i.push(n.dlg.kind));return{keys:Gf.size,slots:t,dlgs:e,drafts:i}}setConfig(t){const e=this._config,i=!!e&&Object.prototype.hasOwnProperty.call(e,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...t};(i!==this._hasFixedFloor||e?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&t.default_floor&&this._commitSpace(t.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(Zf)||"{}")||{}}catch{this._zoomBySpace={}}try{const t=JSON.parse(localStorage.getItem(ev)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(t).filter(t=>"flat"===t[1]||"iso"===t[1]))}catch{this._viewPreference={}}this._labs=Kg(Nf);try{const t=JSON.parse(localStorage.getItem(tv)||"null");this._kioskScale={icon:Es(t?.icon),font:Es(t?.font)}}catch{}try{const t=JSON.parse(localStorage.getItem(Xf)||"null");t&&t.config&&Array.isArray(t.config.spaces)&&(this._serverCfg=t.config,this._cfgEpoch++,this._cfgRev=t.rev||0,this._cfgContentFingerprint=t.config_fingerprint||wd(t.config),this._layout=t.layout||{},this._layoutRev=t.layout_rev||0,this._layoutContentFingerprint=t.layout_fingerprint||wd(this._layout),this._virtualLights=mn(t.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1)}_warmAdopt(){if(this._config?.kiosk)return;const t=Kf(this._config);if(this._warmKey===t&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const e=this.parentNode,i=this._warmIdx(e),s=Gf.get(t);if(!s||!s.length)return;const n=s.find(t=>t.owner===this._warmGen);if(n)return this._warmLongReturn=!!n.freed&&Date.now()-n.freed>=md,clearTimeout(n.evict),n.evict=0,n.freed=0,n.live=!0,this._warmSlot=n,this._warmKey=t,n.frameFingerprint&&this._continuity.adoptCompleteFrame(n.frameFingerprint),void(!this._devices.length&&n.devices?.length&&(this._devices=[...n.devices]));const{slot:o,sure:a}=((t,e,i,s)=>{const n=t=>{const e=!!i&&t.place?.deref()===i;return e&&t.idx===s?4:t.live?0:e?3:2};let o=null,a=0,r=0,l=null;for(const i of t){if(i.owner===e)continue;l=i;const t=n(i);t<=0||(t>a?(o=i,a=t,r=1):t===a&&r++)}return!o||r>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(s,this._warmGen,e,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=md,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),this._warmKey=t,a?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=e?new WeakRef(e):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},s.push(this._warmSlot),this._warmTrim(s)))}_warmIdx(t){const e=t?.children;if(!e)return-1;for(let t=0;t4;){const e=t.findIndex(t=>!t.live);if(e<0)break;clearTimeout(t[e].evict),t.splice(e,1)}}_warmScheduleEvict(t,e){if(clearTimeout(t.evict),!(t.dlg||t.vp&&"view"!==t.vp.mode))return;const i=t.freed,s=t.owner;t.evict=window.setTimeout(()=>{if(t.evict=0,t.freed!==i||t.owner!==s)return;var n;t.dlg=null,t.vp=(n=t.vp)&&"view"!==n.mode?{...n,mode:"view",zoom:n.snap?.space===n.space?n.snap.zoom:n.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:n,t.frameFingerprint="";const o=Gf.get(e);if(!t.live&&o&&o.length>1){const e=o.indexOf(t);e>=0&&o.splice(e,1)}},Yf+250)}_warmAdoptViewport(t){const e=this._warmVp;if(!e||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(t=>t.id===e.space)||"valid"===i.kind&&i.id!==e.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(e.space,!0),this._navApplied=!0,this._adoptMode("view"!==e.mode&&this._canEdit&&!t.kiosk?e.mode:"view"),this._pendingNavMode="view"===e.mode||this._canEdit||t.kiosk?null:e.mode,this._zoom=e.zoom;const s=this._effectiveProjection(),n=s===e.projection&&this._labsIso===e.activeLabsIso;if(this._view=n&&e.view?{...e.view}:null,this._viewModeSnap=n&&e.snap?{...e.snap}:null,!n&&e.logicalCenter){const t="iso"===s?Xg([e.logicalCenter.x,e.logicalCenter.y],0):[e.logicalCenter.x,e.logicalCenter.y];this._applyView(e.zoom,t[0],t[1])}var o;this._tool="opening"===(o=function(t){return"partition"===t?"draw":t}(o=e.tool))?"draw":"string"==typeof o&&av.has(o)?o:"draw",this._decorTool=e.decorTool,this._showHidden=e.showHidden,this._showFar!==e.showFar&&(this._showFar=e.showFar,this._frame=null),this._selId=e.selId,this._rszSel=e.rszSel,this._decorSel=e.decorSel,this._warmVpArmed=!0}_warmPatch(t,e=!1){if(this._config?.kiosk)return;const i=Kf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!e)return;const t=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:this._warmIdx(t),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const s=Gf.get(i)||[];for(s.push(this._warmSlot),Gf.set(i,s),this._warmTrim(s);Gf.size>8;){const t=Gf.keys().next().value;if(void 0===t||t===i)break;for(const e of Gf.get(t)||[])clearTimeout(e.evict);Gf.delete(t)}}Object.assign(this._warmSlot,t)}}_warmViewportState(){const t=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:t,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(t),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._rszSel,decorSel:this._decorSel}}_warmDialogState(){const t=(t,e)=>({kind:t,space:this._space,mode:this._mode,data:e});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?t("openingInfo",this._openingInfo.id):this._infoCard?t("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:t("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:t("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:t("marker",this._markerDialog):this._openingDialog?t("opening",this._openingDialog):this._backdropDialog?t("backdrop",this._backdropDialog):this._decorShapeDialog?t("decorShape",this._decorShapeDialog):this._decorTextDialog?t("decorText",this._decorTextDialog):this._roomDialog?t("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:t("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const t={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices};if(this._warmRevivePending||(t.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const e=this.parentNode;t.place=e?new WeakRef(e):null,t.idx=this._warmIdx(e)}this._warmPatch(t)}_warmReviveDialog(){this._warmRevivePending=!1;const t=this._warmSlot;if(this._warmReviveTimer=void 0,!t||!t.dlg)return;const e=t.dlg,i=t.freed;if(t.dlg=null,t.freed=0,clearTimeout(t.evict),t.evict=0,i&&!(Date.now()-i>Yf)&&e.space===this._space&&e.mode===this._mode){switch(e.kind){case"space":this._spaceDialog={...e.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...e.data,busy:!1};break;case"settings":this._settingsDialog={...e.data,busy:!1};break;case"rules":this._rulesDialog={...e.data,busy:!1};break;case"opening":this._openingDialog={...e.data};break;case"backdrop":this._backdropDialog={...e.data};break;case"decorShape":this._decorShapeDialog={...e.data};break;case"decorText":{this._decorTextDialog={...e.data};const t=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:t,end:t};break}case"room":{const t=e.data;this._roomEditId=t.editId,this._roomFill=t.fill,this._roomCustomFill=t.customFill||null,this._roomTempSrc=t.tempSrc,this._roomHumSrc=t.humSrc,this._roomSrcOpen=t.srcOpen,this._roomSrcFilter=t.srcFilter,this._roomNameScale=t.nameScale,this._roomLabelScale=t.labelScale,this._areaSel=t.areaSel,this._nameSel=t.nameSel,this._pendingSplit=t.pendingSplit,this._wallFaceBatch=t.wallFaceBatch||null,this._path=t.path,this._wallFaceBatch&&(this._activeDraftId=this._wallFaceBatch.activeDraftId,this._draftSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const t=this._devices.find(t=>t.id===e.data);t&&(this._infoCard=t);break}case"openingInfo":{const t=(this._curSpaceCfg?.openings||[]).find(t=>t.id===e.data);t&&(this._openingInfo=t);break}}this.requestUpdate()}}_cacheSnapshot(){if(this._serverCfg)try{this._cfgContentFingerprint=wd(this._serverCfg),this._layoutContentFingerprint=wd(this._layout),this._virtualLights=function(t,e,i){if(t.configRev===i)return t;const s=new Set((Array.isArray(e?.markers)?e.markers:[]).filter(yn).map(t=>t.id));return{...t,configRev:i,off:new Set([...t.off].filter(t=>s.has(t)))}}(this._virtualLights,this._serverCfg,this._cfgRev),localStorage.setItem(Xf,JSON.stringify({config:this._serverCfg,rev:this._cfgRev,config_fingerprint:this._cfgContentFingerprint,layout:this._layout,layout_rev:this._layoutRev,layout_fingerprint:this._layoutContentFingerprint,virtual_lights:fn(this._virtualLights)}))}catch{}}_beginContinuityCandidate(t,e,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=e,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(t,i))}_continuityStageValid(){const t=this._stageEl;return!!t&&t.clientWidth>0&&t.clientHeight>0}_continuityAssetsReady(){if(!this._model.length)return!1;const t=this._model.length?this._spaceModel():null;return!t?.bg?.href||this._signer.isReady(this.hass,t.bg.href)}_initialSpaceSelection(t,e=this._loadOk){const i=this._fixedFloorState(t,e);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(t){const e=new Set(t.spaceIds.filter(t=>!!t));if(!e.size)return{id:null,source:"none"};const i=[["hash",!1===t.acceptHash?null:t.hashSpace],["current",t.preserveCurrent?t.currentSpace:null],["saved",t.savedSpace],["default",t.defaultSpace],["first",t.spaceIds[0]]];for(const[t,s]of i)if(s&&e.has(s))return{id:s,source:t};return{id:null,source:"none"}}({spaceIds:t.map(t=>t.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(t,e=this._loadOk){const i=this._initialSpaceSelection(t,e);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(t,e=this._space){const i=Sh(t),s=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==s.kind)return"";const n=this._initialSpaceSelection(i,!0).id||(i.some(t=>t.id===e)?e:i[0]?.id);return i.find(t=>t.id===n)?.bg?.href||""}_visualFrameFingerprint(){const t=this._stageEl,e=t?[t.clientWidth,t.clientHeight]:[0,0];return kd([this._cfgRev,this._cfgContentFingerprint||wd(this._serverCfg),this._layoutRev,this._layoutContentFingerprint||wd(this._layout),this._space,this._mode,this._view,e,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const t=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==t)return this._stagedDeviceSnapshotToken=t,void this.requestUpdate();this._continuityPaintToken!==t&&(this._continuityPaintToken=t,this._continuity.candidateReady(t)&&this._continuity.commitAfterPaint(t,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(e=>{e&&t===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):t===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(t,e){this._signer.markLoaded(this.hass,t,e),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const t="connection"===this._continuity.recoveryReason;return W`
t.stopPropagation()} @click=${t=>t.stopPropagation()} @@ -4983,7 +4983,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="d77b8f7b11118fb07d4858dfe45d94e740fd style="left:${r.toFixed(1)}%;top:${l.toFixed(1)}%" @click=${t=>{t.stopPropagation(),this._fitAll()}}> - `}_stageAspect(){const t=this._stageEl,e=this._baseVb();return t&&t.clientHeight?t.clientWidth/t.clientHeight:e[2]/e[3]}_viewOr(t){return this._view&&this._view.w?this._view:Ni(t,this._stageAspect())}_roomLabelReferenceViewWidth(t){if(!this._markup)return t.w;const e=this._stageEl,i=this.renderRoot.querySelector(".editorchrome");if(!e||e.clientWidth<=0||e.clientHeight<=0)return t.w;const s=e.clientHeight+(i?.getBoundingClientRect().height||0);return s<=0?t.w:this._viewForModeTarget(this._zoom,void 0,void 0,e.clientWidth,s).w}_screenToVb(t,e){const i=this._stageEl,s=this._viewOr(this._baseVb()),n=i?.clientWidth||1,o=i?.clientHeight||1;return[s.x+t/n*s.w,s.y+e/o*s.h]}_clampView(t,e){const i=(t,e,i,s)=>{const n=1*Math.max(e,s),o=i-n,a=i+s-e+n;return Math.max(Math.min(o,a),Math.min(Math.max(o,a),t))};return{w:t.w,h:t.h,x:i(t.x,t.w,e.x,e.w),y:i(t.y,t.h,e.y,e.h)}}_applyView(t,e,i){const s=this._baseVb(),n=Ni(s,this._stageAspect()),o=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),a=n.w/o,r=n.h/o,l=this._viewOr(s),c=e??l.x+l.w/2,h=i??l.y+l.h/2,d=this._clampView({x:c-a/2,y:h-r/2,w:a,h:r},n);return!(this._view&&Math.abs(this._zoom-o)<1e-9&&Math.abs(this._view.x-d.x)<1e-6&&Math.abs(this._view.y-d.y)<1e-6&&Math.abs(this._view.w-d.w)<1e-6&&Math.abs(this._view.h-d.h)<1e-6)&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=o,this._view=d,!0)}_bootWatch(){clearTimeout(this._bootTimer),this._bootStart=Date.now(),this._bootLastH=-1,this._bootLastChange=this._bootStart;const t=()=>{if(!this._booting)return;const e=Date.now(),i=this._stageEl?this._stageEl.clientHeight:0;i!==this._bootLastH&&(this._bootLastH=i,this._bootLastChange=e);const s=e-this._bootStart;s>=1200||s>=700&&i>0&&e-this._bootLastChange>=250?this._bootSettled():this._bootTimer=window.setTimeout(t,100)};this._bootTimer=window.setTimeout(t,100)}_bootSettled(){this._booting&&!this._bootSettling&&(this._bootSettling=!0,this._refitView(),this._bootSettleRaf=requestAnimationFrame(()=>{this._bootSettleRaf=0,this._finishBootSettled()}))}_finishBootSettled(){if(!this._booting)return;this._refitView(),this._booting=!1,this._bootSettling=!1;const t=this._stageEl?.clientHeight??0;!this._config?.kiosk&&t>0&&this._warmPatch({hdrH:this._hdrH,stageH:t,vp:this._warmViewportState()},!0),this._bootFading=!0,this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220),this._bootSoft=!0,clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)}_bootSoftCancel(){this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoft=!1)}_beginResumeSettle(){this._booting||this._resumeSettling||(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0),this._viewportInvalidAt=0,this._beginContinuityCandidate("warm-resume",!1),this._loading?this.requestUpdate():this._loadFromServer())}_refitView(){if(this._modeTransitionBusy)return;const t=this._stageEl;if(!t||"visible"!==document.visibilityState||t.clientWidth<=0||t.clientHeight<=0)return void(this._viewportInvalidAt||(this._viewportInvalidAt=Date.now()));const e=[t.clientWidth,t.clientHeight],i=this._lastValidStageSize,s=!!i&&Math.abs(i[0]-e[0])<=.5&&Math.abs(i[1]-e[1])<=.5,n=this._viewportInvalidAt?Date.now()-this._viewportInvalidAt:0;if(this._viewportInvalidAt=0,!i)return this._lastValidStageSize=e,void(this._view||this._applyView(this._zoom));s?this._pendingRefitSize=null:(this._pendingRefitSize=e,this._refitRaf||(this._refitRaf=requestAnimationFrame(()=>{this._refitRaf=0;const t=this._pendingRefitSize;this._pendingRefitSize=null;const e=this._stageEl;if(!t||!e||e.clientWidth<=0||e.clientHeight<=0)return;if(Math.abs(e.clientWidth-t[0])>.5||Math.abs(e.clientHeight-t[1])>.5)return void this._refitView();const i=this._lastValidStageSize;if(i&&Math.abs(i[0]-t[0])<=.5&&Math.abs(i[1]-t[1])<=.5)return;this._lastValidStageSize=t;const s=this._view;n>=md?this._beginContinuityCandidate("stage-size-restored",!0,"stage-size"):this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._applyView(this._zoom,s?s.x+s.w/2:void 0,s?s.y+s.h/2:void 0)})))}_zoomAt(t,e,i){const s=this._stageEl;if(!s)return;const n=Ni(this._baseVb(),this._stageAspect()),o=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,i));"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1));const a=s.clientWidth,r=s.clientHeight,l=this._screenToVb(t,e),c=n.w/o,h=n.h/o;this._zoom=o,this._view=this._clampView({x:l[0]-t/a*c,y:l[1]-e/r*h,w:c,h:h},n)}_onWheel(t){const e=this._stageEl;if(!e)return;t.preventDefault();const i=e.getBoundingClientRect(),s=t.deltaY<0?1.15:1/1.15;this._zoomAt(t.clientX-i.left,t.clientY-i.top,this._zoom*s),this._saveZoom()}_stepZoom(t){const e=this._stageEl;e&&(this._zoomAt(e.clientWidth/2,e.clientHeight/2,this._zoom*(t>0?1.4:1/1.4)),this._saveZoom())}_resetZoom(){const t=this._baseVb();"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=1,this._view=Ni(t,this._stageAspect()),this._saveZoom()}_saveZoom(){if("view"===this._mode){this._zoomBySpace={...this._zoomBySpace,[this._space]:this._zoom};try{localStorage.setItem(Zf,JSON.stringify(this._zoomBySpace))}catch{}}}_restoreZoom(){const t=this._zoomBySpace[this._space]||1;this._zoom=t;const e=this._stageEl;if(e&&e.clientHeight){const e=this._baseVb();return this._applyView(t,e[0]+e[2]/2,e[1]+e[3]/2),void this.requestUpdate()}this._view=null,requestAnimationFrame(()=>{if(!this._stageEl)return;const e=this._baseVb();this._applyView(t,e[0]+e[2]/2,e[1]+e[3]/2),this.requestUpdate()})}_stagePointerDown(t){if(this._vacFit)return;if(this._kiosk&&(this._cyclePausedUntil=Date.now()+6e4,0===this._pointers.size?(this._swipeStart={x:t.clientX,y:t.clientY,id:t.pointerId},t.target.closest?.(".dev, .roomlabel, .oplock")||(clearTimeout(this._kioskHoldTimer),this._kioskHoldTimer=window.setTimeout(()=>{this._kioskDialog=!0,this._swipeStart=null},3e3))):(this._swipeStart=null,clearTimeout(this._kioskHoldTimer))),this._drag)return;if(this._markup&&t.target.closest?.(".roomlabel, .rlhandle, .rszhandle, .dev, .oplock, .op-hit, button"))return;if("devices"===this._mode&&t.target.closest(".dev"))return;if("decor"===this._mode&&this._decorPointerDown(t))return;this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY});const e=this._viewOr(this._baseVb());if(1===this._pointers.size)this._panStart={sx:t.clientX,sy:t.clientY,vx:e.x,vy:e.y},this._panLock=null,this._suppressClick=!1;else if(2===this._pointers.size){"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const t=[...this._pointers.values()],e=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y);this._pinchStart={dist:e,zoom:this._zoom},this._panStart=null,this._panLock=null}}get _swipeZone(){return!this._hasFixedFloor&&this._kiosk&&this._zoom<=1.001&&this._model.length>1}_stagePointerMove(t){if(this._physicalRotate?.pid!==t.pointerId)if(this._physicalDrag?.pid!==t.pointerId)if(this._dtDrag?.pid!==t.pointerId)if(this._bdDrag?.pid!==t.pointerId){if(this._decorDraft?.pid===t.pointerId){const e=this._decorDraft;let i=this._decorSnap(this._svgPoint(t),t.pointerType);if(t.shiftKey&&("rect"===e.kind||"ellipse"===e.kind)){const t=i[0]-e.a[0],s=i[1]-e.a[1],n=Math.max(Math.abs(t),Math.abs(s));i=this._snap([e.a[0]+(t<0?-n:n),e.a[1]+(s<0?-n:n)])}return void(this._decorDraft={...e,b:i})}if(this._decorMove?.pid!==t.pointerId)if(this._pointers.has(t.pointerId)){if(this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this._markup&&1===this._pointers.size&&this._markupMove(t),this._pinchStart&&this._pointers.size>=2){"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const t=[...this._pointers.values()],e=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y)/(this._pinchStart.dist||1),i=this._stageEl.getBoundingClientRect(),s=(t[0].x+t[1].x)/2-i.left,n=(t[0].y+t[1].y)/2-i.top;this._zoomAt(s,n,this._pinchStart.zoom*e),this._suppressClick=!0,this._saveZoom()}else if(this._panStart){const e=t.clientX-this._panStart.sx,i=t.clientY-this._panStart.sy;Math.abs(e)+Math.abs(i)>4&&(this._suppressClick=!0,clearTimeout(this._holdTimer),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover()),null===this._panLock&&Math.abs(e)+Math.abs(i)>8&&(this._panLock=this._swipeZone&&Math.abs(e)>1.5*Math.abs(i)?"swipe":"pan");const s=this._stageEl;if("pan"===this._panLock&&s){const t=this._baseVb(),n=this._viewOr(t),o=Ni(t,this._stageAspect());this._view=this._clampView({x:this._panStart.vx-e/(s.clientWidth||1)*n.w,y:this._panStart.vy-i/(s.clientHeight||1)*n.h,w:n.w,h:n.h},o)}}}else this._markupMove(t);else this._decorMoveUpdate(t)}else this._bdMove(t);else this._dtMove(t);else this._physicalMove(t);else this._physicalRotateMove(t)}_stagePointerLeave(t){this._markup&&("opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover())}_stagePointerUp(t){if(this._kiosk){clearTimeout(this._kioskHoldTimer);const e=this._swipeStart;if(this._swipeStart=null,e&&e.id===t.pointerId){const i=t.clientX-e.x,s=t.clientY-e.y;if(Math.abs(i)+Math.abs(s)<8){const t=Date.now();t-this._lastTap<350&&this._resetZoom(),this._lastTap=t}const n="pan"===this._panLock?null:function(t,e,i,s,n,o=60){if(i>1.001||s.length<2)return null;if(Math.abs(t)t.id),this._space);n&&this._slideTo(n,i<0?"left":"right")&&(this._saveNav(),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._showKioskDots())}}if(this._physicalDrag?.pid===t.pointerId)return void this._physicalUp(t);if(this._physicalRotate?.pid===t.pointerId)return void this._physicalRotateUp(t);if(this._dtDrag?.pid===t.pointerId)return void this._dtUp();if(this._bdDrag?.pid===t.pointerId)return void this._bdUp();if(this._decorDraft?.pid===t.pointerId)return void this._decorCommitDraft();if(this._decorMove?.pid===t.pointerId)return this._decorMove.moved&&(this._recordGeometry(this._t("history.decor_move"),this._decorMove.before),this._saveConfig()),void(this._decorMove=null);const e=!!this._pinchStart||!!this._panStart;this._pointers.delete(t.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,setTimeout(()=>this._suppressClick=!1,0)),e&&0===this._pointers.size&&this.requestUpdate()}_clickRoom(t){!this._suppressClick&&t.area&&cv("/config/areas/area/"+t.area)}_pointerDown(t,e){if("plan"===this._mode)return;if("view"===this._mode){this._holdFired=!1,clearTimeout(this._holdTimer);const i=t.pointerId,s=t.currentTarget;return void(this._holdTimer=window.setTimeout(()=>{this._holdFired=!0,this._interruptViewGesture(i,s),this._infoCard=e},600))}if("ha_disabled"===e.bindingStatus?.kind)return;t.preventDefault();const i=this._pos(e);this._drag={id:e.id,sx:t.clientX,sy:t.clientY,ox:i.x,oy:i.y,moved:!1},dv(t),this._tip=null}_pointerMove(t,e){if(!this._drag||this._drag.id!==e.id)return;const i=this.renderRoot.querySelector(".stage");if(!i)return;const s=this._baseVb(),n=i.getBoundingClientRect(),o=this._viewOr(s),a=(t.clientX-this._drag.sx)/n.width*o.w,r=(t.clientY-this._drag.sy)/n.height*o.h;Math.abs(t.clientX-this._drag.sx)+Math.abs(t.clientY-this._drag.sy)>3&&(this._drag.moved=!0,clearTimeout(this._holdTimer));const l=Ah(this._drag.ox+a),c=Ah(this._drag.oy+r);this._savePos(e,l,c)}_pointerUp(t,e){if(clearTimeout(this._holdTimer),!this._drag||this._drag.id!==e.id)return;const i=this._drag.moved;this._drag=i?this._drag:null,i&&(this._selId=e.id,window.setTimeout(()=>this._drag=null,0))}_showToast(t){for(const t of this.renderRoot.querySelectorAll("hp-dialog"))t.closeTransientOverlays("toast");this._toast=t,clearTimeout(this._toastTimer),this._toastTimer=window.setTimeout(()=>{this._toast=""},3500)}_syncPointerHoverTargets(){const t=this._pointerModality.hoverEnabled;for(const e of this.renderRoot.querySelectorAll(iv))e.toggleAttribute("data-pointer-hover",t)}_syncPointerHoverSubtree(t){if(t.nodeType!==Node.ELEMENT_NODE)return;const e=t,i=this._pointerModality.hoverEnabled;e.matches(iv)&&e.toggleAttribute("data-pointer-hover",i);for(const t of e.querySelectorAll(iv))t.toggleAttribute("data-pointer-hover",i)}_clearTransientHover(t=!1){t&&this._pointerModality.suspend(),this._tip&&(this._tip=null),this._hoverRoom&&(this._hoverRoom=null)}_notePointer(t){const e=this._pointerModality.modality,i=this._pointerModality.note(t);"touch"!==i&&"pen"!==i||e===i&&!this._tip&&!this._hoverRoom||this._clearTransientHover()}_guardTouchGesture(t){if(this._editorSecondary.handleOutsideDismiss(t))return;if("click"===t.type){if(!this._suppressClick&&!this._touchSequenceMultitouch&&Date.now()>this._touchClickBlockUntil)return;return t.preventDefault(),void t.stopImmediatePropagation()}const e=t;if(this._notePointer(e),"touch"===e.pointerType)if("pointerdown"!==t.type){if("pointermove"===t.type){const t=this._touchContacts.get(e.pointerId);if(!t)return;const i={...t,x:e.clientX,y:e.clientY};if(this._touchContacts.set(e.pointerId,i),this._touchSequenceMultitouch&&"view"===this._mode&&!this._vacFit&&this._pinchStart&&[...this._touchContacts.values()].every(t=>t.inStage)){this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const t=[...this._touchContacts.values()];if(t.length>=2&&this._stageEl){const[e,i]=t,s=Math.hypot(e.x-i.x,e.y-i.y)/(this._pinchStart.dist||1),n=this._stageEl.getBoundingClientRect();this._zoomAt((e.x+i.x)/2-n.left,(e.y+i.y)/2-n.top,this._pinchStart.zoom*s),this._saveZoom()}}return}if("pointerup"===t.type||"pointercancel"===t.type||"lostpointercapture"===t.type){if(this._clearTransientHover(),this._touchContacts.delete(e.pointerId),this._touchSequenceMultitouch){if(this._touchClickBlockUntil=Date.now()+500,this._pointers.delete(e.pointerId),!this._vacFit&&this._pointers.size>=2){const[t,e]=[...this._pointers.values()];this._pinchStart={dist:Math.hypot(t.x-e.x,t.y-e.y),zoom:this._zoom}}else this._pinchStart=null;0===this._pointers.size&&(this._panStart=null,this._panLock=null)}0===this._touchContacts.size&&(this._touchSequenceMultitouch=!1)}}else if(this._touchContacts.set(e.pointerId,{x:e.clientX,y:e.clientY,inStage:!!e.target?.closest?.(".stage")}),this._touchContacts.size>=2){this._clearTransientHover(),this._touchSequenceMultitouch=!0,this._touchClickBlockUntil=Number.POSITIVE_INFINITY,clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),this._swipeStart=null;const t=[...this._touchContacts.values()];if("view"===this._mode&&!this._vacFit&&t.every(t=>t.inStage)){this._pointers=new Map([...this._touchContacts].map(([t,e])=>[t,{x:e.x,y:e.y}]));const[e,i]=t;this._pinchStart={dist:Math.hypot(e.x-i.x,e.y-i.y),zoom:this._zoom},this._panStart=null,this._panLock=null}else this._vacFit&&(this._pointers.clear(),this._pinchStart=null,this._panStart=null,this._panLock=null)}}_showTip(t,e,i,s,n,o){this._notePointer(t),this._pointerModality.hoverEnabled&&(this._drag||(this._tip={x:t.clientX,y:t.clientY,title:e,meta:i,lqi:s,temp:n,hum:o}))}get _gridPitch(){return Ph}get _cellCm(){const t=Number(this._curSpaceCfg?.cell_cm);return Number.isFinite(t)&&t>0?t:5}_fmtLen(t,e){const i=function(t,e,i,s){return Math.hypot(e[0]-t[0],e[1]-t[1])/i*s}(t,e,this._gridPitch,this._cellCm);return li(i,"mi"===this.hass?.config?.unit_system?.length)}get _curSpaceCfg(){const t=this._rszPreview;return t&&t.space===this._space?t.sp:this._serverCfg?.spaces.find(t=>t.id===this._space)}get _renderCfg(){const t=this._rszPreview;return t&&this._serverCfg?{...this._serverCfg,spaces:this._serverCfg.spaces.map(e=>e.id===t.space?t.sp:e)}:this._serverCfg}get _spaceH(){return this._curSpaceCfg,sv}get _segments(){const t=this._curSpaceCfg,e=this._spaceH;return pi(t?.rooms||[]).map(t=>[t[0]*sv,t[1]*e,t[2]*sv,t[3]*e])}_savedNav(){if(this._hasFixedFloor)return null;try{return JSON.parse(localStorage.getItem(Qf)||"null")}catch{return null}}_saveNav(){if(!this._hasFixedFloor)try{localStorage.setItem(Qf,JSON.stringify({space:this._space}))}catch{}}_leaveCardRoute(){if(this._routeDepartureHandled)return;this._routeDepartureHandled=!0,"view"!==this._mode&&this._setMode("view",!1),this._pendingNavMode=null,this._geometryHistory.clear(),this._activeDraftId=null,this._resumeDraftBySpace={},this._draftSegmentCms=[],this._closingWallCm=null,this._drawWallField=null,this._showHidden=!1,this._tapConfirm=null,this._vacCalConfirm=null,this._decorEraseConfirm=null,this._openingInfo=null,this._closeInfoCard(),this._rulesDialog=null,this._alignDialog=null,this._preflightClipboardFallback=null,this._backupImportDialog=null,this._backupExportDialog=null,this._settingsDialog=null,this._markerDialog=null,this._openingDialog=null,this._physicalDialog=null,this._wallDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._mergeDialog=null,this._roomDialog=!1,this._spaceDialog=null,this._importDialog=null;const t=this._warmSlot;t?.owner===this._warmGen&&(t.vp=this._warmViewportState(),t.dlg=null,t.frameFingerprint="",clearTimeout(t.evict),t.evict=0),this._saveNav()}_setMode(t,e=!0){this._endTabDrag(),this._pendingNavMode=null;const i=this._spaceModel();if(!i)return this._cancelModeTransition(!1),void(this._mode="view");if(this._kiosk&&"view"!==t)return;if(this._mode===t){if(!e&&"view"===t&&this._modeTransitionBusy){const e=this._currentModeVisual(t),i=this._modeTransitionTargetZoom,s=this._modeTransitionTargetCenterX,n=this._modeTransitionTargetCenterY;this._cancelModeTransition(!1),this._commitViewModeAtomic(e,i,s,n)}return}if(this._bootSoftCancel(),("plan"===t||"decor"===t)&&!this._norm)return void this._showToast(this._t("toast.markup_needs_server"));if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._clearTransientHover(!0),this._cancelDevicePressFeedback();const s=this._mode,n=this._effectiveProjection(),o=this._currentModeVisual(s),a=this._modeTransitionBusy,r=o&&"view"!==s&&"view"!==t?{...o,toolbarContentOpacity:this._reducedMotion?1:.35}:o;this._cancelModeTransition(!1),this._editorSecondary.closeForNavigation(),(this._decorMove||this._dtDrag||this._bdDrag)&&this._cancelDecorGesture();const l=!i.bg&&"view"===t!=("view"===s),c=a&&"view"===s&&"view"!==t?this._modeTransitionEditorCamera:null;let h=c?.zoom??(a?this._modeTransitionTargetZoom:this._zoom),d=c?c.centerX:a?this._modeTransitionTargetCenterX:r?.viewport.centerX,p=c?c.centerY:a?this._modeTransitionTargetCenterY:r?.viewport.centerY;if("view"===s&&"view"!==t&&!a){const e=this._view;if(this._viewModeSnap={space:this._space,zoom:this._zoom,cx:e?this._logicalViewCenter(n)?.x:void 0,cy:e?this._logicalViewCenter(n)?.y:void 0},"iso"===n){const e=this._logicalViewCenter("iso");d=e?.x,p=e?.y,this._view=null,this._mode=t,this._applyView(this._zoom,e?.x,e?.y)}l&&(h=1,d=void 0,p=void 0)}if("plan"===s&&this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._mode=t,this._editorChromeMode="view"===t?s:t,"view"===t){"view"===s||a||(this._modeTransitionEditorCamera={zoom:this._zoom,centerX:r?.viewport.centerX,centerY:r?.viewport.centerY});const t=this._viewModeSnap;if(t&&t.space===this._space){h=t.zoom;const e=this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat",i=null!=t.cx&&null!=t.cy&&"iso"===e?Xg([t.cx,t.cy],0):null;d=i?.[0]??t.cx,p=i?.[1]??t.cy}else t&&(h=this._zoomBySpace[this._space]||1,d=void 0,p=void 0)}else this._modeTransitionEditorCamera={zoom:h,centerX:d,centerY:p};this._modeTransitionTargetZoom=h,this._modeTransitionTargetCenterX=d,this._modeTransitionTargetCenterY=p,("iso"===n||"view"===t&&this._labsIso&&"iso"===this._viewPreference[this._space])&&(this._modeTransitionForceAtomic=!0);const u=++this._modeTransitionRequest;e?r?(this._modeTransitionPreparing=!0,this._modeTransitionVisual=r,this._prepareModeTransition(u,r,t,h,d,p)):(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._zoom=h,this._view=null,requestAnimationFrame(()=>{this.isConnected&&u===this._modeTransitionRequest&&this._mode===t&&(this._applyView(h,d,p),"view"===t&&(this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate())})):"view"===t&&this._commitViewModeAtomic(r,h,d,p),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._selId=null,this._physicalSel=null,this._physicalDialog=null,this._physicalDrag=null,this._rszSel=null,this._rszDrag=null,this._rszLive=null,this._rszPreview=null,this._tip=null,this._hoverRoom=null,this._decorDraft=null,this._decorSel=null,this._decorMove=null,this._backdropDialog=null,this._decorTool="select",this._bdDrag=null,this._dtDrag=null,this._dtBox=null,"plan"===t&&(this._primeDrawWallField(),this._resumeLastDraft()),this._saveNav()}_primeDrawWallField(){null===this._drawWallField&&(this._drawWallField=ml(ll,this._imperial))}get _drawWallFieldValue(){return null===this._drawWallField?ml(ll,this._imperial):this._drawWallField}get _drawWallCm(){const t=Wf(this._drawWallFieldValue);if(null==t||t<0)return null;const e=this._imperial?2.54*t:t,i="column"===this._tool?jc:100;return e>=("column"===this._tool?1:0)&&e<=i?e:null}get _drawWallMaxCm(){return"column"===this._tool?jc:100}_showPhysicalRange(t=this._drawWallMaxCm,e=0){this._showToast(this._t("toast.physical_range",{min:ml(e,this._imperial),max:ml(t,this._imperial),unit:this._t(this._imperial?"wallthick.unit_in":"wallthick.unit_cm")}))}_draftSegmentCount(t=this._curSpaceCfg){return(t?.room_drafts||[]).reduce((t,e)=>t+(Array.isArray(e.segments)?e.segments.length:0),0)}_mergeSpacePartitions(t,e){const i=t?.partitions||[];if(i.length<2)return 0;const s=nm(i,{pitch:Th,seedIds:e,geometry:am(t,{excludeDraftId:this._activeDraftId})});return s.merged?(t.partitions=s.partitions,om(t.openings,t.partitions,s.openingMoves,{coordScale:sv,cellCm:this._cellCm,gridPitch:this._gridPitch}),s.merged):0}_finishWallChain(){if("draw"!==this._tool||this._wallFaceBatch||this._roomDialog)return!0;const t=this._curSpaceCfg;if(!t||this._path.length<2)return this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._clearPlanSnapHover(),!0;const e=Zp(this._path,Xp(this._path.length-1,this._draftSegmentCms,this._drawWallCm,ll)),i=e.length;if((t.partitions||[]).length+i>rv)return this._showToast(this._t("toast.physical_limit")),!1;const s=this._geometrySnapshot();t.partitions||=[];const n=Date.now().toString(36),o=[],a=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,r=this._draftSegmentsForPath(this._path,a,e.map(t=>t.cm));for(let s=0;st.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.wall_chain_finish"),s),delete this._resumeDraftBySpace[this._space],this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._clearPlanSnapHover(),!0}_activateMarkupTool(t){t!==this._tool&&(this._wallFaceBatch&&this._roomDialogCancel(),("draw"!==this._tool||this._finishWallChain())&&(this._cancelPath(),this._tool=t,"draw"===t&&this._resumeLastDraft(),"resize"===t&&(this._rszSel=null),"wallthick"===t&&(this._wallDialog=null)))}_limitReached(t){const e=this._curSpaceCfg;if(!e)return!0;const i="draft"===t?(e.room_drafts||[]).length>=200:"partition"===t?(e.partitions||[]).length>=rv:(e.wall_columns||[]).length>=500;return i&&this._showToast(this._t("toast.physical_limit")),i}_svgPoint(t){const e=this.renderRoot.querySelector(".stage").getBoundingClientRect();return this._screenToVb(t.clientX-e.left,t.clientY-e.top)}_snap(t){const e=this._gridPitch;return[Ah(ri(t[0],e)),Ah(ri(t[1],e))]}_snapDrawPoint(t,e=!1){const i=this._path[this._path.length-1],s=e&&i?function(t,e,i,s=1/0){if(!(i>0&&t?.every(Number.isFinite)&&e?.every(Number.isFinite)))return[e[0],e[1]];const n=e[0]-t[0],o=e[1]-t[1];if(Math.abs(n)+Math.abs(o)<=1e-12)return[t[0],t[1]];const a=Math.PI/4;let r=Math.atan2(o,n);r<0&&(r+=2*Math.PI);const l=Math.floor(r/a+.5)%8,[c,h]=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]][l],d=c*c+h*h;let p=Math.max(0,Math.round((n*c+o*h)/(i*d)));if(Number.isFinite(s)&&s>=0){const e=(t,e)=>{if(!e)return 1/0;const n=e>0?s-t:t+s;return Math.max(0,Math.floor((n+1e-9*i)/i))};p=Math.min(p,e(t[0],c),e(t[1],h))}return[t[0]+c*p*i,t[1]+h*p*i]}(i,t,this._gridPitch,Ch):t;return this._snap(s)}_planSnapOpeningCuts(t,e){if(!this._openingsR.length)return[];const i=this._openingWallIndexFor(t,e).value,s=[];for(const e of this._roomWallOpeningInputs(this._openingsR,t)){const t=Lc(i,e);if(!t.negative&&!t.positive)continue;const n=e.angle*Math.PI/180,o=Math.cos(n)*e.length/2,a=Math.sin(n)*e.length/2;s.push([e.x-o,e.y-a,e.x+o,e.y+a])}return s}_planSnapGeometrySnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|empty`,value:{segments:[],endpoints:[]}};const e=[this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._planSnapGeometryCache?.key===e)return this._planSnapGeometryCache;const i=this._openCuts(),s=Wp({space:t,activeDraftId:this._activeDraftId,roomCuts:this._planSnapOpeningCuts(t,i),partitionCuts:this._partitionOpeningCuts(t),epsilon:2e-4*this._gridPitch});return this._planSnapGeometryCache={key:e,value:s},this._planSnapGeometryCache}_hiddenWallDiagnosticSnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|hidden-empty`,value:{segments:[],endpoints:[]}};const e=["hidden",this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._hiddenWallDiagnosticCache?.key===e)return this._hiddenWallDiagnosticCache;const i=qp({space:t,activeDraftId:this._activeDraftId,epsilon:2e-4*this._gridPitch});return this._hiddenWallDiagnosticCache={key:e,value:i},this._hiddenWallDiagnosticCache}_planStructuralGeometrySnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|structural-empty`,value:{segments:[],endpoints:[]}};const e=["structural",this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._planStructuralGeometryCache?.key===e)return this._planStructuralGeometryCache;const i=Wp({space:t,activeDraftId:this._activeDraftId,epsilon:2e-4*this._gridPitch});return this._planStructuralGeometryCache={key:e,value:i},this._planStructuralGeometryCache}_planSnapContextKey(t){const e=this._path[0],i=this._path[this._path.length-1];return[t,this._tool,this._path.length,e?`${e[0]},${e[1]}`:"",i?`${i[0]},${i[1]}`:""].join("|")}_resolvePlanDrawPoint(t,e){const i=this._planSnapGeometrySnapshot(),s=this._path[this._path.length-1],n="draw"===this._tool&&this._path.length>=3?[{point:this._path[0],key:"closure:first-point"}]:[],o={tolerance:this._cssPxToRender(12),distinguishTolerance:this._cssPxToRender(8),gridStep:this._gridPitch,excludePoints:s?[s]:[],extraEndpoints:n,epsilon:2e-4*this._gridPitch},a=e&&s?Yp(i.value,t,{...o,anchor:s}):function(t,e,i){if(!(zp(e)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=i.excludePoints||[],o=Vp(Gp(t,e,i),i.distinguishTolerance||0);if(o)return o;let a=null;for(const o of t.segments){const t=[o.a[0],o.a[1],o.b[0],o.b[1]],r=Ls([e[0],e[1]],t);if(r>i.tolerance)continue;const l=Kp(o,e,i.gridStep);!jp(l,n,s)&&Up(r,o.key,a)&&(a={kind:"line",point:l,key:o.key,distance:r,segment:o})}return a?{kind:"resolved",candidate:a,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}(i.value,t,o),r="resolved"===a.kind?a.candidate:null,l=r?[...r.point]:this._snapDrawPoint(t,e),c=s?ua(s,l):l;return{point:c,candidate:r&&fi(c,r.point)?r:null,conflicts:"ambiguous"===a.kind?a.conflicts:[],ambiguous:"ambiguous"===a.kind,contextKey:this._planSnapContextKey(i.key)}}get _activePlanSnapCandidate(){if(!this._markup||"draw"!==this._tool)return null;const t=this._planSnapHover;if(!t)return null;const e=this._planSnapGeometrySnapshot();return t.contextKey===this._planSnapContextKey(e.key)?t.candidate:null}get _activePlanSnapConflicts(){if(!this._markup||"draw"!==this._tool)return[];const t=this._planSnapHover;if(!t)return[];const e=this._planSnapGeometrySnapshot();return t.contextKey===this._planSnapContextKey(e.key)?t.conflicts:[]}_clearPlanSnapHover(t=!0){this._planSnapHover=null,this._syncPlanSnapActiveMarker(null),this._syncPlanSnapConflictMarkers([]),t&&(this._cursorPt=null)}_samePt(t,e){return fi(t,e)}_dropLegacySegments(){for(const t of this._serverCfg?.markers||[])"ripple"===t.display&&(t.display="icon_ripple");for(const t of this._serverCfg?.spaces||[]){delete t.segments;const e=new Set,i=t=>"string"==typeof t&&t.length>=1&&t.length<=64&&!e.has(t),s=t=>(e.add(t),!0),n=t=>Array.isArray(t)&&2===t.length&&t.every(t=>Number.isFinite(Number(t))&&Math.abs(Number(t))<=Mh);if(Array.isArray(t.partitions)&&(t.partitions=t.partitions.filter(t=>t&&i(t.id)&&n(t.a)&&n(t.b)&&Math.hypot(t.a[0]-t.b[0],t.a[1]-t.b[1])>1e-9&&s(t.id)).map(t=>({...t,cm:Number.isFinite(Number(t.cm))?Math.max(0,Math.min(100,Number(t.cm))):15})),t.partitions.length||delete t.partitions),Array.isArray(t.wall_columns)&&(t.wall_columns=t.wall_columns.filter(t=>t&&i(t.id)&&n(t.center)&&s(t.id)).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[Number(t.center[0]),Number(t.center[1])],cm:Gc(Number(t.cm)||15),..."circle"===t.shape?{}:{angle:Vc(t.angle)}})),t.wall_columns.length||delete t.wall_columns),Array.isArray(t.room_drafts)&&(t.room_drafts=t.room_drafts.filter(t=>t&&i(t.id)&&Array.isArray(t.points)&&t.points.length>=2&&t.points.every(n)&&s(t.id)).map(t=>{const e=Fm(t);return{id:t.id,...e}}).filter(t=>t.points.length>=2),t.room_drafts.length||delete t.room_drafts),Array.isArray(t.walls)){const e=Sd(Sh({spaces:[t]}),t.id),i=e?g_(t,e,sv,.02*Ph).contour.map(t=>t.map(t=>t/sv)):ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]);t.walls=Tl(t.walls,t.rooms||[],Th,1,i),t.walls.length||delete t.walls}}}_rollbackRejectedPhysicalWrites(t){if(!this._serverCfg||!t.length)return!1;let e=!1;for(const[i]of t){const t=this._pendingPhysicalWrites.get(i);t&&(e=this._restoreGeometryStateInConfig(this._serverCfg,t.before)||e,this._pendingPhysicalWrites.delete(i))}return!!e&&(this._clearGeometryGesture(),this._geometryHistory.clear(),this._cfgEpoch++,this._modelCache=null,this._wallUnionCache=null,this._physicalBodiesCache=null,this._frame=null,this._regSignature="",this._cfgContentFingerprint=wd(this._serverCfg),this._maybeRebuildDevices(),this.requestUpdate(),!0)}async _reloadRejectedPhysicalWrite(){const t=this._writeChain;await t.catch(()=>{}),await this._reloadConfigOnly(!0)}get _cfgWriting(){return this._writesPending>0}_writeConfig(){var t,e;this._writesPending++,this._writeChain=(t=this._writeChain,e=async()=>{if(!this._serverCfg)return;this._dropLegacySegments();const t=rl(Gr(this._serverCfg)),e=wd(t),i=[...this._pendingPhysicalWrites.entries()];for(const[e,s]of i){const i=hg(t.spaces.find(t=>t.id===e));if(i===s.fingerprint)continue;let n=!1;try{n=this._checkSpacePhysicalGeometry(t,e).ok}catch{n=!1}if(!n)throw this._restoreGeometryStateLocal(s.before),this._pendingPhysicalWrites.delete(e),this._geometryHistory.clear(),this._showToast(this._t("toast.geometry_unsafe")),Object.assign(new Error("unsafe wall geometry"),{code:"geometry-unsafe"});s.fingerprint=i}let s;e!==wd(this._serverCfg)&&(this._serverCfg=t),this._cfgContentFingerprint=e;try{s=await this.hass.callWS({type:"houseplan/config/set",config:t,expected_rev:this._cfgRev})}catch(t){if(!this._rollbackRejectedPhysicalWrites(i))throw t;const e=t&&"object"==typeof t?t:Object.assign(new Error(String(t)),{cause:t});throw e.physicalGeometryRolledBack=!0,e}this._cfgRev=s?.rev??this._cfgRev+1;for(const[t,e]of i)this._pendingPhysicalWrites.get(t)?.fingerprint===e.fingerprint&&this._pendingPhysicalWrites.delete(t)},t.catch(()=>{}).then(e));return this._writeChain.finally(()=>{this._writesPending--})}_saveConfig(){this._cfgEpoch++,this._saveConfigDebounced()}_geometrySnapshotFromConfig(t,e){const i=t?.spaces?.find(t=>t.id===e);if(!i)return null;const s=t=>JSON.parse(JSON.stringify(t)),n={};for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])void 0!==i[t]&&(n[t]=i[t]);return{spaceId:e,rooms:s(i.rooms||[]),...Array.isArray(i.openings)?{openings:s(i.openings)}:{},...Array.isArray(i.walls)?{walls:s(i.walls)}:{},...Array.isArray(i.wall_segments)?{wall_segments:s(i.wall_segments)}:{},...Array.isArray(i.open_spans)?{open_spans:s(i.open_spans)}:{},...Array.isArray(i.room_drafts)?{room_drafts:s(i.room_drafts)}:{},...Array.isArray(i.partitions)?{partitions:s(i.partitions)}:{},...Array.isArray(i.wall_columns)?{wall_columns:s(i.wall_columns)}:{},...Array.isArray(i.decor)?{decor:s(i.decor)}:{},plan_transform:n}}_geometrySnapshot(t=this._space){return this._geometrySnapshotFromConfig(this._serverCfg,t)}_recordGeometry(t,e){if(!e)return;const i=this._geometrySnapshot(e.spaceId);i&&JSON.stringify(e)!==JSON.stringify(i)&&(this._geometryHistory.push({name:t,before:e,after:i}),this.requestUpdate())}_restoreGeometryStateInConfig(t,e,i=!1){const s=t?.spaces?.find(t=>t.id===e.spaceId);if(!s)return!1;const n=t=>JSON.parse(JSON.stringify(t)),o=new Map((s.rooms||[]).map(t=>[t.id,t]));if(s.rooms=n(e.rooms),i)for(const t of s.rooms){const e=o.get(t.id);!Array.isArray(t.wall_ids)&&Array.isArray(e?.wall_ids)&&e.wall_ids.length===t.poly?.length&&(t.wall_ids=n(e.wall_ids))}const a=(t,e)=>{void 0!==e?s[t]=n(e):i&&"wall_segments"===t||delete s[t]},r=new Map((s.openings||[]).map(t=>[t.id,t])),l=new Map((s.room_drafts||[]).map(t=>[t.id,t]));if(a("openings",e.openings),a("walls",e.walls),a("wall_segments",e.wall_segments),a("open_spans",e.open_spans),a("room_drafts",e.room_drafts),a("partitions",e.partitions),a("wall_columns",e.wall_columns),a("decor",e.decor),i){for(const t of s.openings||[]){const e=r.get(t.id);t.host||"wall"!==e?.host?.kind||(t.host=n(e.host))}for(const t of s.room_drafts||[]){const e=l.get(t.id);for(let i=0;i<(t.segments||[]).length;i++)!t.segments[i]?.id&&e?.segments?.[i]?.id&&(t.segments[i].id=e.segments[i].id)}}for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])delete s[t];return Object.assign(s,n(e.plan_transform||{})),!0}_restoreGeometryStateLocal(t){return!!this._restoreGeometryStateInConfig(this._serverCfg,t)&&(this._cfgEpoch++,this._modelCache=null,this._wallUnionCache=null,this._physicalBodiesCache=null,this._frame=null,this.requestUpdate(),!0)}_wallModelBlockerLabel(t){const e=t instanceof Cm?t.reason:"invalid-room";return this._t(`wall_model.reason.${e}`)}_hasLegacyZeroWallFields(t=this._serverCfg){return(t?.spaces||[]).some(t=>Array.isArray(t?.open_spans)&&t.open_spans.length>0||(t?.rooms||[]).some(t=>Array.isArray(t?.open_to)&&t.open_to.length>0))}_showWallModelMigrationBlocked(t){const e=this._hasLegacyZeroWallFields()?"toast.zero_wall_migration_blocked":"toast.wall_model_migration_blocked";this._showToast(this._t(e,{reason:this._wallModelBlockerLabel(t)}))}_commitPhysicalGeometry(t,e,i=[]){if(!e||!this._serverCfg)return!1;const s=this._serverCfg,n=this._geometrySnapshotFromConfig(s,e.spaceId),o=s.spaces.find(t=>t.id===e.spaceId);if(!o||hg(e)===hg(o))return!1;let a,r=!1;try{r=this._checkSpacePhysicalGeometry(s,e.spaceId).ok}catch{r=!1}if(!r)return this._clearGeometryGesture(),this._restoreGeometryStateLocal(e),this._showToast(this._t("toast.geometry_unsafe")),!1;let l=e;try{if(Number(s.model_version||0)<9){const t=JSON.parse(JSON.stringify(s));if(!this._restoreGeometryStateInConfig(t,e))throw new Cm("invalid-room",e.spaceId);const i=Zm(t).config;l=this._geometrySnapshotFromConfig(i,e.spaceId)||e;const o=JSON.parse(JSON.stringify(i));if(!n||!this._restoreGeometryStateInConfig(o,n,!0))throw new Cm("invalid-room",e.spaceId);const r=i.spaces.find(t=>t.id===e.spaceId),c=o.spaces.find(t=>t.id===e.spaceId);if(!Array.isArray(n.wall_segments)&&JSON.stringify(e.rooms)===JSON.stringify(n.rooms))for(const t of c?.wall_segments||[])t.cm=Pl(n.walls,t.a,t.b,Th,1);const h=((t,e,i)=>{const s=new Map,n=new Map((t?.rooms||[]).map(t=>[t.id,t])),o=new Map((e||[]).map(t=>[t.id,t])),{rooms:a}=Vm(i,Um(t));for(const t of a){const e=o.get(t.id),a=n.get(t.id),r=hi(e),l=hi((i.rooms||[]).find(e=>e.id===t.id)),c=hi(a);if(r&&l&&c&&r.length===l.length&&c.length===a?.wall_ids?.length&&t.poly.length===t.wall_ids.length)for(let e=0;e{const n=[];for(let o=0;oMm||Om(r,i,s)>Mm)continue;const l=Nm(a,i,s),c=Nm(r,i,s);l<-Mm||c>1+Mm||c<=l+Mm||n.push({start:l,id:e[o]})}return n.sort((t,e)=>t.start-e.start)},n=i(c,a.wall_ids,r[e],r[(e+1)%r.length]),o=i(t.poly,t.wall_ids,l[e],l[(e+1)%l.length]);if(n.length&&n.length===o.length)for(let t=0;tt.id===e.spaceId),s=this._path.length>=2?this._path.map(t=>[t[0]/sv,t[1]/sv]):[];s.push(...i.map(t=>[t[0],t[1]])),c=Em(t)<=Em(l,s)&&this._checkSpacePhysicalGeometry(a,e.spaceId).ok}catch{c=!1}if(!c)return this._clearGeometryGesture(),this._restoreGeometryStateLocal(e),this._showToast(this._t("toast.geometry_unsafe")),!1;tg(s,a),this._recordGeometry(t,l);const h=s.spaces.find(t=>t.id===e.spaceId),d=this._pendingPhysicalWrites.get(e.spaceId);return this._pendingPhysicalWrites.set(e.spaceId,{before:d?.before||l,fingerprint:hg(h)}),this._saveConfig(),!0}_clearGeometryGesture(){this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!1),this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._roomDeleteDialog=null,this._wallDialog=null,this._physicalDialog=null,this._physicalSel=null,this._physicalDrag=null,this._physicalRotate=null,this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._openingDialog=null,this._rszSel=null,this._rszDrag=null,this._rszPreview=null,this._rszLive=null,this._decorDraft=null,this._decorMove=null,this._dtDrag=null,this._bdDrag=null}_stagePointerCancel(t){if(clearTimeout(this._kioskHoldTimer),this._swipeStart?.id===t.pointerId&&(this._swipeStart=null),this._physicalDrag?.pid===t.pointerId||this._physicalRotate?.pid===t.pointerId)return void this._cancelPhysicalGesture();if(this._decorDraft?.pid===t.pointerId)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove?.pid===t.pointerId||this._dtDrag?.pid===t.pointerId||this._bdDrag?.pid===t.pointerId)return void this._cancelDecorGesture();"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=!!this._pinchStart||!!this._panStart;this._pointers.delete(t.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null),e&&0===this._pointers.size&&this.requestUpdate()}_applyGeometryState(t,e=!1){if(!this._canCommitSpace(t.spaceId))return!1;const i=this._geometrySnapshot(t.spaceId);if(!i||!this._restoreGeometryStateLocal(t))return!1;const s=this._serverCfg,n=hg(i)!==hg(t);if(n){let n=!1;try{const i=s?this._checkSpacePhysicalGeometry(s,t.spaceId):null;n=!!i?.ok||!(!e||"wall-degraded-extra"!==i?.reason)}catch{n=!1}if(!n)return this._restoreGeometryStateLocal(i),this._showToast(this._t("toast.geometry_unsafe")),!1}let o;try{o=Zm(s).config}catch(t){return this._restoreGeometryStateLocal(i),this._showWallModelMigrationBlocked(t),!1}if(n){let n=!1;try{const i=o?this._checkSpacePhysicalGeometry(o,t.spaceId):null;n=!!i?.ok||!(!e||"wall-degraded-extra"!==i?.reason)}catch{n=!1}if(!n)return this._restoreGeometryStateLocal(i),this._showToast(this._t("toast.geometry_unsafe")),!1;tg(s,o);const a=s?.spaces.find(e=>e.id===t.spaceId),r=this._pendingPhysicalWrites.get(t.spaceId);this._pendingPhysicalWrites.set(t.spaceId,{before:r?.before||i,fingerprint:hg(a)})}else tg(s,o);return this._clearGeometryGesture(),this._space!==t.spaceId&&(this._commitSpace(t.spaceId),this._saveNav(),this._restoreZoom()),this._modelCache=null,this._frame=null,this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate(),!0}_roomAt(t){return this._spaceModel()?.rooms.find(e=>{const i=hi(e);return!!i&&wi(t,i)})}_overlapRoom(t){return this._spaceModel()?.rooms.find(e=>{const i=hi(e);return!!i&&Di(t,i)})}_pointInRoom(t,e){return e.poly?vi(t,e.poly):null!=e.x&&t[0]>=e.x&&t[0]<=e.x+e.w&&t[1]>=e.y&&t[1]<=e.y+e.h}_contourSelfIntersects(t){if(!Ia(t))return!0;const e=t.length,i=.001;for(let s=0;s=500)return this._showToast(this._t("toast.physical_limit")),!1;const t=this._curSpaceCfg;return!(!this._activeDraftId&&(t?.room_drafts||[]).length>=200||this._draftSegmentCount(t)>=2e3||(t?.partitions||[]).length+this._path.length>rv)||(this._showToast(this._t("toast.physical_limit")),!1)}_markupClick(t){if(this._vacFit)return;if(!this._markup)return;const e=this._spaceModel();if(!e)return void this._clearGeometryGesture();if(this._suppressClick)return;if(this._drag||this._rlResize)return;const i=t.composedPath?.()||[];if(i.some(t=>t?.classList?.contains?.("roomlabel")||t?.classList?.contains?.("rlhandle")))return;if(i.some(t=>t?.classList?.contains?.("physical-hit")))return;const s=this._svgPoint(t);if("select"===this._tool)return void(this._physicalSel=null);if("resize"===this._tool){if(this._rszDrag||i.some(t=>t?.classList?.contains?.("rszhandle")))return;const t=[...e.rooms].reverse().find(t=>this._pointInRoom(s,t));return void(this._rszSel=t?.id||null)}if("delroom"===this._tool)return void this._deleteRoomClick(s);if("opening"===this._tool)return void this._openingClick(s);if("merge"===this._tool)return void this._mergeClick(s);if("wallthick"===this._tool)return void this._wallThickClick(s);if("split"===this._tool)return void this._splitClick(s);if("column"===this._tool)return void this._columnClick(s);this._wallRepairDiagnostic=null;const n=this._resolvePlanDrawPoint(s,t.shiftKey);if(n.ambiguous)return this._planSnapHover={contextKey:n.contextKey,candidate:null,conflicts:n.conflicts},this._syncPlanSnapActiveMarker(null),this._syncPlanSnapConflictMarkers(n.conflicts),void this._showToast(this._t("toast.plan_snap_ambiguous"));let o=n.point;if(t.ctrlKey||t.metaKey){if(t.preventDefault(),this._path.length<3)return;o=ua(this._path[this._path.length-1],this._path[0])}if(!this._path.length){if(!t.shiftKey&&!n.candidate&&this._offerExistingWallFace(s))return;const e=this._draftEndAt(o);return e?(this._activeDraftId=e.draft.id,this._resumeDraftBySpace[this._space]=e.draft.id,this._path=e.reverse?[...e.draft.points].reverse().map(t=>[...t]):e.draft.points.map(t=>[...t]),void(this._draftSegmentCms=this._adoptDraftCms(this._path,e.reverse?[...e.draft.segments].reverse().map(t=>t.cm):e.draft.segments.map(t=>t.cm),e.draft.id))):(this._activeDraftId=null,this._draftSegmentCms=[],void(this._path=[o]))}const a=this._path[this._path.length-1];if(this._samePt(o,a))return;const r=this._draftEndAt(o,this._activeDraftId||void 0);if(r)return void this._mergeDraftEndpoint(r);if(!this._canAppendRoomDraftPoint())return;const l=this._drawWallCm;if(null==l)return void this._showPhysicalRange(100);const c=this._path.map(t=>[...t]);this._path=[...this._path,o],this._draftSegmentCms=[...this._draftSegmentCms,l],this._persistActiveDraftSegment(),this._offerWallFaces(c)}_draftEndAt(t,e){const i=this._spaceModel();if(!i)return null;const s=this._viewOr(this._baseVb()),n=Math.max(.15*this._gridPitch,this._stageEl?.clientWidth?s.w/this._stageEl.clientWidth*12:0);for(const s of i.room_drafts||[]){if(s.id===e)continue;if(s.points.length<2)continue;const i=s.points[0],o=s.points[s.points.length-1];if(Math.hypot(t[0]-o[0],t[1]-o[1])<=n)return{draft:s,reverse:!1};if(Math.hypot(t[0]-i[0],t[1]-i[1])<=n)return{draft:s,reverse:!0}}return null}_mergeDraftEndpoint(t){const e=this._curSpaceCfg;if(!e||!this._path.length)return;const i=this._path.map(t=>[...t]),s=this._wallGraphSources(i),n=Array.isArray(e.room_drafts)?e.room_drafts:[],o=this._activeDraftId?n.find(t=>t.id===this._activeDraftId):null,a=n.find(e=>e.id===t.draft.id);if(!a)return;const r=t.reverse?t.draft.points.map(t=>[...t]):[...t.draft.points].reverse().map(t=>[...t]),l=t.reverse?(a.segments||[]).map(t=>({...t})):[...a.segments||[]].reverse().map(t=>({...t})),c=this._path[this._path.length-1],h=this._samePt(c,r[0]),d=h?null:this._drawWallCm;if(!h&&null==d)return void this._showPhysicalRange(100);const p=this._draftSegmentsForPath(this._path,o,this._draftSegmentCms),u=[...this._path.map(t=>[...t]),...h?r.slice(1):r],_=[...p,...null==d?[]:[{cm:d}],...l],m=u.length>=4&&this._samePt(u[0],u[u.length-1]),g=u,f=_;if(g.length>500)return void this._showToast(this._t("toast.physical_limit"));const v=(o?.segments?.length||0)+(a.segments?.length||0);if(this._draftSegmentCount(e)-v+f.length>2e3)return void this._showToast(this._t("toast.physical_limit"));if(m){const t=g.slice(0,-1);if(this._contourSelfIntersects(t)||Ti(t)<=1e-6)return void this._showToast(this._t("toast.contour_cannot_close"));const e=this._overlapRoom(t);if(e)return void this._showToast(this._t("toast.room_overlap",{name:e.name||""}))}const y=this._geometrySnapshot(),b=this._activeDraftId||t.draft.id,w={...o||a,id:b,points:g.map(t=>[t[0]/sv,t[1]/sv]),segments:f};e.room_drafts=n.filter(e=>e.id!==t.draft.id&&(!this._activeDraftId||e.id!==this._activeDraftId)),e.room_drafts.push(w),this._activeDraftId=b,this._resumeDraftBySpace[this._space]=b,this._path=g,this._draftSegmentCms=this._adoptDraftCms(g,f.map(t=>Number(t.cm)),b),this._physicalSel=null,this._commitPhysicalGeometry(this._t("history.draft_merge"),y),null!=d&&this._offerWallFaces(i,i.length-1,s)}_adoptDraftCms(t,e,i){const s=Math.max(0,t.length-1),n=Xp(s,e,this._drawWallCm,ll);return e.length!==s&&console.debug(`[houseplan] draft ${i??"?"}: восстановлено толщин ${s-e.length} (#234)`),n}_draftSegmentsForPath(t,e,i){const s=Array.isArray(e?.points)?e.points.map(t=>[Number(t?.[0])*sv,Number(t?.[1])*sv]):[],n=Array.isArray(e?.segments)?e.segments:[];return Xp(Math.max(0,t.length-1),i,this._drawWallCm,ll).map((e,i)=>{const o=t[i],a=t[i+1],r=s.findIndex((t,e)=>{if(e+1>=s.length)return!1;const i=s[e+1];return this._samePt(o,t)&&this._samePt(a,i)||this._samePt(o,i)&&this._samePt(a,t)});return{...r>=0?n[r]:{},cm:e}})}_persistActiveDraftSegment(){if(this._path.length<2||!this._curSpaceCfg)return;const t=this._geometrySnapshot(),e=this._curSpaceCfg;e.room_drafts||=[],this._activeDraftId||(this._activeDraftId="draft-"+Date.now().toString(36)),this._resumeDraftBySpace[this._space]=this._activeDraftId;const i=e.room_drafts.findIndex(t=>t.id===this._activeDraftId),s={...i>=0?e.room_drafts[i]:{},id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentsForPath(this._path,i>=0?e.room_drafts[i]:null,this._draftSegmentCms)};i>=0?e.room_drafts[i]=s:e.room_drafts.push(s),this._commitPhysicalGeometry(this._t("history.draft_segment"),t)}_activeWallSourceKey(t){return`active:${this._activeDraftId||"session"}:${t}`}_wallGraphSources(t){const e=this._planStructuralGeometrySnapshot().value.segments.map(t=>({a:t.a,b:t.b,key:`static:${t.key}`}));for(let i=0;i+1t.key===i);if(s>=0){const[t]=this._wallFaceGraphCache.splice(s,1);return this._wallFaceGraphCache.push(t),t.value}const n=bu(t,e);return this._wallFaceGraphCache.push({key:i,value:n}),this._wallFaceGraphCache.length>4&&this._wallFaceGraphCache.shift(),n}_offerWallFaces(t,e=this._path.length-2,i){if(this._path.length<2||this._wallFaceBatch||this._roomDialog)return;const s=this._spaceModel();if(!s)return;const n=this._activeWallSourceKey(e),o=2e-4*this._gridPitch;let a,r;try{const e=i||this._wallGraphSources(t);r=this._wallGraphSources(this._path),a=function(t,e,i){const s=new Set(t.faces.map(t=>t.key));return e.faces.filter(t=>!s.has(t.key)&&t.sourceKeys.includes(i))}(this._wallFaceGraph(e,o),this._wallFaceGraph(r,o),n)}catch{return}if(!a.length){const t=Iu(r,{requiredSourceKey:n,maxDistance:gl(2,this._cellCm,this._gridPitch),gridStep:this._gridPitch,epsilon:o});return"ambiguous"===t.kind?(this._wallRepairDiagnostic=t.proposals[0]||null,void this._showToast(this._t(0===this._drawWallCm?"toast.zero_wall_ambiguous":"toast.wall_repair_ambiguous"))):void("repair"!==t.kind||this._overlapRoom(t.face.ring)||this._beginWallFaceBatch([{...t.face,repair:t.proposal}]))}for(const t of s.rooms){const e=hi(t);if(!t.id||!e)continue;const i=zi(e,this._path,.02*this._gridPitch);if(!i)continue;const[s,n]=i,o=Ti(s)>=Ti(n)?s:n,r=o===s?n:s,l=[...a].sort((t,e)=>Math.abs(t.area-Ti(r))-Math.abs(e.area-Ti(r))||t.key.localeCompare(e.key))[0];if(!l)return;return void this._beginWallFaceBatch([{...l,ring:r.map(t=>[t[0],t[1]]),split:{roomId:t.id,mainPoly:o,newPoly:r},consumeAllActive:!0}])}const l=a.filter(t=>!(t.ring.length<3||this._contourSelfIntersects(t.ring))&&!this._overlapRoom(t.ring));l.length&&this._beginWallFaceBatch(l)}_beginWallFaceBatch(t){this._wallRepairDiagnostic=null,this._wallFaceBatch={candidates:[...t].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key)),index:0,decisions:[],activePath:this._path.map(t=>[...t]),activeCms:[...this._draftSegmentCms],activeDraftId:this._activeDraftId},this._clearPlanSnapHover(),this._nameSel="",this._areaSel="",this._resetRoomDialogFields(),this._roomDialog=!0}_offerExistingWallFace(t){if(this._path.length||this._wallFaceBatch||this._roomDialog)return!1;const e=2e-4*this._gridPitch;try{let i,s=wu(this._wallFaceGraph(this._wallGraphSources([]),e),t,e);if(!s){const n=Iu(this._wallGraphSources([]),{point:t,maxDistance:gl(2,this._cellCm,this._gridPitch),gridStep:this._gridPitch,epsilon:e});if("ambiguous"===n.kind)return this._wallRepairDiagnostic=n.proposals[0]||null,this._showToast(this._t(0===this._drawWallCm?"toast.zero_wall_ambiguous":"toast.wall_repair_ambiguous")),!0;if("repair"===n.kind)s=n.face,i=n.proposal;else if("none"===n.kind){const i=Iu(this._wallGraphSources([]),{point:t,maxDistance:this._cssPxToRender(12),gridStep:this._gridPitch,epsilon:e});if("repair"===i.kind)return this._wallRepairDiagnostic=i.proposal,this._showToast(this._t("toast.wall_repair_too_large")),!0}}return!(!s||s.ring.length<3||this._contourSelfIntersects(s.ring)||this._overlapRoom(s.ring))&&(this._beginWallFaceBatch([{...s,existing:!i,repair:i}]),!0)}catch{return!1}}_columnClick(t){const e=this._snap(t),i=this._drawWallCm;if(null==i)return void this._showPhysicalRange(jc,1);if(!this._curSpaceCfg||this._limitReached("column"))return;const s=this._spaceModel();if(!s)return;const n={id:"column-"+Date.now().toString(36),shape:"square",center:e,cm:Gc(i),angle:0},o=(s.wall_columns||[]).find(t=>uh(t,n,.02*this._gridPitch));if(o)return clearTimeout(this._duplicateColumnTimer),this._duplicateColumnId=o.id,this._duplicateColumnTimer=window.setTimeout(()=>{this._duplicateColumnId=null},900),void this._showToast(this._t("toast.column_duplicate"));const a=this._geometrySnapshot(),r=this._curSpaceCfg;r.wall_columns||=[],r.wall_columns.push({...n,center:[e[0]/sv,e[1]/sv]}),this._commitPhysicalGeometry(this._t("history.column_add"),a)}_openPhysicalDialog(t,e,i){const s=this._spaceModel();if(s)if("partition"===t){const i=s.partitions.find(t=>t.id===e);i&&(this._physicalDialog={kind:t,id:e,cm:ml(i.cm,this._imperial),length:this._fmtLen(i.a,i.b)})}else if("column"===t){const i=s.wall_columns.find(t=>t.id===e);i&&(this._physicalDialog={kind:t,id:e,cm:ml(i.cm,this._imperial),shape:i.shape,angle:this._angleField("square"===i.shape?Vc(i.angle):0)})}else{const n=s.room_drafts.find(t=>t.id===e),o=Math.max(0,Math.min(n?.segments.length?n.segments.length-1:0,i||0));n?.segments[o]&&(this._physicalDialog={kind:t,id:e,segment:o,cm:ml(n.segments[o].cm,this._imperial),length:this._fmtLen(n.points[o],n.points[o+1])})}}_physicalDown(t,e,i){const s=this._spaceModel();if(!s)return;t.stopPropagation(),dv(t);const n=this._svgPoint(t),o=[];for(const t of[...s.wall_columns].reverse())dh(n,Qc(t,this._cellCm,this._gridPitch))&&o.push({kind:"column",id:t.id});for(const t of[...s.partitions].reverse()){const e=Zc(t.a,t.b,t.cm,this._cellCm,this._gridPitch);e&&dh(n,e)&&o.push({kind:"partition",id:t.id})}o.some(t=>t.kind===e&&t.id===i)||o.unshift({kind:e,id:i});const a=o.map(t=>`${t.kind}:${t.id}`).sort().join("|"),r=performance.now(),l=this._physicalPickCycle,c=o.length>1&&l?.signature===a&&r-l.at>380&&r-l.at<=1200&&Math.hypot(t.clientX-l.x,t.clientY-l.y)<=10?(l.index+1)%o.length:Math.max(0,o.findIndex(t=>t.kind===e&&t.id===i));this._physicalPickCycle={signature:a,index:c,x:t.clientX,y:t.clientY,at:r},e=o[c].kind,i=o[c].id;const h="partition"===e?s.partitions.find(t=>t.id===i):s.wall_columns.find(t=>t.id===i);h&&(this._physicalSel={kind:e,id:i},this._physicalDrag={pid:t.pointerId,kind:e,id:i,start:this._svgPoint(t),startClient:[t.clientX,t.clientY],before:this._geometrySnapshot(),moved:!1,base:JSON.parse(JSON.stringify(h)),delta:[0,0]})}_clampPhysicalDelta(t,e,i){const s="partition"===t?[e.a,e.b]:[e.center],n=s.map(t=>t[0]),o=s.map(t=>t[1]);return[Math.max(-Mh*sv-Math.min(...n),Math.min(Mh*sv-Math.max(...n),i[0])),Math.max(-Mh*sv-Math.min(...o),Math.min(Mh*sv-Math.max(...o),i[1]))]}_physicalMove(t){const e=this._physicalDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._svgPoint(t),s="partition"===e.kind?e.base.a:e.base.center,n=this._snap([s[0]+i[0]-e.start[0],s[1]+i[1]-e.start[1]]),o=this._clampPhysicalDelta(e.kind,e.base,[n[0]-s[0],n[1]-s[1]]);this._physicalDrag={...e,delta:o,moved:e.moved||Math.hypot(t.clientX-e.startClient[0],t.clientY-e.startClient[1])>=5}}_physicalUp(t){const e=this._physicalDrag;if(!e||e.pid!==t.pointerId)return;if(t.stopPropagation(),this._physicalDrag=null,!e.moved)return void this._registerPhysicalTap(e.kind,e.id);const i=this._spaceModel();if(!this._curSpaceCfg||!i)return;const s=this._curSpaceCfg;if("partition"===e.kind){const t=(s.partitions||[]).find(t=>t.id===e.id),i=e.base;if(t){const n={...i,a:[i.a[0]+e.delta[0],i.a[1]+e.delta[1]],b:[i.b[0]+e.delta[0],i.b[1]+e.delta[1]]};t.a=[n.a[0]/sv,n.a[1]/sv],t.b=[n.b[0]/sv,n.b[1]/sv];for(const t of s.openings||[]){if("partition"!==t.host?.kind||t.host.id!==e.id)continue;const i=Sp(t,[n],sv,this._cellCm,this._gridPitch).resolved;i&&Object.assign(t,Ip(t,i,sv))}}}else{const t=(s.wall_columns||[]).find(t=>t.id===e.id),n=e.base,o={...n,center:[n.center[0]+e.delta[0],n.center[1]+e.delta[1]]};if(i.wall_columns.some(t=>t.id!==e.id&&uh(t,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"));t&&(t.center=[(n.center[0]+e.delta[0])/sv,(n.center[1]+e.delta[1])/sv])}this._commitPhysicalGeometry(this._t("history.physical_move"),e.before)}_registerPhysicalTap(t,e,i){const s=performance.now(),n=this._physicalLastTap?.kind===t&&this._physicalLastTap.id===e&&this._physicalLastTap.segment===i&&s-this._physicalLastTap.at<=360;this._physicalLastTap={kind:t,id:e,segment:i,at:s},n&&(this._physicalLastTap=null,this._openPhysicalDialog(t,e,i))}_cancelPhysicalGesture(){this._physicalDrag=null,this._physicalRotate=null,this.requestUpdate()}_physicalRotateDown(t,e){if("square"!==e.shape||!this._spaceModel())return;t.preventDefault(),t.stopPropagation(),dv(t);const i=this._svgPoint(t);this._physicalSel={kind:"column",id:e.id},this._physicalRotate={pid:t.pointerId,id:e.id,center:[...e.center],startAngle:180*Math.atan2(i[1]-e.center[1],i[0]-e.center[0])/Math.PI,baseAngle:Vc(e.angle),angle:Vc(e.angle),before:this._geometrySnapshot(),moved:!1}}_physicalRotateMove(t){const e=this._physicalRotate;if(!e||e.pid!==t.pointerId)return;t.preventDefault(),t.stopPropagation();const i=this._svgPoint(t),s=180*Math.atan2(i[1]-e.center[1],i[0]-e.center[0])/Math.PI,n=e.baseAngle+s-e.startAngle,o=Vc(t.shiftKey?n:5*Math.round(n/5));this._physicalRotate={...e,angle:o,moved:e.moved||Math.abs(n-e.baseAngle)>=.5}}_physicalRotateUp(t){const e=this._physicalRotate;if(!e||e.pid!==t.pointerId)return;t.preventDefault(),t.stopPropagation(),this._physicalRotate=null;const i=this._spaceModel();if(!e.moved||!this._curSpaceCfg||!i)return;const s=i.wall_columns.find(t=>t.id===e.id);if(!s||"square"!==s.shape)return;const n={...s,angle:e.angle};if(i.wall_columns.some(t=>t.id!==e.id&&uh(t,n,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"));const o=this._curSpaceCfg.wall_columns?.find(t=>t.id===e.id);o&&(o.angle=e.angle,this._commitPhysicalGeometry(this._t("history.physical_edit"),e.before))}_rszRooms(){const t=[],e=this._spaceModel();if(!e)return t;for(const i of e.rooms){const e=i.id?hi(i):null;e&&t.push({id:i.id,poly:e,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0})}return i=t,s=Math.max(1e-12,1e-12*this._gridPitch),i.map(t=>{if(!Array.isArray(t.wall_ids)||t.wall_ids.length!==t.poly.length)return{...t,poly:t.poly.map(t=>[...t])};const e=t.poly.map(t=>[...t]);let i=!0;for(;i&&e.length>3;){i=!1;for(let t=0;t0){e.splice(t,1),i=!0;break}}}return{...t,poly:e}});var i,s}_rszOpenings(){return this._openingsR.map(t=>({id:t.id,x:t.rx,y:t.ry,length:t.rlen,hosted:!!t.host,angle:t.angle,type:t.type}))}_rszObstacles(){const t=this._spaceModel();if(!t)return[];const e=[];for(const i of t.partitions||[])e.push({kind:"segment",a:[...i.a],b:[...i.b],half:gl(i.cm,this._cellCm,this._gridPitch)/2});for(const i of t.room_drafts||[])for(let t=0;t+1Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2).map(t=>({wall:t,a:[t.a[0]*sv,t.a[1]*this._spaceH],b:[t.b[0]*sv,t.b[1]*this._spaceH]})),n=Math.abs(t[0]-e[0])<=.05*this._gridPitch?"v":Math.abs(t[1]-e[1])<=.05*this._gridPitch?"h":null,o=s.filter(i=>!!n&&("h"===n?!(Math.abs(i.a[1]-t[1])>.05*this._gridPitch||Math.abs(i.b[1]-t[1])>.05*this._gridPitch)&&Math.min(Math.max(t[0],e[0]),Math.max(i.a[0],i.b[0]))-Math.max(Math.min(t[0],e[0]),Math.min(i.a[0],i.b[0]))>.05*this._gridPitch:!(Math.abs(i.a[0]-t[0])>.05*this._gridPitch||Math.abs(i.b[0]-t[0])>.05*this._gridPitch)&&Math.min(Math.max(t[1],e[1]),Math.max(i.a[1],i.b[1]))-Math.max(Math.min(t[1],e[1]),Math.min(i.a[1],i.b[1]))>.05*this._gridPitch)),a=new Set(o.map(t=>Number(t.wall.cm)).filter(t=>t>0));return{minDim:this._cmToUnits(30),eps:.05*this._gridPitch,step:this._gridPitch,movingHalf:i>0?gl(i,this._cellCm,this._gridPitch)/2:0,obstacles:this._rszObstacles(),thicknessConflict:a.size>1}}_rszResolution(t,e,i){const s=this._rszDrag?.snap||i||this._rszSnapshot(),n=`${this._space}|${this._cellCm}|${this._gridPitch}|${s}`;this._rszEligibilityCache&&this._rszEligibilityCache.key===n||(this._rszEligibilityCache={key:n,values:new Map});const o=`${t}:${e}`,a=this._rszEligibilityCache.values.get(o);if(a)return a;const r=this._rszDrag?.rooms||this._rszRooms(),l=r.find(e=>e.id===t),c=l?.poly?.[e]||[0,0],h=l?.poly?.[(e+1)%(l?.poly?.length||1)]||[0,0],d=function(t,e,i,s,n){const{eps:o}=n,a=t.find(t=>t.id===i);if(!a||s<0||s>=(a.poly?.length||0)||a.poly.length<4||!Ia(a.poly))return{enabled:!1,reason:"invalid-geometry"};const r=a.poly[s],l=a.poly[(s+1)%a.poly.length],c=Ea(r,l,o);if(!c)return{enabled:!1,reason:"diagonal"};if(!Ha(a.poly,s,c,o))return{enabled:!1,reason:"side-angle"};if(n.thicknessConflict)return{enabled:!1,reason:"thickness-conflict"};for(const t of n.obstacles||[])if(Wa(t,r,l,n))return{enabled:!1,reason:"duplicate-physical-wall"};const h=Da(Sa(l,r)),d=[],p=new Set;let u=!1,_=!1;for(const e of t)if(e.id!==i)for(let t=0;t1||d.length>1)return{enabled:!1,reason:"multiple-rooms"};const m={[i]:s},g=[i];if(1===d.length){const t=d[0];if(!Ia(t.room.poly))return{enabled:!1,reason:"invalid-geometry"};if(!Ha(t.room.poly,t.edge,c,o))return{enabled:!1,reason:"side-angle"};g.push(t.room.id),m[t.room.id]=t.edge}const f=[];for(const t of e)if(!(Ta([t.x,t.y],r,l)>2*o)){if(t.hosted||t.length>h+2*o)return{enabled:!1,reason:"opening-conflict"};f.push(t.id)}const v=Object.fromEntries(g.map(e=>[e,t.find(t=>t.id===e).poly.length])),y=[];for(const e of g){const i=t.find(t=>t.id===e),s=m[e],n=(s-1+i.poly.length)%i.poly.length,a=(s+1)%i.poly.length,r=Ga(t,e,n,1,o),l=Ga(t,e,a,0,o);if(!r||!l)return{enabled:!1,reason:"partial-shared"};y.push(r,l)}const b={roomId:i,edge:s,a:[...r],b:[...l],n:Ra(a.poly,s),roomIds:g,edgeByRoom:m,topology:v,movingOpeningIds:f,sideOwnership:y};if(!Qa(t,e,b,0,n))return{enabled:!1,reason:"invalid-geometry"};const w=Math.abs(Number(n.step));if(Number.isFinite(w)&&w>o){const i=[-w,w];if(!i.some(i=>Qa(t,e,b,i,n))){if(!i.some(i=>Ya(Ja(t,e,b,i),b,o)))return{enabled:!1,reason:"partial-shared"};const s={...n,obstacles:[]};return i.some(i=>Qa(t,e,b,i,s))?{enabled:!1,reason:"duplicate-physical-wall"}:e.length&&i.some(e=>Qa(t,[],b,e,n))?{enabled:!1,reason:"opening-conflict"}:{enabled:!1,reason:"invalid-geometry"}}}return{enabled:!0,plan:b}}(r,this._rszDrag?.openings||this._rszOpenings(),t,e,this._rszOptsFor(c,h));return this._rszEligibilityCache.values.set(o,d),d}_rszSnapshot(){return JSON.stringify(this._geometrySnapshot()||{spaceId:this._space,rooms:[],openings:[],walls:[],open_spans:[]})}_rszApplyPreview(t,e){const i=this._rszDrag,s=this._serverCfg?.spaces.find(t=>t.id===this._space);if(!i||!s||!this._serverCfg)return{ok:!1,reason:"missing-context"};const n=JSON.parse(i.snap),o={...s,rooms:n.rooms,openings:n.openings||[]};for(const t of["walls","wall_segments","open_spans","room_drafts","partitions","wall_columns","decor"])void 0!==n[t]?o[t]=n[t]:delete o[t];for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])void 0!==n.plan_transform?.[t]?o[t]=n.plan_transform[t]:delete o[t];const a=this._spaceH;for(const[e,i]of Object.entries(t)){const t=o.rooms.find(t=>t.id===e);t&&(t.poly=i.map(t=>[t[0]/sv,t[1]/a]),delete t.x,delete t.y,delete t.w,delete t.h)}for(const[t,i]of Object.entries(e)){const e=(o.openings||[]).find(e=>e.id===t);e&&(e.x=i[0]/sv,e.y=i[1]/a)}const r=[],l=[];for(const t of i.changed){const e=i.rooms.find(e=>e.id===t),s=o.rooms.find(e=>e.id===t);if(!e||!s?.poly)continue;const n=s.poly.map(t=>[t[0]*sv,t[1]*a]);if(e.poly.length!==n.length)continue;const c=Array.isArray(e.wall_ids)?e.wall_ids:[];for(let t=0;tt.id===i):null;s&&(s.a=[n[t][0]/sv,n[t][1]/sv],s.b=[n[(t+1)%n.length][0]/sv,n[(t+1)%n.length][1]/sv])}}if(r.length&&Array.isArray(o.walls)&&o.walls.length){const t=function(t,e,i,s,n=1,o="fixed-topology"){let a=!1;const r=Il(t,e,i,s,n,o,()=>{a=!0});return{walls:a?(t||[]).map(t=>({...t})):r,rejected:a}}(o.walls,r,l,this._wallKeyPitch,sv,"fixed-topology");if(t.rejected)return{ok:!1,reason:"wall-metadata"};o.walls=t.walls}const c=t=>t.map(t=>Number(t.cm)).sort((t,e)=>t-e),h=c(n.walls||[]),d=c(o.walls||[]);if(JSON.stringify(h)!==JSON.stringify(d))return{ok:!1,reason:"wall-metadata"};const p=[];for(const t of o.rooms||[]){const e=hi(t);if(e&&!(e.length<2))for(let t=0;tJSON.stringify([t?.key,t?.cm,t?.a,t?.b]),_=new Map;for(const t of n.walls||[]){const e=u(t);_.set(e,(_.get(e)||0)+1)}const m=[];for(const t of o.walls||[]){const e=u(t),i=_.get(e)||0;i?_.set(e,i-1):m.push(t)}if(zl(m,p,this._wallKeyPitch,sv,n.walls||[]).length)return{ok:!1,reason:"wall-metadata"};const g=this._rszSpaceCandidateGeometry(this._space,o);if(!g.ok)return{ok:!1,reason:"physical-geometry"};if(this._rszPreview={space:this._space,sp:o},this._cfgEpoch++,g.wallGeometry){const t=Ac(g.wallGeometry);if(t){const e=`${this._space}|${this._cfgEpoch}|${o.rooms.length}`,i={key:e,value:t};Uf(this._wallUnionPool,e,i,8),this._wallUnionCache=i}}return{ok:!0}}_rszSpaceCandidateGeometry(t,e){if(!this._serverCfg)return{ok:!1,wallGeometry:null};const i={...this._serverCfg,spaces:this._serverCfg.spaces.map(i=>i.id===t?e:i)};let s=null;try{return{ok:this._checkSpacePhysicalGeometry(i,t,t=>{s=t}).ok,wallGeometry:s}}catch{return{ok:!1,wallGeometry:null}}}_rszSpaceCandidateRenderable(t,e){if(!this._serverCfg)return!1;try{const i={...this._serverCfg,spaces:this._serverCfg.spaces.map(i=>i.id===t?e:i)};return this._checkSpacePhysicalGeometry(i,t).ok}catch{return!1}}_rszCandidateRenderable(t){return!!t&&t.space===this._space&&this._rszPreview===t&&this._rszSpaceCandidateRenderable(t.space,t.sp)}_rszEdgeDown(t,e,i){if("resize"!==this._tool||this._rszDrag)return;t.stopPropagation(),t.preventDefault();const s=this._rszRooms(),n=this._rszResolution(e,i);if(!n.enabled)return void this._showToast(this._rszReasonText(n.reason));dv(t);const o=n.plan,a=this._svgPoint(t);this._rszDrag={pid:t.pointerId,start:[a[0],a[1]],roomId:e,plan:o,opts:this._rszOptsFor(o.a,o.b),rooms:s,openings:this._rszOpenings(),snap:this._rszSnapshot(),moved:!1,d:0,changed:[...o.roomIds],rejectNotified:!1}}_rszReasonText(t){return this._t(`resize.disabled.${t}`)}_rszDisabledActivate(t,e){t.stopPropagation(),t.preventDefault(),this._showToast(this._rszReasonText(e))}_rszDisabledKey(t,e){"Enter"!==t.key&&" "!==t.key||this._rszDisabledActivate(t,e)}_rszMove(t){const e=this._rszDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._svgPoint(t),s=e.plan,n=(o=e.start,a=i,r=s.n,[o?.[0],o?.[1],a?.[0],a?.[1],r?.[0],r?.[1]].every(Number.isFinite)?(a[0]-o[0])*r[0]+(a[1]-o[1])*r[1]:0);var o,a,r;const l=this._snap([s.a[0]+s.n[0]*n,s.a[1]+s.n[1]*n]),c=(l[0]-s.a[0])*s.n[0]+(l[1]-s.a[1])*s.n[1];let h=function(t,e,i,s,n,o){if(!Number.isFinite(s)||Math.abs(s)<1e-9)return 0;const a=Math.sign(s),r=Math.abs(s),l=Math.max(Math.abs(n),1e-6);let c=tr.get(i);c&&c.opts===o||(c={opts:o,values:new Map},tr.set(i,c));const h=c.values;let d=0;for(let s=Math.min(l,r),n=0;n<4096&&s<=r+1e-9;n++,s=Math.min(r,s+l)){const n=a*s,c=`${n.toFixed(9)}|${l.toFixed(9)}`;let p=h.get(c);if(void 0===p&&(p=Qa(t,e,i,n,o),h.size<4096&&h.set(c,p)),!p)break;if(d=n,Math.abs(s-r)<=1e-9)break}return d}(e.rooms,e.openings,s,c,this._gridPitch,e.opts);if(h===e.d&&e.moved)return;const d=this._rszPreview,p=this._rszLive,u=e.d;let _=Ja(e.rooms,e.openings,s,h);if(!this._rszApplyPreview(_.polys,_.openings).ok)return this._rszPreview=d,this._rszLive=p,e.d=u,e.rejectNotified||(e.rejectNotified=!0,this._showToast(this._t("resize.preview_failed"))),void this.requestUpdate();e.moved=!0,e.changed=[...s.roomIds],e.d=h,this._rszLive=this._rszEdgeLabels(_,s),this.requestUpdate()}_rszUp(t){const e=this._rszDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._rszPreview,s=e.moved&&Math.abs(e.d)>1e-9,n=this._rszSnapshot()===e.snap,o=Qa(e.rooms,e.openings,e.plan,e.d,e.opts),a=this._rszCandidateRenderable(i);if(this._rszDrag=null,this._rszLive=null,this._rszPreview=null,!s||!i)return this._cfgEpoch++,void this.requestUpdate();if(!n||!o||!a)return this._cfgEpoch++,this._showToast(this._t("resize.commit_failed")),void this.requestUpdate();const r=JSON.parse(e.snap),l=this._curSpaceCfg;l&&(l.rooms=i.sp.rooms,l.openings=i.sp.openings,Array.isArray(i.sp.walls)&&(i.sp.walls.length?l.walls=i.sp.walls:delete l.walls),Array.isArray(i.sp.wall_segments)&&(l.wall_segments=i.sp.wall_segments)),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._commitPhysicalGeometry(this._t("history.resize_room"),r),this._rszEligibilityCache=null,this.requestUpdate()}_rszCancelDrag(){this._rszDrag&&(this._rszDrag=null,this._rszLive=null,this._rszPreview=null,this._cfgEpoch++,this.requestUpdate())}_rszPointerCancel(t){const e=this._rszDrag;e&&e.pid===t.pointerId&&(t.stopPropagation(),this._rszCancelDrag())}_rszEdgeLabels(t,e){const i=this._rszDrag,s=[],n=t.polys[e.roomId]||i.rooms.find(t=>t.id===e.roomId).poly,o=n.length,a=this._rszInnerSpanCms(e.roomId,n,t.polys);for(const t of function(t,e){const i=t.length;return[(e-1+i)%i,(e+1)%i]}(n,e.edge)){const e=n[t],i=n[(t+1)%o],r=a?.[t];s.push({kind:"length",x:(e[0]+i[0])/2,y:(e[1]+i[1])/2,text:null==r?this._fmtLen(e,i):li(r,"mi"===this.hass?.config?.unit_system?.length),edge:{a:[e[0],e[1]],b:[i[0],i[1]]}})}const r="mi"===this.hass?.config?.unit_system?.length,l=e.roomIds,c=this._spaceWalls,h=this._physicalBodiesR(),d=this._baseVb(),p=this._view&&this._view.w>0&&this._view.h>0?this._view:{x:d[0],y:d[1],w:d[2],h:d[3]},[u,_]=this._lastValidStageSize||[p.w,p.h],m={...p,stageWidth:Math.max(1,u),stageHeight:Math.max(1,_)},g=this._spaceModel(),f=this._config?.icon_size??2.5,v=g?Vh(f>8?2.5:f,g,p.w,this._kiosk?this._kioskScale.icon:1)*m.stageWidth/100:24,y=Math.max(10,.77*v),b=this._t("room.settings_short"),w=y*(1.457+.66*Math.max(1,b.length)*.42);for(const n of l){const o=t.polys[n]||i.rooms.find(t=>t.id===n).poly,a=c.length&&g&&this._innerRoomContour(g,n)||o,l=ir(h.length?lh(rh(a,h))*Math.pow(this._cellCm/this._gridPitch,2)/1e4:er(a,this._gridPitch,this._cellCm),r),d=nr({poly:o,edge:e.edgeByRoom[n],text:l,view:m,gearCenter:$i(o),gearWidthPx:w,gearHeightPx:y});s.push({kind:"area",roomId:n,x:d.anchor[0],y:d.anchor[1],text:l,placement:d})}return s}_rszInnerSpanCms(t,e,i){const s=Object.keys(i).length?Object.entries(i).map(([t,e])=>({id:t,poly:e})):this._spaceModel()?.rooms;if(!s?.length)return null;const n=this._spaceWalls;if(!n.length)return null;const o=function(t,e,i,s,n,o,a,r=1){const l=(t||[]).find(t=>t?.id===e),c=hi(l);if(!c||c.length<3)return null;const h=hc(t,e,i,s,n,o,a,r);if(!h)return c.map(()=>0);const d=4*Vl(n,r);return c.map((t,e)=>{const i=c[(e+1)%c.length],s=[(t[0]+i[0])/2,(t[1]+i[1])/2];for(let t=0;tfunction(t,e,i){const s=t?.length||0;if(s<3||!Array.isArray(i)||i.length!==s)return 0;const n=(Math.trunc(e)%s+s)%s,o=t[n],a=t[(n+1)%s],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[n])||0);if(!(h>0))return c;const d=[r/c,l/c],p=Yl(t,n),u=[o[0]+p[0]*h,o[1]+p[1]*h],_=e=>{const n=Math.max(0,Number(i[e])||0);if(!(n>0))return null;const a=t[e],r=t[(e+1)%s],l=r[0]-a[0],c=r[1]-a[1],h=Math.hypot(l,c);if(!(h>0))return null;const p=Yl(t,e),_=Xl(u,d,[a[0]+p[0]*n,a[1]+p[1]*n],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((n-1+s)%s)??0,g=(_((n+1)%s)??c)-m;return g>0?g:0}(e,i,o)*a)}_renderResizeMeasurements(){if(!this._rszLive?.length)return G;const t=this._rszLive.filter(t=>"length"===t.kind),e=this._rszLive.filter(t=>"area"===t.kind);return j`
`}get _glowRadiusCm(){const t=Number(this._settings.glow_radius_cm);return Number.isFinite(t)&&t>0?t:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const t=this._glowRadiusCm;return this._imperial?String(Math.round(t/30.48*10)/10):String(t/100)}_glowTransition(t,e){let i=this._glowRenderedSources.get(t);if(e){const e=this._glowFadeTimers.get(t);if(null!=e&&(clearTimeout(e),this._glowFadeTimers.delete(t)),null==i){this._suspendGlowFeatherForTransition(),i=++this._glowSourceSeq,this._glowRenderedSources.set(t,i),this._glowEnteringSources.add(t);const e=requestAnimationFrame(()=>{this._glowEnterRafs.get(t)===e&&(this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),this.isConnected&&this.requestUpdate())});this._glowEnterRafs.set(t,e)}return{domId:i,entering:this._glowEnteringSources.has(t),leaving:!1}}if(null==i)return null;const s=this._glowEnterRafs.get(t);if(null!=s&&cancelAnimationFrame(s),this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),!this._glowFadeTimers.has(t)){this._suspendGlowFeatherForTransition();const e=window.setTimeout(()=>{this._glowFadeTimers.get(t)===e&&(this._glowFadeTimers.delete(t),this._glowRenderedSources.delete(t),this._glowLastAppearance.delete(t),this.isConnected&&this.requestUpdate())},534);this._glowFadeTimers.set(t,e)}return{domId:i,entering:!1,leaving:!0}}_suspendGlowFeatherForTransition(){if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;this._glowFeatherSuspendUntil=Math.max(this._glowFeatherSuspendUntil,Date.now()+500),clearTimeout(this._glowFeatherResumeTimer);const t=Math.max(0,this._glowFeatherSuspendUntil-Date.now())+17,e=()=>{this._glowFeatherResumeTimer=0,Date.now()=128){const t=this._glowGeometryWarnings.values().next().value;t&&this._glowGeometryWarnings.delete(t)}this._glowGeometryWarnings.add(n),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${i}, phase ${s}`)}}_lightBarriers(t,e){const i=this._zeroWalls(),s=this._openCuts(),n=[...i.transmissive],o=Math.max(this._cmToUnits(10),.5*this._gridPitch),a=t=>e.some(e=>this._pointInRoom(t,e.r)),r=this._openingsR.filter(t=>{if("door"!==(e=String(t.type))&&"gate"!==e&&"passage"!==e)return!1;var e;const i=t.angle*Math.PI/180,s=-Math.sin(i),n=Math.cos(i);return a([t.rx+s*o,t.ry+n*o])&&a([t.rx-s*o,t.ry-n*o])}),l=this._roomWallOpeningInputs(r,t);for(const t of l){const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,s=Math.sin(e)*t.length/2;n.push([t.x-i,t.y-s,t.x+i,t.y+s])}const c=new Set(r.filter(t=>t.partitionHost).map(t=>t.id)),h=[t.id,this._cfgEpoch,this._cellCm,this._gridPitch,[...c].sort().join(",")].join("|");this._lightPhysicalBodiesCache?.key!==h&&(this._lightPhysicalBodiesCache={key:h,all:ih(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t,t=>c.has(t.id))).all});const d=this._lightPhysicalBodiesCache.all;let p=2166136261;const u=t=>{p^=Math.round(64*(Number.isFinite(t)?t:0)),p=Math.imul(p,16777619)>>>0},_=this._spaceWalls;u(this._cellCm),u(this._gridPitch),u(this._wallKeyPitch);for(const{poly:t}of e){u(t.length);for(const e of t)u(e[0]),u(e[1])}for(const t of n)for(const e of t)u(e);u("solid"===i.style?1:0);for(const t of i.barriers)for(const e of t)u(e);for(const t of d){u(t.length);for(const e of t)u(e[0]),u(e[1])}for(const t of _)u(t.cm),u(t.a?.[0]??0),u(t.a?.[1]??0),u(t.b?.[0]??0),u(t.b?.[1]??0);const m=p.toString(36),g=`${t.id}|${m}`;if(this._lightBarrierCache?.key===g)return this._lightBarrierCache.value;const f=.02*this._gridPitch,v=[],y=_.length||d.length?Rc(t.rooms,_,s,l,this._wallKeyPitch,this._cellCm,this._gridPitch,sv,d):null;if(!y||"ok"!==y.status&&"degraded-extra"!==y.status)for(const t of d)v.push(...Fu(t));else for(const t of y.components)for(const e of ch(t.geom))v.push(...Fu(e));for(const{poly:t}of e)for(const e of n.length?Ps(t,n,f):Fu(t))v.push(e);for(const t of i.barriers)v.push(t);const b={occluders:zu(v),floor:e.map(t=>t.poly),fingerprint:m,masonryGeometry:!y||"ok"!==y.status&&"degraded-extra"!==y.status?[]:y.components.flatMap(t=>t.geom),opaqueBodies:d};return this._lightBarrierCache={key:g,value:b},b}_renderGlowLayer(t,e){const i=this._fillColors,s=this._glowRadiusCm/this._cellCm*this._gridPitch,n=t.rooms.map(t=>({r:t,poly:hi(t)})).filter(t=>!!t.poly),o=n.filter(({r:t})=>Fs(e.glow,t));if(!o.length)return this._forgetGlowSpace(t.id),j``;const{occluders:a,floor:r,fingerprint:l,masonryGeometry:c,opaqueBodies:h}=this._lightBarriers(t,n),d=ho(this._renderPlanHass,this._renderDevices,null,this._virtualLights).filter(e=>e.device.space===t.id),p=new Map;for(const t of d){if(!t.device.id)continue;const e=p.get(t.device.id)||[];e.push(t),p.set(t.device.id,e)}const u=[],_=new Set;for(const e of this._renderDevices){if(e.space!==t.id)continue;const o=po(p.get(e.id)||[]);if(!o)continue;const d=`${t.id}|${e.id}`;_.add(d);const m=$s(o.passive?{state:o.on?"on":"off",attributes:{}}:this._renderPlanHass.states[o.eid],e.marker?.glow_color,i.glow_light.c),g=Number(e.marker?.glow_radius_cm),f=Number.isFinite(g)&&g>0?g/this._cellCm*this._gridPitch:s,v=this._pos(e);if(ph([v.x,v.y],c,h)){this._forgetGlowSource(d);continue}const y=this._glowTransition(d,!!m);if(!y)continue;m&&this._glowLastAppearance.set(d,{c:m.c,alpha:Ss(m.bri,i.glow_light.a)});const b=this._glowLastAppearance.get(d);if(!b)continue;let w=null;const k=`${t.id}|${l}|${v.x.toFixed(4)},${v.y.toFixed(4)}|${f.toFixed(4)}`,x=jf(this._glowClipCache,k);if(x.hit)w=x.value;else{const e=Ou([v.x,v.y],f,a,96);w={lit:e.length>=3?ah([e],r,{onBoundsFailure:({boundIndex:e,phase:i})=>{const s=n[e]?.r;this._warnGlowGeometryFallback(t.id,l,s?.id||`#${e}`,i)}}):[]},Uf(this._glowClipCache,k,w,256)}u.push({key:d,sourceEid:o.eid,domId:y.domId,entering:y.entering,leaving:y.leaving,pos:v,c:b.c,alpha:b.alpha,geometry:w,r:f})}const m=`${t.id}|`;for(const t of this._glowRenderedSources.keys())t.startsWith(m)&&!_.has(t)&&this._forgetGlowSource(t);if(!u.length)return j``;const g=this._spaceWalls,f=o.length===n.length?[]:this._openCuts(),v=this._wallUnionGeometry()?.roomGeom,y=o.length===n.length?null:o.map(({r:e,poly:i})=>{const s=g.length&&e.id&&this._innerRoomContour(t,e.id,f,v)||i,o=this._cleanFloor(e,s,t).path,a=Pi(s,n.filter(t=>t.r!==e).map(t=>t.poly)),r=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z";return[o||r(s),...a.map(r)].join(" ")}),b=this._viewOr(this._baseVb()),w=this._stageEl?.clientWidth&&b.w?this._stageEl.clientWidth/b.w:1,k=1/(w>0?w:1),x=!this._pinchStart&&!this._panStart&&Date.now()>=this._glowFeatherSuspendUntil;(null==this._glowFeatherUnits||x)&&(this._glowFeatherUnits=k);const $=this._glowFeatherUnits??k,S=4*$,M=u.reduce((t,e)=>({x:Math.min(t.x,e.pos.x-e.r-S),y:Math.min(t.y,e.pos.y-e.r-S),maxX:Math.max(t.maxX,e.pos.x+e.r+S),maxY:Math.max(t.maxY,e.pos.y+e.r+S),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});return M.w=M.maxX-M.x,M.h=M.maxY-M.y,j` +
`}get _glowRadiusCm(){const t=Number(this._settings.glow_radius_cm);return Number.isFinite(t)&&t>0?t:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const t=this._glowRadiusCm;return this._imperial?String(Math.round(t/30.48*10)/10):String(t/100)}_glowTransition(t,e){let i=this._glowRenderedSources.get(t);if(e){const e=this._glowFadeTimers.get(t);if(null!=e&&(clearTimeout(e),this._glowFadeTimers.delete(t)),null==i){this._suspendGlowFeatherForTransition(),i=++this._glowSourceSeq,this._glowRenderedSources.set(t,i),this._glowEnteringSources.add(t);const e=requestAnimationFrame(()=>{this._glowEnterRafs.get(t)===e&&(this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),this.isConnected&&this.requestUpdate())});this._glowEnterRafs.set(t,e)}return{domId:i,entering:this._glowEnteringSources.has(t),leaving:!1}}if(null==i)return null;const s=this._glowEnterRafs.get(t);if(null!=s&&cancelAnimationFrame(s),this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),!this._glowFadeTimers.has(t)){this._suspendGlowFeatherForTransition();const e=window.setTimeout(()=>{this._glowFadeTimers.get(t)===e&&(this._glowFadeTimers.delete(t),this._glowRenderedSources.delete(t),this._glowLastAppearance.delete(t),this.isConnected&&this.requestUpdate())},534);this._glowFadeTimers.set(t,e)}return{domId:i,entering:!1,leaving:!0}}_suspendGlowFeatherForTransition(){if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;this._glowFeatherSuspendUntil=Math.max(this._glowFeatherSuspendUntil,Date.now()+500),clearTimeout(this._glowFeatherResumeTimer);const t=Math.max(0,this._glowFeatherSuspendUntil-Date.now())+17,e=()=>{this._glowFeatherResumeTimer=0,Date.now()=128){const t=this._glowGeometryWarnings.values().next().value;t&&this._glowGeometryWarnings.delete(t)}this._glowGeometryWarnings.add(n),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${i}, phase ${s}`)}}_lightBarriers(t,e){const i=wd([this._curSpaceCfg,this._cellCm,this._gridPitch]),s=`${t.id}|${i}`,n=jf(this._lightBarrierPool,s);if(n.hit)return this._lightBarrierCache=n.value,n.value.value;const o=this._zeroWalls(),a=this._openCuts(),r=[...o.transmissive],l=Math.max(this._cmToUnits(10),.5*this._gridPitch),c=t=>e.some(e=>this._pointInRoom(t,e.r)),h=this._openingsR.filter(t=>{if("door"!==(e=String(t.type))&&"gate"!==e&&"passage"!==e)return!1;var e;const i=t.angle*Math.PI/180,s=-Math.sin(i),n=Math.cos(i);return c([t.rx+s*l,t.ry+n*l])&&c([t.rx-s*l,t.ry-n*l])}),d=this._roomWallOpeningInputs(h,t);for(const t of d){const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,s=Math.sin(e)*t.length/2;r.push([t.x-i,t.y-s,t.x+i,t.y+s])}const p=new Set(h.filter(t=>t.partitionHost).map(t=>t.id)),u=[t.id,this._cfgEpoch,this._cellCm,this._gridPitch,[...p].sort().join(",")].join("|");this._lightPhysicalBodiesCache?.key!==u&&(this._lightPhysicalBodiesCache={key:u,all:ih(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t,t=>p.has(t.id))).all});const _=this._lightPhysicalBodiesCache.all,m=this._spaceWalls,g=.02*this._gridPitch,f=[],v=this._wallUnionGeometry(),y=v?.sourceFingerprint,b=v&&y===i?function(t,e=[],i=[],s={}){if("failed-core"===t.status||"not-applicable"===t.status)return null;const n=t.roomComponents?.length?t.roomComponents:yc(t.roomGeom)?[{id:"room-primary",geom:t.roomGeom}]:[];let o=n[0]?.geom||null;const a=n.slice(1).map(t=>({...t}));try{for(const i of e){if(!(i.length>0&&t.openingIndex))continue;const e=Lc(t.openingIndex,i,!0);if(!e.negative&&!e.positive)continue;const s=i.angle*Math.PI/180,n=Math.cos(s),r=Math.sin(s),l=-r,c=n,h=i.length/2,d=t.openingPadUnits??1.25*Math.max(t.depthUnits,1),p=vc([[i.x-n*h-l*d,i.y-r*h-c*d],[i.x+n*h-l*d,i.y+r*h-c*d],[i.x+n*h+l*d,i.y+r*h+c*d],[i.x-n*h+l*d,i.y-r*h+c*d]]);o&&(o=oi(o,p));for(const t of a)t.geom=oi(t.geom,p)}const n=[...a];let r=a.length;const l=s.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){r++;continue}const s=[vc(e)];try{const e=l(o,s,t);if(!yc(e))throw new Error("invalid extra union");o=e}catch{r++,yc(s)&&n.push({id:`policy-extra-${t}`,geom:s})}}n.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const c=o||[];return{status:r?"degraded-extra":"ok",geom:c,components:[...yc(c)?[{id:"primary",geom:c}]:[],...n.map((t,e)=>({...t,id:`isolated-${e}`}))]}}catch{return null}}(v,d,_):null,w=b||(m.length||_.length?Rc(t.rooms,m,a,d,this._wallKeyPitch,this._cellCm,this._gridPitch,sv,_):null);if(!w||"ok"!==w.status&&"degraded-extra"!==w.status)for(const t of _)f.push(...Fu(t));else for(const t of w.components)for(const e of ch(t.geom))f.push(...Fu(e));for(const{poly:t}of e)for(const e of r.length?Ps(t,r,g):Fu(t))f.push(e);for(const t of o.barriers)f.push(t);const k={occluders:zu(f),floor:e.map(t=>t.poly),fingerprint:i,masonryGeometry:!w||"ok"!==w.status&&"degraded-extra"!==w.status?[]:w.components.flatMap(t=>t.geom),opaqueBodies:_},x={key:s,value:k};return Uf(this._lightBarrierPool,s,x,8),this._lightBarrierCache=x,k}_renderGlowLayer(t,e){const i=this._fillColors,s=this._glowRadiusCm/this._cellCm*this._gridPitch,n=t.rooms.map(t=>({r:t,poly:hi(t)})).filter(t=>!!t.poly),o=n.filter(({r:t})=>Fs(e.glow,t));if(!o.length)return this._forgetGlowSpace(t.id),j``;const{occluders:a,floor:r,fingerprint:l,masonryGeometry:c,opaqueBodies:h}=this._lightBarriers(t,n),d=ho(this._renderPlanHass,this._renderDevices,null,this._virtualLights).filter(e=>e.device.space===t.id),p=new Map;for(const t of d){if(!t.device.id)continue;const e=p.get(t.device.id)||[];e.push(t),p.set(t.device.id,e)}const u=[],_=new Set;for(const e of this._renderDevices){if(e.space!==t.id)continue;const o=po(p.get(e.id)||[]);if(!o)continue;const d=`${t.id}|${e.id}`;_.add(d);const m=$s(o.passive?{state:o.on?"on":"off",attributes:{}}:this._renderPlanHass.states[o.eid],e.marker?.glow_color,i.glow_light.c),g=Number(e.marker?.glow_radius_cm),f=Number.isFinite(g)&&g>0?g/this._cellCm*this._gridPitch:s,v=this._pos(e);if(ph([v.x,v.y],c,h)){this._forgetGlowSource(d);continue}const y=this._glowTransition(d,!!m);if(!y)continue;m&&this._glowLastAppearance.set(d,{c:m.c,alpha:Ss(m.bri,i.glow_light.a)});const b=this._glowLastAppearance.get(d);if(!b)continue;let w=null;const k=`${t.id}|${l}|${v.x.toFixed(4)},${v.y.toFixed(4)}|${f.toFixed(4)}`,x=jf(this._glowClipCache,k);if(x.hit)w=x.value;else{const e=Ou([v.x,v.y],f,a,96);w={lit:e.length>=3?ah([e],r,{onBoundsFailure:({boundIndex:e,phase:i})=>{const s=n[e]?.r;this._warnGlowGeometryFallback(t.id,l,s?.id||`#${e}`,i)}}):[]},Uf(this._glowClipCache,k,w,256)}u.push({key:d,sourceEid:o.eid,domId:y.domId,entering:y.entering,leaving:y.leaving,pos:v,c:b.c,alpha:b.alpha,geometry:w,r:f})}const m=`${t.id}|`;for(const t of this._glowRenderedSources.keys())t.startsWith(m)&&!_.has(t)&&this._forgetGlowSource(t);if(!u.length)return j``;const g=this._spaceWalls,f=o.length===n.length?[]:this._openCuts(),v=this._wallUnionGeometry()?.roomGeom,y=o.length===n.length?null:o.map(({r:e,poly:i})=>{const s=g.length&&e.id&&this._innerRoomContour(t,e.id,f,v)||i,o=this._cleanFloor(e,s,t).path,a=Pi(s,n.filter(t=>t.r!==e).map(t=>t.poly)),r=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z";return[o||r(s),...a.map(r)].join(" ")}),b=this._viewOr(this._baseVb()),w=this._stageEl?.clientWidth&&b.w?this._stageEl.clientWidth/b.w:1,k=1/(w>0?w:1),x=!this._pinchStart&&!this._panStart&&Date.now()>=this._glowFeatherSuspendUntil;(null==this._glowFeatherUnits||x)&&(this._glowFeatherUnits=k);const $=this._glowFeatherUnits??k,S=4*$,M=u.reduce((t,e)=>({x:Math.min(t.x,e.pos.x-e.r-S),y:Math.min(t.y,e.pos.y-e.r-S),maxX:Math.max(t.maxX,e.pos.x+e.r+S),maxY:Math.max(t.maxY,e.pos.y+e.r+S),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});return M.w=M.maxX-M.x,M.h=M.maxY-M.y,j` ${Mt(u,t=>t.key,t=>{const e=t.domId,i=t.geometry;return j` ${""} {const s=1===t.length?t[0]:e.reduce((e,i,s)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[s+1],t[0]);return new n(s,t,i)},a=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return(t=>new n("string"==typeof t?t:t+"",void 0,i))(e)})(t):t,{is:r,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:p}=Object,u=globalThis,_=u.trustedTypes,m=_?_.emptyScript:"",g=u.reactiveElementPolyfillSupport,f=(t,e)=>t,v={toAttribute(t,e){switch(e){case Boolean:t=t?m:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},y=(t,e)=>!r(t,e),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),u.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=b){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);void 0!==s&&l(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=c(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:s,set(e){const o=s?.call(this);n?.call(this,e),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const t=p(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const t=this.properties,e=[...h(t),...d(t)];for(const i of e)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,i]of e)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const i=this._$Eu(t,e);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(a(t))}else void 0!==t&&e.push(a(t));return e}static _$Eu(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,s)=>{if(e)i.adoptedStyleSheets=s.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of s){const s=document.createElement("style"),n=t.litNonce;void 0!==n&&s.setAttribute("nonce",n),s.textContent=e.cssText,i.appendChild(s)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$ET(t,e){const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(void 0!==s&&!0===i.reflect){const n=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(e,i.type);this._$Em=t,null==n?this.removeAttribute(s):this.setAttribute(s,n),this._$Em=null}}_$AK(t,e){const i=this.constructor,s=i._$Eh.get(t);if(void 0!==s&&this._$Em!==s){const t=i.getPropertyOptions(s),n="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:v;this._$Em=s;const o=n.fromAttribute(e,t.type);this[s]=o??this._$Ej?.get(s)??o,this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(void 0!==t){const o=this.constructor;if(!1===s&&(n=this[t]),i??=o.getPropertyOptions(t),!((i.hasChanged??y)(n,e)||i.useDefault&&i.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,e,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:i,reflect:s,wrapped:n},o){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==n||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),!0===s&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,i]of t){const{wrapped:t}=i,s=this[e];!0!==t||this._$AL.has(e)||void 0===s||this.C(e,void 0,i,s)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(u.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=t=>t,$=k.trustedTypes,S=$?$.createPolicy("lit-html",{createHTML:t=>t}):void 0,M="$lit$",C=`lit$${Math.random().toFixed(9).slice(2)}$`,D="?"+C,P=`<${D}>`,T=document,R=()=>T.createComment(""),I=t=>null===t||"object"!=typeof t&&"function"!=typeof t,A=Array.isArray,z="[ \t\n\f\r]",F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,E=/-->/g,N=/>/g,O=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),L=/'/g,H=/"/g,B=/^(?:script|style|textarea|title)$/i,q=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),W=q(1),j=q(2),U=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),V=new WeakMap,K=T.createTreeWalker(T,129);function Y(t,e){if(!A(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==S?S.createHTML(e):e}const J=(t,e)=>{const i=t.length-1,s=[];let n,o=2===e?"":3===e?"":"",a=F;for(let e=0;e"===l[0]?(a=n??F,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,r=l[1],a=void 0===l[3]?O:'"'===l[3]?H:L):a===H||a===L?a=O:a===E||a===N?a=F:(a=O,n=void 0);const d=a===O&&t[e+1].startsWith("/>")?" ":"";o+=a===F?i+P:c>=0?(s.push(r),i.slice(0,c)+M+i.slice(c)+C+d):i+C+(-2===c?e:d)}return[Y(t,o+(t[i]||"")+(2===e?"":3===e?"":"")),s]};class X{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,o=0;const a=t.length-1,r=this.parts,[l,c]=J(t,e);if(this.el=X.createElement(l,i),K.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(s=K.nextNode())&&r.length0){s.textContent=$?$.emptyScript:"";for(let i=0;iA(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==G&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:i}=t,s="number"==typeof i?this._$AC(t):(void 0===i.el&&(i.el=X.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===s)this._$AH.p(e);else{const t=new Q(s,this),i=t.u(this.options);t.p(e),this.T(i),this._$AH=t}}_$AC(t){let e=V.get(t.strings);return void 0===e&&V.set(t.strings,e=new X(t)),e}k(t){A(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new tt(this.O(R()),this.O(R()),this,this.options)):i=e[s],i._$AI(n),s++;s2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(t,e=this,i,s){const n=this.strings;let o=!1;if(void 0===n)t=Z(this,t,e,0),o=!I(t)||t!==this._$AH&&t!==U,o&&(this._$AH=t);else{const s=t;let a,r;for(t=n[0],a=0;a{const s=i?.renderBefore??e;let n=s._$litPart$;if(void 0===n){const t=i?.renderBefore??null;s._$litPart$=n=new tt(e.insertBefore(R(),t),t,void 0,i??{})}return n._$AI(t),n},ct=globalThis;let ht=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=lt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};ht._$litElement$=!0,ht.finalized=!0,ct.litElementHydrateSupport?.({LitElement:ht});const dt=ct.litElementPolyfillSupport;dt?.({LitElement:ht}),(ct.litElementVersions??=[]).push("4.2.2");const pt=2,ut=t=>(...e)=>({_$litDirective$:t,values:e});let _t=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const mt={},gt=ut(class extends _t{constructor(){super(...arguments),this.ot=mt}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return U}else if(this.ot===e)return U;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}}),{I:ft}=at,vt=t=>t,yt=()=>document.createComment(""),bt=(t,e,i)=>{const s=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=s.insertBefore(yt(),n),o=s.insertBefore(yt(),n);i=new ft(e,o,t,t.options)}else{const e=i._$AB.nextSibling,o=i._$AM,a=o!==t;if(a){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==o._$AU&&i._$AP(e)}if(e!==n||a){let t=i._$AA;for(;t!==e;){const e=vt(t).nextSibling;vt(s).insertBefore(t,n),t=e}}}return i},wt=(t,e,i=t)=>(t._$AI(e,i),t),kt={},xt=(t,e=kt)=>t._$AH=e,$t=t=>{t._$AR(),t._$AA.remove()},St=(t,e,i)=>{const s=new Map;for(let n=e;n<=i;n++)s.set(t[n],n);return s},Mt=ut(class extends _t{constructor(t){if(super(t),t.type!==pt)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let s;void 0===i?i=e:void 0!==e&&(s=e);const n=[],o=[];let a=0;for(const e of t)n[a]=s?s(e,a):a,o[a]=i(e,a),a++;return{values:o,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,s]){const n=(t=>t._$AH)(t),{values:o,keys:a}=this.dt(e,i,s);if(!Array.isArray(n))return this.ut=a,o;const r=this.ut??=[],l=[];let c,h,d=0,p=n.length-1,u=0,_=o.length-1;for(;d<=p&&u<=_;)if(null===n[d])d++;else if(null===n[p])p--;else if(r[d]===a[u])l[u]=wt(n[d],o[u]),d++,u++;else if(r[p]===a[_])l[_]=wt(n[p],o[_]),p--,_--;else if(r[d]===a[_])l[_]=wt(n[d],o[_]),bt(t,l[_+1],n[d]),d++,_--;else if(r[p]===a[u])l[u]=wt(n[p],o[u]),bt(t,n[d],n[p]),p--,u++;else if(void 0===c&&(c=St(a,u,_),h=St(r,d,p)),c.has(r[d]))if(c.has(r[p])){const e=h.get(a[u]),i=void 0!==e?n[e]:null;if(null===i){const e=bt(t,n[d]);wt(e,o[u]),l[u]=e}else l[u]=wt(i,o[u]),bt(t,n[d],i),n[e]=null;u++}else $t(n[p]),p--;else $t(n[d]),d++;for(;u<=_;){const e=bt(t,l[_+1]);wt(e,o[u]),l[u++]=e}for(;d<=p;){const t=n[d++];null!==t&&$t(t)}return this.ut=a,xt(t,l),U}}),Ct=new WeakMap;let Dt=0;class Pt extends ht{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=!1,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Dt,this._focusInitial=()=>{const t=this._focusableElements(),e=t.find(t=>t.hasAttribute("autofocus"))||t[0]||(this._useHaDialog?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");e?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=t=>{if("Escape"===t.key){t.preventDefault(),t.stopImmediatePropagation(),this._pruneOverlays();const e=this._overlays[this._overlays.length-1];return e?void this._closeOverlay(e,"escape"):void this._requestClose()}if("Tab"!==t.key||this._useHaDialog)return;const e=this.renderRoot.querySelector(".close"),i=e?[e,...this._focusableElements()]:this._focusableElements();if(!i.length)return t.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const s=this._deepActiveElement(),n=i[0],o=i[i.length-1];!t.shiftKey||s!==n&&i.includes(s)?t.shiftKey||s!==o||(t.preventDefault(),n.focus()):(t.preventDefault(),o.focus())},this._onFallbackCancel=t=>{t.preventDefault(),this._requestClose()},this._onFallbackClick=t=>{this.dismissOnScrim&&t.target===t.currentTarget&&this._requestClose()}}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const t=this.getRootNode();this._focusRoot=t;const e=Ct.get(t)||{dialogs:new Set,opener:this._opener};e.dialogs.add(this),Ct.set(t,e),this._useHaDialog=!!customElements.get("ha-dialog"),this.addEventListener("keydown",this._onKeyDown,!0)}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const t=[...this._overlays];this._overlays=[];for(const e of t.reverse())e.close("disconnect");const e=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const s=e?Ct.get(e):void 0;s?.dialogs.delete(this),super.disconnectedCallback(),e&&s&&requestAnimationFrame(()=>{const t=Ct.get(e);if(!t)return;if(!t.dialogs.size)return t.opener?.isConnected&&t.opener.focus({preventScroll:!0}),void Ct.delete(e);const s=i?.closest("hp-dialog");i?.isConnected&&s&&t.dialogs.has(s)&&i.focus({preventScroll:!0})})}firstUpdated(t){if(super.firstUpdated(t),!this._useHaDialog){const t=this.renderRoot.querySelector("dialog");t&&!t.open&&t.showModal()}queueMicrotask(()=>this._focusInitial())}_deepActiveElement(){let t=document.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t&&t!==document.body?t:null}_focusableElements(){const t=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),e=[],i=new Set,s=n=>{if(!i.has(n)){if(i.add(n),n instanceof HTMLElement){if(n.matches(t)&&e.push(n),n instanceof HTMLSlotElement){for(const t of n.assignedNodes({flatten:!0}))s(t);return}if(n.shadowRoot){for(const t of n.shadowRoot.childNodes)s(t);return}}for(const t of n.childNodes)s(t)}};for(const t of this.childNodes)s(t);const n=this.overlayPortal();return n&&s(n),e.filter(t=>{let e=t;for(;e;){const t=getComputedStyle(e);if(e.hidden||e.inert||"true"===e.getAttribute("aria-hidden")||"none"===t.display||"hidden"===t.visibility)return!1;if(e=e.assignedSlot||e.parentElement||(e.getRootNode()instanceof ShadowRoot?e.getRootNode().host:null),e===this)break}return!0})}_pruneOverlays(){this._overlays=this._overlays.filter(t=>t.owner.isConnected)}_closeOverlay(t,e){const i=this._overlays.findIndex(e=>e.token===t.token);i>=0&&this._overlays.splice(i,1),t.close(e)}registerOverlay(t){this._pruneOverlays();const e=this._overlays.find(e=>e.owner===t.owner);e&&this._overlays.splice(this._overlays.indexOf(e),1);const i=t.group||"transient";for(const t of[...this._overlays].reverse())t.group===i&&this._closeOverlay(t,"exclusive");const s={...t,group:i,token:Symbol("hp-overlay")};this._overlays.push(s);let n=!1;return()=>{if(n)return;n=!0;const t=this._overlays.findIndex(t=>t.token===s.token);t>=0&&this._overlays.splice(t,1)}}closeTransientOverlays(t="outside"){this._pruneOverlays();const e=[...this._overlays].filter(t=>"transient"===(t.group||"transient"));for(const i of e.reverse())this._closeOverlay(i,t);return e.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const t=W` +globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="fe0a35cf861928503f26ca1e1b7b14f6bd9a18bf8770e41df2f1ff30332973e9";const t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),s=new WeakMap;let n=class{constructor(t,e,s){if(this._$cssResult$=!0,s!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const i=this.t;if(e&&void 0===t){const e=void 0!==i&&1===i.length;e&&(t=s.get(i)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&s.set(i,t))}return t}toString(){return this.cssText}};const o=(t,...e)=>{const s=1===t.length?t[0]:e.reduce((e,i,s)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[s+1],t[0]);return new n(s,t,i)},a=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return(t=>new n("string"==typeof t?t:t+"",void 0,i))(e)})(t):t,{is:r,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:p}=Object,u=globalThis,_=u.trustedTypes,m=_?_.emptyScript:"",g=u.reactiveElementPolyfillSupport,f=(t,e)=>t,v={toAttribute(t,e){switch(e){case Boolean:t=t?m:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},y=(t,e)=>!r(t,e),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),u.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=b){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);void 0!==s&&l(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=c(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:s,set(e){const o=s?.call(this);n?.call(this,e),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const t=p(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const t=this.properties,e=[...h(t),...d(t)];for(const i of e)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,i]of e)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const i=this._$Eu(t,e);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(a(t))}else void 0!==t&&e.push(a(t));return e}static _$Eu(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,s)=>{if(e)i.adoptedStyleSheets=s.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of s){const s=document.createElement("style"),n=t.litNonce;void 0!==n&&s.setAttribute("nonce",n),s.textContent=e.cssText,i.appendChild(s)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$ET(t,e){const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(void 0!==s&&!0===i.reflect){const n=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(e,i.type);this._$Em=t,null==n?this.removeAttribute(s):this.setAttribute(s,n),this._$Em=null}}_$AK(t,e){const i=this.constructor,s=i._$Eh.get(t);if(void 0!==s&&this._$Em!==s){const t=i.getPropertyOptions(s),n="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:v;this._$Em=s;const o=n.fromAttribute(e,t.type);this[s]=o??this._$Ej?.get(s)??o,this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(void 0!==t){const o=this.constructor;if(!1===s&&(n=this[t]),i??=o.getPropertyOptions(t),!((i.hasChanged??y)(n,e)||i.useDefault&&i.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,e,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:i,reflect:s,wrapped:n},o){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==n||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),!0===s&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,i]of t){const{wrapped:t}=i,s=this[e];!0!==t||this._$AL.has(e)||void 0===s||this.C(e,void 0,i,s)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(u.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=t=>t,$=k.trustedTypes,S=$?$.createPolicy("lit-html",{createHTML:t=>t}):void 0,M="$lit$",C=`lit$${Math.random().toFixed(9).slice(2)}$`,D="?"+C,P=`<${D}>`,T=document,R=()=>T.createComment(""),I=t=>null===t||"object"!=typeof t&&"function"!=typeof t,A=Array.isArray,z="[ \t\n\f\r]",F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,E=/-->/g,N=/>/g,O=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),L=/'/g,H=/"/g,B=/^(?:script|style|textarea|title)$/i,q=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),W=q(1),j=q(2),U=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),V=new WeakMap,K=T.createTreeWalker(T,129);function Y(t,e){if(!A(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==S?S.createHTML(e):e}const J=(t,e)=>{const i=t.length-1,s=[];let n,o=2===e?"":3===e?"":"",a=F;for(let e=0;e"===l[0]?(a=n??F,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,r=l[1],a=void 0===l[3]?O:'"'===l[3]?H:L):a===H||a===L?a=O:a===E||a===N?a=F:(a=O,n=void 0);const d=a===O&&t[e+1].startsWith("/>")?" ":"";o+=a===F?i+P:c>=0?(s.push(r),i.slice(0,c)+M+i.slice(c)+C+d):i+C+(-2===c?e:d)}return[Y(t,o+(t[i]||"")+(2===e?"":3===e?"":"")),s]};class X{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,o=0;const a=t.length-1,r=this.parts,[l,c]=J(t,e);if(this.el=X.createElement(l,i),K.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(s=K.nextNode())&&r.length0){s.textContent=$?$.emptyScript:"";for(let i=0;iA(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==G&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:i}=t,s="number"==typeof i?this._$AC(t):(void 0===i.el&&(i.el=X.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===s)this._$AH.p(e);else{const t=new Q(s,this),i=t.u(this.options);t.p(e),this.T(i),this._$AH=t}}_$AC(t){let e=V.get(t.strings);return void 0===e&&V.set(t.strings,e=new X(t)),e}k(t){A(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new tt(this.O(R()),this.O(R()),this,this.options)):i=e[s],i._$AI(n),s++;s2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(t,e=this,i,s){const n=this.strings;let o=!1;if(void 0===n)t=Z(this,t,e,0),o=!I(t)||t!==this._$AH&&t!==U,o&&(this._$AH=t);else{const s=t;let a,r;for(t=n[0],a=0;a{const s=i?.renderBefore??e;let n=s._$litPart$;if(void 0===n){const t=i?.renderBefore??null;s._$litPart$=n=new tt(e.insertBefore(R(),t),t,void 0,i??{})}return n._$AI(t),n},ct=globalThis;let ht=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=lt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};ht._$litElement$=!0,ht.finalized=!0,ct.litElementHydrateSupport?.({LitElement:ht});const dt=ct.litElementPolyfillSupport;dt?.({LitElement:ht}),(ct.litElementVersions??=[]).push("4.2.2");const pt=2,ut=t=>(...e)=>({_$litDirective$:t,values:e});let _t=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const mt={},gt=ut(class extends _t{constructor(){super(...arguments),this.ot=mt}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return U}else if(this.ot===e)return U;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}}),{I:ft}=at,vt=t=>t,yt=()=>document.createComment(""),bt=(t,e,i)=>{const s=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=s.insertBefore(yt(),n),o=s.insertBefore(yt(),n);i=new ft(e,o,t,t.options)}else{const e=i._$AB.nextSibling,o=i._$AM,a=o!==t;if(a){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==o._$AU&&i._$AP(e)}if(e!==n||a){let t=i._$AA;for(;t!==e;){const e=vt(t).nextSibling;vt(s).insertBefore(t,n),t=e}}}return i},wt=(t,e,i=t)=>(t._$AI(e,i),t),kt={},xt=(t,e=kt)=>t._$AH=e,$t=t=>{t._$AR(),t._$AA.remove()},St=(t,e,i)=>{const s=new Map;for(let n=e;n<=i;n++)s.set(t[n],n);return s},Mt=ut(class extends _t{constructor(t){if(super(t),t.type!==pt)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let s;void 0===i?i=e:void 0!==e&&(s=e);const n=[],o=[];let a=0;for(const e of t)n[a]=s?s(e,a):a,o[a]=i(e,a),a++;return{values:o,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,s]){const n=(t=>t._$AH)(t),{values:o,keys:a}=this.dt(e,i,s);if(!Array.isArray(n))return this.ut=a,o;const r=this.ut??=[],l=[];let c,h,d=0,p=n.length-1,u=0,_=o.length-1;for(;d<=p&&u<=_;)if(null===n[d])d++;else if(null===n[p])p--;else if(r[d]===a[u])l[u]=wt(n[d],o[u]),d++,u++;else if(r[p]===a[_])l[_]=wt(n[p],o[_]),p--,_--;else if(r[d]===a[_])l[_]=wt(n[d],o[_]),bt(t,l[_+1],n[d]),d++,_--;else if(r[p]===a[u])l[u]=wt(n[p],o[u]),bt(t,n[d],n[p]),p--,u++;else if(void 0===c&&(c=St(a,u,_),h=St(r,d,p)),c.has(r[d]))if(c.has(r[p])){const e=h.get(a[u]),i=void 0!==e?n[e]:null;if(null===i){const e=bt(t,n[d]);wt(e,o[u]),l[u]=e}else l[u]=wt(i,o[u]),bt(t,n[d],i),n[e]=null;u++}else $t(n[p]),p--;else $t(n[d]),d++;for(;u<=_;){const e=bt(t,l[_+1]);wt(e,o[u]),l[u++]=e}for(;d<=p;){const t=n[d++];null!==t&&$t(t)}return this.ut=a,xt(t,l),U}}),Ct=new WeakMap;let Dt=0;class Pt extends ht{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=!1,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Dt,this._focusInitial=()=>{const t=this._focusableElements(),e=t.find(t=>t.hasAttribute("autofocus"))||t[0]||(this._useHaDialog?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");e?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=t=>{if("Escape"===t.key){t.preventDefault(),t.stopImmediatePropagation(),this._pruneOverlays();const e=this._overlays[this._overlays.length-1];return e?void this._closeOverlay(e,"escape"):void this._requestClose()}if("Tab"!==t.key||this._useHaDialog)return;const e=this.renderRoot.querySelector(".close"),i=e?[e,...this._focusableElements()]:this._focusableElements();if(!i.length)return t.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const s=this._deepActiveElement(),n=i[0],o=i[i.length-1];!t.shiftKey||s!==n&&i.includes(s)?t.shiftKey||s!==o||(t.preventDefault(),n.focus()):(t.preventDefault(),o.focus())},this._onFallbackCancel=t=>{t.preventDefault(),this._requestClose()},this._onFallbackClick=t=>{this.dismissOnScrim&&t.target===t.currentTarget&&this._requestClose()}}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const t=this.getRootNode();this._focusRoot=t;const e=Ct.get(t)||{dialogs:new Set,opener:this._opener};e.dialogs.add(this),Ct.set(t,e),this._useHaDialog=!!customElements.get("ha-dialog"),this.addEventListener("keydown",this._onKeyDown,!0)}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const t=[...this._overlays];this._overlays=[];for(const e of t.reverse())e.close("disconnect");const e=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const s=e?Ct.get(e):void 0;s?.dialogs.delete(this),super.disconnectedCallback(),e&&s&&requestAnimationFrame(()=>{const t=Ct.get(e);if(!t)return;if(!t.dialogs.size)return t.opener?.isConnected&&t.opener.focus({preventScroll:!0}),void Ct.delete(e);const s=i?.closest("hp-dialog");i?.isConnected&&s&&t.dialogs.has(s)&&i.focus({preventScroll:!0})})}firstUpdated(t){if(super.firstUpdated(t),!this._useHaDialog){const t=this.renderRoot.querySelector("dialog");t&&!t.open&&t.showModal()}queueMicrotask(()=>this._focusInitial())}_deepActiveElement(){let t=document.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t&&t!==document.body?t:null}_focusableElements(){const t=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),e=[],i=new Set,s=n=>{if(!i.has(n)){if(i.add(n),n instanceof HTMLElement){if(n.matches(t)&&e.push(n),n instanceof HTMLSlotElement){for(const t of n.assignedNodes({flatten:!0}))s(t);return}if(n.shadowRoot){for(const t of n.shadowRoot.childNodes)s(t);return}}for(const t of n.childNodes)s(t)}};for(const t of this.childNodes)s(t);const n=this.overlayPortal();return n&&s(n),e.filter(t=>{let e=t;for(;e;){const t=getComputedStyle(e);if(e.hidden||e.inert||"true"===e.getAttribute("aria-hidden")||"none"===t.display||"hidden"===t.visibility)return!1;if(e=e.assignedSlot||e.parentElement||(e.getRootNode()instanceof ShadowRoot?e.getRootNode().host:null),e===this)break}return!0})}_pruneOverlays(){this._overlays=this._overlays.filter(t=>t.owner.isConnected)}_closeOverlay(t,e){const i=this._overlays.findIndex(e=>e.token===t.token);i>=0&&this._overlays.splice(i,1),t.close(e)}registerOverlay(t){this._pruneOverlays();const e=this._overlays.find(e=>e.owner===t.owner);e&&this._overlays.splice(this._overlays.indexOf(e),1);const i=t.group||"transient";for(const t of[...this._overlays].reverse())t.group===i&&this._closeOverlay(t,"exclusive");const s={...t,group:i,token:Symbol("hp-overlay")};this._overlays.push(s);let n=!1;return()=>{if(n)return;n=!0;const t=this._overlays.findIndex(t=>t.token===s.token);t>=0&&this._overlays.splice(t,1)}}closeTransientOverlays(t="outside"){this._pruneOverlays();const e=[...this._overlays].filter(t=>"transient"===(t.group||"transient"));for(const i of e.reverse())this._closeOverlay(i,t);return e.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const t=W` ${this.icon?W``:G} ${this.title} `;return this._useHaDialog?W` `})} - `}const Rr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Ir=(t,e=1)=>{const i=Number(t);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):e},Ar=t=>{let e=Number(t);return Number.isFinite(e)?(e=(e%360+360)%360,e>180?e-360:e):0};function zr(t,e,i){return Ar(e)?[t.x,t.y]:i([t.x,t.y])}const Fr=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&s>0?s/n*i:0},Er=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&i>0?s/i*n:0},Nr=(t,e,i,s=Rr.widthCm)=>{const n=Number(t?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(t?.width);return Number.isFinite(o)&&o>0?Er(o,e,i):s};function Or(t,e){return{color:t.color,opacity:Ir(t.opacity),width_cm:Math.max(.1,Math.min(100,Number(t.widthCm)||.1)),...e?{fill:t.fill,fill_color:t.fillColor,fill_opacity:Ir(t.fillOpacity,.25)}:{}}}function Lr(t){const e=t.x+t.w/2,i=t.y+t.h/2,s=Ar(t.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(t,s)=>{const a=t-e,r=s-i;return[e+a*n-r*o,i+a*o+r*n]};return[a(t.x,t.y),a(t.x+t.w,t.y),a(t.x+t.w,t.y+t.h),a(t.x,t.y+t.h)]}function Hr(t){const e=Lr(t),i=(t,e)=>[(t[0]+e[0])/2,(t[1]+e[1])/2],s=[(e[0][0]+e[2][0])/2,(e[0][1]+e[2][1])/2];return{points:[...e,i(e[0],e[1]),i(e[1],e[2]),i(e[2],e[3]),i(e[3],e[0]),s],segments:e.map((t,i)=>({a:t,b:e[(i+1)%4]}))}}function Br(t,e,i,s,n,o,a,r){const l=Ar(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=t.x+t.w/2,_=t.y+t.h/2,m=e>0?-t.w/2:t.w/2,g=i>0?-t.h/2:t.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(e>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const e=w/Math.max(t.w,r),i=k/Math.max(t.h,r);x=Math.max(r/Math.max(t.w,r),r/Math.max(t.h,r),e,i),w=t.w*x,k=t.h*x}if(a>0)if(o){const e=Math.max(1,Math.round(t.w/a)),i=Math.max(1,Math.round(t.h/a));if(Math.abs(t.w-e*a)<1e-6&&Math.abs(t.h-i*a)<1e-6){const s=(t,e)=>{let i=Math.abs(t),s=Math.abs(e);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(e,i),o=Math.max(r/t.w,r/t.h),a=Math.max(o,Math.round((x??1)/n)*n);w=t.w*a,k=t.h*a}else{t.w>=t.h?(w=Math.round(w/a)*a,k=w*(t.h/Math.max(t.w,r))):(k=Math.round(k/a)*a,w=k*(t.w/Math.max(t.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(e>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(e>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Ar(t.angle)||void 0}}const qr=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<1e-12)return[...e];const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return[e[0]+s*a,e[1]+n*a]};const Wr=10**9,jr=240,Ur=1e-4;function Gr(t){if(Array.isArray(t))return t.map(t=>Gr(t));if(null!==t&&"object"==typeof t){const e={};for(const[i,s]of Object.entries(t))e[i]=Gr(s);return e}return t}function Vr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=(t<0||Object.is(t,-0)?-1:1)*(Math.floor(Math.abs(t)*Wr+.5)/Wr);return 0===e?0:e}function Kr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=t*jr,i=Math.round(e);if(Math.abs(e-i)null!==Jr(t)):[]}function Zr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Vr(t[i]))}function Qr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Kr(t[i]))}function tl(t){if(Array.isArray(t))for(let e=0;e{for(const n of s){const s=e[n];"number"==typeof s&&Number.isFinite(s)&&i(s,t)}},s=e=>{if(Array.isArray(e))for(let s=0;s{if(Array.isArray(t))for(const e of t)s(e)};for(const i of Xr(t.rooms))e(i,["x","y","w","h"]),n(i.poly);for(const e of Xr(t.walls))s(e.a),s(e.b);for(const e of Xr(t.wall_segments))s(e.a),s(e.b);for(const i of Xr(t.openings))e(i,["x","y"]);for(const i of Xr(t.decor))"line"===i.kind?e(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?e(i,["x","y","w","h"]):"text"===i.kind&&e(i,["x","y"]);for(const e of Xr(t.room_drafts))n(e.points);for(const e of Xr(t.partitions))s(e.a),s(e.b);for(const e of Xr(t.wall_columns))s(e.center);for(const e of Xr(t.open_spans))s(e.a),s(e.b)}const n=Jr(e);if(!n)return;const o=new Map;if(s)for(const t of Xr(s.spaces))null!=t.id&&o.set(String(t.id),t);for(const t of Object.values(n)){const e=Jr(t);if(!e)continue;const s=null!=e.s&&o.get(String(e.s))||null;for(const t of["x","y"]){const n=e[t];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function sl(t){const e=Number(t?.cell_cm);return e>0?e:5}function nl(t,e={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=Xr(Jr(t)?.spaces);let n=5;for(const t of s)n=Math.max(n,sl(t));il(t,e,(t,e)=>{const s=t*jr,o=Math.abs(s-Math.round(s)),a=Kr(t),r=o>0&&o=Ur))return;const l=r&&"number"==typeof a?Math.abs(a-t):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*jr*(e?sl(e):n)),!e?.id||!r)return;const c=String(e.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(e.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*jr*sl(e))}),i.bySpace.size&&il(t,e,(t,e)=>{if(!e?.id)return;const s=i.bySpace.get(String(e.id));if(!s)return;const n=t*jr;Math.abs(n-Math.round(n))>=Ur&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function ol(t){return function(t){const e=t,i=Jr(e);i&&Qr(i,["x","y"]);return e}(Gr(t))}function al(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Object.values(i)){const e=Jr(t);e&&Qr(e,["x","y"])}return e}function rl(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Xr(i.spaces)){Zr(t,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const e of Xr(t.rooms))Qr(e,["x","y","w","h"]),el(e.poly);for(const e of Xr(t.walls))tl(e.a),tl(e.b);for(const e of Xr(t.wall_segments))tl(e.a),tl(e.b);for(const e of Xr(t.openings)){Qr(e,["x","y"]),Zr(e,["angle","length"]);const t=Jr(e.host);t&&Zr(t,["t"])}for(const e of Xr(t.decor))"line"===e.kind?Qr(e,["x1","y1","x2","y2"]):"rect"===e.kind||"ellipse"===e.kind||"furniture"===e.kind?(Qr(e,["x","y","w","h"]),Zr(e,["angle"])):"text"===e.kind&&(Qr(e,["x","y"]),Zr(e,["scale","angle"]));for(const e of Xr(t.room_drafts))el(e.points);for(const e of Xr(t.partitions))tl(e.a),tl(e.b);for(const e of Xr(t.wall_columns))tl(e.center),"square"===e.shape&&Zr(e,["angle"]);for(const e of Xr(t.open_spans))tl(e.a),tl(e.b)}for(const t of Xr(i.markers))Zr(t,["angle"]);return e}const ll=15;function cl(t,e,i,s,n){const o=i[0]-t[0],a=i[1]-t[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=e=>{const s=(e[0]-t[0])*l+(e[1]-t[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[e[0]+(i[0]-e[0])*o,e[1]+(i[1]-e[1])*o]},d=h(e),p=h(s);return d&&p?[[t[0],t[1]],e,d,p,s]:null}const hl=Math.sin(.25*Math.PI/180);function dl(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<3}function pl(t){const e=Number(t)>0?Number(t):5;if(5===e)return 8;const i=5/e*8;return Math.min(80,Math.max(.5,i))}function ul(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<2}function _l(t){return Number.isFinite(t)?Math.max(1,Math.min(100,t)):1}function ml(t,e){return!Number.isFinite(t)||t<0?"":String(e?Math.round(t/2.54*100)/100:Math.round(100*t)/100)}function gl(t,e,i){if(!Number.isFinite(t)||t<=0)return 0;const s=Number(e)>0?Number(e):5;return _l(t)/s*i}function fl(t,e){return e>0&&Number.isFinite(t)?Math.round(t/e)*e:t}function vl(t){return Math.max(1e-6*Math.abs(t),1e-9)}function yl(t,e){if(!(e>0&&Number.isFinite(t)))return t;const i=fl(t,e);return Math.abs(i-t)<=vl(e)?i:t}function bl(t,e){let i=e[0]-t[0],s=e[1]-t[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function wl(t,e,i){const s=[yl(t[0],i),yl(t[1],i)],n=[yl(e[0],i),yl(e[1],i)],o=fl((s[0]+n[0])/2,i),a=fl((s[1]+n[1])/2,i),[r,l]=bl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function kl(t,e,i,s){return 1===s?wl(t,e,i):wl([t[0]/s,t[1]/s],[e[0]/s,e[1]/s],i)}function xl(t,e){if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return null;const i=[Number(t.a[0]),Number(t.a[1]),Number(t.b[0]),Number(t.b[1])];if(!i.every(Number.isFinite))return null;const s=e>0?e:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function $l(t,e,i,s,n){const o=n>0?n:1;return{key:kl(t,e,s,o),cm:_l(i),a:[t[0]/o,t[1]/o],b:[e[0]/o,e[1]/o]}}function Sl(t,e){const i=e>0?e:1,s=[];for(const e of t){const t=e.key.lastIndexOf("@");if(t<0)continue;const[n,o]=e.key.slice(0,t).split(",").map(Number),a=Number(e.key.slice(t+1));[n,o,a].every(Number.isFinite)&&s.push({w:e,x:n*i,y:o*i,ang:a})}return s}function Ml(t,e){const[i,s]=bl(t,e);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Cl(t,e){let i=Math.abs(t-e);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Dl(t,e,i,s,n=1){if(!t?.length)return null;const o=kl(e,i,s,n),a=t.find(t=>t.key===o);if(a)return a;const r=n>0?n:1,l=vl(s)*r,c=(t,e)=>Math.abs(t[0]-e[0])<=l&&Math.abs(t[1]-e[1])<=l;for(const s of t){const t=xl(s,r);if(t&&(c(t[0],e)&&c(t[1],i)||c(t[0],i)&&c(t[1],e)))return s}const h=(e[0]+i[0])/2,d=(e[1]+i[1])/2,p=Ml(e,i),u=Math.max(.5*s,1e-9)*r;for(const e of Sl(t,r))if(Cl(e.ang,p)&&Math.hypot(e.x-h,e.y-d)<=u)return e.w;return null}function Pl(t,e,i,s,n=1){const o=Dl(t,e,i,s,n);if(o&&o.cm>0)return _l(o.cm);const a=function(t,e,i,s,n){if(!t?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-e[0],i[1]-e[1]);if(a<1e-12)return null;const r=Ml(e,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of t){if(!(s.cm>0))continue;const t=xl(s,o);if(!t)continue;const n=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);if(n<1e-12||!Cl(Ml(t[0],t[1]),r))continue;if(mc(e[0],e[1],t[0][0],t[0][1],t[1][0],t[1][1])>l||mc(i[0],i[1],t[0][0],t[0][1],t[1][0],t[1][1])>l)continue;if(n+l(o.has(t.key)||(t=>{const e=xl(t,s);if(!e)return!1;const[i,o]=e,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];return Cl(Ml(i,o),Ml(e,s))&&mc(i[0],i[1],e[0],e[1],s[0],s[1])<=l&&mc(o[0],o[1],e[0],e[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];if(!Cl(Ml(i,o),Ml(e,s)))return!1;const n=t=>Math.abs((t[0]-i[0])*c-(t[1]-i[1])*r)/h;if(n(e)>l||n(s)>l)return!1;const a=h*h,d=((e[0]-i[0])*r+(e[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(t))&&t.cm>=1&&t.cm<=100)}function Rl(t,e,i,s=8){const[n,o]=bl(t,e);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Il(t,e,i,s,n=1,o="affine",a){if(!t?.length)return[];if(e.length!==i.length)return"fixed-topology"===o&&a?.(),t.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(t,e,i)=>{const s=t.get(e)||new Set;s.add(i),t.set(e,s)};for(let t=0;t[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],m=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=c,g=(t,e)=>{if("fixed-topology"===o){const i=e.na[0]-e.oa[0],s=e.na[1]-e.oa[1],n=e.nb[0]-e.ob[0],o=e.nb[1]-e.ob[1];return Math.hypot(i-n,s-o)<=c?[t[0]+i,t[1]+s]:m(t,e.oa)?[...e.na]:m(t,e.ob)?[...e.nb]:[...t]}const i=Math.max(0,Math.min(1,((t[0]-e.oa[0])*e.dx+(t[1]-e.oa[1])*e.dy)/e.len2));return _(e.na,e.nb,i)},f=(t,e)=>{const[i,s]=bl(t,e);return(e[0]-t[0])*i+(e[1]-t[1])*s>=0?[[...t],[...e]]:[[...e],[...t]]},v=[],y=[],b=(t,e,i)=>{if(Math.hypot(e[0]-t[0],e[1]-t[1])<=c)return;const[n,o]=f(t,e),a=_l(i);if(y.some(t=>t.entry.cm===a&&m(t.span[0],n)&&m(t.span[1],o)))return;const l=$l(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const e of t){const t=xl(e,r);if(t){const[i,s]=f(t[0],t[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...e,cm:_l(e.cm)});continue}const p=[];for(const t of h){if(!Cl(Ml(i,s),Ml(t.oa,t.ob)))continue;const e=t=>Math.abs((t[0]-i[0])*a-(t[1]-i[1])*n)/d;if(e(t.oa)>l||e(t.ob)>l)continue;const o=((t.oa[0]-i[0])*n+(t.oa[1]-i[1])*a)/r,h=((t.ob[0]-i[0])*n+(t.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:t})}if(!p.length){"fixed-topology"===o?v.push({...e}):b(i,s,e.cm);continue}const u=[0,1,...p.flatMap(({lo:t,hi:e})=>[t,e])].sort((t,e)=>t-e).filter((t,e,i)=>0===e||Math.abs(t-i[e-1])*d>c),y=[];for(let t=0;t+1r>=t.lo-1e-12&&r<=t.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(t=>{const e=g(o,t.move),i=g(a,t.move);return!m(h[0],e)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(t,e)=>{const i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],n=e[1][0]-e[0][0],o=e[1][1]-e[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const t of y){const e=k[k.length-1];e&&m(e[1],t[0])&&w(e,t)?e[1]=t[1]:k.push([[...t[0]],[...t[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,t[0])&&m(s,t[1])||m(i,t[1])&&m(s,t[0])){v.push({...e});continue}}for(const[t,i]of k)b(t,i,e.cm);continue}if("fixed-topology"===o){const t=p.get(e.key);if(1===t?.size){const i=[...t][0];v.push(i===e.key?{...e}:{...e,key:i});continue}const i=[Sl([e],r)[0]];1!==r&&i.push(Sl([e],1)[0]);const s=i.filter(Boolean).some(t=>h.some(e=>{if(!Cl(t.ang,Ml(e.oa,e.ob)))return!1;const i=((t.x-e.oa[0])*e.dx+(t.y-e.oa[1])*e.dy)/e.len2;return i>=-1e-6&&i<=1.000001&&mc(t.x,t.y,e.oa[0],e.oa[1],e.ob[0],e.ob[1])<=l}));((t?.size||0)>1||s)&&a?.(),v.push({...e});continue}let i="";const n=d.get(e.key);if(1===n?.size&&(i=[...n][0]),!i){const t=Sl([e],r)[0];if(t){const e=new Set;for(const i of h){if(!Cl(t.ang,Ml(i.oa,i.ob)))continue;const n=((t.x-i.oa[0])*i.dx+(t.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(mc(t.x,t.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([t.x,t.y],i),[a,c]=bl(i.na,i.nb),h=Math.max(s*r,1e-6);e.add(kl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===e.size&&(i=[...e][0])}}v.push({...e,key:i||e.key,cm:_l(e.cm)})}return v}function Al(t,e,i,s,n=1,o="affine"){return Il(t,e,i,s,n,o)}function zl(t,e,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Ur,1e-9),l=(n||[]).flatMap(t=>{const e=xl(t,o);return e?e.map(t=>[...t]):[]}),c=t=>t.every((t,e)=>(t=>{if(!(a>0))return!0;const e=t/o/a;return Math.abs(e-Math.round(e))Math.abs(t-i[e])<=r)),h=[],d=t=>JSON.stringify([t.key,t.cm,t.a,t.b]);for(const i of t||[]){const t=xl(i,o);if(!t)continue;const[s,n]=t;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const t of e){const[e,i]=t;if(![e?.[0],e?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=t=>Math.abs((t[0]-s[0])*_-(t[1]-s[1])*u);if(n(e)>r||n(i)>r)continue;const o=(e[0]-s[0])*u+(e[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let g=0;for(const[t,e]of m){if(t>g+r)break;if(g=Math.max(g,e),g>=p-r)break}gt.key!==a);return null==s||s<1?r:[...r,$l(e,i,s,n,o)]}function El(t,e,i,s,n,o=[],a=1){let r=t?t.slice():[];for(const t of function(t,e,i,s,n=1,o=[]){const a=ec(t,e,i,s,n,o);if(!a)return[];const r=[];for(let t=0;t0||(c=Fl(c,e,i,s,n,a)))}return c}function Ol(t){const{a:e,b:i,halfDepth:s}=t;if(!Array.isArray(e)||!Array.isArray(i)||e.length<2||i.length<2||![e[0],e[1],i[0],i[1]].every(Number.isFinite))return null;const n=i[0]-e[0],o=i[1]-e[1],a=Math.hypot(n,o);if(!(a>1e-9&&s>0&&Number.isFinite(s)))return null;const r=-o/a*s,l=n/a*s;return[[e[0]+r,e[1]+l],[i[0]+r,i[1]+l],[i[0]-r,i[1]-l],[e[0]-r,e[1]-l]]}function Ll(t,e,i){return Math.hypot(t[0]-e[0],t[1]-e[1])<=i}function Hl(t,e,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=s*s+n*n;if(!(o>i*i))return!1;const a=((t[0]-e.a[0])*s+(t[1]-e.a[1])*n)/o;if(!(a>0&&a<1))return!1;const r=[e.a[0]+s*a,e.a[1]+n*a];return Math.hypot(t[0]-r[0],t[1]-r[1])<=i}function Bl(t,e,i,s){const n=Math.hypot(e,i);if(!(n>1e-9&&s>0))return;const o=[e/n,i/n],a=t.find(t=>Math.abs(t.u[0]*o[1]-t.u[1]*o[0])<1e-9&&t.u[0]*o[0]+t.u[1]*o[1]>1-1e-9);a?a.halfDepth=Math.max(a.halfDepth,s):t.push({u:o,halfDepth:s})}function ql(t,e){try{const i=oi(vc(t),vc(e));let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Kl(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function Wl(t,e=1e-6){const i=(t||[]).map((t,e)=>({segment:t,index:e})).filter(({segment:t})=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(({segment:t})=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[];for(const t of o){const e=[];let n=!1;for(const{segment:o,index:a}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Ll(t,o.a,s)?e.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Ll(t,o.b,s)?e.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Hl(t,o,s)&&(n=!0)}if(n||2!==e.length)continue;const[o,r]=e,l=o.u[0]*r.u[1]-o.u[1]*r.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-r.u[1],r.u[0]],p=[t[0]+h[0]*o.halfDepth*c,t[1]+h[1]*o.halfDepth*c],u=[t[0]-d[0]*r.halfDepth*c,t[1]-d[1]*r.halfDepth*c];if(!Xl(p,o.u,u,r.u))continue;const _=[[o,r,u,[d[0]*-c,d[1]*-c]],[r,o,p,[h[0]*c,h[1]*c]]];for(const[e,,i,n]of _){const o=Math.min(2*e.halfDepth,e.length),r=[-e.u[1]*e.halfDepth,e.u[0]*e.halfDepth],l=[[t[0]+r[0],t[1]+r[1]],[t[0]+e.u[0]*o+r[0],t[1]+e.u[1]*o+r[1]],[t[0]+e.u[0]*o-r[0],t[1]+e.u[1]*o-r[1]],[t[0]-r[0],t[1]-r[1]]],c=t=>(t[0]-i[0])*n[0]+(t[1]-i[1])*n[1],h=[];for(let t=0;t=-1e-12&&h.push(e),s>1e-12&&n<-1e-12||s<-1e-12&&n>1e-12){const t=s/(s-n);h.push([e[0]+(i[0]-e[0])*t,e[1]+(i[1]-e[1])*t])}}h.length>=3&&Math.abs(Kl(h))>s*s&&a.push({segmentIndex:e.index,wedge:h})}}return a}function jl(t,e=1e-6){const i=(t||[]).filter(t=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(t=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[],r=i.map((t,e)=>({roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`join-${e}`,kind:"outer",cm:0,open:!1,half:t.halfDepth})),l=ac(r,s);for(const t of rc(l).fans)a.push(t);const c=t=>!!lc(l,t);for(const t of o){if(c(t))continue;const e=[];for(const n of i)Ll(t,n.a,s)?Bl(e,n.b[0]-n.a[0],n.b[1]-n.a[1],n.halfDepth):Ll(t,n.b,s)?Bl(e,n.a[0]-n.b[0],n.a[1]-n.b[1],n.halfDepth):Hl(t,n,s)&&(Bl(e,n.a[0]-t[0],n.a[1]-t[1],n.halfDepth),Bl(e,n.b[0]-t[0],n.b[1]-t[1],n.halfDepth));if(!(e.length<2)){e.sort((t,e)=>Math.atan2(t.u[1],t.u[0])-Math.atan2(e.u[1],e.u[0])||t.halfDepth-e.halfDepth);for(let i=0;is*s&&a.push(m)}}}return a}function Ul(t,e,i,s){if(!(e>0)||!t||t.length<2)return"";if(i&&t.length>=3){let i=t;const n=t[t.length-1];if(t.length>=4&&Math.hypot(t[0][0]-n[0],t[0][1]-n[1])<1e-9&&(i=t.slice(0,-1)),i.length>=3){const t=i.map((t,i)=>s?.[i]||e),n=Fc(i,t),o=Zl(i,t);if(n&&o)return`${Ql(n)} ${Ql(tc(o))}`}}const n=[];for(let i=0;i=1e-9&&r>0&&n.push({a:o,b:a,halfDepth:r})}const o=n.map(Ol);for(const{segmentIndex:t,wedge:e}of Wl(n)){const i=o[t];if(!i)continue;const s=ql(i,e);s&&(o[t]=s)}const a=[...o.filter(t=>!!t),...jl(n)],r=function(t){let e=null;try{for(const i of t){if(i.length<3)continue;const t=vc(i);e=e?si(e,t):[t]}return e}catch{return null}}(a);return r?Tc(r):a.map(t=>Ql(t)).join(" ")}function Gl(t,e,i,s,n=1){if(!i.length)return!1;const o=Vl(s,n),a=(t[0]+e[0])/2,r=(t[1]+e[1])/2,[l,c]=bl(t,e);for(const t of i){const[e,i]=bl([t[0],t[1]],[t[2],t[3]]);if(!(Math.abs(l*i-c*e)>.05)&&mc(a,r,t[0],t[1],t[2],t[3])<=o)return!0}return!1}function Vl(t,e){return Math.max(t*(e>0?e:1)*.04,1e-9)}function Kl(t){let e=0;for(let i=0;it[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a+0)+o&&(i=!i)}return i}([c[0]+.001*r,c[1]+.001*l],t)||(r=-r,l=-l),[r,l]}function Jl(t,e){const i=t[0]*e[1]-t[1]*e[0],s=t[0]*e[0]+t[1]*e[1];return Math.abs(i)<1e-9&&s>0}function Xl(t,e,i,s){const n=e[0]*s[1]-e[1]*s[0];if(Math.abs(n)<1e-12)return null;const o=[i[0]-t[0],i[1]-t[1]],a=(o[0]*s[1]-o[1]*s[0])/n;return[t[0]+a*e[0],t[1]+a*e[1]]}function Zl(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);const n=[];for(let o=0;o0||p>0)){n.push([t[o][0],t[o][1]]);continue}if(d>0!=p>0){const e=t[o],i=d>0?[e[0]+u*d,e[1]+_*d]:[e[0],e[1]],s=p>0?[e[0]+m*p,e[1]+g*p]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]+u*d,e[1]+_*d],s=[e[0]+m*p,e[1]+g*p];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(d,p,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}d>0&&n.push([t[o][0]+u*d,t[o][1]+_*d]),p>0&&n.push([t[o][0]+m*p,t[o][1]+g*p]),d>0||p>0||n.push([t[o][0],t[o][1]])}return n.length>=3?n:null}function Ql(t,e=!0){if(!t.length)return"";let i=`M ${t[0][0]} ${t[0][1]}`;for(let e=1;et?.id===e),r=hi(a);if(!r||r.length<3)return null;const l=Vl(s,n),c=[];for(const i of t||[]){if(!i||i.id===e)continue;const t=hi(i);if(t)for(const e of Cs(r,t,l))c.push([e[0],e[1]],[e[2],e[3]])}for(const t of i||[])c.push([t[0],t[1]],[t[2],t[3]]);for(const t of o||[]){const e=xl(t,n);e&&c.push(e[0],e[1])}const h=[],d=[];for(let t=0;tl)continue;const a=((t[0]-e[0])*(i[0]-e[0])+(t[1]-e[1])*(i[1]-e[1]))/(s*s);a<=n||a>=1-n||(o.some(t=>Math.abs(t-a)*s<=2*l)||o.push(a))}o.sort((t,e)=>t-e);for(const s of o)h.push([e[0]+(i[0]-e[0])*s,e[1]+(i[1]-e[1])*s]),d.push(t)}return{poly:h,parent:d,orig:r}}function ic(t,e,i,s){const n=e.poly.length,o=new Array(n).fill(0);if(!t?.length)return o;const a=new Set,r=[];for(let l=0;l0?(o[l]=_l(c.cm),a.add(c.key)):r.push(l)}if(!r.length)return o;const l=s>0?s:1,c=Math.max(.5*i,1e-9)*l,h=Sl(t,l).filter(t=>t.w.cm>0);for(let t=r.length-1;t>=0;t--){const i=r[t],s=e.poly[i],a=e.poly[(i+1)%n],d=Ml(s,a);let p=null;for(const t of h){const e=xl(t.w,l);if(!e||!Cl(Ml(e[0],e[1]),d))continue;if(mc(s[0],s[1],e[0][0],e[0][1],e[1][0],e[1][1])>c||mc(a[0],a[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;const i=Math.hypot(a[0]-s[0],a[1]-s[1]),n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]),o=Math.max(0,n-i);(!p||oc||mc(n[0],n[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1])-_)}else{if(mc(t.x,t.y,s[0],s[1],n[0],n[1])>c)continue;o=Math.hypot(t.x-d,t.y-p)}(!u||i&&!u.exact||i===u.exact&&o0?i:1,o=(t||[]).filter(t=>t&&!t.open&&null!==t.kind&&Number.isFinite(t.half)&&t.half>0&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&[t.a[0],t.a[1],t.b[0],t.b[1]].every(Number.isFinite)&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>s).sort((t,e)=>t.key.localeCompare(e.key)||t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.b[0]-e.b[0]||t.b[1]-e.b[1]||t.half-e.half),a=new Map;for(const t of o){const e=a.get(t.key);e?t.half>e.half&&a.set(t.key,{...e,half:t.half}):a.set(t.key,t)}const r=[...a.values()].flatMap(t=>[{point:[t.a[0],t.a[1]],other:t.b,halfDepth:t.half,kind:t.kind,key:t.key},{point:[t.b[0],t.b[1]],other:t.a,halfDepth:t.half,kind:t.kind,key:t.key}]).sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]||t.other[0]-e.other[0]||t.other[1]-e.other[1]||t.halfDepth-e.halfDepth),l=new Map;for(const t of r){const[e,i]=sc(t.point,s),n=nc(e,i),o=l.get(n)||[];o.push(t),l.set(n,o)}const c=[],h=new Map;for(const t of r){const e=oc(h,t.point,s).filter(e=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])<=s).sort((e,i)=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])-Math.hypot(i.point[0]-t.point[0],i.point[1]-t.point[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1]);let i=e[0];if(!i){i={point:[...t.point],rays:[]},c.push(i);const[e,n]=sc(i.point,s),o=nc(e,n),a=h.get(o)||[];a.push(i),h.set(o,a)}const n=t.other[0]-t.point[0],o=t.other[1]-t.point[1],a=Math.hypot(n,o);if(!(a>s))continue;const r=[n/a,o/a];let l=Math.atan2(r[1],r[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:r,halfDepth:t.halfDepth,length:a,angle:l})}const d=[],p=t=>{const e=1e-9*Math.max(1,n),i=t.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);return i.filter((t,s)=>!i.some((i,n)=>n!==s&&i.halfDepth>=t.halfDepth-e&&i.length>=t.length-e&&(i.halfDepth>t.halfDepth+e||i.length>t.length+e||nt.length-e.length||t.halfDepth-e.halfDepth).map(t=>({...t}))};for(const t of c){const e=t.rays.sort((t,e)=>t.angle-e.angle||t.length-e.length||t.halfDepth-e.halfDepth),i=[];for(const t of e){const e=i[i.length-1];e&&Math.abs(t.angle-e.angle)<=1e-9?e.supports.push({halfDepth:t.halfDepth,length:t.length}):i.push({u:[...t.u],angle:t.angle,supports:[{halfDepth:t.halfDepth,length:t.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const t=i.pop();i[0].supports.push(...t.supports)}if(i.length<3)continue;const n=i.map(e=>{const i=p(e.supports),n=new Set,o=[];for(const a of i){const i=[t.point[0]+e.u[0]*a.length,t.point[1]+e.u[1]*a.length];for(const e of oc(l,i,s)){if("shared"!==e.kind||Math.hypot(e.point[0]-i[0],e.point[1]-i[1])>s)continue;const a=e.other[0]-e.point[0],r=e.other[1]-e.point[1],l=Math.hypot(a,r);if(!(l>s))continue;const c=a/l,h=r/l;if(Math.hypot(e.other[0]-t.point[0],e.other[1]-t.point[1])<=s)continue;const d=`${e.key}|${e.point[0]}|${e.point[1]}|${e.other[0]}|${e.other[1]}|${e.halfDepth}`;n.has(d)||(n.add(d),o.push({start:[e.point[0],e.point[1]],u:[c,h],length:l,halfDepth:e.halfDepth}))}}return o.sort((t,e)=>t.start[0]-e.start[0]||t.start[1]-e.start[1]||t.u[0]-e.u[0]||t.u[1]-e.u[1]||t.length-e.length||t.halfDepth-e.halfDepth),{u:[...e.u],halfDepth:Math.max(...i.map(t=>t.halfDepth)),length:Math.max(...i.map(t=>t.length)),supports:i,continuations:o}}).filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);if(n.length<3)continue;const o=Math.max(...n.map(t=>t.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...t.point],rays:n,halfDepth:o,limit:1.25*o})}d.sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]);const u=new Map;for(const t of d){const[e,i]=sc(t.point,s),n=nc(e,i),o=u.get(n)||[];o.push(t),u.set(n,o)}return{epsilon:s,coordinateScale:n,nodes:d,index:u}}function rc(t){const e={fans:[],supports:[]};if(!t?.nodes?.length)return e;const i=Math.max(t.epsilon,1e-9)**2;for(const s of t.nodes){const t=s.rays.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0).map(t=>({...t,thickLength:Math.max(...t.supports.filter(e=>e.halfDepth>=t.halfDepth-1e-12).map(t=>t.length),0),angle:(()=>{const e=Math.atan2(t.u[1],t.u[0]);return e<0?e+2*Math.PI:e})()})).sort((t,e)=>t.angle-e.angle);if(t.length<2)continue;const n=s.point;for(const i of t)for(const t of i.supports){if(!(t.halfDepth>0&&t.length>0))continue;const s=-i.u[1]*t.halfDepth,o=i.u[0]*t.halfDepth,a=[n[0]+i.u[0]*t.length,n[1]+i.u[1]*t.length];e.supports.push([[n[0]+s,n[1]+o],[a[0]+s,a[1]+o],[a[0]-s,a[1]-o],[n[0]-s,n[1]-o]])}for(let s=0;s{const t=a.angle-o.angle;return t>0?t:t+2*Math.PI})();if(r<1e-9)continue;const l=r>Math.PI+1e-9,c=4*Math.max(o.halfDepth,a.halfDepth),h=[n[0]-o.u[1]*o.halfDepth,n[1]+o.u[0]*o.halfDepth],d=[n[0]+a.u[1]*a.halfDepth,n[1]-a.u[0]*a.halfDepth],p=o.u[0]*a.u[1]-o.u[1]*a.u[0],u=t=>{let e=Math.atan2(t[1]-n[1],t[0]-n[0])-o.angle;for(;e<0;)e+=2*Math.PI;return e<=r+1e-9};let _=null;if(Math.abs(p)>1e-9){const t=((d[0]-h[0])*a.u[1]-(d[1]-h[1])*a.u[0])/p,e=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/p,i=[h[0]+o.u[0]*t,h[1]+o.u[1]*t];(l?t<=1e-9&&e<=1e-9:t>1e-9&&t<=o.thickLength&&e<=a.thickLength)&&Math.hypot(i[0]-n[0],i[1]-n[1])<=c&&u(i)&&(_=i)}const m=t=>{Math.abs(Kl(t))>i&&e.fans.push(t)};if(_){const t=1.5*Math.max(o.halfDepth,a.halfDepth);m(cl([n[0],n[1]],h,_,d,t)??[[n[0],n[1]],h,_,d]);continue}if(l){m([[n[0],n[1]],h,d]);continue}const g=(t,e)=>Math.min(e,Math.sqrt(Math.max(c**2-t**2,0)),2*Math.max(o.halfDepth,a.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+a.u[0]*g(a.halfDepth,a.thickLength),d[1]+a.u[1]*g(a.halfDepth,a.thickLength)];m([[n[0],n[1]],h,f,v,d])}}return e}function lc(t,e){return!t||!Array.isArray(e)||e.length<2||!e.slice(0,2).every(Number.isFinite)?null:oc(t.index,e,t.epsilon).filter(i=>Math.hypot(i.point[0]-e[0],i.point[1]-e[1])<=t.epsilon).sort((t,i)=>Math.hypot(t.point[0]-e[0],t.point[1]-e[1])-Math.hypot(i.point[0]-e[0],i.point[1]-e[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1])[0]||null}function cc(t,e,i,s,n,o,a){return ac(dc(t,e,i,s,n,o,a),4*Vl(s,a),a)}function hc(t,e,i,s,n,o,a,r=1){const l=ec(t,e,s,n,r,i);if(!l)return null;const c=function(t,e,i){const s=(t||[]).find(t=>t?.id===e),n=hi(s);if(!n)return[];const o=[];for(const s of t||[]){if(!s||s.id===e)continue;const t=hi(s);if(t)for(const e of Cs(n,t,i))o.push(e)}return o}(t,e,Vl(n,r)),h=function(t,e,i,s,n){const o=Vl(s,n),a=[];for(let r=0;rmc(h,d,t[0],t[1],t[2],t[3])<=o);a.push(p?"shared":"outer")}return a}(l.poly,c,s,n,r),d=ic(i,l,n,r),p=d.map((t,e)=>h[e]&&t>0?gl(t,o,a)/2:0);return{...l,kinds:h,cms:d,offsets:p}}function dc(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(c)for(let t=0;t0&&(r=Fl(r,t.a,t.b,t.cm,s,a));return r}function uc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=dc(t,e,i,s,n,o,a),l=new Map;for(const t of r){if(t.open||!t.kind||!t.roomId)continue;const e=l.get(t.key)||new Set;e.add(t.roomId),l.set(t.key,e)}const c=t=>{const e=[...l.get(t)||[]].sort();return 1!==e.length&&2!==e.length?`ambiguous:${t}`:`${1===e.length?"outer":"shared"}:${e.join("|")}`},h=[],d=new Set;for(const t of r)!t.open&&t.cm>0&&!d.has(t.key)&&(d.add(t.key),h.push({...t,ownerSignature:c(t.key)}));const p=[];for(const r of t||[]){if(!r?.id)continue;const l=hc(t,r.id,e,i,s,n,o,a);if(l)for(let t=0;t0)||null===l.kinds[i]){t++;continue}const o=c(kl(l.poly[i],l.poly[(i+1)%l.poly.length],s,a));let r=t;for(;r+10&&p.push({a:[d[0],d[1]],b:[u[0],u[1]],key:kl(d,u,s,a),cm:n,len:_,ownerSignature:o}),t=r+1}}}p.sort((t,e)=>e.len-t.len||t.key.localeCompare(e.key));const u=[],_=new Set,m=new Set,g=4*Vl(s,a);for(const t of p){const e=h.filter(e=>!m.has(e.key)&&e.cm===t.cm&&e.ownerSignature===t.ownerSignature&&Cl(Ml(e.a,e.b),Ml(t.a,t.b))&&mc(e.a[0],e.a[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g&&mc(e.b[0],e.b[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g);if(e.length){for(const t of e)m.add(t.key);_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)))}}for(const t of h)m.has(t.key)||_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)));return u}function _c(t,e,i,s,n,o,a,r=1){const l=Vl(n,r),c=(s[0]+s[2])/2,h=(s[1]+s[3])/2,d=Ml([s[0],s[1]],[s[2],s[3]]);let p=null;for(const s of dc(t,e,i,n,o,a,r)){if(!Cl(Ml(s.a,s.b),d))continue;const t=mc(c,h,s.a[0],s.a[1],s.b[0],s.b[1]);t>4*l||(!p||t[t[0],t[1]]),o=Math.abs(Kl(n));n.length>=3&&o>i&&(e=n,i=o)}return e}function fc(t,e,i,s,n,o,a,r=1,l,c){const h=(t||[]).find(t=>t?.id===e),d=hi(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(t=>[t[0],t[1]]);const p=hc(t,e,i,s,n,o,a,r);if(!p||!p.offsets.some(t=>t>0))return d.map(t=>[t[0],t[1]]);const u=c||cc(t,i,s,n,o,a,r),_=Zl(p.poly,p.offsets,u);if(!_)return d.map(t=>[t[0],t[1]]);if(!u.nodes.length)return _;const m=void 0===l?Rc(t,i,s,[],n,o,a,r):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const t=gc(oi(vc(p.poly),g));if(t)return t}catch{}return function(t,e){try{return gc(ni(vc(t),vc(e)))}catch{return null}}(_,p.poly)||d.map(t=>[t[0],t[1]])}function vc(t){const e=t.map(t=>[t[0],t[1]]);return e.push([t[0][0],t[0][1]]),[e]}function yc(t){return!(!Array.isArray(t)||!t.length)&&t.every(t=>Array.isArray(t)&&t.length&&t.every(t=>Array.isArray(t)&&t.length>=4&&t.every(t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])))&&Math.abs(Ti(t[0]))>1e-9)}function bc(t,e,i,s){const n=s?new Set(s):null;let o=null;for(let s=0;se.epsilon))continue;const l=Sc([[t.point[0]+r[0]*s.halfDepth,t.point[1]+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n+r[0]*s.halfDepth,t.point[1]+a.u[1]*n+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n-r[0]*s.halfDepth,t.point[1]+a.u[1]*n-r[1]*s.halfDepth],[t.point[0]-r[0]*s.halfDepth,t.point[1]-r[1]*s.halfDepth]],e.coordinateScale);if(!l)continue;const c=vc(l);o=o?si(o,c):c}}return o}function wc(t,e,i){let s=null;for(const n of t.rays)for(const t of n.continuations){const n=[-t.u[1],t.u[0]],o=[t.start[0]+t.u[0]*t.length,t.start[1]+t.u[1]*t.length],a=Sc([[t.start[0]+n[0]*t.halfDepth,t.start[1]+n[1]*t.halfDepth],[o[0]+n[0]*t.halfDepth,o[1]+n[1]*t.halfDepth],[o[0]-n[0]*t.halfDepth,o[1]-n[1]*t.halfDepth],[t.start[0]-n[0]*t.halfDepth,t.start[1]-n[1]*t.halfDepth]],e.coordinateScale);if(!a)continue;const r=ni(vc(a),i);Array.isArray(r)&&0!==r.length&&(s=s?si(s,r):r)}return s}function kc(t,e,i=2*(4*t.halfDepth+2*e.epsilon)){const s=function(t,e=hl){const i=new Set,s=Number.isFinite(e)&&e>=0?e:hl;for(let e=0;et-e)}(t);return s.length?bc(t,e,i,s):null}function xc(t,e,i,s,n){const o=function(t){let e=null;for(const i of t){const t=vc(i);try{e=e?si(e,t):t}catch{}}return e}(function(t,e,i=!1){if(!t)return[];const s=[];for(const n of t.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-a.u[1],a.u[0]],p=[-r.u[1],r.u[0]],u=[n.point[0]+d[0]*a.halfDepth,n.point[1]+d[1]*a.halfDepth],_=[n.point[0]-p[0]*r.halfDepth,n.point[1]-p[1]*r.halfDepth],m=Xl(u,a.u,_,r.u);if(!m)continue;const g=Math.hypot(m[0]-n.point[0],m[1]-n.point[1]);if(!Number.isFinite(g)||g<=n.limit)continue;const f=e?Math.sqrt(Math.max(0,n.limit*n.limit-a.halfDepth*a.halfDepth)):0,v=e?Math.sqrt(Math.max(0,n.limit*n.limit-r.halfDepth*r.halfDepth)):0,y=Sc([[u[0]+a.u[0]*f,u[1]+a.u[1]*f],[_[0]+r.u[0]*v,_[1]+r.u[1]*v],m],t.coordinateScale);if(y&&s.push(y),i){const e=m[0]-n.point[0],i=m[1]-n.point[1],o=Math.hypot(e,i),a=g-n.limit;if(o>t.epsilon&&a>t.epsilon){const r=Math.min(Math.max(8*t.epsilon,.05*n.halfDepth),.25*a),l=e/o,c=i/o,h=-c,d=l,p=Sc([[m[0]-l*r+h*r,m[1]-c*r+d*r],[m[0]-l*r-h*r,m[1]-c*r-d*r],[m[0]+l*r,m[1]+c*r]],t.coordinateScale);p&&s.push(p)}}}return s}({...e,nodes:[t]},i,s));return o&&n?oi(o,n):o}function $c(t,e,i,s){if(!t||!e.nodes.length)return t;let n=null;try{n=function(t){let e=null;for(const i of t.nodes){const s=kc(i,t);s&&(e=e?si(e,s):s)}return e}(e)}catch{return t}let o=t;for(const t of e.nodes){const a=4*t.halfDepth+2*e.epsilon,r=2*a,l=[[t.point[0]-a,t.point[1]-a],[t.point[0]+a,t.point[1]-a],[t.point[0]+a,t.point[1]+a],[t.point[0]-a,t.point[1]+a]];try{let a=o;const c=xc(t,e,!1,!0,n);c&&(a=oi(a,c));let h=bc(t,e,r);const d=xc(t,e,!0,!0,n);d&&(h=oi(h,d)),n&&(h=si(h,n));const p=.02*Math.min(...t.rays.map(t=>t.halfDepth));if(h=si(h,vc([[t.point[0]-p,t.point[1]-p],[t.point[0]+p,t.point[1]-p],[t.point[0]+p,t.point[1]+p],[t.point[0]-p,t.point[1]+p]])),!h)continue;let u=ni(h,vc(l));s?u=ni(u,s):i&&(u=ni(u,i));const _=vc(l),m=oi(a,_),g=i?oi(ni(a,_),i):null,f=wc(t,e,_);o=si(m,...g?[g]:[],...f?[f]:[],u)}catch{}}if(n)try{let t=n;s?t=ni(t,s):i&&(t=ni(t,i)),o=si(o,t)}catch{}return o}function Sc(t,e=1){if(!Array.isArray(t)||t.length<3)return null;const i=Number.isFinite(e)&&e>0?e:1,s=1e-12*Math.max(1,i),n=[];for(const e of t){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),i=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(i))return null;const o=Math.round(t/s)*s,a=Math.round(i/s)*s;if(!Number.isFinite(o)||!Number.isFinite(a))return null;n.push([Object.is(o,-0)?0:o,Object.is(a,-0)?0:a])}return Math.abs(Kl(n))>s*s?n:null}function Mc(t,e,i,s){if(mc(t[0],t[1],e[0],e[1],i[0],i[1])>s)return!1;const n=i[0]-e[0],o=i[1]-e[1],a=(t[0]-e[0])*n+(t[1]-e[1])*o,r=n*n+o*o,l=s*Math.sqrt(r);return a>=-l&&a<=r+l}function Cc(t,e,i){const s=[],n=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),p=[0,1];for(const t of e)for(const e of[t.a,t.b]){if(!Mc(e,a,r,i))continue;const t=((e[0]-a[0])*l+(e[1]-a[1])*c)/h;t>d&&t<1-d&&p.push(t)}p.sort((t,e)=>t-e);const u=p.filter((t,e)=>0===e||Math.abs(t-p[e-1])>d);for(let t=0;t=3&&n.length===s.length?{poly:s,offsets:n}:null}function Dc(t,e,i,s,n,o,a,r){const l=(t||[]).map(hi).filter(t=>!!t&&t.length>=3);if(!l.length)return null;let c=si(vc(l[0]));for(let t=1;t"outer"===t.kind&&t.half>0),p=4*Vl(s,a),u=r||ac(h,p,a);let _=null;for(const t of function(t){const e=[];for(const i of Array.isArray(t)?t:[])if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,-1).map(t=>[t[0],t[1]]);i.length>=3&&e.push(i)}return e}(c)){const e=Cc(t,d,p);if(!e||!e.offsets.some(t=>t>0))continue;const i=Fc(e.poly,e.offsets,u),s=Zl(e.poly,e.offsets,u);if(!i||!s)continue;const n=oi(vc(i),vc(s));_=_?si(_,n):n}return{centre:c,shell:_||[]}}function Pc(t,e,i,s,n,o,a=1){try{const r=Dc(t,e,i,s,n,o,a,cc(t,e,i,s,n,o,a));if(!r)return[];return r.shell?.length?si(r.centre,r.shell):r.centre}catch{return null}}function Tc(t){if(!t)return"";let e="";for(const i of t)if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,t.length-1);i.length<3||(e+=(e?" ":"")+Ql(i.map(t=>[t[0],t[1]])))}return e}function Rc(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return{status:"not-applicable",geom:[],components:[],roomGeom:[],paperGeom:[],depthUnits:0,openingIndex:null,multiWallNodes:null,degradedExtraCount:0};const h=[],d=cc(t,e,i,n,o,a,r);let p=0;for(const s of t||[]){if(!s?.id)continue;const l=hc(t,s.id,e,i,n,o,a,r);if(!l||l.poly.length<3||!l.offsets.some(t=>t>0))continue;for(const t of l.offsets)t>0&&(p=Math.max(p,2*t));const c=Fc(l.poly,l.offsets,d),u=Zl(l.poly,l.offsets,d);c&&h.push({outset:c,inset:u})}for(const t of l){const e=t.map(t=>t[0]),i=t.map(t=>t[1]);if(e.length){const s=Math.min(Math.max(...e)-Math.min(...e),Math.max(...i)-Math.min(...i)),n=Math.min(...t.map((e,i)=>{const s=t[(i+1)%t.length];return Math.hypot(s[0]-e[0],s[1]-e[1])}));p=Math.max(p,t.length>16?s:n)}}const u=function(t,e,i,s,n,o,a,r){if(!e?.length||!i?.length)return[];const l=4*Vl(s,a),c=new Map;for(const r of dc(t,e,i,s,n,o,a))!r.open&&r.half>0&&!c.has(r.key)&&c.set(r.key,r);const h=[...c.values()];if(h.length<2)return[];const d=r||ac(h,l),p=[];for(const t of i)for(const e of[[t[0],t[1]],[t[2],t[3]]])p.some(t=>Math.hypot(t[0]-e[0],t[1]-e[1])<=l)||p.push(e);const u=[],_=(t,e)=>{let i=0,s=0;if(Math.hypot(t.a[0]-e[0],t.a[1]-e[1])<=l)i=t.b[0]-t.a[0],s=t.b[1]-t.a[1];else{if(!(Math.hypot(t.b[0]-e[0],t.b[1]-e[1])<=l))return null;i=t.a[0]-t.b[0],s=t.a[1]-t.b[1]}const n=Math.hypot(i,s);return n>l?[i/n,s/n]:null};for(const t of p){const e=h.map(e=>({iv:e,u:_(e,t)})).filter(t=>!!t.u);for(let i=0;i0?[t.slice(),p,m,_]:[t.slice(),_,m,p];else{if(!f)continue;{const e=[-n.u[1],n.u[0]],i=[-o.u[1],o.u[0]],s=a<0?1:-1,r=[t[0]+e[0]*n.iv.half*s,t[1]+e[1]*n.iv.half*s],l=[t[0]-i[0]*o.iv.half*s,t[1]-i[1]*o.iv.half*s];y=a>0?[t.slice(),r,l]:[t.slice(),l,r]}}Math.abs(Kl(y))>l*l&&u.push(y)}}return u}(t,e,i,n,o,a,r,d),_=s.length?Ec(t,e,i,n,o,a,r):null;let m="exterior";try{const v=Dc(t,e,i,n,o,a,r,d);m="paper";const y=v?v.shell?.length?si(v.centre,v.shell):v.centre:[],b=t=>{const e=vc(t.outset);return t.inset?oi(e,vc(t.inset)):e};m="room-rings";let w=null;for(const t of h)try{const e=b(t);w=w?si(w,e):e}catch{}if(m="edge-bodies",v)for(const s of zc(t,e,i,n,o,a,r))try{const t=ni(vc(s.quad),v.centre);w=w?si(w,t):t}catch{}m="junctions",w=function(t,e,i=1,s=si){let n=t;for(const t of e||[]){const e=Sc(t,i);if(e)try{const t=vc(e);n=n?s(n,t):t}catch{}}return n}(w,u,r),m="facade-clip",w&&v&&(w=ni(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const t=si(w,v.shell);if(!yc(t))throw new Error("invalid shell union");w=t}catch{if(!yc(w)||!yc(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const t=t=>t.rays.some(t=>t.supports.some(t=>t.length<2*t.halfDepth)),e=d.nodes.filter(t);if(e.length){w=$c(w,{...d,nodes:e},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const s=rc(d),l=function(t,e,i,s,n,o,a,r){try{const l=Dc(t,e,i,s,n,o,a,{epsilon:r.epsilon,coordinateScale:r.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?si(l.centre,l.shell):l.centre:null}catch{return null}}(t,e,i,n,o,a,r,d);for(const t of s.fans)try{let e=[vc(t)];if(l&&(e=ni(e,l)),!e?.length)continue;w=w?si(w,e):e}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(t=>{if(!Array.isArray(t)||!t.length)return t;const[e,...i]=t;return Math.abs(Kl(e||[]))<=f?null:[e,...i.filter(t=>Math.abs(Kl(t||[]))>f)]}).filter(t=>!!t):g}const $=w||[];m="openings";for(const t of s){if(!(t.length>0))continue;const e=Lc(_,t,!0);if(!e.negative&&!e.positive)continue;const i=t.angle*Math.PI/180,s=Math.cos(i),o=Math.sin(i),a=-o,l=s,c=t.length/2,h=1.25*Math.max(p,n*r),d=[[t.x-s*c-a*h,t.y-o*c-l*h],[t.x+s*c-a*h,t.y+o*c-l*h],[t.x+s*c+a*h,t.y+o*c+l*h],[t.x-s*c+a*h,t.y-o*c+l*h]];w&&(w=oi(w,vc(d)));for(const t of k)t.geom=oi(t.geom,vc(d))}m="extras";const S=[];let M=0;const C=c.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){M++;continue}const i=[vc(e)];try{const e=C(w,i,t);if(!yc(e))throw new Error("invalid extra union");w=e}catch{M++,yc(i)&&S.push({id:`extra-${t}`,geom:i})}}S.push(...k),S.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const D=w||[];return{status:M||x?"degraded-extra":"ok",geom:D,components:[...yc(D)?[{id:"primary",geom:D}]:[],...S.map((t,e)=>({...t,id:`isolated-${e}`}))],roomGeom:$,paperGeom:y,depthUnits:p,openingIndex:_,multiWallNodes:d,degradedExtraCount:M+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],depthUnits:p,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ic(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return null;return Ac(Rc(t,e,i,s,n,o,a,r,l,c))}function Ac(t){if("failed-core"===t.status||"not-applicable"===t.status)return null;const e=t.components.map(t=>({id:t.id,d:Tc(t.geom),fillRule:"evenodd"})).filter(t=>!!t.d),i=e[0]?.d||"",s=Tc(t.paperGeom);return e.length?{status:t.status,d:i,paths:e,components:t.components,roomGeom:t.roomGeom,multiWallNodes:t.multiWallNodes,paperD:s,depthUnits:t.depthUnits,fillRule:"evenodd"}:null}function zc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=new Set,l=[];for(const c of t||[]){if(!c?.id)continue;const h=hc(t,c.id,e,i,s,n,o,a);if(!h)continue;const d=h.poly;for(let t=0;t0))continue;const u=kl(e,i,s,a);if(r.has(u))continue;r.add(u);const _=gl(p,n,o),[m,g]=Yl(d,t),f=-m,v=-g,y=_/2,b=[[e[0]+f*y,e[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[e[0]+m*y,e[1]+g*y]];l.push({key:u,kind:c,cm:p,quad:b,a:[e[0],e[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Fc(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);tc(t),e.slice().reverse();const n=[];for(let o=0;o0||l>0)){n.push([t[o][0],t[o][1]]);continue}if(r>0!=l>0){const e=t[o],i=r>0?[e[0]-c*r,e[1]-h*r]:[e[0],e[1]],s=l>0?[e[0]-d*l,e[1]-p*l]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]-c*r,e[1]-h*r],s=[e[0]-d*l,e[1]-p*l];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(r,l,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}r>0&&n.push([t[o][0]-c*r,t[o][1]-h*r]),l>0&&n.push([t[o][0]-d*l,t[o][1]-p*l])}return n.length>=3?n:null}function Ec(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(!c)continue;const h=Math.abs(Ti(c.poly));for(let t=0;t[Math.max(e,t.x0),Math.min(i,t.x1)]).filter(t=>t[1]-t[0]>s).sort((t,e)=>t[0]-e[0]||t[1]-e[1]);if(!n.length)return{coverage:0,full:!1};let o=n[0][0],a=n[0][1],r=0,l=o<=e+s;for(let t=1;t=i-s,{coverage:r,full:l}}function Oc(t,e){return Number(e.full)-Number(t.full)||t.faceDistance-e.faceDistance||t.area-e.area||t.roomId.localeCompare(e.roomId)}function Lc(t,e,i=!1){const s=Number(e?.x),n=Number(e?.y),o=Number(e?.angle),a=Number(e?.length);if(!([s,n,o,a].every(Number.isFinite)&&a>0))return{negative:null,positive:null};const r=o*Math.PI/180,l=Math.cos(r),c=Math.sin(r),h=-c,d=l,p=a/2,u=Math.max(1e-9,t.adjacencyEps),_=new Map;let m=0;for(const e of t.edges){if(i&&!(e.half>0))continue;if(!Rl(e.a,e.b,o))continue;const[t,a]=bl(e.a,e.b);if(Math.abs((s-e.a[0])*a-(n-e.a[1])*t)>u)continue;const r=(e.a[0]-s)*l+(e.a[1]-n)*c,g=(e.b[0]-s)*l+(e.b[1]-n)*c,f=Math.max(-p,Math.min(r,g)),v=Math.min(p,Math.max(r,g));if(v-f<=u)continue;const y=e.inward[0]*h+e.inward[1]*d>=0?1:-1,b=((e.a[0]+e.b[0])/2-s)*h+((e.a[1]+e.b[1])/2-n)*d,w=Math.abs(b+y*e.half),k=`${y}|${e.roomId}`,x={x0:f,x1:v,half:e.half,cm:e.cm,key:e.key,axis:[t,a]},$=_.get(k);$?($.pieces.push(x),$.faceDistance=Math.min($.faceDistance,w)):_.set(k,{roomId:e.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:e.area,coverage:0,full:!1})}for(const t of _.values()){const e=Nc(t.pieces,-p,p,u);t.coverage=e.coverage,t.full=e.full}const g=t=>{const e=[..._.values()].filter(e=>e.side===t&&e.coverage>u);return e.sort(Oc),e[0]||null};return{negative:g(-1),positive:g(1)}}function Hc(t,e){const i=Lc(t,e),s=[i.negative,i.positive].filter(t=>!!t);if(!s.length)return{ox:0,oy:0,cm:0,side:-1};const n=i.negative&&i.positive?-1:s[0].side,o=e.flip_v?-n:n,a=(-1===o?i.negative:i.positive)||s[0],r=[...a.pieces].sort((t,e)=>(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))-(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))||e.x1-e.x0-(t.x1-t.x0)||t.key.localeCompare(e.key))[0];if(!(r.half>0&&r.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=e.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*r.half,oy:h*o*r.half,cm:r.cm,side:o}}function Bc(t,e){const i=1e-9,s=e.filter(t=>Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&Number.isFinite(t.half)&&t.x1>t.x0&&t.half>0);if(!s.length)return"";const n=s.flatMap(t=>[t.x0,t.x1]).sort((t,e)=>t-e),o=[];for(const t of n){const e=o[o.length-1];(void 0===e||t>e+i)&&o.push(t)}const a=[];for(let t=0;t+1e+i))continue;const r=(e+n)/2,l=s.reduce((t,e)=>r>=e.x0-i&&r<=e.x1+i?Math.max(t,e.half):t,0);if(!(l>0))continue;const c=a[a.length-1];c&&e<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=n:a.push({x0:e,x1:n,half:l})}const r=[];for(const t of a){const e=r[r.length-1],s=e?.[e.length-1];s&&t.x0<=s.x1+i?(t.x0=s.x1,e.push(t)):r.push([t])}return r.map(e=>{const i=e[0],s=e[e.length-1],n=Math.min(.25*Math.min(...e.map(t=>t.half)),.75),o=-t*n,a=[];if(1===t){a.push(`M ${i.x0} ${o} L ${s.x1} ${o}`);for(let t=e.length-1;t>=0;t--){const i=e[t];a.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{a.push(`M ${s.x1} ${o} L ${i.x0} ${o}`);for(const t of e)a.push(`L ${t.x0} ${-t.half} L ${t.x1} ${-t.half}`)}return a.push("Z"),a.join(" ")}).join(" ")}function qc(t,e,i,s){if(!s)return i;const n=t.angle*Math.PI/180,o=Math.cos(n),a=Math.sin(n),r=[],l=1e-9;for(const n of i){const[i,c]=n.axis,h=o*i+a*c;if(Math.abs(h)<=l)continue;const d=t.x*i+t.y*c,p=d+h*n.x0,u=d+h*n.x1,_=Math.min(p,u),m=Math.max(p,u),g=`${n.key}|${e}`,f=s.get(g)||[];let v=[[_,m]];for(const[t,e]of f){const i=[];for(const[s,n]of v)e<=s+l||t>=n-l?i.push([s,n]):(t>s+l&&i.push([s,Math.min(n,t)]),et[0]-e[0]||t[1]-e[1]),b=[];for(const t of y){const e=b[b.length-1];e&&t[0]<=e[1]+l?e[1]=Math.max(e[1],t[1]):b.push([t[0],t[1]])}s.set(g,b)}return r}function Wc(t,e){const i=new Map;return e.map(e=>function(t,e,i){const s=Lc(t,e,!0),n=s.negative,o=s.positive;if(!n&&!o)return null;let a;if(n&&o)a=[{candidate:n,side:-1},{candidate:o,side:1}];else{const t=n||o;a=[{candidate:t,side:-1},{candidate:t,side:1}]}const r=a.map(({candidate:t,side:s})=>({candidate:t,side:s,pieces:qc(e,s,t.pieces,i)})),l=r.map(({candidate:t,side:e,pieces:i})=>({side:e,roomId:t.roomId,d:Bc(e,i)})),c=r.flatMap(({pieces:t})=>t);if(!c.length)return null;const h=Math.max(...c.map(t=>t.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(t=>t.key))].sort().join("|")}}(t,e,i))}const jc=150,Uc=1e-6;function Gc(t){return Number.isFinite(t)?Math.max(1,Math.min(jc,t)):1}function Vc(t){return((Number.isFinite(Number(t))?Number(t):0)%90+90)%90}const Kc=t=>{const e=t.map(t=>[t[0],t[1]]);return!e.length||e[0][0]===e[e.length-1][0]&&e[0][1]===e[e.length-1][1]||e.push([...e[0]]),[e]},Yc=(t,e)=>t[0]===e[0]&&t[1]===e[1];function Jc(t,e=1e-6){const i=Number.isFinite(e)&&e>0?e:Uc,s=[];for(const e of t||[]){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(n))return null;const o=Math.round(t/i)*i,a=Math.round(n/i)*i;if(!Number.isFinite(o)||!Number.isFinite(a))return null;const r=[Object.is(o,-0)?0:o,Object.is(a,-0)?0:a];s.length&&Yc(s[s.length-1],r)||s.push(r)}return s.length>1&&Yc(s[0],s[s.length-1])&&s.pop(),s.length<3||new Set(s.map(t=>`${t[0]},${t[1]}`)).size<3?null:Ti(s)>i*i?s:null}function Xc(t){const e=[];for(const i of t||[])for(const t of i||[]){const i=(t||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||e.push(`M ${i.slice(0,-1).map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`)}return e.join(" ")}function Zc(t,e,i,s,n){return Ol({a:t,b:e,halfDepth:gl(i,s,n)/2})}function Qc(t,e,i){const s=Number(e)>0?Number(e):5,n=Gc(t.cm)/s*i,o=t.center[0],a=t.center[1];if("circle"===t.shape){const t=n/2;return Array.from({length:96},(e,i)=>{const s=i/96*Math.PI*2;return[o+Math.cos(s)*t,a+Math.sin(s)*t]})}const r=n/2,l=Vc(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-r,-r],[r,-r],[r,r],[-r,r]].map(([t,e])=>[o+t*c-e*h,a+t*h+e*c])}function th(t,e,i=1e-9){if(!e.length)return[t];let s=[Kc(t)];try{for(const t of e){const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(e,n);if(!(o>i))continue;const a=e/o,r=n/o,l=-r,c=a,h=1.25*Math.max(Number(t.depth)||0,4*i),d=Math.max(2*i,1e-9*o),p=[[t.a[0]-a*d-l*h,t.a[1]-r*d-c*h],[t.b[0]+a*d-l*h,t.b[1]+r*d-c*h],[t.b[0]+a*d+l*h,t.b[1]+r*d+c*h],[t.a[0]-a*d+l*h,t.a[1]-r*d+c*h]];s=oi(s,Kc(p))}return hh(s)}catch{return[t]}}function eh(t,e){try{const i=oi([[...t.map(t=>[t[0],t[1]]),[t[0][0],t[0][1]]]],[[...e.map(t=>[t[0],t[1]]),[e[0][0],e[0][1]]]]);let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Ti(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function ih(t,e,i,s=Math.max(2e-4*i,1e-9),n=[]){const o=[],a=[],r=new Map;for(const t of n){const e=r.get(t.hostId)||[];e.push(t),r.set(t.hostId,e)}const l=[],c=[],h=[];for(const s of t.room_drafts||[])for(let t=0;t+10))continue;const r={a:s.points[t],b:s.points[t+1],halfDepth:a},c=Ol(r);c&&(o.push(r),l.push(c))}const d=[];for(const s of t.partitions||[]){const t={a:s.a,b:s.b,halfDepth:gl(s.cm,e,i)/2};if(!(t.halfDepth>0))continue;const n=Ol(t);n&&(a.push(t),c.push(n),d.push({id:s.id,body:n}))}const p=[...o,...a];for(const{segmentIndex:t,wedge:e}of Wl(p,s)){const i=t=o.length&&(d[i.at].body=s))}for(const t of d)h.push(...th(t.body,r.get(t.id)||[],s));const u=(t.wall_columns||[]).map(t=>Qc(t,e,i)),_=jl([...o,...a],s).flatMap(t=>th(t,n,s));return{drafts:l,partitions:c,columns:u,patches:_,all:[...l,...h,..._,...u]}}function sh(t){try{const e=t.map(t=>Jc(t)).filter(t=>!!t).map(t=>Kc(t));return e.length?si(e[0],...e.slice(1)):null}catch{return null}}const nh=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`;function oh(t){const e=[];for(const i of t||[]){if(lh([i])<=1e-6)continue;const t=[];for(const e of i||[]){const i=(e||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||t.push(nh(i.slice(0,-1)))}t.length&&e.push(t.join(" "))}return e}function ah(t,e,i={}){const s=sh(t.filter(t=>t.length>=3)),n=e.some(t=>!Jc(t))?null:sh(e);if(!s)return[];if(n)try{return oh(ni(s,n))}catch{}return function(t,e,i){let s=null;for(let n=0;n=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]));return e}function hh(t){const e=[];for(const i of t||[]){const t=i?.[0];t?.length>=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]))}return e}function dh(t,e){let i=!1;for(let s=0,n=e.length-1;st[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a||1e-12)+o&&(i=!i)}return i}function ph(t,e,i){return function(t,e){for(const i of e||[]){const e=i?.[0];if(!e?.length||!dh(t,e))continue;let s=!1;for(let e=1;edh(t,e))}function uh(t,e,i){if(Math.hypot(t.center[0]-e.center[0],t.center[1]-e.center[1])>i)return!1;if(Math.abs(Gc(t.cm)-Gc(e.cm))>1e-6)return!1;if(t.shape!==e.shape)return!0;if("circle"===t.shape||"circle"===e.shape)return!0;const s=Math.abs(Vc(t.angle)-Vc(e.angle));return Math.min(s,90-s)<=1e-6}const _h=2.54;function mh(t){const e="number"==typeof t?t:NaN;return!Number.isFinite(e)||e<=0||5===e?1:5/e}function gh(t,e){return t*mh(e)}function fh(t){return t?_h:1}function vh(t,e){if(!e)return String(t);const i=t/_h;return String(Math.round(1e6*i)/1e6)}const yh=1e3;function bh(t,e){const i=Number(t),s=Number.isFinite(i)&&i>0?i:1,n=s>=1?e:e*s,o=s>=1?e/s:e;return{x:(e-n)/2,y:(e-o)/2,w:n,h:o}}const wh=.01,kh=100;function xh(t,e=1e3){const i=bh(t?.plan_aspect,e),s=Number(t?.plan_scale),n=Number.isFinite(s)&&s>0?Math.min(kh,Math.max(wh,s)):1,o=Number(t?.plan_scale_x),a=Number(t?.plan_scale_y),r=Number.isFinite(o)&&o>0?Math.min(kh,Math.max(wh,o)):n,l=Number.isFinite(a)&&a>0?Math.min(kh,Math.max(wh,a)):n,c=Number(t?.plan_x),h=Number(t?.plan_y),d=Ar(t?.plan_angle);return{x:i.x+(Number.isFinite(c)?zh(c):0)*e,y:i.y+(Number.isFinite(h)?zh(h):0)*e,w:i.w*r,h:i.h*l,...d?{angle:d}:{}}}function $h(t){if(null==t.x||null==t.y)return{x:t.x,y:t.y,w:t.w,h:t.h};const e=Number(t.w)||0,i=Number(t.h)||0;return{x:e<0?t.x+e:t.x,y:i<0?t.y+i:t.y,w:Math.abs(e),h:Math.abs(i)}}function Sh(t){return t&&Array.isArray(t.spaces)?t.spaces.map(t=>{const e=yh,i=function(t){return Array.isArray(t)&&4===t.length&&t.every(t=>Number.isFinite(t))&&t[2]>1e-6&&t[3]>1e-6?t:[0,0,1,1]}(t.view_box);return{id:t.id,title:t.title,cellCm:Number.isFinite(Number(t.cell_cm))&&Number(t.cell_cm)>0?Number(t.cell_cm):5,vb:[i[0]*yh,i[1]*e,i[2]*yh,i[3]*e],bg:t.plan_url?{href:As(t.plan_url),...xh(t,yh)}:null,rooms:(t.rooms||[]).map(t=>{const i={...t,...$h(t)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*yh:void 0,y:null!=i.y?i.y*e:void 0,w:null!=i.w?i.w*yh:void 0,h:null!=i.h?i.h*e:void 0,poly:i.poly?i.poly.map(t=>[t[0]*yh,t[1]*e]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(t.wall_segments||[]).map(t=>({...t,id:String(t.id),a:[Number(t.a?.[0])*yh,Number(t.a?.[1])*e],b:[Number(t.b?.[0])*yh,Number(t.b?.[1])*e],cm:Number(t.cm)})),room_drafts:(t.room_drafts||[]).map(t=>({id:t.id,points:(t.points||[]).map(t=>[t[0]*yh,t[1]*e]),segments:(t.segments||[]).map(t=>({..."string"==typeof t.id&&t.id?{id:t.id}:{},cm:Number(t.cm)}))})),partitions:(t.partitions||[]).map(t=>({id:t.id,a:[t.a[0]*yh,t.a[1]*e],b:[t.b[0]*yh,t.b[1]*e],cm:Number(t.cm)})),wall_columns:(t.wall_columns||[]).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[t.center[0]*yh,t.center[1]*e],cm:Number(t.cm),..."circle"===t.shape?{}:{angle:Vc(t.angle)}}))}}):[]}const Mh=5e3,Ch=Mh*yh,Dh=240,Ph=yh/Dh,Th=1/Dh;function Rh(t){if(!Number.isFinite(t))return t;const e=Math.round(t*Dh/yh)*yh/Dh;return Math.abs(e-t)<=1e-9*Ph?t:e}function Ih(t){return{x:Rh(t.x),y:Rh(t.y)}}function Ah(t){return Number.isFinite(t)?Math.min(Ch,Math.max(-Ch,t)):0}function zh(t){return Number.isFinite(t)?Math.min(Mh,Math.max(-Mh,t)):0}const Fh=1/3,Eh=200;function Nh(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t){const t=Number(o[0]),a=Number(o[1]);Number.isFinite(t)&&Number.isFinite(a)&&(ts&&(s=t),a>n&&(n=a))}return e>s?null:{minX:e,minY:i,maxX:s,maxY:n}}function Oh(t){return t.poly&&t.poly.length?Nh(t.poly):null==t.x||null==t.y?null:Nh([[t.x,t.y],[t.x+(t.w||0),t.y+(t.h||0)]])}function Lh(t,e){const i=[];for(const e of t.rooms||[]){const t=Oh(e);t&&i.push(t)}if(t.bg){const e=Nh(Lr(t.bg));e&&i.push(e)}for(const t of e||[])if(Array.isArray(t)){const e=Nh([t]);e&&i.push(e)}else i.push(t);return i}const Hh=t=>{if(!t.length)return 0;const e=[...t].sort((t,e)=>t-e),i=e.length>>1;return e.length%2?e[i]:(e[i-1]+e[i])/2},Bh=t=>{let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t)o.minXs&&(s=o.maxX),o.maxY>n&&(n=o.maxY);return e>s||i>n?null:{x:e,y:i,w:s-e,h:n-i}};function qh(t,e){let{x:i,y:s,w:n,h:o}=t;n<30&&(i=i+n/2-100,n=Eh),o<30&&(s=s+o/2-100,o=Eh);const a=Math.max(n,o)*e;return{x:i-a,y:s-a,w:n+2*a,h:o+2*a}}function Wh(t,e={}){const i=e.pad??.05,s=e.k??10,n=e.minSpread??50,o=t.filter(t=>Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&Math.abs(t.minX)<=Ch&&Math.abs(t.maxX)<=Ch&&Math.abs(t.minY)<=Ch&&Math.abs(t.maxY)<=Ch);if(!o.length)return{core:null,all:null,outliers:0};const a=Bh(o);if(o.length<4){const t=qh(a,i);return{core:t,all:t,outliers:0}}const r=o.map(t=>(t.minX+t.maxX)/2),l=o.map(t=>(t.minY+t.maxY)/2),c=Hh(r),h=Hh(l),d=o.map((t,e)=>Math.max(Math.abs(r[e]-c),Math.abs(l[e]-h))),p=Math.max(((t,e)=>t.length?t[Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))))]:0)([...d].sort((t,e)=>t-e),.75),n),u=d.map(t=>t>s*p),_=u.filter(Boolean).length,m=_&&_<=o.length*Fh?o.filter((t,e)=>!u[e]):o;return{core:qh(Bh(m)||a,i),all:qh(a,i),outliers:m===o?0:_}}function jh(t,e,i=.05){const s=Wh(Lh(t,e),{pad:i});if(s.core)return s.core;const n=t.vb&&4===t.vb.length&&t.vb[2]>0&&t.vb[3]>0?t.vb:[0,0,yh,yh];return{x:n[0],y:n[1],w:n[2],h:n[3]}}function Uh(t){const e=jh(t);return{x:e.x+e.w/2,y:e.y+e.h/2}}function Gh(t){const e=[];for(const i of t.rooms||[]){const t=Oh(i);t&&e.push(t)}const i=Wh(e,{pad:0}).core,s=yh*mh(t.cellCm??5);return i?Math.max(s,Math.min(Ch,Math.max(i.w,i.h))):s}function Vh(t,e,i,s=1){const n=Number(i),o=Number.isFinite(s)&&s>0?s:1;return!Number.isFinite(n)||n<=0?t*o:t*Gh(e)*o/n}const Kh=[1,2,5,10,20,50,100,200,500,1e3];function Yh(t){if(t.poly&&t.poly.length){const e=t.poly.map(t=>t[0]),i=t.poly.map(t=>t[1]),s=Math.min(...e),n=Math.min(...i);return{x:s,y:n,w:Math.max(...e)-s,h:Math.max(...i)-n}}return{x:t.x??0,y:t.y??0,w:t.w??0,h:t.h??0}}function Jh(t,e,i,s){const n=i["rl_"+(t.id||"")];if(n&&n.s===e)return{x:n.x*yh,y:n.y*yh};const o=function(t){if(t.poly){const e=t.poly.length;return[t.poly.reduce((t,e)=>t+e[0],0)/e,t.poly.reduce((t,e)=>t+e[1],0)/e]}return[t.x+t.w/2,t.y+.1*Math.min(t.w,t.h)]}(t);return Ih({x:o[0],y:o[1]})}const Xh=["furniture","appliance","sanitary","other"],Zh=[{id:"sofa",group:"furniture",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Qh=new Map(Zh.map(t=>[t.id,t]));function td(t){return t&&Qh.get(t)||null}function ed(t){return Zh.filter(e=>e.group===t)}function id(t,e,i=Ph,s=1e3){const n=Number(e)>0?Number(e):5;return(Number(t)||0)/n*i/s}const sd=5e-4,nd=Mh;function od(t){return Number.isFinite(t)?Math.max(sd,Math.min(nd,t)):sd}const ad=t=>{const e=Math.round(1e3*t)/1e3;return Object.is(e,-0)?"0":String(e)};function rd(t,e,i){const s=td(t);if(!(s&&e>0&&i>0))return"";const n=t=>ad(t*e),o=t=>ad(t*i),a=[];for(const t of s.g)if("r"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}H${n(e+s)}V${o(i+r)}H${n(e)}Z`)}else if("l"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}L${n(s)} ${o(r)}`)}else if("e"===t[0]){const[,s,r,l,c]=t;a.push(`M${n(s-l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s+l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s-l)} ${o(r)}Z`)}else{const e=t.slice(1);if(e.length<4)continue;let i=`M${n(e[0])} ${o(e[1])}`;for(let t=2;t+1{let e=(t%360+360)%360;return e>180&&(e-=360),e};function cd(t,e,i,s,n,o=0){let a=null,r=n;for(const n of s){const[s,l,c,h]=n,d=c-s,p=h-l,u=d*d+p*p;if(!u)continue;const _=Math.sqrt(u);let m=((t-s)*d+(e-l)*p)/u;m=Math.max(0,Math.min(1,m));let g=s+m*d,f=l+m*p;const v=Math.hypot(t-g,e-f);if(!(v0){const t=Math.round(m*_/o)*o;g=s+t/_*d,f=l+t/_*p}a={cx:g+y*(i/2),cy:f+b*(i/2),angle:ld(180*Math.atan2(-y,b)/Math.PI),dist:v}}return a}function hd(t,e,i){const s=i>0?i:1;return{a:[t[0]/s,t[1]/s],b:[e[0]/s,e[1]/s]}}function dd(t,e){const i=e>0?e:1;return[t.a[0]*i,t.a[1]*i,t.b[0]*i,t.b[1]*i]}function pd(t){return Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1]))}function ud(t){if(!Array.isArray(t))return[];const e=[];for(const i of t){if(!i||"object"!=typeof i)continue;const t=i;if(!pd(t.a)||!pd(t.b))continue;const s=[Number(t.a[0]),Number(t.a[1])],n=[Number(t.b[0]),Number(t.b[1])];Math.hypot(n[0]-s[0],n[1]-s[1])<.001||e.push({a:s,b:n})}return e}function _d(t,e,i,s,n=!0){const o=(t||[]).filter(t=>t?.id),a=ud(e);if(a.length)return function(t,e,i,s){const n=ud(t);if(!n.length)return[];const o=function(t,e){const i=[],s=(t||[]).filter(t=>t?.id);for(let t=0;t4*s||o>4*s)continue;const a=(t[0]-n)*p+(t[1]-l)*u,c=(t[2]-n)*p+(t[3]-l)*u,h=Math.max(0,Math.min(a,c)),m=Math.min(d,Math.max(a,c));if(m-ht.lo-e.lo||t.hi-e.hi);const i=[];for(const t of e){const e=i[i.length-1];e&&t.lo<=e.hi+r?e.hi=Math.max(e.hi,t.hi):i.push({...t})}for(const e of i){const i=[n+p*e.lo,l+u*e.lo],s=[n+p*e.hi,l+u*e.hi];Math.hypot(s[0]-i[0],s[1]-i[1])i.pair===t&&Math.abs(i.ux*a-i.uy*o)<=1e-6&&Math.abs((e[0]-i.origin[0])*i.uy-(e[1]-i.origin[1])*i.ux)<=c&&Math.abs((e[2]-i.origin[0])*i.uy-(e[3]-i.origin[1])*i.ux)<=c);h||(h={pair:t,origin:[e[0],e[1]],ux:o,uy:a,ranges:[]},l.push(h));const d=(e[0]-h.origin[0])*h.ux+(e[1]-h.origin[1])*h.uy,p=(e[2]-h.origin[0])*h.ux+(e[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,p),hi:Math.max(d,p)})}const h=[];for(const t of l){t.ranges.sort((t,e)=>t.lo-e.lo||t.hi-e.hi);const e=[];for(const i of t.ranges){const t=e[e.length-1];t&&i.lo<=t.hi+r?t.hi=Math.max(t.hi,i.hi):e.push({...i})}for(const s of e){const e=[t.origin[0]+t.ux*s.lo,t.origin[1]+t.uy*s.lo],n=[t.origin[0]+t.ux*s.hi,t.origin[1]+t.uy*s.hi];Math.hypot(n[0]-e[0],n[1]-e[1])>=r&&h.push(hd(e,n,i))}}return h}(a,t,i,s).map(t=>dd(t,i));if(!n)return[];const r=[],l=(t,e)=>(t.open_to||[]).includes(e.id)||(e.open_to||[]).includes(t.id);for(let t=0;t{const e=fd.get(t);if(!e)return;const i=Date.now();if("hidden"===t.visibilityState){e.hiddenAt||(e.hiddenAt=i);const t={kind:"hidden",token:e.token,at:i,hiddenFor:0,long:!1};for(const i of[...e.subscribers])i(t);return}const s=e.hiddenAt?Math.max(0,i-e.hiddenAt):0;e.hiddenAt=0,e.token++;const n={kind:"visible",token:e.token,at:i,hiddenFor:s,long:s>=md};for(const t of[...e.subscribers])t(n)},onPageShow:e=>{const i=fd.get(t);if(!i)return;const s=Date.now();i.token++;const n={kind:"pageshow",token:i.token,at:s,hiddenFor:0,long:!!e.persisted,persisted:!!e.persisted};for(const t of[...i.subscribers])t(n)}},fd.set(t,i),t.addEventListener("visibilitychange",i.onVisibility),t.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(e),()=>{const i=fd.get(t);i&&(i.subscribers.delete(e),i.subscribers.size||(t.removeEventListener("visibilitychange",i.onVisibility),t.defaultView?.removeEventListener("pageshow",i.onPageShow),fd.delete(t)))}}const yd={now:()=>Date.now(),setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),requestAnimationFrame:t=>window.requestAnimationFrame(t),cancelAnimationFrame:t=>window.cancelAnimationFrame(t)};class bd{constructor(t,e=yd){this.onChange=t,this.clock=e,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(t=>({...t,...t.stage?{stage:[...t.stage]}:{}}))}note(t,e={}){this.record(t,void 0,e)}record(t,e,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:t,state:this._state,...e?{reason:e}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(t){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&t&&t!==this._frameFingerprint&&(this._frameFingerprint=t,this.record("frame-refreshed"))}visibility(t){return"hidden"===t.kind?(this.record("visibility-hidden"),this._token):t.long||"visible"!==t.kind&&"pageshow"!==t.kind?this.beginCandidate("pageshow"===t.kind?"pageshow":"long-resume"):(this.record("pageshow"===t.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(t,e="plan"){return this._token++,this._recoveryReason=e,this._hasCompleteFrame?(this._state="connection"===e?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(e)),this.record("candidate-start",t),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(t){return!this._disposed&&t===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(t,e){if(this._disposed||t!==this._token)return!1;let i=!0;const s=(async()=>{for(await e.updateComplete();i&&!this._disposed&&t===this._token;)if(e.stageValid()&&e.assetsReady()){if(await this.nextFrame(),t!==this._token||!e.stageValid()||!e.assetsReady())continue;if(await this.nextFrame(),t===this._token&&e.stageValid()&&e.assetsReady())return!0}else await this.nextFrame();return!1})();let n=0;const o=new Promise(t=>{n=this.clock.setTimeout(()=>t({ready:!1,timedOut:!0}),gd)}),a=await Promise.race([s.then(t=>({ready:t,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(n),!this._disposed&&t===this._token&&(!(!a.ready&&!a.timedOut)&&(a.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=e.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(t=this._recoveryReason||"plan"){return this.beginCandidate("retry",t)}nextFrame(){return new Promise(t=>{const e=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(e),t()});this._barrierRafs.add(e)})}scheduleOverlay(t){this.clearOverlayTimer(),this._recoveryReason=t,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const t=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},t)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const t of this._barrierRafs)this.clock.cancelAnimationFrame(t);this._barrierRafs.clear()}}function wd(t){let e=2166136261,i=2654435769;const s=new WeakSet,n=t=>{for(let s=0;s>>0)+(i>>>2)}},o=t=>{if(null===t)return void n("n");const e=typeof t;if("string"===e)return void n(`s${t.length}:${t}`);if("number"===e)return void n(`d${Number.isNaN(t)?"NaN":String(t)}`);if("boolean"===e)return void n(t?"t":"f");if("undefined"===e)return void n("u");if("object"!==e)return void n(`${e}:${String(t)}`);const i=t;if(s.has(i))n("[cycle]");else{if(s.add(i),Array.isArray(t)){n("[");for(const e of t)o(e);return n("]"),void s.delete(i)}n("{");for(const e of Object.keys(t).sort())n(e),o(t[e]);n("}"),s.delete(i)}};return o(t),`${(e>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function kd(t){return wd(t)}const xd=new WeakMap;class $d{constructor(t,e=()=>Date.now()){this.onUpdate=t,this.now=e,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(t){const e=((t,e)=>{const i=t?.connection||t?.callWS||e;return!i||"object"!=typeof i&&"function"!=typeof i?e:i})(t,this.fallbackAuthority);return this.shared&&this.authority===e||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=e,this.shared=(t=>{let e=xd.get(t);return e||(e={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},xd.set(t,e)),e})(e),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(t,e){this.disposed=!1,this.referenced=new Set(e());const i=this.bind(t());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(t(),e()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const t of this.queued)this.shared.queued.delete(t)}this.queued.clear()}invalidate(t){const e=this.bind(t);clearTimeout(this.batchTimer),this.queued.clear(),e.queued.clear(),e.inFlight.clear(),e.retry.clear(),e.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return i;const s=this.bind(t);this.referenced.add(i),s.references.set(this.referenceOwner,new Set(this.referenced));const n=s.signed[i],o=n?this.now()-n.at:1/0;return o{const e=[...this.queued];this.queued.clear();for(const t of e)i.queued.delete(t);this.sign(t,e)},30))}sign(t,e){if(!e.length||!t?.callWS)return;const i=this.bind(t);for(const s of function(t,e){const i=Math.max(1,Math.floor(e)),s=[];for(let e=0;e{const s=i.inFlight.get(t);return!(void 0!==s&&e-s<15e3)&&(i.inFlight.set(t,e),!0)});n.length&&t.callWS({type:"houseplan/content/sign",paths:n}).then(t=>{const e=this.now();let s=0,o=!1;for(const a of n){const n=t?.urls?.[a];if("string"==typeof n&&n){const t=i.signed[a];t?.loaded&&t.url!==n?(t.pending={url:n,at:e},this.preloadReplacement(i,a,n,e)):(i.signed[a]={url:n,at:e,loaded:t?.url===n&&!!t.loaded},o=!0),i.retry.delete(a),s++}else this.backOff(i,a)}if(s&&(this.trimShared(i),o))for(const t of[...i.listeners])t()}).catch(()=>{for(const t of n)this.backOff(i,t)}).finally(()=>{for(const t of n)i.inFlight.get(t)===e&&i.inFlight.delete(t);for(const t of[...i.settlers])t()})}}preloadReplacement(t,e,i,s){const n=()=>{const n=t.signed[e];if(n?.pending?.url===i){t.signed[e]={url:i,at:s,loaded:!0},t.retry.delete(e),this.trimShared(t);for(const e of[...t.listeners])e()}},o=()=>{const s=t.signed[e];s?.pending?.url===i&&(delete s.pending,this.backOff(t,e))};if("undefined"==typeof Image)return void n();const a=new Image;a.onload=()=>{("function"==typeof a.decode?a.decode():Promise.resolve()).then(n).catch(o)},a.onerror=o,a.src=i}preloadCurrentImage(t,e,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const s=i.url;return i.preload=new Promise(n=>{const o=new Image;let a=!1;const r=o=>{if(a)return;a=!0,clearTimeout(l);const r=t.signed[e];if(r===i&&delete r.preload,o&&r===i&&r.url===s){r.loaded=!0;for(const e of[...t.listeners])e();n(!0)}else o||r!==i||this.backOff(t,e),n(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>r(!0)).catch(()=>r(!1))},o.onerror=()=>r(!1);const l=setTimeout(()=>r(!1),gd);o.src=s}),i.preload}prepareImage(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const s=this.bind(t),n=()=>{const e=s.signed[i];if(e&&this.now()-e.atthis.now()&&!s.inFlight.has(i)&&!s.queued.has(i)?Promise.resolve(!1):null},o=n();return o?(a=o,new Promise(t=>{let e=!1;const i=i=>{e||(e=!0,clearTimeout(s),t(i))},s=setTimeout(()=>i(!1),gd);a.then(i).catch(()=>i(!1))})):new Promise(t=>{let e=!1,i=null;const o=i=>{e||(e=!0,clearTimeout(r),s.settlers.delete(a),t(i))},a=()=>{e||i||(i=n(),i&&i.then(o).catch(()=>o(!1)))},r=setTimeout(()=>o(!1),gd);s.settlers.add(a),a()});var a}backOff(t,e){const i=t.retry.get(e)?.delay||0,s=Math.min(6e4,i?2*i:2e3);t.retry.set(e,{notBefore:this.now()+s,delay:s})}trimShared(t){const e=Object.entries(t.signed);if(e.length<=512)return;const i=new Set(t.inFlight.keys());for(const e of t.references.values())for(const t of e)i.add(t);for(const[t,s]of e)(s.pending||s.preload)&&i.add(t);e.sort((t,e)=>e[1].at-t[1].at);const s=e.filter(([t])=>i.has(t));for(const t of e){if(s.length>=512)break;i.has(t[0])||s.push(t)}t.signed=Object.fromEntries(s)}resign(t,e){const i=this.bind(t);this.referenced=new Set(e),i.references.set(this.referenceOwner,new Set(this.referenced));const s=this.now(),n=new Set;for(const t of i.references.values())for(const e of t)n.add(e);const o={};for(const[t,e]of Object.entries(i.signed))n.has(t)&&s-e.at!!o[t]&&!o[t].pending))}markLoaded(t,e,i){const s=As(e);if(!s.startsWith("/api/houseplan/content/"))return;const n=this.bind(t).signed[s];if(n&&(!i||n.url===i)&&!n.loaded){n.loaded=!0;for(const e of[...this.bind(t).listeners])e()}}isReady(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return!0;const s=this.bind(t).signed[i];return!!s&&this.now()-s.att.id===e)}function Md(t="file"){const e="draw"===t;return{source:t,showBorders:e,showNames:e,displayTouched:!1}}function Cd(t,e){if(t.displayTouched)return{...t,source:e};const i="draw"===e;return{...t,source:e,showBorders:i,showNames:i}}function Dd(t,e,i){return{...t,[e]:i,displayTouched:!0}}function Pd(t,e,i){return[t[0]*e+t[1]*i+t[2],t[3]*e+t[4]*i+t[5]]}function Td(t,e){let i=0;for(const[s,n]of e){const e=Pd(t,s[0],s[1]);i=Math.max(i,Math.hypot(e[0]-n[0],e[1]-n[1]))}return i}const Rd=t=>{if(null==t||""===t)return null;const e=Number(t);return Number.isFinite(e)?e:null},Id=t=>{const e=t,i=Rd(Array.isArray(e)?e[0]:e?.x),s=Rd(Array.isArray(e)?e[1]:e?.y);return null==i||null==s?null:[i,s]};function Ad(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}if(e.length<3)return null;let i=0,s=0,n=0;for(let t=0;tt+e[0],0)/e.length,e.reduce((t,e)=>t+e[1],0)/e.length]:[s/(3*i),n/(3*i)]}function zd(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}const i=Ad(e);if(!i)return null;const s=e.map(t=>t[0]),n=e.map(t=>t[1]);return{centroid:i,bbox:[Math.min(...s),Math.min(...n),Math.max(...s),Math.max(...n)]}}function Fd(t){let e=t;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;e=t.path??t.points??e}if(!Array.isArray(e)||!e.length)return[];let i=(e.some(t=>(t=>Array.isArray(t)?t.length>=2&&!Array.isArray(t[0])&&("object"!=typeof t[0]||null==t[0]):!!t&&"object"==typeof t&&("x"in t||"y"in t))(t))?[e]:e.filter(Array.isArray)).map(t=>t.map(Id).filter(t=>null!=t)).filter(t=>t.length>=2);i.length>64&&(i=i.slice(-64));const s=i.reduce((t,e)=>t+e.length,0);if(s<=4e3)return i.map(t=>t.slice());const n=4e3-2*i.length,o=i.map(t=>t.length-2),a=o.reduce((t,e)=>t+e,0),r=o.map(t=>n*t/a),l=r.map(Math.floor);let c=n-l.reduce((t,e)=>t+e,0);const h=r.map((t,e)=>({index:e,fraction:t-Math.floor(t)})).sort((t,e)=>e.fraction-t.fraction||t.index-e.index);for(let t=0;tfunction(t,e){if(e>=t.length)return t.slice();if(e<=2)return[t[0],t[t.length-1]];const i=[];for(let s=0;st.slice()),i=e[e.length-1];return i?(i.length>2?i.pop():e.pop(),e):[]}function Od(t){if(!t)return null;const e=t.vacuum_position||t.robot_position||null,i=e&&null!=Rd(e.x)&&null!=Rd(e.y)?{x:Rd(e.x),y:Rd(e.y),a:Rd(e.a??e.angle??e.theta)}:null,s=Fd(t.path?.path??t.path?.points??t.path),n=[],o=t.rooms,a=Array.isArray(o)?o.map((t,e)=>[String(t?.id??e),t]):o&&"object"==typeof o?Object.entries(o):[];for(const[t,e]of a){if(!e||"object"!=typeof e)continue;const i=String(e.name??e.label??"").trim(),s=[[Rd(e.cx),Rd(e.cy)],[Rd(e.center?.x),Rd(e.center?.y)],[Rd(e.x),Rd(e.y)]].find(([t,e])=>null!=t&&null!=e);let o=s?.[0]??null,a=s?.[1]??null;const r=zd(e.outline),l=Rd(e.x0),c=Rd(e.y0),h=Rd(e.x1),d=Rd(e.y1),p=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||r?.bbox||null;if(null!=o&&null!=a||!r||([o,a]=r.centroid),null!=o&&null!=a||!p||(o=(p[0]+p[2])/2,a=(p[1]+p[3])/2),i&&null!=o&&null!=a){const e={id:t,name:i,cx:o,cy:a};p&&([e.x0,e.y0,e.x1,e.y1]=p),n.push(e)}}const r=function(t){return String(t.map_name??t.current_map??t.map_index??t.selected_map??"default")}(t);return i||n.length||s.length?{pos:i,path:s,rooms:n,mapId:r}:null}function Ld(t,e,i){if(!t||!e)return null;const s=e.attributes||{},n=t.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,a=!!Id(s.vacuum_position??s.robot_position),r=!(!s.rooms||"object"!=typeof s.rooms),l=Fd(s.path?.path??s.path?.points??s.path).length>0,c=[s.map_name,s.current_map,s.map_index,s.selected_map].some(t=>null!=t),h="xiaomi_cloud_map_extractor"===o,d=r||l||c;let p=null;if(a?p="compatible":h?p="known_xcme_incomplete":d?p="partial":"camera"===n&&(p="camera"),!p)return null;const u=a?"camera"===n?300:200:h?100:d?50:0;return{entityId:t,name:String(s.friendly_name||t),platform:o,category:p,hasPosition:a,hasRooms:r,hasPath:l,hasMapId:c,score:u}}const Hd=t=>t.toLowerCase().replace(/[\s_\-.,]+/g,"");function Bd(t,e){const i=new Map(e.map(t=>[Hd(t.name),t])),s=[],n=[];for(const e of t){const t=i.get(Hd(e.name));t&&(s.push([[e.cx,e.cy],[t.cx,t.cy]]),n.push(e.name))}if(s.length<3)return null;const o=function(t){if(t.length<3)return null;let e=0,i=0,s=0,n=0,o=0,a=0,r=0,l=0,c=0,h=0,d=0,p=0;for(const[[u,_],[m,g]]of t){if(![u,_,m,g].every(Number.isFinite))return null;e+=u*u,i+=u*_,s+=u,n+=_*_,o+=_,a+=1,r+=u*m,l+=_*m,c+=m,h+=u*g,d+=_*g,p+=g}const u=[e,i,s,i,n,o,s,o,a],_=t=>{const[e,i,s,n,o,a,r,l,c]=u,h=e*(o*c-a*l)-i*(n*c-a*r)+s*(n*l-o*r);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-a*l)/h,(s*l-i*c)/h,(i*a-s*o)/h,(a*r-n*c)/h,(e*c-s*r)/h,(s*n-e*a)/h,(n*l-o*r)/h,(i*r-e*l)/h,(e*o-i*n)/h];return[d[0]*t[0]+d[1]*t[1]+d[2]*t[2],d[3]*t[0]+d[4]*t[1]+d[5]*t[2],d[6]*t[0]+d[7]*t[1]+d[8]*t[2]]},m=_([r,l,c]),g=_([h,d,p]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(s);return o?{matrix:o,matched:n,residual:Td(o,s)}:null}function qd(t,e,i){const s=t[t.length-1];if(s&&s[0]===e[0]&&s[1]===e[1])return t;if(t.push(e),t.length<=600)return t;let n=function(t,e){if(t.length<3)return t.slice();const i=new Uint8Array(t.length);i[0]=i[t.length-1]=1;const s=[[0,t.length-1]];for(;s.length;){const[n,o]=s.pop(),[a,r]=t[n],[l,c]=t[o],h=l-a,d=c-r,p=Math.hypot(h,d)||1e-9;let u=0,_=-1;for(let e=n+1;eu&&(u=i,_=e)}_>0&&u>e&&(i[_]=1,s.push([n,_],[_,o]))}const n=[];for(let e=0;e600&&(n=n.filter((t,e)=>e%2==0||e===n.length-1)),n}function Wd(t){return"cleaning"===t||"returning"===t||"on"===t}const jd={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Ud(t){const[e,i]=jd[t.rot]||[1,0],s=t.mir?-1:1;return[t.s*e*s,-t.s*i,t.ox,t.s*i*s,t.s*e,t.oy]}function Gd(t){const e=t[0]*t[4]-t[1]*t[3];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;const i=e<0,s=Math.sqrt(Math.abs(e));let n=180*Math.atan2(-t[1],t[4])/Math.PI;return n=(90*Math.round(n/90)%360+360)%360,{ox:t[2],oy:t[5],s:s,rot:n,mir:i}}function Vd(t,e,i,s){const[n,o]=Pd(Ud(e),i,s),a=Ud({...t,ox:0,oy:0}),[r,l]=Pd(a,i,s);return{...t,ox:n-r,oy:o-l}}function Kd(t){const e=t?.trail_mode;return"never"===e||"cleaning"===e||"always"===e?e:!1===t?.trail?"never":"cleaning"}const Yd={offStates:["off"],unknownUsesToggle:!0},Jd={light:Yd,switch:Yd,fan:Yd,humidifier:Yd,input_boolean:Yd,automation:Yd,remote:Yd,group:Yd,climate:{...Yd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Yd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Yd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Yd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function Xd(t){return t.slice(0,t.indexOf("."))}function Zd(t,e,i){if(!t?.services||"object"!=typeof t.services)return!1;const s=t.services?.[e];return!!s&&Object.prototype.hasOwnProperty.call(s,i)}function Qd(t,e,i){return Zd(t,e,i)?{domain:e,service:i}:Zd(t,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function tp(t,e){return t?.entities?.[e]||null}function ep(t,e,i){const s=t?.states?.[i],n=tp(e,i);return s?.attributes?.friendly_name||n?.name||n?.original_name||i}function ip(t,e){const i=tp(t,e);if(null!=i?.disabled_by)return!0;const s=i?.device_id?t?.devices?.[i.device_id]:null;return null!=s?.disabled_by}function sp(t,e){const i=t?.attributes?.supported_features;if(null==i||""===i)return!1;const s=Number(i);return Number.isFinite(s)&&(s&e)===e}function np(t,e,i){const s=Xd(i);if("lock"===s||"alarm_control_panel"===s)return!0;if("cover"!==s)return!1;const n=t?.states?.[i],o=tp(e,i),a=String(n?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Ui.has(a)}function op(t,e,i,s,n){return{ref:i,entityId:s,name:s?ep(t,e,s):null,reason:n}}function ap(t,e,i,s,n,o=null){return{target:null,skipped:op(t,e,i,s,n),semantics:o,nextEffect:null,command:null}}function rp(t,e,i,s,n=i){const o=Xd(i);if("cover"!==o&&"valve"!==o)return function(t,e,i,s,n=i){const o=Xd(i),a=t?.states?.[i];if(ip(e,i))return ap(t,e,n,i,"ha-disabled","power");if(np(t,e,i))return ap(t,e,n,i,"secure");if(!a)return ap(t,e,n,i,"missing","power");if("unavailable"===a.state)return ap(t,e,n,i,"unavailable","power");const r=Jd[o];if(!r)return ap(t,e,n,i,"unsupported");let l,c;if("unknown"===a.state||""===a.state){if(!r.unknownUsesToggle)return ap(t,e,n,i,"unsupported","power");l="toggle",c="toggle"}else r.offStates.includes(String(a.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=r.featureMasks?.[c];if(h&&!sp(a,h))return ap(t,e,n,i,"unsupported","power");const d=Qd(t,o,c);return d?{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:ap(t,e,n,i,"unsupported","power")}(t,e,i,s,n);if(ip(e,i))return ap(t,e,n,i,"ha-disabled",o);if(np(t,e,i))return ap(t,e,n,i,"secure",o);const a=t?.states?.[i];if(!a)return ap(t,e,n,i,"missing",o);if("unavailable"===a.state)return ap(t,e,n,i,"unavailable",o);const r=function(t,e,i){const s=String(i?.state||""),n="closed"===s?{service:`open_${e}`,effect:"open",feature:1}:"open"===s?{service:`close_${e}`,effect:"close",feature:2}:"opening"===s||"closing"===s?{service:`stop_${e}`,effect:"stop",feature:8}:null;return n&&sp(i,n.feature)&&Zd(t,e,n.service)?n:sp(i,3)&&Zd(t,e,"toggle")?{service:"toggle",effect:"toggle"}:null}(t,o,a);if(!r)return ap(t,e,n,i,"unsupported",o);return{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:o,nextEffect:r.effect,command:{domain:o,service:r.service,data:{entity_id:i}}}}function lp(t){return"entity"===t.bindingKind?t.bindingRef&&Ms(t.bindingRef)?[t.bindingRef]:[]:"virtual"===t.bindingKind?[]:to(t)}function cp(t){const e=t.marker?.toggle_entity;return e&&lp(t).includes(e)?e:null}function hp(t,e,i){const s=function(t,e){if("entity"===t.bindingKind&&t.bindingRef){const e=t.marker?.light_entity?eo(t):null;return[...new Set([e,t.bindingRef].filter(t=>!!t))]}const i=t.entities.length?t.entities:t.allEntities||[],s=t.marker?.light_entity||t.primary&&Ms(t.primary)?eo(t):null;return[...new Set([s,...Yn(e,i)].filter(t=>!!t))]}(i,e);if(!s.length)return null;const n="entity"===i.bindingKind?"binding":"device-role";if("binding"===n)return rp(t,e,s[0],n);let o=null,a=null;for(const i of s){const s=rp(t,e,i,n);if(s.command)return s;const r=s.skipped?.reason;if("missing"===r||"unavailable"===r||"secure"===r)return s;"ha-disabled"!==r?o||=s:a||=s}return o||a}function dp(t){const e=t.skipped?.reason;return"missing"===e?"unavailable":e||"unsupported"}function pp(t,e){return{origin:t,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:e,nextEffect:null,command:null}}function up(t,e){return"cover"===t||"toggle"===t?"toggle":"more-info"===t||"run"===t||"info"===t?t:(null==t||""===t)&&"light"===e?"toggle":"info"}function _p(t,e){return{origin:t,kind:"single",semantics:e.semantics,targets:e.target?[e.target]:[],skippedTargets:e.skipped?[e.skipped]:[],noneReason:e.command?null:dp(e),nextEffect:e.nextEffect,command:e.command}}function mp(t,e,i,s=[]){const n=new Map,o=[],a=new Set,r=t=>{const e=`${t.ref}\n${t.entityId||""}\n${t.reason}`;a.has(e)||(a.add(e),o.push(t))};for(const t of s)r(t);for(const s of i){const i=rp(t,e,s.entityId,s.via,s.ref);i.target?n.set(s.entityId,n.get(s.entityId)||i.target):i.skipped&&r(i.skipped)}const l=[...n.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(t=>"secure"===t.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(t=>"on"===t.state)?"turn_off":"turn_on",h=Qd(t,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(t=>t.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>op(t,e,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function gp(t){return String(t.marker?.id||t.id||"")}function fp(t){const{hass:e,device:i}=t,s=t.registryHass||e,n=function(t){return"toggle"===t.tapAction?"explicit-toggle":"cover"===t.tapAction?"legacy-cover":!t.tapAction&&t.primary?.startsWith("light.")?"default-light":null}(i);if(!n)return null;const o=i.marker;if("explicit-toggle"===n&&yn(o)){const e=String(o?.id||i.id||""),s=ro(t.devices).get(e);if(s)return function(t,e){const i=t.registryHass||t.hass;return mp(t.hass,i,e.driverEids.map(t=>({entityId:t,via:"control-marker-driver",ref:`marker:${e.markerId}`})))}(t,s);const a=bn(o,t.virtualLights);return{origin:n,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:a?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:a?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===n){if(Zn(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(t,e=null){const{hass:i,device:s,devices:n}=t,o=t.registryHass||i,a=Zn(s.marker?.binding,s.marker?.controls??s.controls,s.entities),r=t.lightSources||ho(i,n,null,t.virtualLights),l=new Map;for(const t of r){if(!t.key.startsWith("marker:"))continue;const e=l.get(t.key)||[];e.push(t),l.set(t.key,e)}const c=ro(n),h=new Map;for(const t of n){const e=String(t.marker?.id||t.id||"");e&&h.set(e,t)}const d=[],p=[];e&&d.push({entityId:e,via:"entity"===s.bindingKind?"binding":"device-role",ref:e});for(const t of a){if(!t.startsWith("marker:")){Ms(t)?d.push({entityId:t,via:"control-entity",ref:t}):p.push(op(i,o,t,t.includes(".")?t:null,"unsupported"));continue}const e=l.get(t)||[];if(!e.length){const e=h.get(t.slice(7));if("ha_disabled"===e?.bindingStatus?.kind){const s=e.bindingStatus.allEntityIds[0]||null;p.push({ref:t,entityId:s,name:e.name||(s?ep(i,o,s):null),reason:"ha-disabled"})}else p.push(op(i,o,t,null,"missing"));continue}const n=[...new Set(e.flatMap(t=>t.serviceEids))];if(n.length){for(const e of n)d.push({entityId:e,via:"control-entity",ref:t});continue}const a=e.some(t=>t.passive),r=t.slice(7),u=gp(s),_=c.get(r)?.controllers.find(t=>gp(t.device)===u);if(a&&_?.driverEids.length)for(const e of _.driverEids)d.push({entityId:e,via:"control-marker-driver",ref:t});else p.push(op(i,o,t,null,a?"missing":"unsupported"))}return mp(i,o,d,p)}(t,cp(i))}if("legacy-cover"===n){const t=i.entities.find(t=>t.startsWith("cover."))||i.allEntities?.find(t=>t.startsWith("cover."));return t?_p(n,rp(e,s,t,"device-role")):pp(n,"no-actionable-entity")}const a=cp(i),r=a?rp(e,s,a,"entity"===i.bindingKind?"binding":"device-role"):hp(e,s,i);return r?_p(n,r):pp(n,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function vp(t){if(!t)return[];const e=Array.isArray(t.data.entity_id)?t.data.entity_id:[t.data.entity_id];return[...new Set(e)].sort()}function yp(t){return t?t.operation?t.operation:t.command?{kind:"ha-service",command:t.command}:null:null}const bp=new Set(["missing","ha-disabled","unavailable"]);function wp(t,e){const i=yp(t),s=yp(e);return!(!i||!s||i.kind!==s.kind)&&("virtual-light"===i.kind&&"virtual-light"===s.kind?i.markerId===s.markerId:"ha-service"===i.kind&&"ha-service"===s.kind&&function(t,e){const i=vp(t),s=vp(e);return i.length===s.length&&i.every((t,e)=>t===s[e])}(i.command,s.command))}const kp=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]);function xp(t,e=5,i=5){return gl(t.cm,e,i)/2}function $p(t,e,i=1,s=5,n=5,o=0){const a=t.host;if(!a||"partition"!==a.kind||"string"!=typeof a.id||!a.id)return{resolved:null,reason:"invalid-host"};const r=e.find(t=>t.id===a.id);if(!r)return{resolved:null,reason:"missing-partition"};if(!kp(r.a)||!kp(r.b)||!Number.isFinite(a.t)||a.t<0||a.t>1)return{resolved:null,reason:"invalid-position"};const l=r.b[0]-r.a[0],c=r.b[1]-r.a[1],h=Math.hypot(l,c),d=Number(t.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const p=a.t*h;if(p-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const u=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:t,host:a,partition:r,center:[r.a[0]+l*a.t,r.a[1]+c*a.t],angle:m,length:d,depth:gl(r.cm,s,n),t:a.t,axis:{a:[r.a[0],r.a[1]],b:[r.b[0],r.b[1]],ux:u,uy:_,length:h}}}}function Sp(t,e,i=1,s=5,n=5){return $p(t,e,i,s,n,0)}function Mp(t,e,i=1,s=5,n=5){const o=t.host,a="partition"===o?.kind?e.find(t=>t.id===o.id):void 0;if(!a)return Sp(t,e,i,s,n);const r=$p(t,e,i,s,n,xp(a,s,n));return"does-not-fit"===r.reason?{resolved:null,reason:"does-not-fit-jamb"}:r}function Cp(t,e){return!t||(t.length!==e.length||t.host?.kind!==e.host?.kind||t.host?.id!==e.host?.id||t.host?.t!==e.host?.t)}function Dp(t){const{center:e,length:i,axis:s,host:n}=t,o=i/2;return{hostId:n.id,a:[e[0]-s.ux*o,e[1]-s.uy*o],b:[e[0]+s.ux*o,e[1]+s.uy*o],depth:t.depth}}function Pp(t,e=!1){const i=e?1:-1,s=t.depth/2;return{ox:-t.axis.uy*i*s,oy:t.axis.ux*i*s,cm:t.partition.cm,side:i}}function Tp(t,e,i){return t.flatMap(t=>!kp(t.a)||!kp(t.b)||Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])<=1e-9?[]:[{roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`partition:${t.id}`,kind:"outer",cm:t.cm,open:!1,half:gl(t.cm,e,i)/2,partitionHost:{kind:"partition",id:t.id}}])}function Rp(t,e,i){const{center:s,length:n,axis:o}=t,a=n/2,r=e.flatMap(t=>{if(!t.kind||t.open)return[];const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(e,n);if(!(r>i))return[];const l=e/r,c=n/r;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((s[0]-t.a[0])*c-(s[1]-t.a[1])*l)>i)return[];const h=t=>(t[0]-s[0])*o.ux+(t[1]-s[1])*o.uy,d=h(t.a),p=h(t.b),u=Math.max(-a,Math.min(d,p)),_=Math.min(a,Math.max(d,p));return _>=u-i?[[u,_]]:[]});if(!r.length)return!1;r.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let l=-a;for(const[t,e]of r){if(t>l+i)return!1;if(l=Math.max(l,e),l>=a-i)return!0}return!1}function Ip(t,e,i){return{...t,x:e.center[0]/i,y:e.center[1]/i,angle:e.angle}}const Ap=.001;function zp(t){return!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function Fp(t){return`${t[0].toFixed(6)},${t[1].toFixed(6)}`}function Ep(t,e,i){return Math.abs(t[0]-e[0])"room"!==t.kind&&i.some(i=>i!==t&&function(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>i))return!1;const a=s/o,r=n/o,l=e=>Math.abs((e[0]-t.a[0])*r-(e[1]-t.a[1])*a);if(l(e.a)>i||l(e.b)>i)return!1;const c=(e.a[0]-t.a[0])*a+(e.a[1]-t.a[1])*r,h=(e.b[0]-t.a[0])*a+(e.b[1]-t.a[1])*r;return Math.min(o,Math.max(c,h))-Math.max(0,Math.min(c,h))>i}(t,i,e))),n=s.map(t=>{const[e,i]=Np(t.a,t.b);return{a:e,b:i,key:`hidden|${Lp(t,e,i)}`,sourceKind:t.kind,sourceId:t.id}}).sort((t,e)=>t.key.localeCompare(e.key)),o=s.flatMap(t=>[t.a,t.b].map((e,i)=>({point:[e[0],e[1]],key:`hidden|${Op(t)}|endpoint-${i}`,sourceKind:t.kind,sourceId:t.id}))).sort((t,e)=>t.key.localeCompare(e.key));return{segments:n,endpoints:o}}function Wp(t){const e=t.epsilon??Ap,i=t.roomCuts||[],s=new Map;for(const e of t.partitionCuts||[]){if("string"!=typeof e.hostId||!e.hostId||!zp(e.a)||!zp(e.b))continue;const t=s.get(e.hostId)||[];t.push([e.a[0],e.a[1],e.b[0],e.b[1]]),s.set(e.hostId,t)}const n=[];for(const[e,s]of pi(t.space.rooms).entries())s.length<4||n.push({a:[s[0],s[1]],b:[s[2],s[3]],kind:"room",id:`room-edge-${e}`,cuts:i});for(const e of t.space.room_drafts||[])if(e.id!==t.activeDraftId)for(let t=0;t+1Bp(s,t,e)))continue;const t=Fp(s);a.has(t)||a.set(t,{point:[s[0],s[1]],key:t})}}}return{segments:[...o.values()].sort((t,e)=>t.key.localeCompare(e.key)),endpoints:[...a.values()].sort((t,e)=>t.key.localeCompare(e.key))}}function jp(t,e,i){return e.some(e=>zp(e)&&Ep(t,e,i))}function Up(t,e,i){if(!i)return!0;const s=t-i.distance;return s<-1e-9||Math.abs(s)<=1e-9&&e.localeCompare(i.key)<0}function Gp(t,e,i){const s=i.epsilon??Ap,n=i.excludePoints||[],o=[...t.endpoints,...(i.extraEndpoints||[]).filter(t=>zp(t.point)).map(t=>({point:[t.point[0],t.point[1]],key:t.key}))],a=new Map;for(const t of o){if(jp(t.point,n,s))continue;const e=Fp(t.point),i=a.get(e);(!i||t.key.localeCompare(i.key)<0)&&a.set(e,t)}return[...a.values()].map(t=>({kind:"endpoint",point:[...t.point],key:t.key,distance:Math.hypot(e[0]-t.point[0],e[1]-t.point[1])})).filter(t=>t.distance<=i.tolerance).sort((t,e)=>t.distance-e.distance||t.key.localeCompare(e.key))}function Vp(t,e){if(!t.length)return null;if(e>0){const i=new Set;for(let s=0;s1)return{kind:"ambiguous",candidate:null,conflicts:t.filter(t=>i.has(t.key)).map(t=>({point:[...t.point],key:t.key}))}}return{kind:"resolved",candidate:t[0],conflicts:[]}}function Kp(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>0))return[...t.a];const a=s/o,r=n/o,l=Math.max(0,Math.min(o,(e[0]-t.a[0])*a+(e[1]-t.a[1])*r)),c=i>0?Math.max(0,Math.min(o,Math.round(l/i)*i)):l;return[t.a[0]+a*c,t.a[1]+r*c]}function Yp(t,e,i){if(!(zp(e)&&zp(i.anchor)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=function(t,e){const i=e[0]-t[0],s=e[1]-t[1];if(!(Math.hypot(i,s)>Number.EPSILON))return null;const n=Math.round(Math.atan2(s,i)/(Math.PI/4))*(Math.PI/4);return[Math.cos(n),Math.sin(n)]}(i.anchor,e);if(!n)return{kind:"none",candidate:null,conflicts:[]};const o=Gp(t,e,i).filter(t=>function(t,e,i,s){const n=t[0]-e[0],o=t[1]-e[1];return n*i[0]+o*i[1]>s&&Math.abs(n*i[1]-o*i[0])<=s*Math.max(Math.hypot(n,o),1)}(t.point,i.anchor,n,s)),a=Vp(o,i.distinguishTolerance||0);if(a)return a;let r=null;for(const o of t.segments){const t=o.b[0]-o.a[0],a=o.b[1]-o.a[1],l=o.a[0]-i.anchor[0],c=o.a[1]-i.anchor[1],h=n[0]*a-n[1]*t;let d=null;if(Math.abs(h)<=s*Math.max(Math.hypot(t,a),1)){if(Math.abs(l*n[1]-c*n[0])>s*Math.max(Math.hypot(l,c),1))continue;const t=[o.a,o.b].map(t=>({point:t,along:(t[0]-i.anchor[0])*n[0]+(t[1]-i.anchor[1])*n[1]})).filter(t=>t.along>s).sort((t,e)=>t.along-e.along);t.length&&(d=[...t[0].point])}else{const e=(l*a-c*t)/h,o=(l*n[1]-c*n[0])/h;e>s&&o>=-s&&o<=1+s&&(d=[i.anchor[0]+n[0]*e,i.anchor[1]+n[1]*e])}if(!d)continue;const p=Math.hypot(e[0]-d[0],e[1]-d[1]);p>i.tolerance||jp(d,i.excludePoints||[],s)||!Up(p,o.key,r)||(r={kind:"line",point:d,key:o.key,distance:p,segment:o})}return r?{kind:"resolved",candidate:r,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}const Jp=.001;function Xp(t,e,i,s){const n=Number.isFinite(t)&&t>0?Math.floor(t):0,o=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null,a=o(i),r=o(s)??0,l=[];let c=null;for(let t=0;t=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function tu(t,e,i,s){return t*s-e*i}function eu(t){let e=0;for(let i=0;it.localeCompare(e)),e[0]}function au(t,e,i){const s=[...t];for(let t=!0;t&&s.length>=3;){t=!1;for(let n=0;n=0){s.splice(n,1),t=!0;break}}}return s}function ru(t,e){const i=t.map(t=>Math.max(0,Math.min(1,t))).sort((t,e)=>t-e),s=[];for(const t of i)(!s.length||Math.abs(t-s[s.length-1])>e)&&s.push(t);return s}function lu(t,e){return[t.a[0]+(t.b[0]-t.a[0])*e,t.a[1]+(t.b[1]-t.a[1])*e]}function cu(t,e,i){const s=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n:0}(t,e);if(s<-i||s>1+i)return null;const n=lu(e,s);return Math.hypot(n[0]-t[0],n[1]-t[1])<=i?Math.max(0,Math.min(1,s)):null}function hu(t,e,i,s,n){const o=t.b[0]-t.a[0],a=t.b[1]-t.a[1],r=e.b[0]-e.a[0],l=e.b[1]-e.a[1],c=e.a[0]-t.a[0],h=e.a[1]-t.a[1],d=tu(o,a,r,l),p=Math.max(Math.hypot(o,a),Math.hypot(r,l),1);if(Math.abs(d)>n*p){const t=tu(c,h,r,l)/d,e=tu(c,h,o,a)/d;return void(t>=-n&&t<=1+n&&e>=-n&&e<=1+n&&(i.push(Math.max(0,Math.min(1,t))),s.push(Math.max(0,Math.min(1,e)))))}if(!(Math.abs(tu(c,h,o,a))>n*p)){for(const s of[e.a,e.b]){const e=cu(s,t,n);null!=e&&i.push(e)}for(const i of[t.a,t.b]){const t=cu(i,e,n);null!=t&&s.push(t)}}}function du(t){let e=t+1|0;return e^=e<<13,e^=e>>>17,e^=e<<5,e>>>0}function pu(t,e){return t.minY-e.minY||t.index-e.index}function uu(t){return t.subtreeMaxY=Math.max(t.item.maxY,t.left?.subtreeMaxY??-1/0,t.right?.subtreeMaxY??-1/0),t}function _u(t){const e=t.right;return t.right=e.left,e.left=uu(t),uu(e)}function mu(t){const e=t.left;return t.left=e.right,e.right=uu(t),uu(e)}function gu(t,e){return t?(pu(e,t.item)<0?(t.left=gu(t.left,e),t.left.priority0)t.right=fu(t.right,e);else{if(!t.left)return t.right;if(!t.right)return t.left;t.left.priority=e&&vu(t.left,e,i,s),t.item.minY<=i&&t.item.maxY>=e&&s.push(t.item),t.item.minY<=i&&vu(t.right,e,i,s))}function yu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=t.filter(t=>Qp(t.a)&&Qp(t.b)&&"string"==typeof t.key&&t.key.length>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>i),n=s.map(()=>[0,1]);!function(t,e,i){const s=t.map((t,e)=>({index:e,minX:Math.min(t.a[0],t.b[0])-i,maxX:Math.max(t.a[0],t.b[0])+i,minY:Math.min(t.a[1],t.b[1])-i,maxY:Math.max(t.a[1],t.b[1])+i})),n=[...s].sort((t,e)=>t.minX-e.minX||t.minY-e.minY||t.index-e.index),o=[...s].sort((t,e)=>t.maxX-e.maxX||t.index-e.index),a=new Set;let r=null,l=0;for(const s of n){for(;lt.index-e.index);for(const o of n)hu(t[o.index],t[s.index],e[o.index],e[s.index],i);a.add(s.index),r=gu(r,s)}}(s,n,i);const o=new Map;for(let t=0;t({key:t,a:e.a,b:e.b,sourceKeys:[...e.sourceKeys].sort((t,e)=>t.localeCompare(e))})).sort((t,e)=>t.key.localeCompare(e.key))}function bu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=yu(t,i),n=new Map,o=new Map,a=new Map(s.map(t=>[t.key,t]));for(const t of s){const e=su(t.a,i),s=su(t.b,i);n.set(e,t.a),n.set(s,t.b),o.has(e)||o.set(e,new Set),o.has(s)||o.set(s,new Set),o.get(e).add(s),o.get(s).add(e)}const r=new Map;for(const[t,e]of o){const i=n.get(t);r.set(t,[...e].sort((t,e)=>{const s=n.get(t),o=n.get(e);return Math.atan2(s[1]-i[1],s[0]-i[0])-Math.atan2(o[1]-i[1],o[0]-i[0])||t.localeCompare(e)}))}const l=new Set,c=new Map,h=(t,e)=>`${t}>${e}`;for(const t of s){const e=[su(t.a,i),su(t.b,i)];for(const[t,o]of[e,[e[1],e[0]]]){if(l.has(h(t,o)))continue;const e=[],d=[];let p=t,u=o,_=!1;for(let i=0;i<=2*s.length+2;i++){const i=h(p,u);if(l.has(i)){_=p===t&&u===o;break}l.add(i),e.push(p),d.push(nu(p,u));const s=r.get(u)||[],n=s.indexOf(p);if(n<0||!s.length)break;if(p=u,u=s[(n-1+s.length)%s.length],p===t&&u===o){_=!0;break}}if(!_||new Set(e).size<3||new Set(e).size!==e.length)continue;const m=e.map(t=>n.get(t)),g=eu(m);if(!(g>i*i))continue;const f=ou(au(e,n,i)),v=new Set;for(const t of d)for(const e of a.get(t)?.sourceKeys||[])v.add(e);const y={ring:m,key:f,area:g,atomKeys:[...d],sourceKeys:[...v].sort((t,e)=>t.localeCompare(e))};c.has(f)||c.set(f,y)}}return{atoms:s,faces:[...c.values()].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))}}function wu(t,e,i=.001){if(!Qp(e))return null;const s=t.faces.filter(t=>{if(t.ring.some((s,n)=>function(t,e,i,s){const n=i[0]-e[0],o=i[1]-e[1],a=n*n+o*o;if(!(a>0))return Math.hypot(t[0]-e[0],t[1]-e[1])<=s;const r=((t[0]-e[0])*n+(t[1]-e[1])*o)/a;return!(r<0||r>1)&&Math.hypot(e[0]+n*r-t[0],e[1]+o*r-t[1])<=s}(e,s,t.ring[(n+1)%t.ring.length],i)))return!1;let s=!1;for(let i=0,n=t.ring.length-1;ie[1]!=a[1]>e[1]&&e[0]<(a[0]-o[0])*(e[1]-o[1])/(a[1]-o[1])+o[0]&&(s=!s)}return s});return[...s].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))[0]||null}function ku(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n,a=o>0?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o)):0;return Math.hypot(e[0]+s*a-t[0],e[1]+n*a-t[1])}function xu(t,e,i=.5){let s=Math.abs(t-e)%180;return s>90&&(s=180-s),s<=i}function $u(t,e,i,s){const n=t.filter(t=>"outer"===t.kind&&!t.open&&t.cm>0).map(t=>({interval:t,reusePartitionId:e.find(e=>function(t,e,i){return!(Math.abs(t.cm-e.cm)>1e-6)&&(xu(180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI,180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI,.001)&&ku(e.a,t.a,t.b)<=i&&ku(e.b,t.a,t.b)<=i)}(e,t,s))?.id||null})),o=new Map;for(const e of i){if("partition"===e.host?.kind)continue;const i=t.map(t=>{const i=180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI;return{interval:t,distance:xu(e.angle,i)?ku([e.x,e.y],t.a,t.b):1/0}}).filter(t=>t.distance<=s).sort((t,e)=>t.distance-e.distance||t.interval.key.localeCompare(e.interval.key)),n=i[0]?.interval;"outer"===n?.kind&&!n.open&&n.cm>0&&o.set(e.id,n.key)}return{materialize:n,openingIntervals:o,removeOpeningIds:[...o.keys()].sort((t,e)=>t.localeCompare(e))}}function Su(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?Math.max(0,Math.min(1,((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n)):0}const Mu=t=>!t.key.startsWith("static:room|");function Cu(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;if(!(n>0))return null;const o=((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n,a=[e.a[0]+i*o,e.a[1]+s*o];return{point:a,t:o,distance:Math.hypot(a[0]-t[0],a[1]-t[1])}}function Du(t,e){return e>0?Math.hypot(t[0]-Math.round(t[0]/e)*e,t[1]-Math.round(t[1]/e)*e):0}function Pu(t,e,i){if(Mu(t.source)!==Mu(e.source))return Mu(t.source)?t:e;const s=Du(t.point,i),n=Du(e.point,i);return Math.abs(s-n)>1e-9?s>n?t:e:function(t,e){return t[0]-e[0]||t[1]-e[1]}(t.point,e.point)>0?t:e}function Tu(t){return[t.from[0],t.from[1],t.to[0],t.to[1],t.targetKind].map(t=>"number"==typeof t?t.toFixed(6):t).join("|")}function Ru(t,e){return t.map(t=>t.key!==e.sourceKey?t:{...t,[e.endpoint]:[...e.to]})}function Iu(t,e){const i=e.epsilon??.001;if(!(e.maxDistance>=0)||!e.point&&!e.requiredSourceKey)return{kind:"none"};const s=new Map,n=t.flatMap(t=>[{source:t,endpoint:"a",point:t.a},{source:t,endpoint:"b",point:t.b}]);for(let t=0;ti)||l>e.maxDistance)continue;const c=Pu(a,r,e.gridStep||0),h=c===a?r:a;if(!Mu(c.source))continue;const d={sourceKey:c.source.key,endpoint:c.endpoint,from:[c.point[0],c.point[1]],to:[h.point[0],h.point[1]],targetSourceKey:h.source.key,targetKind:"endpoint",distance:l};s.set(Tu(d),d)}for(const o of n)if(Mu(o.source))for(const n of t){if(n===o.source)continue;const t=Cu(o.point,n);if(!t||t.t<=i||t.t>=1-i||!(t.distance>i)||t.distance>e.maxDistance)continue;const a={sourceKey:o.source.key,endpoint:o.endpoint,from:[o.point[0],o.point[1]],to:t.point,targetSourceKey:n.key,targetKind:"line",distance:t.distance};s.set(Tu(a),a)}const o=[];for(const n of s.values()){const s=bu(Ru(t,n),i),a=e.point?wu(s,e.point,i):s.faces.find(t=>!e.requiredSourceKey||t.sourceKeys.includes(e.requiredSourceKey))||null;a&&o.push({proposal:n,face:a})}if(o.sort((t,e)=>t.proposal.distance-e.proposal.distance||Tu(t.proposal).localeCompare(Tu(e.proposal))),!o.length)return{kind:"none"};return new Set(o.map(t=>`${Tu(t.proposal)}|${t.face.key}`)).size>1?{kind:"ambiguous",proposals:o.map(t=>t.proposal)}:{kind:"repair",...o[0]}}const Au=1e-5;function zu(t){const e=t.map(()=>[]);for(let i=0;i=1-1e-9||p<=1e-9||p>=1-1e-9||(e[i].push(d),e[a].push(p))}}const i=[];for(let s=0;st-e),1];for(let t=1;t{const i=e[2]-e[0],s=e[3]-e[1],n=i*i+s*s;if(!(n>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const o=Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/n));return Math.hypot(t[0]-(e[0]+o*i),t[1]-(e[1]+o*s))},Nu=(t,e,i,s)=>{const n=s[2]-s[0],o=s[3]-s[1],a=e*o-i*n;if(Math.abs(a)<1e-12)return 1/0;const r=s[0]-t[0],l=s[1]-t[1],c=(r*o-l*n)/a;if(!(c>1e-9))return 1/0;const h=(r*i-l*e)/a;return h<-1e-9||h>1+1e-9?1/0:c};function Ou(t,e,i,s=96){if(!(e>0&&Number.isFinite(t[0])&&Number.isFinite(t[1])))return[];const n=[];for(const s of i){if(!s||s.length<4)continue;if(![s[0],s[1],s[2],s[3]].every(Number.isFinite))continue;const i=Eu(t,s);if(i<1e-7)return[];i>e||n.push(s)}const o=[],a=Math.max(12,Math.round(s));for(let t=0;tt-e);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const s=Math.cos(i),o=Math.sin(i);let a=e;for(const e of n){const i=Nu(t,s,o,e);i=3?l:[]}class Lu extends ht{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(t){this._config=t}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const t=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(t?.config?.spaces||[]).map(t=>({value:t.id,label:t.title||t.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return ra(this.hass,this._config?.language)}get _floorToken(){const t=this._config?.floor;return"number"==typeof t?`__houseplan_yaml_floor_index__:${String(t)}`:null}get _formData(){const t={...this._config},e=this._floorToken;return e?t.floor=e:Object.prototype.hasOwnProperty.call(t,"floor")||(t.floor=""),t}get _schema(){const t=this._spaces||[],e=this._lang,i=[{value:"",label:la(e,"editor.floor_none")}],s=this._floorToken;s&&i.push({value:s,label:la(e,"editor.floor_index",{index:String(this._config?.floor)})});const n="string"==typeof this._config?.floor?this._config.floor:"";n&&!t.some(t=>t.value===n)&&i.push({value:n,label:n}),i.push(...t);const o="string"==typeof this._config?.default_floor?this._config.default_floor:"",a=[...t];return o&&!t.some(t=>t.value===o)&&a.unshift({value:o,label:o}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:i}}},t.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:a}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:[{value:"",label:la(e,"editor.lang_auto")},{value:"en",label:la(e,"editor.lang_en")},{value:"ru",label:la(e,"editor.lang_ru")}]}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return G;this._loadSpaces();const t=this._lang,e={title:la(t,"editor.title"),floor:la(t,"editor.floor"),default_floor:la(t,"editor.default_floor"),language:la(t,"editor.language"),icon_size:la(t,"editor.icon_size"),show_temperature:la(t,"editor.show_temperature"),live_states:la(t,"editor.live_states"),show_signal:la(t,"editor.show_signal"),kiosk:la(t,"editor.kiosk"),cycle:la(t,"editor.cycle")},i=this._schema,s=function(t,e,i){if(!i||null===e)return null;const s="string"==typeof t?.default_floor?t.default_floor:"";return!s||e.some(t=>t.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),n=t=>W``}const Rr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Ir=(t,e=1)=>{const i=Number(t);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):e},Ar=t=>{let e=Number(t);return Number.isFinite(e)?(e=(e%360+360)%360,e>180?e-360:e):0};function zr(t,e,i){return Ar(e)?[t.x,t.y]:i([t.x,t.y])}const Fr=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&s>0?s/n*i:0},Er=(t,e,i)=>{const s=Number(t),n=Number.isFinite(e)&&e>0?e:5;return Number.isFinite(s)&&i>0?s/i*n:0},Nr=(t,e,i,s=Rr.widthCm)=>{const n=Number(t?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(t?.width);return Number.isFinite(o)&&o>0?Er(o,e,i):s};function Or(t,e){return{color:t.color,opacity:Ir(t.opacity),width_cm:Math.max(.1,Math.min(100,Number(t.widthCm)||.1)),...e?{fill:t.fill,fill_color:t.fillColor,fill_opacity:Ir(t.fillOpacity,.25)}:{}}}function Lr(t){const e=t.x+t.w/2,i=t.y+t.h/2,s=Ar(t.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(t,s)=>{const a=t-e,r=s-i;return[e+a*n-r*o,i+a*o+r*n]};return[a(t.x,t.y),a(t.x+t.w,t.y),a(t.x+t.w,t.y+t.h),a(t.x,t.y+t.h)]}function Hr(t){const e=Lr(t),i=(t,e)=>[(t[0]+e[0])/2,(t[1]+e[1])/2],s=[(e[0][0]+e[2][0])/2,(e[0][1]+e[2][1])/2];return{points:[...e,i(e[0],e[1]),i(e[1],e[2]),i(e[2],e[3]),i(e[3],e[0]),s],segments:e.map((t,i)=>({a:t,b:e[(i+1)%4]}))}}function Br(t,e,i,s,n,o,a,r){const l=Ar(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=t.x+t.w/2,_=t.y+t.h/2,m=e>0?-t.w/2:t.w/2,g=i>0?-t.h/2:t.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(e>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const e=w/Math.max(t.w,r),i=k/Math.max(t.h,r);x=Math.max(r/Math.max(t.w,r),r/Math.max(t.h,r),e,i),w=t.w*x,k=t.h*x}if(a>0)if(o){const e=Math.max(1,Math.round(t.w/a)),i=Math.max(1,Math.round(t.h/a));if(Math.abs(t.w-e*a)<1e-6&&Math.abs(t.h-i*a)<1e-6){const s=(t,e)=>{let i=Math.abs(t),s=Math.abs(e);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(e,i),o=Math.max(r/t.w,r/t.h),a=Math.max(o,Math.round((x??1)/n)*n);w=t.w*a,k=t.h*a}else{t.w>=t.h?(w=Math.round(w/a)*a,k=w*(t.h/Math.max(t.w,r))):(k=Math.round(k/a)*a,w=k*(t.w/Math.max(t.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(e>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(e>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Ar(t.angle)||void 0}}const qr=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<1e-12)return[...e];const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return[e[0]+s*a,e[1]+n*a]};const Wr=10**9,jr=240,Ur=1e-4;function Gr(t){if(Array.isArray(t))return t.map(t=>Gr(t));if(null!==t&&"object"==typeof t){const e={};for(const[i,s]of Object.entries(t))e[i]=Gr(s);return e}return t}function Vr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=(t<0||Object.is(t,-0)?-1:1)*(Math.floor(Math.abs(t)*Wr+.5)/Wr);return 0===e?0:e}function Kr(t){if("number"!=typeof t||!Number.isFinite(t))return t;const e=t*jr,i=Math.round(e);if(Math.abs(e-i)null!==Jr(t)):[]}function Zr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Vr(t[i]))}function Qr(t,e){for(const i of e)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Kr(t[i]))}function tl(t){if(Array.isArray(t))for(let e=0;e{for(const n of s){const s=e[n];"number"==typeof s&&Number.isFinite(s)&&i(s,t)}},s=e=>{if(Array.isArray(e))for(let s=0;s{if(Array.isArray(t))for(const e of t)s(e)};for(const i of Xr(t.rooms))e(i,["x","y","w","h"]),n(i.poly);for(const e of Xr(t.walls))s(e.a),s(e.b);for(const e of Xr(t.wall_segments))s(e.a),s(e.b);for(const i of Xr(t.openings))e(i,["x","y"]);for(const i of Xr(t.decor))"line"===i.kind?e(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?e(i,["x","y","w","h"]):"text"===i.kind&&e(i,["x","y"]);for(const e of Xr(t.room_drafts))n(e.points);for(const e of Xr(t.partitions))s(e.a),s(e.b);for(const e of Xr(t.wall_columns))s(e.center);for(const e of Xr(t.open_spans))s(e.a),s(e.b)}const n=Jr(e);if(!n)return;const o=new Map;if(s)for(const t of Xr(s.spaces))null!=t.id&&o.set(String(t.id),t);for(const t of Object.values(n)){const e=Jr(t);if(!e)continue;const s=null!=e.s&&o.get(String(e.s))||null;for(const t of["x","y"]){const n=e[t];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function sl(t){const e=Number(t?.cell_cm);return e>0?e:5}function nl(t,e={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=Xr(Jr(t)?.spaces);let n=5;for(const t of s)n=Math.max(n,sl(t));il(t,e,(t,e)=>{const s=t*jr,o=Math.abs(s-Math.round(s)),a=Kr(t),r=o>0&&o=Ur))return;const l=r&&"number"==typeof a?Math.abs(a-t):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*jr*(e?sl(e):n)),!e?.id||!r)return;const c=String(e.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(e.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*jr*sl(e))}),i.bySpace.size&&il(t,e,(t,e)=>{if(!e?.id)return;const s=i.bySpace.get(String(e.id));if(!s)return;const n=t*jr;Math.abs(n-Math.round(n))>=Ur&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function ol(t){return function(t){const e=t,i=Jr(e);i&&Qr(i,["x","y"]);return e}(Gr(t))}function al(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Object.values(i)){const e=Jr(t);e&&Qr(e,["x","y"])}return e}function rl(t){const e=t,i=Jr(e);if(!i)return e;for(const t of Xr(i.spaces)){Zr(t,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const e of Xr(t.rooms))Qr(e,["x","y","w","h"]),el(e.poly);for(const e of Xr(t.walls))tl(e.a),tl(e.b);for(const e of Xr(t.wall_segments))tl(e.a),tl(e.b);for(const e of Xr(t.openings)){Qr(e,["x","y"]),Zr(e,["angle","length"]);const t=Jr(e.host);t&&Zr(t,["t"])}for(const e of Xr(t.decor))"line"===e.kind?Qr(e,["x1","y1","x2","y2"]):"rect"===e.kind||"ellipse"===e.kind||"furniture"===e.kind?(Qr(e,["x","y","w","h"]),Zr(e,["angle"])):"text"===e.kind&&(Qr(e,["x","y"]),Zr(e,["scale","angle"]));for(const e of Xr(t.room_drafts))el(e.points);for(const e of Xr(t.partitions))tl(e.a),tl(e.b);for(const e of Xr(t.wall_columns))tl(e.center),"square"===e.shape&&Zr(e,["angle"]);for(const e of Xr(t.open_spans))tl(e.a),tl(e.b)}for(const t of Xr(i.markers))Zr(t,["angle"]);return e}const ll=15;function cl(t,e,i,s,n){const o=i[0]-t[0],a=i[1]-t[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=e=>{const s=(e[0]-t[0])*l+(e[1]-t[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[e[0]+(i[0]-e[0])*o,e[1]+(i[1]-e[1])*o]},d=h(e),p=h(s);return d&&p?[[t[0],t[1]],e,d,p,s]:null}const hl=Math.sin(.25*Math.PI/180);function dl(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<3}function pl(t){const e=Number(t)>0?Number(t):5;if(5===e)return 8;const i=5/e*8;return Math.min(80,Math.max(.5,i))}function ul(t,e){return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&t*e<2}function _l(t){return Number.isFinite(t)?Math.max(1,Math.min(100,t)):1}function ml(t,e){return!Number.isFinite(t)||t<0?"":String(e?Math.round(t/2.54*100)/100:Math.round(100*t)/100)}function gl(t,e,i){if(!Number.isFinite(t)||t<=0)return 0;const s=Number(e)>0?Number(e):5;return _l(t)/s*i}function fl(t,e){return e>0&&Number.isFinite(t)?Math.round(t/e)*e:t}function vl(t){return Math.max(1e-6*Math.abs(t),1e-9)}function yl(t,e){if(!(e>0&&Number.isFinite(t)))return t;const i=fl(t,e);return Math.abs(i-t)<=vl(e)?i:t}function bl(t,e){let i=e[0]-t[0],s=e[1]-t[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function wl(t,e,i){const s=[yl(t[0],i),yl(t[1],i)],n=[yl(e[0],i),yl(e[1],i)],o=fl((s[0]+n[0])/2,i),a=fl((s[1]+n[1])/2,i),[r,l]=bl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function kl(t,e,i,s){return 1===s?wl(t,e,i):wl([t[0]/s,t[1]/s],[e[0]/s,e[1]/s],i)}function xl(t,e){if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return null;const i=[Number(t.a[0]),Number(t.a[1]),Number(t.b[0]),Number(t.b[1])];if(!i.every(Number.isFinite))return null;const s=e>0?e:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function $l(t,e,i,s,n){const o=n>0?n:1;return{key:kl(t,e,s,o),cm:_l(i),a:[t[0]/o,t[1]/o],b:[e[0]/o,e[1]/o]}}function Sl(t,e){const i=e>0?e:1,s=[];for(const e of t){const t=e.key.lastIndexOf("@");if(t<0)continue;const[n,o]=e.key.slice(0,t).split(",").map(Number),a=Number(e.key.slice(t+1));[n,o,a].every(Number.isFinite)&&s.push({w:e,x:n*i,y:o*i,ang:a})}return s}function Ml(t,e){const[i,s]=bl(t,e);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Cl(t,e){let i=Math.abs(t-e);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Dl(t,e,i,s,n=1){if(!t?.length)return null;const o=kl(e,i,s,n),a=t.find(t=>t.key===o);if(a)return a;const r=n>0?n:1,l=vl(s)*r,c=(t,e)=>Math.abs(t[0]-e[0])<=l&&Math.abs(t[1]-e[1])<=l;for(const s of t){const t=xl(s,r);if(t&&(c(t[0],e)&&c(t[1],i)||c(t[0],i)&&c(t[1],e)))return s}const h=(e[0]+i[0])/2,d=(e[1]+i[1])/2,p=Ml(e,i),u=Math.max(.5*s,1e-9)*r;for(const e of Sl(t,r))if(Cl(e.ang,p)&&Math.hypot(e.x-h,e.y-d)<=u)return e.w;return null}function Pl(t,e,i,s,n=1){const o=Dl(t,e,i,s,n);if(o&&o.cm>0)return _l(o.cm);const a=function(t,e,i,s,n){if(!t?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-e[0],i[1]-e[1]);if(a<1e-12)return null;const r=Ml(e,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of t){if(!(s.cm>0))continue;const t=xl(s,o);if(!t)continue;const n=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);if(n<1e-12||!Cl(Ml(t[0],t[1]),r))continue;if(mc(e[0],e[1],t[0][0],t[0][1],t[1][0],t[1][1])>l||mc(i[0],i[1],t[0][0],t[0][1],t[1][0],t[1][1])>l)continue;if(n+l(o.has(t.key)||(t=>{const e=xl(t,s);if(!e)return!1;const[i,o]=e,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];return Cl(Ml(i,o),Ml(e,s))&&mc(i[0],i[1],e[0],e[1],s[0],s[1])<=l&&mc(o[0],o[1],e[0],e[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(t=>{const e=[t[0],t[1]],s=[t[2],t[3]];if(!Cl(Ml(i,o),Ml(e,s)))return!1;const n=t=>Math.abs((t[0]-i[0])*c-(t[1]-i[1])*r)/h;if(n(e)>l||n(s)>l)return!1;const a=h*h,d=((e[0]-i[0])*r+(e[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(t))&&t.cm>=1&&t.cm<=100)}function Rl(t,e,i,s=8){const[n,o]=bl(t,e);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Il(t,e,i,s,n=1,o="affine",a){if(!t?.length)return[];if(e.length!==i.length)return"fixed-topology"===o&&a?.(),t.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(t,e,i)=>{const s=t.get(e)||new Set;s.add(i),t.set(e,s)};for(let t=0;t[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],m=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=c,g=(t,e)=>{if("fixed-topology"===o){const i=e.na[0]-e.oa[0],s=e.na[1]-e.oa[1],n=e.nb[0]-e.ob[0],o=e.nb[1]-e.ob[1];return Math.hypot(i-n,s-o)<=c?[t[0]+i,t[1]+s]:m(t,e.oa)?[...e.na]:m(t,e.ob)?[...e.nb]:[...t]}const i=Math.max(0,Math.min(1,((t[0]-e.oa[0])*e.dx+(t[1]-e.oa[1])*e.dy)/e.len2));return _(e.na,e.nb,i)},f=(t,e)=>{const[i,s]=bl(t,e);return(e[0]-t[0])*i+(e[1]-t[1])*s>=0?[[...t],[...e]]:[[...e],[...t]]},v=[],y=[],b=(t,e,i)=>{if(Math.hypot(e[0]-t[0],e[1]-t[1])<=c)return;const[n,o]=f(t,e),a=_l(i);if(y.some(t=>t.entry.cm===a&&m(t.span[0],n)&&m(t.span[1],o)))return;const l=$l(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const e of t){const t=xl(e,r);if(t){const[i,s]=f(t[0],t[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...e,cm:_l(e.cm)});continue}const p=[];for(const t of h){if(!Cl(Ml(i,s),Ml(t.oa,t.ob)))continue;const e=t=>Math.abs((t[0]-i[0])*a-(t[1]-i[1])*n)/d;if(e(t.oa)>l||e(t.ob)>l)continue;const o=((t.oa[0]-i[0])*n+(t.oa[1]-i[1])*a)/r,h=((t.ob[0]-i[0])*n+(t.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:t})}if(!p.length){"fixed-topology"===o?v.push({...e}):b(i,s,e.cm);continue}const u=[0,1,...p.flatMap(({lo:t,hi:e})=>[t,e])].sort((t,e)=>t-e).filter((t,e,i)=>0===e||Math.abs(t-i[e-1])*d>c),y=[];for(let t=0;t+1r>=t.lo-1e-12&&r<=t.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(t=>{const e=g(o,t.move),i=g(a,t.move);return!m(h[0],e)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(t,e)=>{const i=t[1][0]-t[0][0],s=t[1][1]-t[0][1],n=e[1][0]-e[0][0],o=e[1][1]-e[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const t of y){const e=k[k.length-1];e&&m(e[1],t[0])&&w(e,t)?e[1]=t[1]:k.push([[...t[0]],[...t[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,t[0])&&m(s,t[1])||m(i,t[1])&&m(s,t[0])){v.push({...e});continue}}for(const[t,i]of k)b(t,i,e.cm);continue}if("fixed-topology"===o){const t=p.get(e.key);if(1===t?.size){const i=[...t][0];v.push(i===e.key?{...e}:{...e,key:i});continue}const i=[Sl([e],r)[0]];1!==r&&i.push(Sl([e],1)[0]);const s=i.filter(Boolean).some(t=>h.some(e=>{if(!Cl(t.ang,Ml(e.oa,e.ob)))return!1;const i=((t.x-e.oa[0])*e.dx+(t.y-e.oa[1])*e.dy)/e.len2;return i>=-1e-6&&i<=1.000001&&mc(t.x,t.y,e.oa[0],e.oa[1],e.ob[0],e.ob[1])<=l}));((t?.size||0)>1||s)&&a?.(),v.push({...e});continue}let i="";const n=d.get(e.key);if(1===n?.size&&(i=[...n][0]),!i){const t=Sl([e],r)[0];if(t){const e=new Set;for(const i of h){if(!Cl(t.ang,Ml(i.oa,i.ob)))continue;const n=((t.x-i.oa[0])*i.dx+(t.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(mc(t.x,t.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([t.x,t.y],i),[a,c]=bl(i.na,i.nb),h=Math.max(s*r,1e-6);e.add(kl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===e.size&&(i=[...e][0])}}v.push({...e,key:i||e.key,cm:_l(e.cm)})}return v}function Al(t,e,i,s,n=1,o="affine"){return Il(t,e,i,s,n,o)}function zl(t,e,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Ur,1e-9),l=(n||[]).flatMap(t=>{const e=xl(t,o);return e?e.map(t=>[...t]):[]}),c=t=>t.every((t,e)=>(t=>{if(!(a>0))return!0;const e=t/o/a;return Math.abs(e-Math.round(e))Math.abs(t-i[e])<=r)),h=[],d=t=>JSON.stringify([t.key,t.cm,t.a,t.b]);for(const i of t||[]){const t=xl(i,o);if(!t)continue;const[s,n]=t;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const t of e){const[e,i]=t;if(![e?.[0],e?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=t=>Math.abs((t[0]-s[0])*_-(t[1]-s[1])*u);if(n(e)>r||n(i)>r)continue;const o=(e[0]-s[0])*u+(e[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let g=0;for(const[t,e]of m){if(t>g+r)break;if(g=Math.max(g,e),g>=p-r)break}gt.key!==a);return null==s||s<1?r:[...r,$l(e,i,s,n,o)]}function El(t,e,i,s,n,o=[],a=1){let r=t?t.slice():[];for(const t of function(t,e,i,s,n=1,o=[]){const a=ec(t,e,i,s,n,o);if(!a)return[];const r=[];for(let t=0;t0||(c=Fl(c,e,i,s,n,a)))}return c}function Ol(t){const{a:e,b:i,halfDepth:s}=t;if(!Array.isArray(e)||!Array.isArray(i)||e.length<2||i.length<2||![e[0],e[1],i[0],i[1]].every(Number.isFinite))return null;const n=i[0]-e[0],o=i[1]-e[1],a=Math.hypot(n,o);if(!(a>1e-9&&s>0&&Number.isFinite(s)))return null;const r=-o/a*s,l=n/a*s;return[[e[0]+r,e[1]+l],[i[0]+r,i[1]+l],[i[0]-r,i[1]-l],[e[0]-r,e[1]-l]]}function Ll(t,e,i){return Math.hypot(t[0]-e[0],t[1]-e[1])<=i}function Hl(t,e,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=s*s+n*n;if(!(o>i*i))return!1;const a=((t[0]-e.a[0])*s+(t[1]-e.a[1])*n)/o;if(!(a>0&&a<1))return!1;const r=[e.a[0]+s*a,e.a[1]+n*a];return Math.hypot(t[0]-r[0],t[1]-r[1])<=i}function Bl(t,e,i,s){const n=Math.hypot(e,i);if(!(n>1e-9&&s>0))return;const o=[e/n,i/n],a=t.find(t=>Math.abs(t.u[0]*o[1]-t.u[1]*o[0])<1e-9&&t.u[0]*o[0]+t.u[1]*o[1]>1-1e-9);a?a.halfDepth=Math.max(a.halfDepth,s):t.push({u:o,halfDepth:s})}function ql(t,e){try{const i=oi(vc(t),vc(e));let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Kl(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function Wl(t,e=1e-6){const i=(t||[]).map((t,e)=>({segment:t,index:e})).filter(({segment:t})=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(({segment:t})=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[];for(const t of o){const e=[];let n=!1;for(const{segment:o,index:a}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Ll(t,o.a,s)?e.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Ll(t,o.b,s)?e.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Hl(t,o,s)&&(n=!0)}if(n||2!==e.length)continue;const[o,r]=e,l=o.u[0]*r.u[1]-o.u[1]*r.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-r.u[1],r.u[0]],p=[t[0]+h[0]*o.halfDepth*c,t[1]+h[1]*o.halfDepth*c],u=[t[0]-d[0]*r.halfDepth*c,t[1]-d[1]*r.halfDepth*c];if(!Xl(p,o.u,u,r.u))continue;const _=[[o,r,u,[d[0]*-c,d[1]*-c]],[r,o,p,[h[0]*c,h[1]*c]]];for(const[e,,i,n]of _){const o=Math.min(2*e.halfDepth,e.length),r=[-e.u[1]*e.halfDepth,e.u[0]*e.halfDepth],l=[[t[0]+r[0],t[1]+r[1]],[t[0]+e.u[0]*o+r[0],t[1]+e.u[1]*o+r[1]],[t[0]+e.u[0]*o-r[0],t[1]+e.u[1]*o-r[1]],[t[0]-r[0],t[1]-r[1]]],c=t=>(t[0]-i[0])*n[0]+(t[1]-i[1])*n[1],h=[];for(let t=0;t=-1e-12&&h.push(e),s>1e-12&&n<-1e-12||s<-1e-12&&n>1e-12){const t=s/(s-n);h.push([e[0]+(i[0]-e[0])*t,e[1]+(i[1]-e[1])*t])}}h.length>=3&&Math.abs(Kl(h))>s*s&&a.push({segmentIndex:e.index,wedge:h})}}return a}function jl(t,e=1e-6){const i=(t||[]).filter(t=>t&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&t.a.every(Number.isFinite)&&t.b.every(Number.isFinite)&&Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(e)?e:0,1e-9),n=i.flatMap(t=>[t.a,t.b]).map(t=>[t[0],t[1]]).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),o=[];for(const t of n)o.some(e=>Ll(e,t,s))||o.push(t);const a=[],r=i.map((t,e)=>({roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`join-${e}`,kind:"outer",cm:0,open:!1,half:t.halfDepth})),l=ac(r,s);for(const t of rc(l).fans)a.push(t);const c=t=>!!lc(l,t);for(const t of o){if(c(t))continue;const e=[];for(const n of i)Ll(t,n.a,s)?Bl(e,n.b[0]-n.a[0],n.b[1]-n.a[1],n.halfDepth):Ll(t,n.b,s)?Bl(e,n.a[0]-n.b[0],n.a[1]-n.b[1],n.halfDepth):Hl(t,n,s)&&(Bl(e,n.a[0]-t[0],n.a[1]-t[1],n.halfDepth),Bl(e,n.b[0]-t[0],n.b[1]-t[1],n.halfDepth));if(!(e.length<2)){e.sort((t,e)=>Math.atan2(t.u[1],t.u[0])-Math.atan2(e.u[1],e.u[0])||t.halfDepth-e.halfDepth);for(let i=0;is*s&&a.push(m)}}}return a}function Ul(t,e,i,s){if(!(e>0)||!t||t.length<2)return"";if(i&&t.length>=3){let i=t;const n=t[t.length-1];if(t.length>=4&&Math.hypot(t[0][0]-n[0],t[0][1]-n[1])<1e-9&&(i=t.slice(0,-1)),i.length>=3){const t=i.map((t,i)=>s?.[i]||e),n=Fc(i,t),o=Zl(i,t);if(n&&o)return`${Ql(n)} ${Ql(tc(o))}`}}const n=[];for(let i=0;i=1e-9&&r>0&&n.push({a:o,b:a,halfDepth:r})}const o=n.map(Ol);for(const{segmentIndex:t,wedge:e}of Wl(n)){const i=o[t];if(!i)continue;const s=ql(i,e);s&&(o[t]=s)}const a=[...o.filter(t=>!!t),...jl(n)],r=function(t){let e=null;try{for(const i of t){if(i.length<3)continue;const t=vc(i);e=e?si(e,t):[t]}return e}catch{return null}}(a);return r?Tc(r):a.map(t=>Ql(t)).join(" ")}function Gl(t,e,i,s,n=1){if(!i.length)return!1;const o=Vl(s,n),a=(t[0]+e[0])/2,r=(t[1]+e[1])/2,[l,c]=bl(t,e);for(const t of i){const[e,i]=bl([t[0],t[1]],[t[2],t[3]]);if(!(Math.abs(l*i-c*e)>.05)&&mc(a,r,t[0],t[1],t[2],t[3])<=o)return!0}return!1}function Vl(t,e){return Math.max(t*(e>0?e:1)*.04,1e-9)}function Kl(t){let e=0;for(let i=0;it[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a+0)+o&&(i=!i)}return i}([c[0]+.001*r,c[1]+.001*l],t)||(r=-r,l=-l),[r,l]}function Jl(t,e){const i=t[0]*e[1]-t[1]*e[0],s=t[0]*e[0]+t[1]*e[1];return Math.abs(i)<1e-9&&s>0}function Xl(t,e,i,s){const n=e[0]*s[1]-e[1]*s[0];if(Math.abs(n)<1e-12)return null;const o=[i[0]-t[0],i[1]-t[1]],a=(o[0]*s[1]-o[1]*s[0])/n;return[t[0]+a*e[0],t[1]+a*e[1]]}function Zl(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);const n=[];for(let o=0;o0||p>0)){n.push([t[o][0],t[o][1]]);continue}if(d>0!=p>0){const e=t[o],i=d>0?[e[0]+u*d,e[1]+_*d]:[e[0],e[1]],s=p>0?[e[0]+m*p,e[1]+g*p]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]+u*d,e[1]+_*d],s=[e[0]+m*p,e[1]+g*p];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(d,p,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}d>0&&n.push([t[o][0]+u*d,t[o][1]+_*d]),p>0&&n.push([t[o][0]+m*p,t[o][1]+g*p]),d>0||p>0||n.push([t[o][0],t[o][1]])}return n.length>=3?n:null}function Ql(t,e=!0){if(!t.length)return"";let i=`M ${t[0][0]} ${t[0][1]}`;for(let e=1;et?.id===e),r=hi(a);if(!r||r.length<3)return null;const l=Vl(s,n),c=[];for(const i of t||[]){if(!i||i.id===e)continue;const t=hi(i);if(t)for(const e of Cs(r,t,l))c.push([e[0],e[1]],[e[2],e[3]])}for(const t of i||[])c.push([t[0],t[1]],[t[2],t[3]]);for(const t of o||[]){const e=xl(t,n);e&&c.push(e[0],e[1])}const h=[],d=[];for(let t=0;tl)continue;const a=((t[0]-e[0])*(i[0]-e[0])+(t[1]-e[1])*(i[1]-e[1]))/(s*s);a<=n||a>=1-n||(o.some(t=>Math.abs(t-a)*s<=2*l)||o.push(a))}o.sort((t,e)=>t-e);for(const s of o)h.push([e[0]+(i[0]-e[0])*s,e[1]+(i[1]-e[1])*s]),d.push(t)}return{poly:h,parent:d,orig:r}}function ic(t,e,i,s){const n=e.poly.length,o=new Array(n).fill(0);if(!t?.length)return o;const a=new Set,r=[];for(let l=0;l0?(o[l]=_l(c.cm),a.add(c.key)):r.push(l)}if(!r.length)return o;const l=s>0?s:1,c=Math.max(.5*i,1e-9)*l,h=Sl(t,l).filter(t=>t.w.cm>0);for(let t=r.length-1;t>=0;t--){const i=r[t],s=e.poly[i],a=e.poly[(i+1)%n],d=Ml(s,a);let p=null;for(const t of h){const e=xl(t.w,l);if(!e||!Cl(Ml(e[0],e[1]),d))continue;if(mc(s[0],s[1],e[0][0],e[0][1],e[1][0],e[1][1])>c||mc(a[0],a[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;const i=Math.hypot(a[0]-s[0],a[1]-s[1]),n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]),o=Math.max(0,n-i);(!p||oc||mc(n[0],n[1],e[0][0],e[0][1],e[1][0],e[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1])-_)}else{if(mc(t.x,t.y,s[0],s[1],n[0],n[1])>c)continue;o=Math.hypot(t.x-d,t.y-p)}(!u||i&&!u.exact||i===u.exact&&o0?i:1,o=(t||[]).filter(t=>t&&!t.open&&null!==t.kind&&Number.isFinite(t.half)&&t.half>0&&Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2&&[t.a[0],t.a[1],t.b[0],t.b[1]].every(Number.isFinite)&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>s).sort((t,e)=>t.key.localeCompare(e.key)||t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.b[0]-e.b[0]||t.b[1]-e.b[1]||t.half-e.half),a=new Map;for(const t of o){const e=a.get(t.key);e?t.half>e.half&&a.set(t.key,{...e,half:t.half}):a.set(t.key,t)}const r=[...a.values()].flatMap(t=>[{point:[t.a[0],t.a[1]],other:t.b,halfDepth:t.half,kind:t.kind,key:t.key},{point:[t.b[0],t.b[1]],other:t.a,halfDepth:t.half,kind:t.kind,key:t.key}]).sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]||t.other[0]-e.other[0]||t.other[1]-e.other[1]||t.halfDepth-e.halfDepth),l=new Map;for(const t of r){const[e,i]=sc(t.point,s),n=nc(e,i),o=l.get(n)||[];o.push(t),l.set(n,o)}const c=[],h=new Map;for(const t of r){const e=oc(h,t.point,s).filter(e=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])<=s).sort((e,i)=>Math.hypot(e.point[0]-t.point[0],e.point[1]-t.point[1])-Math.hypot(i.point[0]-t.point[0],i.point[1]-t.point[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1]);let i=e[0];if(!i){i={point:[...t.point],rays:[]},c.push(i);const[e,n]=sc(i.point,s),o=nc(e,n),a=h.get(o)||[];a.push(i),h.set(o,a)}const n=t.other[0]-t.point[0],o=t.other[1]-t.point[1],a=Math.hypot(n,o);if(!(a>s))continue;const r=[n/a,o/a];let l=Math.atan2(r[1],r[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:r,halfDepth:t.halfDepth,length:a,angle:l})}const d=[],p=t=>{const e=1e-9*Math.max(1,n),i=t.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);return i.filter((t,s)=>!i.some((i,n)=>n!==s&&i.halfDepth>=t.halfDepth-e&&i.length>=t.length-e&&(i.halfDepth>t.halfDepth+e||i.length>t.length+e||nt.length-e.length||t.halfDepth-e.halfDepth).map(t=>({...t}))};for(const t of c){const e=t.rays.sort((t,e)=>t.angle-e.angle||t.length-e.length||t.halfDepth-e.halfDepth),i=[];for(const t of e){const e=i[i.length-1];e&&Math.abs(t.angle-e.angle)<=1e-9?e.supports.push({halfDepth:t.halfDepth,length:t.length}):i.push({u:[...t.u],angle:t.angle,supports:[{halfDepth:t.halfDepth,length:t.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const t=i.pop();i[0].supports.push(...t.supports)}if(i.length<3)continue;const n=i.map(e=>{const i=p(e.supports),n=new Set,o=[];for(const a of i){const i=[t.point[0]+e.u[0]*a.length,t.point[1]+e.u[1]*a.length];for(const e of oc(l,i,s)){if("shared"!==e.kind||Math.hypot(e.point[0]-i[0],e.point[1]-i[1])>s)continue;const a=e.other[0]-e.point[0],r=e.other[1]-e.point[1],l=Math.hypot(a,r);if(!(l>s))continue;const c=a/l,h=r/l;if(Math.hypot(e.other[0]-t.point[0],e.other[1]-t.point[1])<=s)continue;const d=`${e.key}|${e.point[0]}|${e.point[1]}|${e.other[0]}|${e.other[1]}|${e.halfDepth}`;n.has(d)||(n.add(d),o.push({start:[e.point[0],e.point[1]],u:[c,h],length:l,halfDepth:e.halfDepth}))}}return o.sort((t,e)=>t.start[0]-e.start[0]||t.start[1]-e.start[1]||t.u[0]-e.u[0]||t.u[1]-e.u[1]||t.length-e.length||t.halfDepth-e.halfDepth),{u:[...e.u],halfDepth:Math.max(...i.map(t=>t.halfDepth)),length:Math.max(...i.map(t=>t.length)),supports:i,continuations:o}}).filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0&&Number.isFinite(t.length)&&t.length>s);if(n.length<3)continue;const o=Math.max(...n.map(t=>t.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...t.point],rays:n,halfDepth:o,limit:1.25*o})}d.sort((t,e)=>t.point[0]-e.point[0]||t.point[1]-e.point[1]);const u=new Map;for(const t of d){const[e,i]=sc(t.point,s),n=nc(e,i),o=u.get(n)||[];o.push(t),u.set(n,o)}return{epsilon:s,coordinateScale:n,nodes:d,index:u}}function rc(t){const e={fans:[],supports:[]};if(!t?.nodes?.length)return e;const i=Math.max(t.epsilon,1e-9)**2;for(const s of t.nodes){const t=s.rays.filter(t=>Number.isFinite(t.halfDepth)&&t.halfDepth>0).map(t=>({...t,thickLength:Math.max(...t.supports.filter(e=>e.halfDepth>=t.halfDepth-1e-12).map(t=>t.length),0),angle:(()=>{const e=Math.atan2(t.u[1],t.u[0]);return e<0?e+2*Math.PI:e})()})).sort((t,e)=>t.angle-e.angle);if(t.length<2)continue;const n=s.point;for(const i of t)for(const t of i.supports){if(!(t.halfDepth>0&&t.length>0))continue;const s=-i.u[1]*t.halfDepth,o=i.u[0]*t.halfDepth,a=[n[0]+i.u[0]*t.length,n[1]+i.u[1]*t.length];e.supports.push([[n[0]+s,n[1]+o],[a[0]+s,a[1]+o],[a[0]-s,a[1]-o],[n[0]-s,n[1]-o]])}for(let s=0;s{const t=a.angle-o.angle;return t>0?t:t+2*Math.PI})();if(r<1e-9)continue;const l=r>Math.PI+1e-9,c=4*Math.max(o.halfDepth,a.halfDepth),h=[n[0]-o.u[1]*o.halfDepth,n[1]+o.u[0]*o.halfDepth],d=[n[0]+a.u[1]*a.halfDepth,n[1]-a.u[0]*a.halfDepth],p=o.u[0]*a.u[1]-o.u[1]*a.u[0],u=t=>{let e=Math.atan2(t[1]-n[1],t[0]-n[0])-o.angle;for(;e<0;)e+=2*Math.PI;return e<=r+1e-9};let _=null;if(Math.abs(p)>1e-9){const t=((d[0]-h[0])*a.u[1]-(d[1]-h[1])*a.u[0])/p,e=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/p,i=[h[0]+o.u[0]*t,h[1]+o.u[1]*t];(l?t<=1e-9&&e<=1e-9:t>1e-9&&t<=o.thickLength&&e<=a.thickLength)&&Math.hypot(i[0]-n[0],i[1]-n[1])<=c&&u(i)&&(_=i)}const m=t=>{Math.abs(Kl(t))>i&&e.fans.push(t)};if(_){const t=1.5*Math.max(o.halfDepth,a.halfDepth);m(cl([n[0],n[1]],h,_,d,t)??[[n[0],n[1]],h,_,d]);continue}if(l){m([[n[0],n[1]],h,d]);continue}const g=(t,e)=>Math.min(e,Math.sqrt(Math.max(c**2-t**2,0)),2*Math.max(o.halfDepth,a.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+a.u[0]*g(a.halfDepth,a.thickLength),d[1]+a.u[1]*g(a.halfDepth,a.thickLength)];m([[n[0],n[1]],h,f,v,d])}}return e}function lc(t,e){return!t||!Array.isArray(e)||e.length<2||!e.slice(0,2).every(Number.isFinite)?null:oc(t.index,e,t.epsilon).filter(i=>Math.hypot(i.point[0]-e[0],i.point[1]-e[1])<=t.epsilon).sort((t,i)=>Math.hypot(t.point[0]-e[0],t.point[1]-e[1])-Math.hypot(i.point[0]-e[0],i.point[1]-e[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1])[0]||null}function cc(t,e,i,s,n,o,a){return ac(dc(t,e,i,s,n,o,a),4*Vl(s,a),a)}function hc(t,e,i,s,n,o,a,r=1){const l=ec(t,e,s,n,r,i);if(!l)return null;const c=function(t,e,i){const s=(t||[]).find(t=>t?.id===e),n=hi(s);if(!n)return[];const o=[];for(const s of t||[]){if(!s||s.id===e)continue;const t=hi(s);if(t)for(const e of Cs(n,t,i))o.push(e)}return o}(t,e,Vl(n,r)),h=function(t,e,i,s,n){const o=Vl(s,n),a=[];for(let r=0;rmc(h,d,t[0],t[1],t[2],t[3])<=o);a.push(p?"shared":"outer")}return a}(l.poly,c,s,n,r),d=ic(i,l,n,r),p=d.map((t,e)=>h[e]&&t>0?gl(t,o,a)/2:0);return{...l,kinds:h,cms:d,offsets:p}}function dc(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(c)for(let t=0;t0&&(r=Fl(r,t.a,t.b,t.cm,s,a));return r}function uc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=dc(t,e,i,s,n,o,a),l=new Map;for(const t of r){if(t.open||!t.kind||!t.roomId)continue;const e=l.get(t.key)||new Set;e.add(t.roomId),l.set(t.key,e)}const c=t=>{const e=[...l.get(t)||[]].sort();return 1!==e.length&&2!==e.length?`ambiguous:${t}`:`${1===e.length?"outer":"shared"}:${e.join("|")}`},h=[],d=new Set;for(const t of r)!t.open&&t.cm>0&&!d.has(t.key)&&(d.add(t.key),h.push({...t,ownerSignature:c(t.key)}));const p=[];for(const r of t||[]){if(!r?.id)continue;const l=hc(t,r.id,e,i,s,n,o,a);if(l)for(let t=0;t0)||null===l.kinds[i]){t++;continue}const o=c(kl(l.poly[i],l.poly[(i+1)%l.poly.length],s,a));let r=t;for(;r+10&&p.push({a:[d[0],d[1]],b:[u[0],u[1]],key:kl(d,u,s,a),cm:n,len:_,ownerSignature:o}),t=r+1}}}p.sort((t,e)=>e.len-t.len||t.key.localeCompare(e.key));const u=[],_=new Set,m=new Set,g=4*Vl(s,a);for(const t of p){const e=h.filter(e=>!m.has(e.key)&&e.cm===t.cm&&e.ownerSignature===t.ownerSignature&&Cl(Ml(e.a,e.b),Ml(t.a,t.b))&&mc(e.a[0],e.a[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g&&mc(e.b[0],e.b[1],t.a[0],t.a[1],t.b[0],t.b[1])<=g);if(e.length){for(const t of e)m.add(t.key);_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)))}}for(const t of h)m.has(t.key)||_.has(t.key)||(_.add(t.key),u.push($l(t.a,t.b,t.cm,s,a)));return u}function _c(t,e,i,s,n,o,a,r=1){const l=Vl(n,r),c=(s[0]+s[2])/2,h=(s[1]+s[3])/2,d=Ml([s[0],s[1]],[s[2],s[3]]);let p=null;for(const s of dc(t,e,i,n,o,a,r)){if(!Cl(Ml(s.a,s.b),d))continue;const t=mc(c,h,s.a[0],s.a[1],s.b[0],s.b[1]);t>4*l||(!p||t[t[0],t[1]]),o=Math.abs(Kl(n));n.length>=3&&o>i&&(e=n,i=o)}return e}function fc(t,e,i,s,n,o,a,r=1,l,c){const h=(t||[]).find(t=>t?.id===e),d=hi(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(t=>[t[0],t[1]]);const p=hc(t,e,i,s,n,o,a,r);if(!p||!p.offsets.some(t=>t>0))return d.map(t=>[t[0],t[1]]);const u=c||cc(t,i,s,n,o,a,r),_=Zl(p.poly,p.offsets,u);if(!_)return d.map(t=>[t[0],t[1]]);if(!u.nodes.length)return _;const m=void 0===l?Rc(t,i,s,[],n,o,a,r):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const t=gc(oi(vc(p.poly),g));if(t)return t}catch{}return function(t,e){try{return gc(ni(vc(t),vc(e)))}catch{return null}}(_,p.poly)||d.map(t=>[t[0],t[1]])}function vc(t){const e=t.map(t=>[t[0],t[1]]);return e.push([t[0][0],t[0][1]]),[e]}function yc(t){return!(!Array.isArray(t)||!t.length)&&t.every(t=>Array.isArray(t)&&t.length&&t.every(t=>Array.isArray(t)&&t.length>=4&&t.every(t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])))&&Math.abs(Ti(t[0]))>1e-9)}function bc(t,e,i,s){const n=s?new Set(s):null;let o=null;for(let s=0;se.epsilon))continue;const l=Sc([[t.point[0]+r[0]*s.halfDepth,t.point[1]+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n+r[0]*s.halfDepth,t.point[1]+a.u[1]*n+r[1]*s.halfDepth],[t.point[0]+a.u[0]*n-r[0]*s.halfDepth,t.point[1]+a.u[1]*n-r[1]*s.halfDepth],[t.point[0]-r[0]*s.halfDepth,t.point[1]-r[1]*s.halfDepth]],e.coordinateScale);if(!l)continue;const c=vc(l);o=o?si(o,c):c}}return o}function wc(t,e,i){let s=null;for(const n of t.rays)for(const t of n.continuations){const n=[-t.u[1],t.u[0]],o=[t.start[0]+t.u[0]*t.length,t.start[1]+t.u[1]*t.length],a=Sc([[t.start[0]+n[0]*t.halfDepth,t.start[1]+n[1]*t.halfDepth],[o[0]+n[0]*t.halfDepth,o[1]+n[1]*t.halfDepth],[o[0]-n[0]*t.halfDepth,o[1]-n[1]*t.halfDepth],[t.start[0]-n[0]*t.halfDepth,t.start[1]-n[1]*t.halfDepth]],e.coordinateScale);if(!a)continue;const r=ni(vc(a),i);Array.isArray(r)&&0!==r.length&&(s=s?si(s,r):r)}return s}function kc(t,e,i=2*(4*t.halfDepth+2*e.epsilon)){const s=function(t,e=hl){const i=new Set,s=Number.isFinite(e)&&e>=0?e:hl;for(let e=0;et-e)}(t);return s.length?bc(t,e,i,s):null}function xc(t,e,i,s,n){const o=function(t){let e=null;for(const i of t){const t=vc(i);try{e=e?si(e,t):t}catch{}}return e}(function(t,e,i=!1){if(!t)return[];const s=[];for(const n of t.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-a.u[1],a.u[0]],p=[-r.u[1],r.u[0]],u=[n.point[0]+d[0]*a.halfDepth,n.point[1]+d[1]*a.halfDepth],_=[n.point[0]-p[0]*r.halfDepth,n.point[1]-p[1]*r.halfDepth],m=Xl(u,a.u,_,r.u);if(!m)continue;const g=Math.hypot(m[0]-n.point[0],m[1]-n.point[1]);if(!Number.isFinite(g)||g<=n.limit)continue;const f=e?Math.sqrt(Math.max(0,n.limit*n.limit-a.halfDepth*a.halfDepth)):0,v=e?Math.sqrt(Math.max(0,n.limit*n.limit-r.halfDepth*r.halfDepth)):0,y=Sc([[u[0]+a.u[0]*f,u[1]+a.u[1]*f],[_[0]+r.u[0]*v,_[1]+r.u[1]*v],m],t.coordinateScale);if(y&&s.push(y),i){const e=m[0]-n.point[0],i=m[1]-n.point[1],o=Math.hypot(e,i),a=g-n.limit;if(o>t.epsilon&&a>t.epsilon){const r=Math.min(Math.max(8*t.epsilon,.05*n.halfDepth),.25*a),l=e/o,c=i/o,h=-c,d=l,p=Sc([[m[0]-l*r+h*r,m[1]-c*r+d*r],[m[0]-l*r-h*r,m[1]-c*r-d*r],[m[0]+l*r,m[1]+c*r]],t.coordinateScale);p&&s.push(p)}}}return s}({...e,nodes:[t]},i,s));return o&&n?oi(o,n):o}function $c(t,e,i,s){if(!t||!e.nodes.length)return t;let n=null;try{n=function(t){let e=null;for(const i of t.nodes){const s=kc(i,t);s&&(e=e?si(e,s):s)}return e}(e)}catch{return t}let o=t;for(const t of e.nodes){const a=4*t.halfDepth+2*e.epsilon,r=2*a,l=[[t.point[0]-a,t.point[1]-a],[t.point[0]+a,t.point[1]-a],[t.point[0]+a,t.point[1]+a],[t.point[0]-a,t.point[1]+a]];try{let a=o;const c=xc(t,e,!1,!0,n);c&&(a=oi(a,c));let h=bc(t,e,r);const d=xc(t,e,!0,!0,n);d&&(h=oi(h,d)),n&&(h=si(h,n));const p=.02*Math.min(...t.rays.map(t=>t.halfDepth));if(h=si(h,vc([[t.point[0]-p,t.point[1]-p],[t.point[0]+p,t.point[1]-p],[t.point[0]+p,t.point[1]+p],[t.point[0]-p,t.point[1]+p]])),!h)continue;let u=ni(h,vc(l));s?u=ni(u,s):i&&(u=ni(u,i));const _=vc(l),m=oi(a,_),g=i?oi(ni(a,_),i):null,f=wc(t,e,_);o=si(m,...g?[g]:[],...f?[f]:[],u)}catch{}}if(n)try{let t=n;s?t=ni(t,s):i&&(t=ni(t,i)),o=si(o,t)}catch{}return o}function Sc(t,e=1){if(!Array.isArray(t)||t.length<3)return null;const i=Number.isFinite(e)&&e>0?e:1,s=1e-12*Math.max(1,i),n=[];for(const e of t){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),i=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(i))return null;const o=Math.round(t/s)*s,a=Math.round(i/s)*s;if(!Number.isFinite(o)||!Number.isFinite(a))return null;n.push([Object.is(o,-0)?0:o,Object.is(a,-0)?0:a])}return Math.abs(Kl(n))>s*s?n:null}function Mc(t,e,i,s){if(mc(t[0],t[1],e[0],e[1],i[0],i[1])>s)return!1;const n=i[0]-e[0],o=i[1]-e[1],a=(t[0]-e[0])*n+(t[1]-e[1])*o,r=n*n+o*o,l=s*Math.sqrt(r);return a>=-l&&a<=r+l}function Cc(t,e,i){const s=[],n=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),p=[0,1];for(const t of e)for(const e of[t.a,t.b]){if(!Mc(e,a,r,i))continue;const t=((e[0]-a[0])*l+(e[1]-a[1])*c)/h;t>d&&t<1-d&&p.push(t)}p.sort((t,e)=>t-e);const u=p.filter((t,e)=>0===e||Math.abs(t-p[e-1])>d);for(let t=0;t=3&&n.length===s.length?{poly:s,offsets:n}:null}function Dc(t,e,i,s,n,o,a,r){const l=(t||[]).map(hi).filter(t=>!!t&&t.length>=3);if(!l.length)return null;let c=si(vc(l[0]));for(let t=1;t"outer"===t.kind&&t.half>0),p=4*Vl(s,a),u=r||ac(h,p,a);let _=null;for(const t of function(t){const e=[];for(const i of Array.isArray(t)?t:[])if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,-1).map(t=>[t[0],t[1]]);i.length>=3&&e.push(i)}return e}(c)){const e=Cc(t,d,p);if(!e||!e.offsets.some(t=>t>0))continue;const i=Fc(e.poly,e.offsets,u),s=Zl(e.poly,e.offsets,u);if(!i||!s)continue;const n=oi(vc(i),vc(s));_=_?si(_,n):n}return{centre:c,shell:_||[]}}function Pc(t,e,i,s,n,o,a=1){try{const r=Dc(t,e,i,s,n,o,a,cc(t,e,i,s,n,o,a));if(!r)return[];return r.shell?.length?si(r.centre,r.shell):r.centre}catch{return null}}function Tc(t){if(!t)return"";let e="";for(const i of t)if(Array.isArray(i))for(const t of i){if(!Array.isArray(t)||t.length<4)continue;const i=t.slice(0,t.length-1);i.length<3||(e+=(e?" ":"")+Ql(i.map(t=>[t[0],t[1]])))}return e}function Rc(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return{status:"not-applicable",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:0,openingIndex:null,multiWallNodes:null,degradedExtraCount:0};const h=[],d=cc(t,e,i,n,o,a,r);let p=0;for(const s of t||[]){if(!s?.id)continue;const l=hc(t,s.id,e,i,n,o,a,r);if(!l||l.poly.length<3||!l.offsets.some(t=>t>0))continue;for(const t of l.offsets)t>0&&(p=Math.max(p,2*t));const c=Fc(l.poly,l.offsets,d),u=Zl(l.poly,l.offsets,d);c&&h.push({outset:c,inset:u})}for(const t of l){const e=t.map(t=>t[0]),i=t.map(t=>t[1]);if(e.length){const s=Math.min(Math.max(...e)-Math.min(...e),Math.max(...i)-Math.min(...i)),n=Math.min(...t.map((e,i)=>{const s=t[(i+1)%t.length];return Math.hypot(s[0]-e[0],s[1]-e[1])}));p=Math.max(p,t.length>16?s:n)}}const u=function(t,e,i,s,n,o,a,r){if(!e?.length||!i?.length)return[];const l=4*Vl(s,a),c=new Map;for(const r of dc(t,e,i,s,n,o,a))!r.open&&r.half>0&&!c.has(r.key)&&c.set(r.key,r);const h=[...c.values()];if(h.length<2)return[];const d=r||ac(h,l),p=[];for(const t of i)for(const e of[[t[0],t[1]],[t[2],t[3]]])p.some(t=>Math.hypot(t[0]-e[0],t[1]-e[1])<=l)||p.push(e);const u=[],_=(t,e)=>{let i=0,s=0;if(Math.hypot(t.a[0]-e[0],t.a[1]-e[1])<=l)i=t.b[0]-t.a[0],s=t.b[1]-t.a[1];else{if(!(Math.hypot(t.b[0]-e[0],t.b[1]-e[1])<=l))return null;i=t.a[0]-t.b[0],s=t.a[1]-t.b[1]}const n=Math.hypot(i,s);return n>l?[i/n,s/n]:null};for(const t of p){const e=h.map(e=>({iv:e,u:_(e,t)})).filter(t=>!!t.u);for(let i=0;i0?[t.slice(),p,m,_]:[t.slice(),_,m,p];else{if(!f)continue;{const e=[-n.u[1],n.u[0]],i=[-o.u[1],o.u[0]],s=a<0?1:-1,r=[t[0]+e[0]*n.iv.half*s,t[1]+e[1]*n.iv.half*s],l=[t[0]-i[0]*o.iv.half*s,t[1]-i[1]*o.iv.half*s];y=a>0?[t.slice(),r,l]:[t.slice(),l,r]}}Math.abs(Kl(y))>l*l&&u.push(y)}}return u}(t,e,i,n,o,a,r,d),_=s.length?Ec(t,e,i,n,o,a,r):null;let m="exterior";try{const v=Dc(t,e,i,n,o,a,r,d);m="paper";const y=v?v.shell?.length?si(v.centre,v.shell):v.centre:[],b=t=>{const e=vc(t.outset);return t.inset?oi(e,vc(t.inset)):e};m="room-rings";let w=null;for(const t of h)try{const e=b(t);w=w?si(w,e):e}catch{}if(m="edge-bodies",v)for(const s of zc(t,e,i,n,o,a,r))try{const t=ni(vc(s.quad),v.centre);w=w?si(w,t):t}catch{}m="junctions",w=function(t,e,i=1,s=si){let n=t;for(const t of e||[]){const e=Sc(t,i);if(e)try{const t=vc(e);n=n?s(n,t):t}catch{}}return n}(w,u,r),m="facade-clip",w&&v&&(w=ni(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const t=si(w,v.shell);if(!yc(t))throw new Error("invalid shell union");w=t}catch{if(!yc(w)||!yc(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const t=t=>t.rays.some(t=>t.supports.some(t=>t.length<2*t.halfDepth)),e=d.nodes.filter(t);if(e.length){w=$c(w,{...d,nodes:e},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const s=rc(d),l=function(t,e,i,s,n,o,a,r){try{const l=Dc(t,e,i,s,n,o,a,{epsilon:r.epsilon,coordinateScale:r.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?si(l.centre,l.shell):l.centre:null}catch{return null}}(t,e,i,n,o,a,r,d);for(const t of s.fans)try{let e=[vc(t)];if(l&&(e=ni(e,l)),!e?.length)continue;w=w?si(w,e):e}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(t=>{if(!Array.isArray(t)||!t.length)return t;const[e,...i]=t;return Math.abs(Kl(e||[]))<=f?null:[e,...i.filter(t=>Math.abs(Kl(t||[]))>f)]}).filter(t=>!!t):g}const $=w||[],S=[...yc($)?[{id:"room-primary",geom:$}]:[],...k.map((t,e)=>({id:`room-isolated-${e}`,geom:t.geom}))];m="openings";for(const t of s){if(!(t.length>0))continue;const e=Lc(_,t,!0);if(!e.negative&&!e.positive)continue;const i=t.angle*Math.PI/180,s=Math.cos(i),o=Math.sin(i),a=-o,l=s,c=t.length/2,h=1.25*Math.max(p,n*r),d=[[t.x-s*c-a*h,t.y-o*c-l*h],[t.x+s*c-a*h,t.y+o*c-l*h],[t.x+s*c+a*h,t.y+o*c+l*h],[t.x-s*c+a*h,t.y-o*c+l*h]];w&&(w=oi(w,vc(d)));for(const t of k)t.geom=oi(t.geom,vc(d))}m="extras";const M=[];let C=0;const D=c.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){C++;continue}const i=[vc(e)];try{const e=D(w,i,t);if(!yc(e))throw new Error("invalid extra union");w=e}catch{C++,yc(i)&&M.push({id:`extra-${t}`,geom:i})}}M.push(...k),M.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const P=w||[];return{status:C||x?"degraded-extra":"ok",geom:P,components:[...yc(P)?[{id:"primary",geom:P}]:[],...M.map((t,e)=>({...t,id:`isolated-${e}`}))],roomGeom:$,roomComponents:S,paperGeom:y,depthUnits:p,openingPadUnits:1.25*Math.max(p,n*r),openingIndex:_,multiWallNodes:d,degradedExtraCount:C+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:p,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ic(t,e,i,s=[],n,o,a,r=1,l=[],c={}){if(!e?.length&&!l.length)return null;return Ac(Rc(t,e,i,s,n,o,a,r,l,c))}function Ac(t){if("failed-core"===t.status||"not-applicable"===t.status)return null;const e=t.components.map(t=>({id:t.id,d:Tc(t.geom),fillRule:"evenodd"})).filter(t=>!!t.d),i=e[0]?.d||"",s=Tc(t.paperGeom);if(e.length){const n={status:t.status,d:i,paths:e,components:t.components,roomGeom:t.roomGeom,multiWallNodes:t.multiWallNodes,paperD:s,depthUnits:t.depthUnits,fillRule:"evenodd"};return Object.defineProperties(n,{roomComponents:{value:t.roomComponents||[],enumerable:!1},openingIndex:{value:t.openingIndex,enumerable:!1},openingPadUnits:{value:t.openingPadUnits,enumerable:!1}}),n}return null}function zc(t,e,i,s,n,o,a=1){if(!e?.length)return[];const r=new Set,l=[];for(const c of t||[]){if(!c?.id)continue;const h=hc(t,c.id,e,i,s,n,o,a);if(!h)continue;const d=h.poly;for(let t=0;t0))continue;const u=kl(e,i,s,a);if(r.has(u))continue;r.add(u);const _=gl(p,n,o),[m,g]=Yl(d,t),f=-m,v=-g,y=_/2,b=[[e[0]+f*y,e[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[e[0]+m*y,e[1]+g*y]];l.push({key:u,kind:c,cm:p,quad:b,a:[e[0],e[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Fc(t,e,i){const s=t?.length||0;if(s<3||e.length!==s)return null;if(e.every(t=>!(t>0)))return t.map(t=>[t[0],t[1]]);tc(t),e.slice().reverse();const n=[];for(let o=0;o0||l>0)){n.push([t[o][0],t[o][1]]);continue}if(r>0!=l>0){const e=t[o],i=r>0?[e[0]-c*r,e[1]-h*r]:[e[0],e[1]],s=l>0?[e[0]-d*l,e[1]-p*l]:[e[0],e[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(Jl(w,k)){const e=t[o],i=[e[0]-c*r,e[1]-h*r],s=[e[0]-d*l,e[1]-p*l];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=Xl(x,w,$,k),M=Math.max(r,l,1e-9),C=lc(i,t[o])?.limit??4*M;if(S){const e=Math.hypot(S[0]-t[o][0],S[1]-t[o][1]);if(Number.isFinite(e)&&e<=C){n.push(S);continue}}r>0&&n.push([t[o][0]-c*r,t[o][1]-h*r]),l>0&&n.push([t[o][0]-d*l,t[o][1]-p*l])}return n.length>=3?n:null}function Ec(t,e,i,s,n,o,a=1){const r=[];for(const l of t||[]){if(!l?.id)continue;const c=hc(t,l.id,e,i,s,n,o,a);if(!c)continue;const h=Math.abs(Ti(c.poly));for(let t=0;t[Math.max(e,t.x0),Math.min(i,t.x1)]).filter(t=>t[1]-t[0]>s).sort((t,e)=>t[0]-e[0]||t[1]-e[1]);if(!n.length)return{coverage:0,full:!1};let o=n[0][0],a=n[0][1],r=0,l=o<=e+s;for(let t=1;t=i-s,{coverage:r,full:l}}function Oc(t,e){return Number(e.full)-Number(t.full)||t.faceDistance-e.faceDistance||t.area-e.area||t.roomId.localeCompare(e.roomId)}function Lc(t,e,i=!1){const s=Number(e?.x),n=Number(e?.y),o=Number(e?.angle),a=Number(e?.length);if(!([s,n,o,a].every(Number.isFinite)&&a>0))return{negative:null,positive:null};const r=o*Math.PI/180,l=Math.cos(r),c=Math.sin(r),h=-c,d=l,p=a/2,u=Math.max(1e-9,t.adjacencyEps),_=new Map;let m=0;for(const e of t.edges){if(i&&!(e.half>0))continue;if(!Rl(e.a,e.b,o))continue;const[t,a]=bl(e.a,e.b);if(Math.abs((s-e.a[0])*a-(n-e.a[1])*t)>u)continue;const r=(e.a[0]-s)*l+(e.a[1]-n)*c,g=(e.b[0]-s)*l+(e.b[1]-n)*c,f=Math.max(-p,Math.min(r,g)),v=Math.min(p,Math.max(r,g));if(v-f<=u)continue;const y=e.inward[0]*h+e.inward[1]*d>=0?1:-1,b=((e.a[0]+e.b[0])/2-s)*h+((e.a[1]+e.b[1])/2-n)*d,w=Math.abs(b+y*e.half),k=`${y}|${e.roomId}`,x={x0:f,x1:v,half:e.half,cm:e.cm,key:e.key,axis:[t,a]},$=_.get(k);$?($.pieces.push(x),$.faceDistance=Math.min($.faceDistance,w)):_.set(k,{roomId:e.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:e.area,coverage:0,full:!1})}for(const t of _.values()){const e=Nc(t.pieces,-p,p,u);t.coverage=e.coverage,t.full=e.full}const g=t=>{const e=[..._.values()].filter(e=>e.side===t&&e.coverage>u);return e.sort(Oc),e[0]||null};return{negative:g(-1),positive:g(1)}}function Hc(t,e){const i=Lc(t,e),s=[i.negative,i.positive].filter(t=>!!t);if(!s.length)return{ox:0,oy:0,cm:0,side:-1};const n=i.negative&&i.positive?-1:s[0].side,o=e.flip_v?-n:n,a=(-1===o?i.negative:i.positive)||s[0],r=[...a.pieces].sort((t,e)=>(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))-(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))||e.x1-e.x0-(t.x1-t.x0)||t.key.localeCompare(e.key))[0];if(!(r.half>0&&r.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=e.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*r.half,oy:h*o*r.half,cm:r.cm,side:o}}function Bc(t,e){const i=1e-9,s=e.filter(t=>Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&Number.isFinite(t.half)&&t.x1>t.x0&&t.half>0);if(!s.length)return"";const n=s.flatMap(t=>[t.x0,t.x1]).sort((t,e)=>t-e),o=[];for(const t of n){const e=o[o.length-1];(void 0===e||t>e+i)&&o.push(t)}const a=[];for(let t=0;t+1e+i))continue;const r=(e+n)/2,l=s.reduce((t,e)=>r>=e.x0-i&&r<=e.x1+i?Math.max(t,e.half):t,0);if(!(l>0))continue;const c=a[a.length-1];c&&e<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=n:a.push({x0:e,x1:n,half:l})}const r=[];for(const t of a){const e=r[r.length-1],s=e?.[e.length-1];s&&t.x0<=s.x1+i?(t.x0=s.x1,e.push(t)):r.push([t])}return r.map(e=>{const i=e[0],s=e[e.length-1],n=Math.min(.25*Math.min(...e.map(t=>t.half)),.75),o=-t*n,a=[];if(1===t){a.push(`M ${i.x0} ${o} L ${s.x1} ${o}`);for(let t=e.length-1;t>=0;t--){const i=e[t];a.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{a.push(`M ${s.x1} ${o} L ${i.x0} ${o}`);for(const t of e)a.push(`L ${t.x0} ${-t.half} L ${t.x1} ${-t.half}`)}return a.push("Z"),a.join(" ")}).join(" ")}function qc(t,e,i,s){if(!s)return i;const n=t.angle*Math.PI/180,o=Math.cos(n),a=Math.sin(n),r=[],l=1e-9;for(const n of i){const[i,c]=n.axis,h=o*i+a*c;if(Math.abs(h)<=l)continue;const d=t.x*i+t.y*c,p=d+h*n.x0,u=d+h*n.x1,_=Math.min(p,u),m=Math.max(p,u),g=`${n.key}|${e}`,f=s.get(g)||[];let v=[[_,m]];for(const[t,e]of f){const i=[];for(const[s,n]of v)e<=s+l||t>=n-l?i.push([s,n]):(t>s+l&&i.push([s,Math.min(n,t)]),et[0]-e[0]||t[1]-e[1]),b=[];for(const t of y){const e=b[b.length-1];e&&t[0]<=e[1]+l?e[1]=Math.max(e[1],t[1]):b.push([t[0],t[1]])}s.set(g,b)}return r}function Wc(t,e){const i=new Map;return e.map(e=>function(t,e,i){const s=Lc(t,e,!0),n=s.negative,o=s.positive;if(!n&&!o)return null;let a;if(n&&o)a=[{candidate:n,side:-1},{candidate:o,side:1}];else{const t=n||o;a=[{candidate:t,side:-1},{candidate:t,side:1}]}const r=a.map(({candidate:t,side:s})=>({candidate:t,side:s,pieces:qc(e,s,t.pieces,i)})),l=r.map(({candidate:t,side:e,pieces:i})=>({side:e,roomId:t.roomId,d:Bc(e,i)})),c=r.flatMap(({pieces:t})=>t);if(!c.length)return null;const h=Math.max(...c.map(t=>t.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(t=>t.key))].sort().join("|")}}(t,e,i))}const jc=150,Uc=1e-6;function Gc(t){return Number.isFinite(t)?Math.max(1,Math.min(jc,t)):1}function Vc(t){return((Number.isFinite(Number(t))?Number(t):0)%90+90)%90}const Kc=t=>{const e=t.map(t=>[t[0],t[1]]);return!e.length||e[0][0]===e[e.length-1][0]&&e[0][1]===e[e.length-1][1]||e.push([...e[0]]),[e]},Yc=(t,e)=>t[0]===e[0]&&t[1]===e[1];function Jc(t,e=1e-6){const i=Number.isFinite(e)&&e>0?e:Uc,s=[];for(const e of t||[]){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);if(!Number.isFinite(t)||!Number.isFinite(n))return null;const o=Math.round(t/i)*i,a=Math.round(n/i)*i;if(!Number.isFinite(o)||!Number.isFinite(a))return null;const r=[Object.is(o,-0)?0:o,Object.is(a,-0)?0:a];s.length&&Yc(s[s.length-1],r)||s.push(r)}return s.length>1&&Yc(s[0],s[s.length-1])&&s.pop(),s.length<3||new Set(s.map(t=>`${t[0]},${t[1]}`)).size<3?null:Ti(s)>i*i?s:null}function Xc(t){const e=[];for(const i of t||[])for(const t of i||[]){const i=(t||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||e.push(`M ${i.slice(0,-1).map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`)}return e.join(" ")}function Zc(t,e,i,s,n){return Ol({a:t,b:e,halfDepth:gl(i,s,n)/2})}function Qc(t,e,i){const s=Number(e)>0?Number(e):5,n=Gc(t.cm)/s*i,o=t.center[0],a=t.center[1];if("circle"===t.shape){const t=n/2;return Array.from({length:96},(e,i)=>{const s=i/96*Math.PI*2;return[o+Math.cos(s)*t,a+Math.sin(s)*t]})}const r=n/2,l=Vc(t.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-r,-r],[r,-r],[r,r],[-r,r]].map(([t,e])=>[o+t*c-e*h,a+t*h+e*c])}function th(t,e,i=1e-9){if(!e.length)return[t];let s=[Kc(t)];try{for(const t of e){const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(e,n);if(!(o>i))continue;const a=e/o,r=n/o,l=-r,c=a,h=1.25*Math.max(Number(t.depth)||0,4*i),d=Math.max(2*i,1e-9*o),p=[[t.a[0]-a*d-l*h,t.a[1]-r*d-c*h],[t.b[0]+a*d-l*h,t.b[1]+r*d-c*h],[t.b[0]+a*d+l*h,t.b[1]+r*d+c*h],[t.a[0]-a*d+l*h,t.a[1]-r*d+c*h]];s=oi(s,Kc(p))}return hh(s)}catch{return[t]}}function eh(t,e){try{const i=oi([[...t.map(t=>[t[0],t[1]]),[t[0][0],t[0][1]]]],[[...e.map(t=>[t[0],t[1]]),[e[0][0],e[0][1]]]]);let s=null,n=0;for(const t of i||[]){const e=t?.[0]||[],i=Math.abs(Ti(e));e.length>=4&&i>n&&(n=i,s=e.slice(0,-1).map(t=>[t[0],t[1]]))}return s}catch{return null}}function ih(t,e,i,s=Math.max(2e-4*i,1e-9),n=[]){const o=[],a=[],r=new Map;for(const t of n){const e=r.get(t.hostId)||[];e.push(t),r.set(t.hostId,e)}const l=[],c=[],h=[];for(const s of t.room_drafts||[])for(let t=0;t+10))continue;const r={a:s.points[t],b:s.points[t+1],halfDepth:a},c=Ol(r);c&&(o.push(r),l.push(c))}const d=[];for(const s of t.partitions||[]){const t={a:s.a,b:s.b,halfDepth:gl(s.cm,e,i)/2};if(!(t.halfDepth>0))continue;const n=Ol(t);n&&(a.push(t),c.push(n),d.push({id:s.id,body:n}))}const p=[...o,...a];for(const{segmentIndex:t,wedge:e}of Wl(p,s)){const i=t=o.length&&(d[i.at].body=s))}for(const t of d)h.push(...th(t.body,r.get(t.id)||[],s));const u=(t.wall_columns||[]).map(t=>Qc(t,e,i)),_=jl([...o,...a],s).flatMap(t=>th(t,n,s));return{drafts:l,partitions:c,columns:u,patches:_,all:[...l,...h,..._,...u]}}function sh(t){try{const e=t.map(t=>Jc(t)).filter(t=>!!t).map(t=>Kc(t));return e.length?si(e[0],...e.slice(1)):null}catch{return null}}const nh=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`;function oh(t){const e=[];for(const i of t||[]){if(lh([i])<=1e-6)continue;const t=[];for(const e of i||[]){const i=(e||[]).filter(t=>Array.isArray(t)&&t.length>=2);i.length<4||t.push(nh(i.slice(0,-1)))}t.length&&e.push(t.join(" "))}return e}function ah(t,e,i={}){const s=sh(t.filter(t=>t.length>=3)),n=e.some(t=>!Jc(t))?null:sh(e);if(!s)return[];if(n)try{return oh(ni(s,n))}catch{}return function(t,e,i){let s=null;for(let n=0;n=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]));return e}function hh(t){const e=[];for(const i of t||[]){const t=i?.[0];t?.length>=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]))}return e}function dh(t,e){let i=!1;for(let s=0,n=e.length-1;st[1]!=l>t[1]&&t[0]<(r-o)*(t[1]-a)/(l-a||1e-12)+o&&(i=!i)}return i}function ph(t,e,i){return function(t,e){for(const i of e||[]){const e=i?.[0];if(!e?.length||!dh(t,e))continue;let s=!1;for(let e=1;edh(t,e))}function uh(t,e,i){if(Math.hypot(t.center[0]-e.center[0],t.center[1]-e.center[1])>i)return!1;if(Math.abs(Gc(t.cm)-Gc(e.cm))>1e-6)return!1;if(t.shape!==e.shape)return!0;if("circle"===t.shape||"circle"===e.shape)return!0;const s=Math.abs(Vc(t.angle)-Vc(e.angle));return Math.min(s,90-s)<=1e-6}const _h=2.54;function mh(t){const e="number"==typeof t?t:NaN;return!Number.isFinite(e)||e<=0||5===e?1:5/e}function gh(t,e){return t*mh(e)}function fh(t){return t?_h:1}function vh(t,e){if(!e)return String(t);const i=t/_h;return String(Math.round(1e6*i)/1e6)}const yh=1e3;function bh(t,e){const i=Number(t),s=Number.isFinite(i)&&i>0?i:1,n=s>=1?e:e*s,o=s>=1?e/s:e;return{x:(e-n)/2,y:(e-o)/2,w:n,h:o}}const wh=.01,kh=100;function xh(t,e=1e3){const i=bh(t?.plan_aspect,e),s=Number(t?.plan_scale),n=Number.isFinite(s)&&s>0?Math.min(kh,Math.max(wh,s)):1,o=Number(t?.plan_scale_x),a=Number(t?.plan_scale_y),r=Number.isFinite(o)&&o>0?Math.min(kh,Math.max(wh,o)):n,l=Number.isFinite(a)&&a>0?Math.min(kh,Math.max(wh,a)):n,c=Number(t?.plan_x),h=Number(t?.plan_y),d=Ar(t?.plan_angle);return{x:i.x+(Number.isFinite(c)?zh(c):0)*e,y:i.y+(Number.isFinite(h)?zh(h):0)*e,w:i.w*r,h:i.h*l,...d?{angle:d}:{}}}function $h(t){if(null==t.x||null==t.y)return{x:t.x,y:t.y,w:t.w,h:t.h};const e=Number(t.w)||0,i=Number(t.h)||0;return{x:e<0?t.x+e:t.x,y:i<0?t.y+i:t.y,w:Math.abs(e),h:Math.abs(i)}}function Sh(t){return t&&Array.isArray(t.spaces)?t.spaces.map(t=>{const e=yh,i=function(t){return Array.isArray(t)&&4===t.length&&t.every(t=>Number.isFinite(t))&&t[2]>1e-6&&t[3]>1e-6?t:[0,0,1,1]}(t.view_box);return{id:t.id,title:t.title,cellCm:Number.isFinite(Number(t.cell_cm))&&Number(t.cell_cm)>0?Number(t.cell_cm):5,vb:[i[0]*yh,i[1]*e,i[2]*yh,i[3]*e],bg:t.plan_url?{href:As(t.plan_url),...xh(t,yh)}:null,rooms:(t.rooms||[]).map(t=>{const i={...t,...$h(t)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*yh:void 0,y:null!=i.y?i.y*e:void 0,w:null!=i.w?i.w*yh:void 0,h:null!=i.h?i.h*e:void 0,poly:i.poly?i.poly.map(t=>[t[0]*yh,t[1]*e]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(t.wall_segments||[]).map(t=>({...t,id:String(t.id),a:[Number(t.a?.[0])*yh,Number(t.a?.[1])*e],b:[Number(t.b?.[0])*yh,Number(t.b?.[1])*e],cm:Number(t.cm)})),room_drafts:(t.room_drafts||[]).map(t=>({id:t.id,points:(t.points||[]).map(t=>[t[0]*yh,t[1]*e]),segments:(t.segments||[]).map(t=>({..."string"==typeof t.id&&t.id?{id:t.id}:{},cm:Number(t.cm)}))})),partitions:(t.partitions||[]).map(t=>({id:t.id,a:[t.a[0]*yh,t.a[1]*e],b:[t.b[0]*yh,t.b[1]*e],cm:Number(t.cm)})),wall_columns:(t.wall_columns||[]).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[t.center[0]*yh,t.center[1]*e],cm:Number(t.cm),..."circle"===t.shape?{}:{angle:Vc(t.angle)}}))}}):[]}const Mh=5e3,Ch=Mh*yh,Dh=240,Ph=yh/Dh,Th=1/Dh;function Rh(t){if(!Number.isFinite(t))return t;const e=Math.round(t*Dh/yh)*yh/Dh;return Math.abs(e-t)<=1e-9*Ph?t:e}function Ih(t){return{x:Rh(t.x),y:Rh(t.y)}}function Ah(t){return Number.isFinite(t)?Math.min(Ch,Math.max(-Ch,t)):0}function zh(t){return Number.isFinite(t)?Math.min(Mh,Math.max(-Mh,t)):0}const Fh=1/3,Eh=200;function Nh(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t){const t=Number(o[0]),a=Number(o[1]);Number.isFinite(t)&&Number.isFinite(a)&&(ts&&(s=t),a>n&&(n=a))}return e>s?null:{minX:e,minY:i,maxX:s,maxY:n}}function Oh(t){return t.poly&&t.poly.length?Nh(t.poly):null==t.x||null==t.y?null:Nh([[t.x,t.y],[t.x+(t.w||0),t.y+(t.h||0)]])}function Lh(t,e){const i=[];for(const e of t.rooms||[]){const t=Oh(e);t&&i.push(t)}if(t.bg){const e=Nh(Lr(t.bg));e&&i.push(e)}for(const t of e||[])if(Array.isArray(t)){const e=Nh([t]);e&&i.push(e)}else i.push(t);return i}const Hh=t=>{if(!t.length)return 0;const e=[...t].sort((t,e)=>t-e),i=e.length>>1;return e.length%2?e[i]:(e[i-1]+e[i])/2},Bh=t=>{let e=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of t)o.minXs&&(s=o.maxX),o.maxY>n&&(n=o.maxY);return e>s||i>n?null:{x:e,y:i,w:s-e,h:n-i}};function qh(t,e){let{x:i,y:s,w:n,h:o}=t;n<30&&(i=i+n/2-100,n=Eh),o<30&&(s=s+o/2-100,o=Eh);const a=Math.max(n,o)*e;return{x:i-a,y:s-a,w:n+2*a,h:o+2*a}}function Wh(t,e={}){const i=e.pad??.05,s=e.k??10,n=e.minSpread??50,o=t.filter(t=>Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&Math.abs(t.minX)<=Ch&&Math.abs(t.maxX)<=Ch&&Math.abs(t.minY)<=Ch&&Math.abs(t.maxY)<=Ch);if(!o.length)return{core:null,all:null,outliers:0};const a=Bh(o);if(o.length<4){const t=qh(a,i);return{core:t,all:t,outliers:0}}const r=o.map(t=>(t.minX+t.maxX)/2),l=o.map(t=>(t.minY+t.maxY)/2),c=Hh(r),h=Hh(l),d=o.map((t,e)=>Math.max(Math.abs(r[e]-c),Math.abs(l[e]-h))),p=Math.max(((t,e)=>t.length?t[Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))))]:0)([...d].sort((t,e)=>t-e),.75),n),u=d.map(t=>t>s*p),_=u.filter(Boolean).length,m=_&&_<=o.length*Fh?o.filter((t,e)=>!u[e]):o;return{core:qh(Bh(m)||a,i),all:qh(a,i),outliers:m===o?0:_}}function jh(t,e,i=.05){const s=Wh(Lh(t,e),{pad:i});if(s.core)return s.core;const n=t.vb&&4===t.vb.length&&t.vb[2]>0&&t.vb[3]>0?t.vb:[0,0,yh,yh];return{x:n[0],y:n[1],w:n[2],h:n[3]}}function Uh(t){const e=jh(t);return{x:e.x+e.w/2,y:e.y+e.h/2}}function Gh(t){const e=[];for(const i of t.rooms||[]){const t=Oh(i);t&&e.push(t)}const i=Wh(e,{pad:0}).core,s=yh*mh(t.cellCm??5);return i?Math.max(s,Math.min(Ch,Math.max(i.w,i.h))):s}function Vh(t,e,i,s=1){const n=Number(i),o=Number.isFinite(s)&&s>0?s:1;return!Number.isFinite(n)||n<=0?t*o:t*Gh(e)*o/n}const Kh=[1,2,5,10,20,50,100,200,500,1e3];function Yh(t){if(t.poly&&t.poly.length){const e=t.poly.map(t=>t[0]),i=t.poly.map(t=>t[1]),s=Math.min(...e),n=Math.min(...i);return{x:s,y:n,w:Math.max(...e)-s,h:Math.max(...i)-n}}return{x:t.x??0,y:t.y??0,w:t.w??0,h:t.h??0}}function Jh(t,e,i,s){const n=i["rl_"+(t.id||"")];if(n&&n.s===e)return{x:n.x*yh,y:n.y*yh};const o=function(t){if(t.poly){const e=t.poly.length;return[t.poly.reduce((t,e)=>t+e[0],0)/e,t.poly.reduce((t,e)=>t+e[1],0)/e]}return[t.x+t.w/2,t.y+.1*Math.min(t.w,t.h)]}(t);return Ih({x:o[0],y:o[1]})}const Xh=["furniture","appliance","sanitary","other"],Zh=[{id:"sofa",group:"furniture",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Qh=new Map(Zh.map(t=>[t.id,t]));function td(t){return t&&Qh.get(t)||null}function ed(t){return Zh.filter(e=>e.group===t)}function id(t,e,i=Ph,s=1e3){const n=Number(e)>0?Number(e):5;return(Number(t)||0)/n*i/s}const sd=5e-4,nd=Mh;function od(t){return Number.isFinite(t)?Math.max(sd,Math.min(nd,t)):sd}const ad=t=>{const e=Math.round(1e3*t)/1e3;return Object.is(e,-0)?"0":String(e)};function rd(t,e,i){const s=td(t);if(!(s&&e>0&&i>0))return"";const n=t=>ad(t*e),o=t=>ad(t*i),a=[];for(const t of s.g)if("r"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}H${n(e+s)}V${o(i+r)}H${n(e)}Z`)}else if("l"===t[0]){const[,e,i,s,r]=t;a.push(`M${n(e)} ${o(i)}L${n(s)} ${o(r)}`)}else if("e"===t[0]){const[,s,r,l,c]=t;a.push(`M${n(s-l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s+l)} ${o(r)}A${ad(l*e)} ${ad(c*i)} 0 0 1 ${n(s-l)} ${o(r)}Z`)}else{const e=t.slice(1);if(e.length<4)continue;let i=`M${n(e[0])} ${o(e[1])}`;for(let t=2;t+1{let e=(t%360+360)%360;return e>180&&(e-=360),e};function cd(t,e,i,s,n,o=0){let a=null,r=n;for(const n of s){const[s,l,c,h]=n,d=c-s,p=h-l,u=d*d+p*p;if(!u)continue;const _=Math.sqrt(u);let m=((t-s)*d+(e-l)*p)/u;m=Math.max(0,Math.min(1,m));let g=s+m*d,f=l+m*p;const v=Math.hypot(t-g,e-f);if(!(v0){const t=Math.round(m*_/o)*o;g=s+t/_*d,f=l+t/_*p}a={cx:g+y*(i/2),cy:f+b*(i/2),angle:ld(180*Math.atan2(-y,b)/Math.PI),dist:v}}return a}function hd(t,e,i){const s=i>0?i:1;return{a:[t[0]/s,t[1]/s],b:[e[0]/s,e[1]/s]}}function dd(t,e){const i=e>0?e:1;return[t.a[0]*i,t.a[1]*i,t.b[0]*i,t.b[1]*i]}function pd(t){return Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1]))}function ud(t){if(!Array.isArray(t))return[];const e=[];for(const i of t){if(!i||"object"!=typeof i)continue;const t=i;if(!pd(t.a)||!pd(t.b))continue;const s=[Number(t.a[0]),Number(t.a[1])],n=[Number(t.b[0]),Number(t.b[1])];Math.hypot(n[0]-s[0],n[1]-s[1])<.001||e.push({a:s,b:n})}return e}function _d(t,e,i,s,n=!0){const o=(t||[]).filter(t=>t?.id),a=ud(e);if(a.length)return function(t,e,i,s){const n=ud(t);if(!n.length)return[];const o=function(t,e){const i=[],s=(t||[]).filter(t=>t?.id);for(let t=0;t4*s||o>4*s)continue;const a=(t[0]-n)*p+(t[1]-l)*u,c=(t[2]-n)*p+(t[3]-l)*u,h=Math.max(0,Math.min(a,c)),m=Math.min(d,Math.max(a,c));if(m-ht.lo-e.lo||t.hi-e.hi);const i=[];for(const t of e){const e=i[i.length-1];e&&t.lo<=e.hi+r?e.hi=Math.max(e.hi,t.hi):i.push({...t})}for(const e of i){const i=[n+p*e.lo,l+u*e.lo],s=[n+p*e.hi,l+u*e.hi];Math.hypot(s[0]-i[0],s[1]-i[1])i.pair===t&&Math.abs(i.ux*a-i.uy*o)<=1e-6&&Math.abs((e[0]-i.origin[0])*i.uy-(e[1]-i.origin[1])*i.ux)<=c&&Math.abs((e[2]-i.origin[0])*i.uy-(e[3]-i.origin[1])*i.ux)<=c);h||(h={pair:t,origin:[e[0],e[1]],ux:o,uy:a,ranges:[]},l.push(h));const d=(e[0]-h.origin[0])*h.ux+(e[1]-h.origin[1])*h.uy,p=(e[2]-h.origin[0])*h.ux+(e[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,p),hi:Math.max(d,p)})}const h=[];for(const t of l){t.ranges.sort((t,e)=>t.lo-e.lo||t.hi-e.hi);const e=[];for(const i of t.ranges){const t=e[e.length-1];t&&i.lo<=t.hi+r?t.hi=Math.max(t.hi,i.hi):e.push({...i})}for(const s of e){const e=[t.origin[0]+t.ux*s.lo,t.origin[1]+t.uy*s.lo],n=[t.origin[0]+t.ux*s.hi,t.origin[1]+t.uy*s.hi];Math.hypot(n[0]-e[0],n[1]-e[1])>=r&&h.push(hd(e,n,i))}}return h}(a,t,i,s).map(t=>dd(t,i));if(!n)return[];const r=[],l=(t,e)=>(t.open_to||[]).includes(e.id)||(e.open_to||[]).includes(t.id);for(let t=0;t{const e=fd.get(t);if(!e)return;const i=Date.now();if("hidden"===t.visibilityState){e.hiddenAt||(e.hiddenAt=i);const t={kind:"hidden",token:e.token,at:i,hiddenFor:0,long:!1};for(const i of[...e.subscribers])i(t);return}const s=e.hiddenAt?Math.max(0,i-e.hiddenAt):0;e.hiddenAt=0,e.token++;const n={kind:"visible",token:e.token,at:i,hiddenFor:s,long:s>=md};for(const t of[...e.subscribers])t(n)},onPageShow:e=>{const i=fd.get(t);if(!i)return;const s=Date.now();i.token++;const n={kind:"pageshow",token:i.token,at:s,hiddenFor:0,long:!!e.persisted,persisted:!!e.persisted};for(const t of[...i.subscribers])t(n)}},fd.set(t,i),t.addEventListener("visibilitychange",i.onVisibility),t.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(e),()=>{const i=fd.get(t);i&&(i.subscribers.delete(e),i.subscribers.size||(t.removeEventListener("visibilitychange",i.onVisibility),t.defaultView?.removeEventListener("pageshow",i.onPageShow),fd.delete(t)))}}const yd={now:()=>Date.now(),setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),requestAnimationFrame:t=>window.requestAnimationFrame(t),cancelAnimationFrame:t=>window.cancelAnimationFrame(t)};class bd{constructor(t,e=yd){this.onChange=t,this.clock=e,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(t=>({...t,...t.stage?{stage:[...t.stage]}:{}}))}note(t,e={}){this.record(t,void 0,e)}record(t,e,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:t,state:this._state,...e?{reason:e}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(t){t&&(this._hasCompleteFrame=!0,this._frameFingerprint=t,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(t){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&t&&t!==this._frameFingerprint&&(this._frameFingerprint=t,this.record("frame-refreshed"))}visibility(t){return"hidden"===t.kind?(this.record("visibility-hidden"),this._token):t.long||"visible"!==t.kind&&"pageshow"!==t.kind?this.beginCandidate("pageshow"===t.kind?"pageshow":"long-resume"):(this.record("pageshow"===t.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(t,e="plan"){return this._token++,this._recoveryReason=e,this._hasCompleteFrame?(this._state="connection"===e?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(e)),this.record("candidate-start",t),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(t){return!this._disposed&&t===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(t,e){if(this._disposed||t!==this._token)return!1;let i=!0;const s=(async()=>{for(await e.updateComplete();i&&!this._disposed&&t===this._token;)if(e.stageValid()&&e.assetsReady()){if(await this.nextFrame(),t!==this._token||!e.stageValid()||!e.assetsReady())continue;if(await this.nextFrame(),t===this._token&&e.stageValid()&&e.assetsReady())return!0}else await this.nextFrame();return!1})();let n=0;const o=new Promise(t=>{n=this.clock.setTimeout(()=>t({ready:!1,timedOut:!0}),gd)}),a=await Promise.race([s.then(t=>({ready:t,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(n),!this._disposed&&t===this._token&&(!(!a.ready&&!a.timedOut)&&(a.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=e.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(t=this._recoveryReason||"plan"){return this.beginCandidate("retry",t)}nextFrame(){return new Promise(t=>{const e=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(e),t()});this._barrierRafs.add(e)})}scheduleOverlay(t){this.clearOverlayTimer(),this._recoveryReason=t,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const t=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},t)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const t of this._barrierRafs)this.clock.cancelAnimationFrame(t);this._barrierRafs.clear()}}function wd(t){let e=2166136261,i=2654435769;const s=new WeakSet,n=t=>{for(let s=0;s>>0)+(i>>>2)}},o=t=>{if(null===t)return void n("n");const e=typeof t;if("string"===e)return void n(`s${t.length}:${t}`);if("number"===e)return void n(`d${Number.isNaN(t)?"NaN":String(t)}`);if("boolean"===e)return void n(t?"t":"f");if("undefined"===e)return void n("u");if("object"!==e)return void n(`${e}:${String(t)}`);const i=t;if(s.has(i))n("[cycle]");else{if(s.add(i),Array.isArray(t)){n("[");for(const e of t)o(e);return n("]"),void s.delete(i)}n("{");for(const e of Object.keys(t).sort())n(e),o(t[e]);n("}"),s.delete(i)}};return o(t),`${(e>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function kd(t){return wd(t)}const xd=new WeakMap;class $d{constructor(t,e=()=>Date.now()){this.onUpdate=t,this.now=e,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(t){const e=((t,e)=>{const i=t?.connection||t?.callWS||e;return!i||"object"!=typeof i&&"function"!=typeof i?e:i})(t,this.fallbackAuthority);return this.shared&&this.authority===e||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=e,this.shared=(t=>{let e=xd.get(t);return e||(e={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},xd.set(t,e)),e})(e),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(t,e){this.disposed=!1,this.referenced=new Set(e());const i=this.bind(t());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(t(),e()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const t of this.queued)this.shared.queued.delete(t)}this.queued.clear()}invalidate(t){const e=this.bind(t);clearTimeout(this.batchTimer),this.queued.clear(),e.queued.clear(),e.inFlight.clear(),e.retry.clear(),e.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return i;const s=this.bind(t);this.referenced.add(i),s.references.set(this.referenceOwner,new Set(this.referenced));const n=s.signed[i],o=n?this.now()-n.at:1/0;return o{const e=[...this.queued];this.queued.clear();for(const t of e)i.queued.delete(t);this.sign(t,e)},30))}sign(t,e){if(!e.length||!t?.callWS)return;const i=this.bind(t);for(const s of function(t,e){const i=Math.max(1,Math.floor(e)),s=[];for(let e=0;e{const s=i.inFlight.get(t);return!(void 0!==s&&e-s<15e3)&&(i.inFlight.set(t,e),!0)});n.length&&t.callWS({type:"houseplan/content/sign",paths:n}).then(t=>{const e=this.now();let s=0,o=!1;for(const a of n){const n=t?.urls?.[a];if("string"==typeof n&&n){const t=i.signed[a];t?.loaded&&t.url!==n?(t.pending={url:n,at:e},this.preloadReplacement(i,a,n,e)):(i.signed[a]={url:n,at:e,loaded:t?.url===n&&!!t.loaded},o=!0),i.retry.delete(a),s++}else this.backOff(i,a)}if(s&&(this.trimShared(i),o))for(const t of[...i.listeners])t()}).catch(()=>{for(const t of n)this.backOff(i,t)}).finally(()=>{for(const t of n)i.inFlight.get(t)===e&&i.inFlight.delete(t);for(const t of[...i.settlers])t()})}}preloadReplacement(t,e,i,s){const n=()=>{const n=t.signed[e];if(n?.pending?.url===i){t.signed[e]={url:i,at:s,loaded:!0},t.retry.delete(e),this.trimShared(t);for(const e of[...t.listeners])e()}},o=()=>{const s=t.signed[e];s?.pending?.url===i&&(delete s.pending,this.backOff(t,e))};if("undefined"==typeof Image)return void n();const a=new Image;a.onload=()=>{("function"==typeof a.decode?a.decode():Promise.resolve()).then(n).catch(o)},a.onerror=o,a.src=i}preloadCurrentImage(t,e,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const s=i.url;return i.preload=new Promise(n=>{const o=new Image;let a=!1;const r=o=>{if(a)return;a=!0,clearTimeout(l);const r=t.signed[e];if(r===i&&delete r.preload,o&&r===i&&r.url===s){r.loaded=!0;for(const e of[...t.listeners])e();n(!0)}else o||r!==i||this.backOff(t,e),n(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>r(!0)).catch(()=>r(!1))},o.onerror=()=>r(!1);const l=setTimeout(()=>r(!1),gd);o.src=s}),i.preload}prepareImage(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const s=this.bind(t),n=()=>{const e=s.signed[i];if(e&&this.now()-e.atthis.now()&&!s.inFlight.has(i)&&!s.queued.has(i)?Promise.resolve(!1):null},o=n();return o?(a=o,new Promise(t=>{let e=!1;const i=i=>{e||(e=!0,clearTimeout(s),t(i))},s=setTimeout(()=>i(!1),gd);a.then(i).catch(()=>i(!1))})):new Promise(t=>{let e=!1,i=null;const o=i=>{e||(e=!0,clearTimeout(r),s.settlers.delete(a),t(i))},a=()=>{e||i||(i=n(),i&&i.then(o).catch(()=>o(!1)))},r=setTimeout(()=>o(!1),gd);s.settlers.add(a),a()});var a}backOff(t,e){const i=t.retry.get(e)?.delay||0,s=Math.min(6e4,i?2*i:2e3);t.retry.set(e,{notBefore:this.now()+s,delay:s})}trimShared(t){const e=Object.entries(t.signed);if(e.length<=512)return;const i=new Set(t.inFlight.keys());for(const e of t.references.values())for(const t of e)i.add(t);for(const[t,s]of e)(s.pending||s.preload)&&i.add(t);e.sort((t,e)=>e[1].at-t[1].at);const s=e.filter(([t])=>i.has(t));for(const t of e){if(s.length>=512)break;i.has(t[0])||s.push(t)}t.signed=Object.fromEntries(s)}resign(t,e){const i=this.bind(t);this.referenced=new Set(e),i.references.set(this.referenceOwner,new Set(this.referenced));const s=this.now(),n=new Set;for(const t of i.references.values())for(const e of t)n.add(e);const o={};for(const[t,e]of Object.entries(i.signed))n.has(t)&&s-e.at!!o[t]&&!o[t].pending))}markLoaded(t,e,i){const s=As(e);if(!s.startsWith("/api/houseplan/content/"))return;const n=this.bind(t).signed[s];if(n&&(!i||n.url===i)&&!n.loaded){n.loaded=!0;for(const e of[...this.bind(t).listeners])e()}}isReady(t,e){const i=As(e);if(!i.startsWith("/api/houseplan/content/"))return!0;const s=this.bind(t).signed[i];return!!s&&this.now()-s.att.id===e)}function Md(t="file"){const e="draw"===t;return{source:t,showBorders:e,showNames:e,displayTouched:!1}}function Cd(t,e){if(t.displayTouched)return{...t,source:e};const i="draw"===e;return{...t,source:e,showBorders:i,showNames:i}}function Dd(t,e,i){return{...t,[e]:i,displayTouched:!0}}function Pd(t,e,i){return[t[0]*e+t[1]*i+t[2],t[3]*e+t[4]*i+t[5]]}function Td(t,e){let i=0;for(const[s,n]of e){const e=Pd(t,s[0],s[1]);i=Math.max(i,Math.hypot(e[0]-n[0],e[1]-n[1]))}return i}const Rd=t=>{if(null==t||""===t)return null;const e=Number(t);return Number.isFinite(e)?e:null},Id=t=>{const e=t,i=Rd(Array.isArray(e)?e[0]:e?.x),s=Rd(Array.isArray(e)?e[1]:e?.y);return null==i||null==s?null:[i,s]};function Ad(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}if(e.length<3)return null;let i=0,s=0,n=0;for(let t=0;tt+e[0],0)/e.length,e.reduce((t,e)=>t+e[1],0)/e.length]:[s/(3*i),n/(3*i)]}function zd(t){if(!Array.isArray(t))return null;const e=[];for(const i of t){const t=Id(i);if(!t)return null;e.push(t)}if(e.length>1){const t=e[0],i=e[e.length-1];t[0]===i[0]&&t[1]===i[1]&&e.pop()}const i=Ad(e);if(!i)return null;const s=e.map(t=>t[0]),n=e.map(t=>t[1]);return{centroid:i,bbox:[Math.min(...s),Math.min(...n),Math.max(...s),Math.max(...n)]}}function Fd(t){let e=t;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;e=t.path??t.points??e}if(!Array.isArray(e)||!e.length)return[];let i=(e.some(t=>(t=>Array.isArray(t)?t.length>=2&&!Array.isArray(t[0])&&("object"!=typeof t[0]||null==t[0]):!!t&&"object"==typeof t&&("x"in t||"y"in t))(t))?[e]:e.filter(Array.isArray)).map(t=>t.map(Id).filter(t=>null!=t)).filter(t=>t.length>=2);i.length>64&&(i=i.slice(-64));const s=i.reduce((t,e)=>t+e.length,0);if(s<=4e3)return i.map(t=>t.slice());const n=4e3-2*i.length,o=i.map(t=>t.length-2),a=o.reduce((t,e)=>t+e,0),r=o.map(t=>n*t/a),l=r.map(Math.floor);let c=n-l.reduce((t,e)=>t+e,0);const h=r.map((t,e)=>({index:e,fraction:t-Math.floor(t)})).sort((t,e)=>e.fraction-t.fraction||t.index-e.index);for(let t=0;tfunction(t,e){if(e>=t.length)return t.slice();if(e<=2)return[t[0],t[t.length-1]];const i=[];for(let s=0;st.slice()),i=e[e.length-1];return i?(i.length>2?i.pop():e.pop(),e):[]}function Od(t){if(!t)return null;const e=t.vacuum_position||t.robot_position||null,i=e&&null!=Rd(e.x)&&null!=Rd(e.y)?{x:Rd(e.x),y:Rd(e.y),a:Rd(e.a??e.angle??e.theta)}:null,s=Fd(t.path?.path??t.path?.points??t.path),n=[],o=t.rooms,a=Array.isArray(o)?o.map((t,e)=>[String(t?.id??e),t]):o&&"object"==typeof o?Object.entries(o):[];for(const[t,e]of a){if(!e||"object"!=typeof e)continue;const i=String(e.name??e.label??"").trim(),s=[[Rd(e.cx),Rd(e.cy)],[Rd(e.center?.x),Rd(e.center?.y)],[Rd(e.x),Rd(e.y)]].find(([t,e])=>null!=t&&null!=e);let o=s?.[0]??null,a=s?.[1]??null;const r=zd(e.outline),l=Rd(e.x0),c=Rd(e.y0),h=Rd(e.x1),d=Rd(e.y1),p=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||r?.bbox||null;if(null!=o&&null!=a||!r||([o,a]=r.centroid),null!=o&&null!=a||!p||(o=(p[0]+p[2])/2,a=(p[1]+p[3])/2),i&&null!=o&&null!=a){const e={id:t,name:i,cx:o,cy:a};p&&([e.x0,e.y0,e.x1,e.y1]=p),n.push(e)}}const r=function(t){return String(t.map_name??t.current_map??t.map_index??t.selected_map??"default")}(t);return i||n.length||s.length?{pos:i,path:s,rooms:n,mapId:r}:null}function Ld(t,e,i){if(!t||!e)return null;const s=e.attributes||{},n=t.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,a=!!Id(s.vacuum_position??s.robot_position),r=!(!s.rooms||"object"!=typeof s.rooms),l=Fd(s.path?.path??s.path?.points??s.path).length>0,c=[s.map_name,s.current_map,s.map_index,s.selected_map].some(t=>null!=t),h="xiaomi_cloud_map_extractor"===o,d=r||l||c;let p=null;if(a?p="compatible":h?p="known_xcme_incomplete":d?p="partial":"camera"===n&&(p="camera"),!p)return null;const u=a?"camera"===n?300:200:h?100:d?50:0;return{entityId:t,name:String(s.friendly_name||t),platform:o,category:p,hasPosition:a,hasRooms:r,hasPath:l,hasMapId:c,score:u}}const Hd=t=>t.toLowerCase().replace(/[\s_\-.,]+/g,"");function Bd(t,e){const i=new Map(e.map(t=>[Hd(t.name),t])),s=[],n=[];for(const e of t){const t=i.get(Hd(e.name));t&&(s.push([[e.cx,e.cy],[t.cx,t.cy]]),n.push(e.name))}if(s.length<3)return null;const o=function(t){if(t.length<3)return null;let e=0,i=0,s=0,n=0,o=0,a=0,r=0,l=0,c=0,h=0,d=0,p=0;for(const[[u,_],[m,g]]of t){if(![u,_,m,g].every(Number.isFinite))return null;e+=u*u,i+=u*_,s+=u,n+=_*_,o+=_,a+=1,r+=u*m,l+=_*m,c+=m,h+=u*g,d+=_*g,p+=g}const u=[e,i,s,i,n,o,s,o,a],_=t=>{const[e,i,s,n,o,a,r,l,c]=u,h=e*(o*c-a*l)-i*(n*c-a*r)+s*(n*l-o*r);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-a*l)/h,(s*l-i*c)/h,(i*a-s*o)/h,(a*r-n*c)/h,(e*c-s*r)/h,(s*n-e*a)/h,(n*l-o*r)/h,(i*r-e*l)/h,(e*o-i*n)/h];return[d[0]*t[0]+d[1]*t[1]+d[2]*t[2],d[3]*t[0]+d[4]*t[1]+d[5]*t[2],d[6]*t[0]+d[7]*t[1]+d[8]*t[2]]},m=_([r,l,c]),g=_([h,d,p]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(s);return o?{matrix:o,matched:n,residual:Td(o,s)}:null}function qd(t,e,i){const s=t[t.length-1];if(s&&s[0]===e[0]&&s[1]===e[1])return t;if(t.push(e),t.length<=600)return t;let n=function(t,e){if(t.length<3)return t.slice();const i=new Uint8Array(t.length);i[0]=i[t.length-1]=1;const s=[[0,t.length-1]];for(;s.length;){const[n,o]=s.pop(),[a,r]=t[n],[l,c]=t[o],h=l-a,d=c-r,p=Math.hypot(h,d)||1e-9;let u=0,_=-1;for(let e=n+1;eu&&(u=i,_=e)}_>0&&u>e&&(i[_]=1,s.push([n,_],[_,o]))}const n=[];for(let e=0;e600&&(n=n.filter((t,e)=>e%2==0||e===n.length-1)),n}function Wd(t){return"cleaning"===t||"returning"===t||"on"===t}const jd={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Ud(t){const[e,i]=jd[t.rot]||[1,0],s=t.mir?-1:1;return[t.s*e*s,-t.s*i,t.ox,t.s*i*s,t.s*e,t.oy]}function Gd(t){const e=t[0]*t[4]-t[1]*t[3];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;const i=e<0,s=Math.sqrt(Math.abs(e));let n=180*Math.atan2(-t[1],t[4])/Math.PI;return n=(90*Math.round(n/90)%360+360)%360,{ox:t[2],oy:t[5],s:s,rot:n,mir:i}}function Vd(t,e,i,s){const[n,o]=Pd(Ud(e),i,s),a=Ud({...t,ox:0,oy:0}),[r,l]=Pd(a,i,s);return{...t,ox:n-r,oy:o-l}}function Kd(t){const e=t?.trail_mode;return"never"===e||"cleaning"===e||"always"===e?e:!1===t?.trail?"never":"cleaning"}const Yd={offStates:["off"],unknownUsesToggle:!0},Jd={light:Yd,switch:Yd,fan:Yd,humidifier:Yd,input_boolean:Yd,automation:Yd,remote:Yd,group:Yd,climate:{...Yd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Yd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Yd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Yd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Yd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function Xd(t){return t.slice(0,t.indexOf("."))}function Zd(t,e,i){if(!t?.services||"object"!=typeof t.services)return!1;const s=t.services?.[e];return!!s&&Object.prototype.hasOwnProperty.call(s,i)}function Qd(t,e,i){return Zd(t,e,i)?{domain:e,service:i}:Zd(t,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function tp(t,e){return t?.entities?.[e]||null}function ep(t,e,i){const s=t?.states?.[i],n=tp(e,i);return s?.attributes?.friendly_name||n?.name||n?.original_name||i}function ip(t,e){const i=tp(t,e);if(null!=i?.disabled_by)return!0;const s=i?.device_id?t?.devices?.[i.device_id]:null;return null!=s?.disabled_by}function sp(t,e){const i=t?.attributes?.supported_features;if(null==i||""===i)return!1;const s=Number(i);return Number.isFinite(s)&&(s&e)===e}function np(t,e,i){const s=Xd(i);if("lock"===s||"alarm_control_panel"===s)return!0;if("cover"!==s)return!1;const n=t?.states?.[i],o=tp(e,i),a=String(n?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Ui.has(a)}function op(t,e,i,s,n){return{ref:i,entityId:s,name:s?ep(t,e,s):null,reason:n}}function ap(t,e,i,s,n,o=null){return{target:null,skipped:op(t,e,i,s,n),semantics:o,nextEffect:null,command:null}}function rp(t,e,i,s,n=i){const o=Xd(i);if("cover"!==o&&"valve"!==o)return function(t,e,i,s,n=i){const o=Xd(i),a=t?.states?.[i];if(ip(e,i))return ap(t,e,n,i,"ha-disabled","power");if(np(t,e,i))return ap(t,e,n,i,"secure");if(!a)return ap(t,e,n,i,"missing","power");if("unavailable"===a.state)return ap(t,e,n,i,"unavailable","power");const r=Jd[o];if(!r)return ap(t,e,n,i,"unsupported");let l,c;if("unknown"===a.state||""===a.state){if(!r.unknownUsesToggle)return ap(t,e,n,i,"unsupported","power");l="toggle",c="toggle"}else r.offStates.includes(String(a.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=r.featureMasks?.[c];if(h&&!sp(a,h))return ap(t,e,n,i,"unsupported","power");const d=Qd(t,o,c);return d?{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:ap(t,e,n,i,"unsupported","power")}(t,e,i,s,n);if(ip(e,i))return ap(t,e,n,i,"ha-disabled",o);if(np(t,e,i))return ap(t,e,n,i,"secure",o);const a=t?.states?.[i];if(!a)return ap(t,e,n,i,"missing",o);if("unavailable"===a.state)return ap(t,e,n,i,"unavailable",o);const r=function(t,e,i){const s=String(i?.state||""),n="closed"===s?{service:`open_${e}`,effect:"open",feature:1}:"open"===s?{service:`close_${e}`,effect:"close",feature:2}:"opening"===s||"closing"===s?{service:`stop_${e}`,effect:"stop",feature:8}:null;return n&&sp(i,n.feature)&&Zd(t,e,n.service)?n:sp(i,3)&&Zd(t,e,"toggle")?{service:"toggle",effect:"toggle"}:null}(t,o,a);if(!r)return ap(t,e,n,i,"unsupported",o);return{target:{entityId:i,name:ep(t,e,i),state:String(a.state||""),via:s},skipped:null,semantics:o,nextEffect:r.effect,command:{domain:o,service:r.service,data:{entity_id:i}}}}function lp(t){return"entity"===t.bindingKind?t.bindingRef&&Ms(t.bindingRef)?[t.bindingRef]:[]:"virtual"===t.bindingKind?[]:to(t)}function cp(t){const e=t.marker?.toggle_entity;return e&&lp(t).includes(e)?e:null}function hp(t,e,i){const s=function(t,e){if("entity"===t.bindingKind&&t.bindingRef){const e=t.marker?.light_entity?eo(t):null;return[...new Set([e,t.bindingRef].filter(t=>!!t))]}const i=t.entities.length?t.entities:t.allEntities||[],s=t.marker?.light_entity||t.primary&&Ms(t.primary)?eo(t):null;return[...new Set([s,...Yn(e,i)].filter(t=>!!t))]}(i,e);if(!s.length)return null;const n="entity"===i.bindingKind?"binding":"device-role";if("binding"===n)return rp(t,e,s[0],n);let o=null,a=null;for(const i of s){const s=rp(t,e,i,n);if(s.command)return s;const r=s.skipped?.reason;if("missing"===r||"unavailable"===r||"secure"===r)return s;"ha-disabled"!==r?o||=s:a||=s}return o||a}function dp(t){const e=t.skipped?.reason;return"missing"===e?"unavailable":e||"unsupported"}function pp(t,e){return{origin:t,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:e,nextEffect:null,command:null}}function up(t,e){return"cover"===t||"toggle"===t?"toggle":"more-info"===t||"run"===t||"info"===t?t:(null==t||""===t)&&"light"===e?"toggle":"info"}function _p(t,e){return{origin:t,kind:"single",semantics:e.semantics,targets:e.target?[e.target]:[],skippedTargets:e.skipped?[e.skipped]:[],noneReason:e.command?null:dp(e),nextEffect:e.nextEffect,command:e.command}}function mp(t,e,i,s=[]){const n=new Map,o=[],a=new Set,r=t=>{const e=`${t.ref}\n${t.entityId||""}\n${t.reason}`;a.has(e)||(a.add(e),o.push(t))};for(const t of s)r(t);for(const s of i){const i=rp(t,e,s.entityId,s.via,s.ref);i.target?n.set(s.entityId,n.get(s.entityId)||i.target):i.skipped&&r(i.skipped)}const l=[...n.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(t=>"secure"===t.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(t=>"on"===t.state)?"turn_off":"turn_on",h=Qd(t,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(t=>t.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>op(t,e,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function gp(t){return String(t.marker?.id||t.id||"")}function fp(t){const{hass:e,device:i}=t,s=t.registryHass||e,n=function(t){return"toggle"===t.tapAction?"explicit-toggle":"cover"===t.tapAction?"legacy-cover":!t.tapAction&&t.primary?.startsWith("light.")?"default-light":null}(i);if(!n)return null;const o=i.marker;if("explicit-toggle"===n&&yn(o)){const e=String(o?.id||i.id||""),s=ro(t.devices).get(e);if(s)return function(t,e){const i=t.registryHass||t.hass;return mp(t.hass,i,e.driverEids.map(t=>({entityId:t,via:"control-marker-driver",ref:`marker:${e.markerId}`})))}(t,s);const a=bn(o,t.virtualLights);return{origin:n,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:a?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:a?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===n){if(Zn(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(t,e=null){const{hass:i,device:s,devices:n}=t,o=t.registryHass||i,a=Zn(s.marker?.binding,s.marker?.controls??s.controls,s.entities),r=t.lightSources||ho(i,n,null,t.virtualLights),l=new Map;for(const t of r){if(!t.key.startsWith("marker:"))continue;const e=l.get(t.key)||[];e.push(t),l.set(t.key,e)}const c=ro(n),h=new Map;for(const t of n){const e=String(t.marker?.id||t.id||"");e&&h.set(e,t)}const d=[],p=[];e&&d.push({entityId:e,via:"entity"===s.bindingKind?"binding":"device-role",ref:e});for(const t of a){if(!t.startsWith("marker:")){Ms(t)?d.push({entityId:t,via:"control-entity",ref:t}):p.push(op(i,o,t,t.includes(".")?t:null,"unsupported"));continue}const e=l.get(t)||[];if(!e.length){const e=h.get(t.slice(7));if("ha_disabled"===e?.bindingStatus?.kind){const s=e.bindingStatus.allEntityIds[0]||null;p.push({ref:t,entityId:s,name:e.name||(s?ep(i,o,s):null),reason:"ha-disabled"})}else p.push(op(i,o,t,null,"missing"));continue}const n=[...new Set(e.flatMap(t=>t.serviceEids))];if(n.length){for(const e of n)d.push({entityId:e,via:"control-entity",ref:t});continue}const a=e.some(t=>t.passive),r=t.slice(7),u=gp(s),_=c.get(r)?.controllers.find(t=>gp(t.device)===u);if(a&&_?.driverEids.length)for(const e of _.driverEids)d.push({entityId:e,via:"control-marker-driver",ref:t});else p.push(op(i,o,t,null,a?"missing":"unsupported"))}return mp(i,o,d,p)}(t,cp(i))}if("legacy-cover"===n){const t=i.entities.find(t=>t.startsWith("cover."))||i.allEntities?.find(t=>t.startsWith("cover."));return t?_p(n,rp(e,s,t,"device-role")):pp(n,"no-actionable-entity")}const a=cp(i),r=a?rp(e,s,a,"entity"===i.bindingKind?"binding":"device-role"):hp(e,s,i);return r?_p(n,r):pp(n,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function vp(t){if(!t)return[];const e=Array.isArray(t.data.entity_id)?t.data.entity_id:[t.data.entity_id];return[...new Set(e)].sort()}function yp(t){return t?t.operation?t.operation:t.command?{kind:"ha-service",command:t.command}:null:null}const bp=new Set(["missing","ha-disabled","unavailable"]);function wp(t,e){const i=yp(t),s=yp(e);return!(!i||!s||i.kind!==s.kind)&&("virtual-light"===i.kind&&"virtual-light"===s.kind?i.markerId===s.markerId:"ha-service"===i.kind&&"ha-service"===s.kind&&function(t,e){const i=vp(t),s=vp(e);return i.length===s.length&&i.every((t,e)=>t===s[e])}(i.command,s.command))}const kp=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]);function xp(t,e=5,i=5){return gl(t.cm,e,i)/2}function $p(t,e,i=1,s=5,n=5,o=0){const a=t.host;if(!a||"partition"!==a.kind||"string"!=typeof a.id||!a.id)return{resolved:null,reason:"invalid-host"};const r=e.find(t=>t.id===a.id);if(!r)return{resolved:null,reason:"missing-partition"};if(!kp(r.a)||!kp(r.b)||!Number.isFinite(a.t)||a.t<0||a.t>1)return{resolved:null,reason:"invalid-position"};const l=r.b[0]-r.a[0],c=r.b[1]-r.a[1],h=Math.hypot(l,c),d=Number(t.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const p=a.t*h;if(p-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const u=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:t,host:a,partition:r,center:[r.a[0]+l*a.t,r.a[1]+c*a.t],angle:m,length:d,depth:gl(r.cm,s,n),t:a.t,axis:{a:[r.a[0],r.a[1]],b:[r.b[0],r.b[1]],ux:u,uy:_,length:h}}}}function Sp(t,e,i=1,s=5,n=5){return $p(t,e,i,s,n,0)}function Mp(t,e,i=1,s=5,n=5){const o=t.host,a="partition"===o?.kind?e.find(t=>t.id===o.id):void 0;if(!a)return Sp(t,e,i,s,n);const r=$p(t,e,i,s,n,xp(a,s,n));return"does-not-fit"===r.reason?{resolved:null,reason:"does-not-fit-jamb"}:r}function Cp(t,e){return!t||(t.length!==e.length||t.host?.kind!==e.host?.kind||t.host?.id!==e.host?.id||t.host?.t!==e.host?.t)}function Dp(t){const{center:e,length:i,axis:s,host:n}=t,o=i/2;return{hostId:n.id,a:[e[0]-s.ux*o,e[1]-s.uy*o],b:[e[0]+s.ux*o,e[1]+s.uy*o],depth:t.depth}}function Pp(t,e=!1){const i=e?1:-1,s=t.depth/2;return{ox:-t.axis.uy*i*s,oy:t.axis.ux*i*s,cm:t.partition.cm,side:i}}function Tp(t,e,i){return t.flatMap(t=>!kp(t.a)||!kp(t.b)||Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])<=1e-9?[]:[{roomId:"",a:[t.a[0],t.a[1]],b:[t.b[0],t.b[1]],key:`partition:${t.id}`,kind:"outer",cm:t.cm,open:!1,half:gl(t.cm,e,i)/2,partitionHost:{kind:"partition",id:t.id}}])}function Rp(t,e,i){const{center:s,length:n,axis:o}=t,a=n/2,r=e.flatMap(t=>{if(!t.kind||t.open)return[];const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(e,n);if(!(r>i))return[];const l=e/r,c=n/r;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((s[0]-t.a[0])*c-(s[1]-t.a[1])*l)>i)return[];const h=t=>(t[0]-s[0])*o.ux+(t[1]-s[1])*o.uy,d=h(t.a),p=h(t.b),u=Math.max(-a,Math.min(d,p)),_=Math.min(a,Math.max(d,p));return _>=u-i?[[u,_]]:[]});if(!r.length)return!1;r.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);let l=-a;for(const[t,e]of r){if(t>l+i)return!1;if(l=Math.max(l,e),l>=a-i)return!0}return!1}function Ip(t,e,i){return{...t,x:e.center[0]/i,y:e.center[1]/i,angle:e.angle}}const Ap=.001;function zp(t){return!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function Fp(t){return`${t[0].toFixed(6)},${t[1].toFixed(6)}`}function Ep(t,e,i){return Math.abs(t[0]-e[0])"room"!==t.kind&&i.some(i=>i!==t&&function(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>i))return!1;const a=s/o,r=n/o,l=e=>Math.abs((e[0]-t.a[0])*r-(e[1]-t.a[1])*a);if(l(e.a)>i||l(e.b)>i)return!1;const c=(e.a[0]-t.a[0])*a+(e.a[1]-t.a[1])*r,h=(e.b[0]-t.a[0])*a+(e.b[1]-t.a[1])*r;return Math.min(o,Math.max(c,h))-Math.max(0,Math.min(c,h))>i}(t,i,e))),n=s.map(t=>{const[e,i]=Np(t.a,t.b);return{a:e,b:i,key:`hidden|${Lp(t,e,i)}`,sourceKind:t.kind,sourceId:t.id}}).sort((t,e)=>t.key.localeCompare(e.key)),o=s.flatMap(t=>[t.a,t.b].map((e,i)=>({point:[e[0],e[1]],key:`hidden|${Op(t)}|endpoint-${i}`,sourceKind:t.kind,sourceId:t.id}))).sort((t,e)=>t.key.localeCompare(e.key));return{segments:n,endpoints:o}}function Wp(t){const e=t.epsilon??Ap,i=t.roomCuts||[],s=new Map;for(const e of t.partitionCuts||[]){if("string"!=typeof e.hostId||!e.hostId||!zp(e.a)||!zp(e.b))continue;const t=s.get(e.hostId)||[];t.push([e.a[0],e.a[1],e.b[0],e.b[1]]),s.set(e.hostId,t)}const n=[];for(const[e,s]of pi(t.space.rooms).entries())s.length<4||n.push({a:[s[0],s[1]],b:[s[2],s[3]],kind:"room",id:`room-edge-${e}`,cuts:i});for(const e of t.space.room_drafts||[])if(e.id!==t.activeDraftId)for(let t=0;t+1Bp(s,t,e)))continue;const t=Fp(s);a.has(t)||a.set(t,{point:[s[0],s[1]],key:t})}}}return{segments:[...o.values()].sort((t,e)=>t.key.localeCompare(e.key)),endpoints:[...a.values()].sort((t,e)=>t.key.localeCompare(e.key))}}function jp(t,e,i){return e.some(e=>zp(e)&&Ep(t,e,i))}function Up(t,e,i){if(!i)return!0;const s=t-i.distance;return s<-1e-9||Math.abs(s)<=1e-9&&e.localeCompare(i.key)<0}function Gp(t,e,i){const s=i.epsilon??Ap,n=i.excludePoints||[],o=[...t.endpoints,...(i.extraEndpoints||[]).filter(t=>zp(t.point)).map(t=>({point:[t.point[0],t.point[1]],key:t.key}))],a=new Map;for(const t of o){if(jp(t.point,n,s))continue;const e=Fp(t.point),i=a.get(e);(!i||t.key.localeCompare(i.key)<0)&&a.set(e,t)}return[...a.values()].map(t=>({kind:"endpoint",point:[...t.point],key:t.key,distance:Math.hypot(e[0]-t.point[0],e[1]-t.point[1])})).filter(t=>t.distance<=i.tolerance).sort((t,e)=>t.distance-e.distance||t.key.localeCompare(e.key))}function Vp(t,e){if(!t.length)return null;if(e>0){const i=new Set;for(let s=0;s1)return{kind:"ambiguous",candidate:null,conflicts:t.filter(t=>i.has(t.key)).map(t=>({point:[...t.point],key:t.key}))}}return{kind:"resolved",candidate:t[0],conflicts:[]}}function Kp(t,e,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=Math.hypot(s,n);if(!(o>0))return[...t.a];const a=s/o,r=n/o,l=Math.max(0,Math.min(o,(e[0]-t.a[0])*a+(e[1]-t.a[1])*r)),c=i>0?Math.max(0,Math.min(o,Math.round(l/i)*i)):l;return[t.a[0]+a*c,t.a[1]+r*c]}function Yp(t,e,i){if(!(zp(e)&&zp(i.anchor)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=function(t,e){const i=e[0]-t[0],s=e[1]-t[1];if(!(Math.hypot(i,s)>Number.EPSILON))return null;const n=Math.round(Math.atan2(s,i)/(Math.PI/4))*(Math.PI/4);return[Math.cos(n),Math.sin(n)]}(i.anchor,e);if(!n)return{kind:"none",candidate:null,conflicts:[]};const o=Gp(t,e,i).filter(t=>function(t,e,i,s){const n=t[0]-e[0],o=t[1]-e[1];return n*i[0]+o*i[1]>s&&Math.abs(n*i[1]-o*i[0])<=s*Math.max(Math.hypot(n,o),1)}(t.point,i.anchor,n,s)),a=Vp(o,i.distinguishTolerance||0);if(a)return a;let r=null;for(const o of t.segments){const t=o.b[0]-o.a[0],a=o.b[1]-o.a[1],l=o.a[0]-i.anchor[0],c=o.a[1]-i.anchor[1],h=n[0]*a-n[1]*t;let d=null;if(Math.abs(h)<=s*Math.max(Math.hypot(t,a),1)){if(Math.abs(l*n[1]-c*n[0])>s*Math.max(Math.hypot(l,c),1))continue;const t=[o.a,o.b].map(t=>({point:t,along:(t[0]-i.anchor[0])*n[0]+(t[1]-i.anchor[1])*n[1]})).filter(t=>t.along>s).sort((t,e)=>t.along-e.along);t.length&&(d=[...t[0].point])}else{const e=(l*a-c*t)/h,o=(l*n[1]-c*n[0])/h;e>s&&o>=-s&&o<=1+s&&(d=[i.anchor[0]+n[0]*e,i.anchor[1]+n[1]*e])}if(!d)continue;const p=Math.hypot(e[0]-d[0],e[1]-d[1]);p>i.tolerance||jp(d,i.excludePoints||[],s)||!Up(p,o.key,r)||(r={kind:"line",point:d,key:o.key,distance:p,segment:o})}return r?{kind:"resolved",candidate:r,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}const Jp=.001;function Xp(t,e,i,s){const n=Number.isFinite(t)&&t>0?Math.floor(t):0,o=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null,a=o(i),r=o(s)??0,l=[];let c=null;for(let t=0;t=2&&Number.isFinite(t[0])&&Number.isFinite(t[1])}function tu(t,e,i,s){return t*s-e*i}function eu(t){let e=0;for(let i=0;it.localeCompare(e)),e[0]}function au(t,e,i){const s=[...t];for(let t=!0;t&&s.length>=3;){t=!1;for(let n=0;n=0){s.splice(n,1),t=!0;break}}}return s}function ru(t,e){const i=t.map(t=>Math.max(0,Math.min(1,t))).sort((t,e)=>t-e),s=[];for(const t of i)(!s.length||Math.abs(t-s[s.length-1])>e)&&s.push(t);return s}function lu(t,e){return[t.a[0]+(t.b[0]-t.a[0])*e,t.a[1]+(t.b[1]-t.a[1])*e]}function cu(t,e,i){const s=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n:0}(t,e);if(s<-i||s>1+i)return null;const n=lu(e,s);return Math.hypot(n[0]-t[0],n[1]-t[1])<=i?Math.max(0,Math.min(1,s)):null}function hu(t,e,i,s,n){const o=t.b[0]-t.a[0],a=t.b[1]-t.a[1],r=e.b[0]-e.a[0],l=e.b[1]-e.a[1],c=e.a[0]-t.a[0],h=e.a[1]-t.a[1],d=tu(o,a,r,l),p=Math.max(Math.hypot(o,a),Math.hypot(r,l),1);if(Math.abs(d)>n*p){const t=tu(c,h,r,l)/d,e=tu(c,h,o,a)/d;return void(t>=-n&&t<=1+n&&e>=-n&&e<=1+n&&(i.push(Math.max(0,Math.min(1,t))),s.push(Math.max(0,Math.min(1,e)))))}if(!(Math.abs(tu(c,h,o,a))>n*p)){for(const s of[e.a,e.b]){const e=cu(s,t,n);null!=e&&i.push(e)}for(const i of[t.a,t.b]){const t=cu(i,e,n);null!=t&&s.push(t)}}}function du(t){let e=t+1|0;return e^=e<<13,e^=e>>>17,e^=e<<5,e>>>0}function pu(t,e){return t.minY-e.minY||t.index-e.index}function uu(t){return t.subtreeMaxY=Math.max(t.item.maxY,t.left?.subtreeMaxY??-1/0,t.right?.subtreeMaxY??-1/0),t}function _u(t){const e=t.right;return t.right=e.left,e.left=uu(t),uu(e)}function mu(t){const e=t.left;return t.left=e.right,e.right=uu(t),uu(e)}function gu(t,e){return t?(pu(e,t.item)<0?(t.left=gu(t.left,e),t.left.priority0)t.right=fu(t.right,e);else{if(!t.left)return t.right;if(!t.right)return t.left;t.left.priority=e&&vu(t.left,e,i,s),t.item.minY<=i&&t.item.maxY>=e&&s.push(t.item),t.item.minY<=i&&vu(t.right,e,i,s))}function yu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=t.filter(t=>Qp(t.a)&&Qp(t.b)&&"string"==typeof t.key&&t.key.length>0&&Math.hypot(t.b[0]-t.a[0],t.b[1]-t.a[1])>i),n=s.map(()=>[0,1]);!function(t,e,i){const s=t.map((t,e)=>({index:e,minX:Math.min(t.a[0],t.b[0])-i,maxX:Math.max(t.a[0],t.b[0])+i,minY:Math.min(t.a[1],t.b[1])-i,maxY:Math.max(t.a[1],t.b[1])+i})),n=[...s].sort((t,e)=>t.minX-e.minX||t.minY-e.minY||t.index-e.index),o=[...s].sort((t,e)=>t.maxX-e.maxX||t.index-e.index),a=new Set;let r=null,l=0;for(const s of n){for(;lt.index-e.index);for(const o of n)hu(t[o.index],t[s.index],e[o.index],e[s.index],i);a.add(s.index),r=gu(r,s)}}(s,n,i);const o=new Map;for(let t=0;t({key:t,a:e.a,b:e.b,sourceKeys:[...e.sourceKeys].sort((t,e)=>t.localeCompare(e))})).sort((t,e)=>t.key.localeCompare(e.key))}function bu(t,e=.001){const i=Number.isFinite(e)&&e>0?e:Jp,s=yu(t,i),n=new Map,o=new Map,a=new Map(s.map(t=>[t.key,t]));for(const t of s){const e=su(t.a,i),s=su(t.b,i);n.set(e,t.a),n.set(s,t.b),o.has(e)||o.set(e,new Set),o.has(s)||o.set(s,new Set),o.get(e).add(s),o.get(s).add(e)}const r=new Map;for(const[t,e]of o){const i=n.get(t);r.set(t,[...e].sort((t,e)=>{const s=n.get(t),o=n.get(e);return Math.atan2(s[1]-i[1],s[0]-i[0])-Math.atan2(o[1]-i[1],o[0]-i[0])||t.localeCompare(e)}))}const l=new Set,c=new Map,h=(t,e)=>`${t}>${e}`;for(const t of s){const e=[su(t.a,i),su(t.b,i)];for(const[t,o]of[e,[e[1],e[0]]]){if(l.has(h(t,o)))continue;const e=[],d=[];let p=t,u=o,_=!1;for(let i=0;i<=2*s.length+2;i++){const i=h(p,u);if(l.has(i)){_=p===t&&u===o;break}l.add(i),e.push(p),d.push(nu(p,u));const s=r.get(u)||[],n=s.indexOf(p);if(n<0||!s.length)break;if(p=u,u=s[(n-1+s.length)%s.length],p===t&&u===o){_=!0;break}}if(!_||new Set(e).size<3||new Set(e).size!==e.length)continue;const m=e.map(t=>n.get(t)),g=eu(m);if(!(g>i*i))continue;const f=ou(au(e,n,i)),v=new Set;for(const t of d)for(const e of a.get(t)?.sourceKeys||[])v.add(e);const y={ring:m,key:f,area:g,atomKeys:[...d],sourceKeys:[...v].sort((t,e)=>t.localeCompare(e))};c.has(f)||c.set(f,y)}}return{atoms:s,faces:[...c.values()].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))}}function wu(t,e,i=.001){if(!Qp(e))return null;const s=t.faces.filter(t=>{if(t.ring.some((s,n)=>function(t,e,i,s){const n=i[0]-e[0],o=i[1]-e[1],a=n*n+o*o;if(!(a>0))return Math.hypot(t[0]-e[0],t[1]-e[1])<=s;const r=((t[0]-e[0])*n+(t[1]-e[1])*o)/a;return!(r<0||r>1)&&Math.hypot(e[0]+n*r-t[0],e[1]+o*r-t[1])<=s}(e,s,t.ring[(n+1)%t.ring.length],i)))return!1;let s=!1;for(let i=0,n=t.ring.length-1;ie[1]!=a[1]>e[1]&&e[0]<(a[0]-o[0])*(e[1]-o[1])/(a[1]-o[1])+o[0]&&(s=!s)}return s});return[...s].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key))[0]||null}function ku(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n,a=o>0?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o)):0;return Math.hypot(e[0]+s*a-t[0],e[1]+n*a-t[1])}function xu(t,e,i=.5){let s=Math.abs(t-e)%180;return s>90&&(s=180-s),s<=i}function $u(t,e,i,s){const n=t.filter(t=>"outer"===t.kind&&!t.open&&t.cm>0).map(t=>({interval:t,reusePartitionId:e.find(e=>function(t,e,i){return!(Math.abs(t.cm-e.cm)>1e-6)&&(xu(180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI,180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI,.001)&&ku(e.a,t.a,t.b)<=i&&ku(e.b,t.a,t.b)<=i)}(e,t,s))?.id||null})),o=new Map;for(const e of i){if("partition"===e.host?.kind)continue;const i=t.map(t=>{const i=180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI;return{interval:t,distance:xu(e.angle,i)?ku([e.x,e.y],t.a,t.b):1/0}}).filter(t=>t.distance<=s).sort((t,e)=>t.distance-e.distance||t.interval.key.localeCompare(e.interval.key)),n=i[0]?.interval;"outer"===n?.kind&&!n.open&&n.cm>0&&o.set(e.id,n.key)}return{materialize:n,openingIntervals:o,removeOpeningIds:[...o.keys()].sort((t,e)=>t.localeCompare(e))}}function Su(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;return n>0?Math.max(0,Math.min(1,((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n)):0}const Mu=t=>!t.key.startsWith("static:room|");function Cu(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=i*i+s*s;if(!(n>0))return null;const o=((t[0]-e.a[0])*i+(t[1]-e.a[1])*s)/n,a=[e.a[0]+i*o,e.a[1]+s*o];return{point:a,t:o,distance:Math.hypot(a[0]-t[0],a[1]-t[1])}}function Du(t,e){return e>0?Math.hypot(t[0]-Math.round(t[0]/e)*e,t[1]-Math.round(t[1]/e)*e):0}function Pu(t,e,i){if(Mu(t.source)!==Mu(e.source))return Mu(t.source)?t:e;const s=Du(t.point,i),n=Du(e.point,i);return Math.abs(s-n)>1e-9?s>n?t:e:function(t,e){return t[0]-e[0]||t[1]-e[1]}(t.point,e.point)>0?t:e}function Tu(t){return[t.from[0],t.from[1],t.to[0],t.to[1],t.targetKind].map(t=>"number"==typeof t?t.toFixed(6):t).join("|")}function Ru(t,e){return t.map(t=>t.key!==e.sourceKey?t:{...t,[e.endpoint]:[...e.to]})}function Iu(t,e){const i=e.epsilon??.001;if(!(e.maxDistance>=0)||!e.point&&!e.requiredSourceKey)return{kind:"none"};const s=new Map,n=t.flatMap(t=>[{source:t,endpoint:"a",point:t.a},{source:t,endpoint:"b",point:t.b}]);for(let t=0;ti)||l>e.maxDistance)continue;const c=Pu(a,r,e.gridStep||0),h=c===a?r:a;if(!Mu(c.source))continue;const d={sourceKey:c.source.key,endpoint:c.endpoint,from:[c.point[0],c.point[1]],to:[h.point[0],h.point[1]],targetSourceKey:h.source.key,targetKind:"endpoint",distance:l};s.set(Tu(d),d)}for(const o of n)if(Mu(o.source))for(const n of t){if(n===o.source)continue;const t=Cu(o.point,n);if(!t||t.t<=i||t.t>=1-i||!(t.distance>i)||t.distance>e.maxDistance)continue;const a={sourceKey:o.source.key,endpoint:o.endpoint,from:[o.point[0],o.point[1]],to:t.point,targetSourceKey:n.key,targetKind:"line",distance:t.distance};s.set(Tu(a),a)}const o=[];for(const n of s.values()){const s=bu(Ru(t,n),i),a=e.point?wu(s,e.point,i):s.faces.find(t=>!e.requiredSourceKey||t.sourceKeys.includes(e.requiredSourceKey))||null;a&&o.push({proposal:n,face:a})}if(o.sort((t,e)=>t.proposal.distance-e.proposal.distance||Tu(t.proposal).localeCompare(Tu(e.proposal))),!o.length)return{kind:"none"};return new Set(o.map(t=>`${Tu(t.proposal)}|${t.face.key}`)).size>1?{kind:"ambiguous",proposals:o.map(t=>t.proposal)}:{kind:"repair",...o[0]}}const Au=1e-5;function zu(t){const e=t.map(()=>[]);for(let i=0;i=1-1e-9||p<=1e-9||p>=1-1e-9||(e[i].push(d),e[a].push(p))}}const i=[];for(let s=0;st-e),1];for(let t=1;t{const i=e[2]-e[0],s=e[3]-e[1],n=i*i+s*s;if(!(n>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const o=Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/n));return Math.hypot(t[0]-(e[0]+o*i),t[1]-(e[1]+o*s))},Nu=(t,e,i,s)=>{const n=s[2]-s[0],o=s[3]-s[1],a=e*o-i*n;if(Math.abs(a)<1e-12)return 1/0;const r=s[0]-t[0],l=s[1]-t[1],c=(r*o-l*n)/a;if(!(c>1e-9))return 1/0;const h=(r*i-l*e)/a;return h<-1e-9||h>1+1e-9?1/0:c};function Ou(t,e,i,s=96){if(!(e>0&&Number.isFinite(t[0])&&Number.isFinite(t[1])))return[];const n=[];for(const s of i){if(!s||s.length<4)continue;if(![s[0],s[1],s[2],s[3]].every(Number.isFinite))continue;const i=Eu(t,s);if(i<1e-7)return[];i>e||n.push(s)}const o=[],a=Math.max(12,Math.round(s));for(let t=0;tt-e);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const s=Math.cos(i),o=Math.sin(i);let a=e;for(const e of n){const i=Nu(t,s,o,e);i=3?l:[]}class Lu extends ht{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(t){this._config=t}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const t=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(t?.config?.spaces||[]).map(t=>({value:t.id,label:t.title||t.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return ra(this.hass,this._config?.language)}get _floorToken(){const t=this._config?.floor;return"number"==typeof t?`__houseplan_yaml_floor_index__:${String(t)}`:null}get _formData(){const t={...this._config},e=this._floorToken;return e?t.floor=e:Object.prototype.hasOwnProperty.call(t,"floor")||(t.floor=""),t}get _schema(){const t=this._spaces||[],e=this._lang,i=[{value:"",label:la(e,"editor.floor_none")}],s=this._floorToken;s&&i.push({value:s,label:la(e,"editor.floor_index",{index:String(this._config?.floor)})});const n="string"==typeof this._config?.floor?this._config.floor:"";n&&!t.some(t=>t.value===n)&&i.push({value:n,label:n}),i.push(...t);const o="string"==typeof this._config?.default_floor?this._config.default_floor:"",a=[...t];return o&&!t.some(t=>t.value===o)&&a.unshift({value:o,label:o}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:i}}},t.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:a}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:[{value:"",label:la(e,"editor.lang_auto")},{value:"en",label:la(e,"editor.lang_en")},{value:"ru",label:la(e,"editor.lang_ru")}]}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return G;this._loadSpaces();const t=this._lang,e={title:la(t,"editor.title"),floor:la(t,"editor.floor"),default_floor:la(t,"editor.default_floor"),language:la(t,"editor.language"),icon_size:la(t,"editor.icon_size"),show_temperature:la(t,"editor.show_temperature"),live_states:la(t,"editor.live_states"),show_signal:la(t,"editor.show_signal"),kiosk:la(t,"editor.kiosk"),cycle:la(t,"editor.cycle")},i=this._schema,s=function(t,e,i){if(!i||null===e)return null;const s="string"==typeof t?.default_floor?t.default_floor:"";return!s||e.some(t=>t.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),n=t=>W`${t.visibleLabel}`:G}
${t?.content||G}
- `}afterRender(){const t=this.host.root();this._blocked&&(this._openGroupId?this.closeGroup(!1):"palette"===this._currentModel?.kind&&this._currentModel.dismiss?.()),this._syncGlobalDismissListener();const e=t.querySelector(".editor-secondary"),i=this._renderedContext,s=e?.dataset.contextId||"";if(s&&i&&s!==i&&!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches&&(this._contentAnimation?.cancel(),this._contentAnimation=e?.querySelector(".editor-secondary-content")?.animate([{opacity:.35,transform:"translateY(-4px)"},{opacity:1,transform:"translateY(0)"}],{duration:100,easing:"ease-out"})),this._renderedContext=s,i&&s!==i&&this._focusOwned){const i=s?e?.querySelector('[tabindex="0"], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'):t.querySelector(".editbar-tools");i?.focus?.(),this._focusOwned=!!s}if("palette"===this._currentModel?.kind&&this._currentModel.launcherId){const e=[...t.querySelectorAll("[data-editor-palette]")].find(t=>t.dataset.editorPalette===this._currentModel?.launcherId);e&&null!==e.offsetParent||this._currentModel.dismiss?.()}if(!this._openGroupId)return;const n=[...t.querySelectorAll("[data-editor-group]")].find(t=>t.dataset.editorGroup===this._openGroupId);n&&null!==n.offsetParent||this.closeGroup(!0)}handleOutsideDismiss(t){if(q_(t,t=>t.hasAttribute("data-editor-navigation")))return"pointerdown"===t.type?this.closeForNavigation():"click"===t.type&&this._dismissPointerTarget&&this._clearDismissClick(),!1;if("click"===t.type&&this._dismissPointerTarget){return!!(t.composedPath?.()||[t.target]).includes(this._dismissPointerTarget)&&(this._clearDismissClick(),t.preventDefault(),t.stopImmediatePropagation(),!0)}const e=this._openGroupId||this._blocked||"palette"!==this._currentModel?.kind?null:this._currentModel;if("pointerdown"===t.type&&(this._openGroupId||e)){const i=q_(t,t=>t.classList.contains("editor-secondary")),s=q_(t,t=>!!t.dataset.editorGroup),n=q_(t,t=>!!t.dataset.editorPalette),o=q_(t,t=>t.classList.contains("stage"));if(!(i||s||n||"stay-open-on-canvas"===e?.dismissPolicy&&o))return t.preventDefault(),t.stopImmediatePropagation(),this._dismissPointerTarget=t.target,clearTimeout(this._dismissTimer),this._dismissTimer=window.setTimeout(()=>{this._clearDismissClick()},800),this._openGroupId?this.closeGroup(!1):e?.dismiss?.(),this._syncGlobalDismissListener(),!0}return!1}_activateGroupItem(t,e,i){if(t.id!==this._openGroupId)return;const s=t.items.find(t=>t.id===e);if(!s||s.disabled)return;const n="toggle"===s.role&&"stay-open"===s.closePolicy,o=0===i.detail;n||(this._openGroupId=null,this.host.requestUpdate(),this._syncGlobalDismissListener()),s.invoke(),!n&&o&&this.host.updateComplete().then(()=>{const e=[...this.host.root().querySelectorAll("[data-editor-group]")].find(e=>e.dataset.editorGroup===t.id&&null!==e.offsetParent);e?.focus()})}_groupKeydown(t){if(!["ArrowLeft","ArrowRight","Home","End"].includes(t.key))return;const e=[...t.currentTarget.querySelectorAll(".editor-group-item:not([disabled])")];if(!e.length)return;t.preventDefault();const i=e.indexOf(this.host.root().activeElement),s="Home"===t.key?0:"End"===t.key?e.length-1:"ArrowLeft"===t.key?i<=0?e.length-1:i-1:(i+1)%e.length;e[s]?.focus()}_clearDismissClick(){this._dismissPointerTarget=null,clearTimeout(this._dismissTimer),this._dismissTimer=void 0,this._syncGlobalDismissListener()}_syncGlobalDismissListener(){const t=!this._blocked&&"palette"===this._currentModel?.kind,e=!!this._openGroupId||t||!!this._dismissPointerTarget;e!==this._globalDismissListening&&(this._globalDismissListening=e,e?(window.addEventListener("pointerdown",this._globalDismissGuard,!0),window.addEventListener("click",this._globalDismissGuard,!0)):(window.removeEventListener("pointerdown",this._globalDismissGuard,!0),window.removeEventListener("click",this._globalDismissGuard,!0)))}}const j_=t=>t.stopPropagation(),U_=4.166666666666667e-9;function G_(t){return Number.isFinite(t)?Math.round(t/Th)*Th:t}const V_=(t,e,i,s)=>Math.hypot(i-t,s-e),K_=(t,e,i,s,n,o,a,r)=>Math.hypot(Math.max(Math.abs(n-t),Math.abs(n+a-(t+i))),Math.max(Math.abs(o-e),Math.abs(o+r-(e+s)))),Y_=(t,e,i,s,n,o,a)=>{const r=Math.max(Number(s)||0,0)/2,l=Math.PI/180,c=Math.cos(i*l)*r,h=Math.sin(i*l)*r,d=Math.cos(a*l)*r,p=Math.sin(a*l)*r,u=Math.max(V_(t+c,e+h,n+d,o+p),V_(t-c,e-h,n-d,o-p)),_=Math.max(V_(t+c,e+h,n-d,o-p),V_(t-c,e-h,n+d,o+p));return Math.min(u,_)},J_=t=>{const e=Number(t?.cell_cm);return e>0?e:5};function X_(t,e){const i=JSON.parse(JSON.stringify(t||[])),s=JSON.parse(JSON.stringify(e||{}));let n=0,o=0,a=0,r=0,l="",c=0,h=0,d=0;const p=(t,e)=>{Number.isFinite(t)&&Number.isFinite(e)&&t!==e&&Math.abs(e-t)<=U_&&h++},u=(t,e)=>{p(t[0],e[0]),p(t[1],e[1])},_={};let m=5;for(const t of i){const e=J_(t);null!=t?.id&&(_[String(t.id)]=e),e>m&&(m=e)}const g=(t,e,i,s=!1)=>{if(!(t>U_||s))return;n++,t>a&&(a=t);const o=t*Dh*e;o>r&&(r=o,l=i)};for(const t of i){const e=J_(t),i=null!=t?.id?String(t.id):"";for(const s of t.rooms||[]){o++;let t=0;if(s.poly?.length)s.poly=s.poly.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),u(e,i),i});else if(null!=s.x&&null!=s.y){const e=s.x,i=s.y,n=s.w||0,o=s.h||0,a=G_(e+n),r=G_(i+o),l=G_(e),c=G_(i),h=Math.max(Th,a-l),d=Math.max(Th,r-c);t=K_(e,i,n,o,l,c,h,d),s.x=l,s.y=c,s.w=h,s.h=d,p(e,l),p(i,c),p(e+n,l+h),p(i+o,c+d)}g(t,e,i)}for(const s of t.room_drafts||[]){o++;let t=0;const n=s.points||[],a=n.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),i}),r=a.length?[a[0]]:[],l=a.length?[[n[0],a[0]]]:[],c=[];for(let t=0;t+1=2)for(const[t,e]of l)u(t,e);g(t,e,i)}if(Array.isArray(t.room_drafts)){const e=t.room_drafts.length;t.room_drafts=t.room_drafts.filter(t=>t.points?.length>=2),d+=e-t.room_drafts.length,t.room_drafts.length||delete t.room_drafts}for(const s of t.partitions||[]){o++;const n=[s.a[0],s.a[1]],a=[s.b[0],s.b[1]],r=[G_(n[0]),G_(n[1])],l=[G_(a[0]),G_(a[1])];let c=Math.max(V_(n[0],n[1],r[0],r[1]),V_(a[0],a[1],l[0],l[1]));const h=V_(r[0],r[1],l[0],l[1]),d=(t.openings||[]).filter(t=>"partition"===t.host?.kind&&t.host.id===s.id).every(t=>{const e=Number(t.length),i=Number(t.host.t),s=i*h;return Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>=0&&i<=1&&s-e/2>=-U_&&s+e/2<=h+U_});h>U_&&d?(s.a=r,s.b=l,u(n,r),u(a,l)):c=0,g(c,e,i)}for(const s of t.wall_columns||[]){o++;const t=[s.center[0],s.center[1]],n=[G_(t[0]),G_(t[1])],a=V_(t[0],t[1],n[0],n[1]);s.center=n,u(t,n),g(a,e,i)}for(const s of t.decor||[]){o++;let t=0;if("line"===s.kind){const e=[s.x1,s.y1],i=[s.x2,s.y2],n=[G_(e[0]),G_(e[1])],o=[G_(i[0]),G_(i[1])];t=Math.max(V_(e[0],e[1],n[0],n[1]),V_(i[0],i[1],o[0],o[1])),s.x1=n[0],s.y1=n[1],s.x2=o[0],s.y2=o[1],u(e,n),u(i,o)}else{const e=s.x,i=s.y,n=s.w,o=s.h,a=G_(e),r=G_(i);if(null!=s.w&&null!=s.h){const l=G_(e+n),c=G_(i+o),h=Math.max(Th,l-a),d=Math.max(Th,c-r);t=K_(e,i,n,o,a,r,h,d),s.w=h,s.h=d,p(e+n,a+h),p(i+o,r+d)}else t=V_(e,i,a,r);s.x=a,s.y=r,p(e,a),p(i,r)}g(t,e,i)}for(const s of t.openings||[]){if(o++,"partition"===s.host?.kind){const n=(t.partitions||[]).find(t=>t.id===s.host.id),o=Number(s.host.t);if(!n||!Number.isFinite(o)||o<0||o>1)continue;const a=n.b[0]-n.a[0],r=n.b[1]-n.a[1];if(Math.hypot(a,r)<=U_)continue;const l=n.a[0]+a*o,h=n.a[1]+r*o;let d=180*Math.atan2(r,a)/Math.PI;d>=90?d-=180:d<-90&&(d+=180);const p=Number(s.angle),u=!(Number.isFinite(p)&&p===d),_=Y_(s.x,s.y,Number.isFinite(p)?p:d,Number(s.length)||0,l,h,d);s.x=l,s.y=h,s.angle=d,u&&c++,g(_,e,i,u);continue}const n=ui([s.x,s.y],t.rooms||[],.025,{step:Th,length:Number(s.length)||0});if(!n)continue;const a=Number(s.angle),r=!(Number.isFinite(a)&&a===n.angle),l=Y_(s.x,s.y,Number.isFinite(a)?a:n.angle,Number(s.length)||0,n.x,n.y,n.angle);s.x=n.x,s.y=n.y,s.angle=n.angle,r&&c++,g(l,e,i,r)}}for(const[t,e]of Object.entries(s)){if(!e||"object"!=typeof e)continue;const i=e;if("number"!=typeof i.x||"number"!=typeof i.y)continue;o++;const n=G_(i.x),a=G_(i.y),r=V_(i.x,i.y,n,a);s[t]={...i,x:n,y:a},p(i.x,n),p(i.y,a);const l="string"==typeof i.s?i.s:"";g(r,_[l]??m,l)}return{spaces:i,layout:s,report:{moved:n,coordsCanonicalized:h,total:o,maxShift:a,maxShiftCm:r,maxSpace:l,rotated:c,removedDrafts:d},changed:n>0||h>0}}function Z_(t,e){const i=e.base+t*e.span;return Math.min(1,Math.max(0,i))}const Q_=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),tm=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1]);function em(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<=0)return tm(t,e);let a=((t[0]-e[0])*s+(t[1]-e[1])*n)/o;return a=Math.max(0,Math.min(1,a)),Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))}function im(t,e,i,s,n){for(const s of e)if(s&&!i.has(s.id)&&Q_(s.a)&&Q_(s.b)&&(tm(t,s.a)<=n||tm(t,s.b)<=n))return!0;for(const e of s?.roomPolygons||[])for(let i=0;i0&&r>0))return null;if(Math.abs(n[0]/a*(o[1]/r)-n[1]/a*(o[0]/r))>i)return null;for(const[i,n]of[[t.a,e.a],[t.a,e.b],[t.b,e.a],[t.b,e.b]])if(tm(i,n)<=s)return[(i[0]+n[0])/2,(i[1]+n[1])/2];return null}function nm(t,e){const i=.05*(Number(e.pitch)>0?Number(e.pitch):1),s=new Map;let n=(t||[]).filter(t=>!!t&&"string"==typeof t.id&&Q_(t.a)&&Q_(t.b));if(n.length<2)return{partitions:[...t||[]],merged:0,openingMoves:[]};const o=e.seedIds&&e.seedIds.length?new Set(e.seedIds):null;let a=0;for(let t=0;ttm(e,t.at)>i);let h=c[0]??r.a,d=c[c.length-1]??l.b;if(c.length<2&&(h=r.a,d=l.b),d[0]0?(d[0]-h[0])/u:0,m=u>0?(d[1]-h[1])/u:0,g=t=>u>0?((t[0]-h[0])*_+(t[1]-h[1])*m)/u:0;for(const t of[r,l]){const e=g(t.a),i=g(t.b)-e;for(const[n,o]of s)o.toId===t.id&&s.set(n,{fromId:o.fromId,toId:p.id,base:e+o.base*i,span:o.span*i});s.set(t.id,{fromId:t.id,toId:p.id,base:e,span:i})}o&&o.add(p.id),n=n.filter((e,i)=>i!==t.i&&i!==t.j),n.splice(t.i,0,p),a++}return{partitions:n,merged:a,openingMoves:[...s.values()]}}function om(t,e,i,s){if(!t?.length||!i.length)return 0;const n=new Map(i.map(t=>[t.fromId,t]));let o=0;for(const i of t){const t=i?.host;if(!t||"partition"!==t.kind)continue;const a=n.get(t.id);if(!a)continue;i.host={...t,id:a.toId,t:Z_(t.t,a)},o++;const r=Sp(i,e,s.coordScale,s.cellCm,s.gridPitch).resolved;r&&Object.assign(i,Ip(i,r,s.coordScale))}return o}function am(t,e){const i=e?.excludeDraftId||null;return{roomPolygons:(t?.rooms||[]).map(t=>hi(t)).filter(t=>!!t),columns:t?.wall_columns||[],draftEnds:(t?.room_drafts||[]).flatMap(t=>{if(i&&t?.id===i)return[];const e=t?.points||[];return e.length?[e[0],e[e.length-1]]:[]})}}const rm=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),lm=(t,e)=>t[0]-e[0]||t[1]-e[1],cm=(t,e,i,s)=>[t[0]+e*s,t[1]+i*s],hm=(t,e,i,s)=>(t[0]-e[0])*i+(t[1]-e[1])*s,dm=(t,e,i,s,n)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n))return null;const l=o/r,c=a/r,h=e=>Math.abs((e[0]-t[0])*c-(e[1]-t[1])*l);if(h(i)>n||h(s)>n)return null;const d=hm(i,t,l,c),p=hm(s,t,l,c),u=Math.max(0,Math.min(d,p)),_=Math.min(r,Math.max(d,p));return _-u>n?{lo:u,hi:_}:null},pm=(t,e,i)=>Math.min(t.hi,e.hi)-Math.max(t.lo,e.lo)>i,um=t=>{const e=new Set(["id","a","b","cm"]);return Object.keys(t||{}).every(t=>e.has(t))},_m=(t,e,i,s)=>{const n=t.b[0]-t.a[0],o=t.b[1]-t.a[1],a=Math.hypot(n,o);if(!(a>s))return!0;const r=n/a,l=o/a,c=gl(t.cm,i.cellCm,i.gridPitch)/2;return e.some(e=>{const n=e?.center;if(!rm(n))return!0;const o=hm(n,t.a,r,l),h=Math.abs((n[0]-t.a[0])*l-(n[1]-t.a[1])*r),d=gl(Number(e.cm),i.cellCm,i.gridPitch)*("square"===e.shape?Math.SQRT1_2:.5);return!(Number.isFinite(d)&&d>0)||o>=-d-s&&o<=a+d+s&&h<=c+d+s})},mm=(t,e,i)=>{if(t.host){const s=Sp(t,e,i.coordScale,i.cellCm,i.gridPitch).resolved;return s?{center:s.center,angle:s.angle,length:s.length}:null}const s=Number(t.x)*i.coordScale,n=Number(t.y)*i.coordScale,o=Number(t.angle),a=Number(t.length)*i.coordScale;return[s,n,o,a].every(Number.isFinite)&&a>0?{center:[s,n],angle:o,length:a}:null},gm=(t,e,i)=>{const s=t.angle*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=e.angle*Math.PI/180,r=Math.cos(a),l=Math.sin(a);if(Math.abs(n*l-o*r)>1e-6)return!1;const c=e.center[0]-t.center[0],h=e.center[1]-t.center[1];if(Math.abs(c*o-h*n)>i)return!1;const d=c*n+h*o;return Math.max(-t.length/2,d-e.length/2)({...t,a:[t.a[0]*e,t.a[1]*e],b:[t.b[0]*e,t.b[1]*e]}),vm=(t,e,i,s)=>{const n=`~r-${(t=>{let e=2166136261;for(let i=0;i>>0;return e.toString(36)})(`${t}|${e[0].toFixed(9)},${e[1].toFixed(9)}|${i[0].toFixed(9)},${i[1].toFixed(9)}`)}`,o=`${t.slice(0,Math.max(1,64-n.length))}${n}`;let a=o;for(let t=2;s.has(a);t++){const e=`-${t}`;a=`${o.slice(0,64-e.length)}${e}`}return s.add(a),a},ym=(t,e)=>{const i=[];for(const s of t){const t=i[i.length-1];!(t&&Math.abs(t.hi-s.lo)<=e&&t.safe===s.safe)||s.safe&&t.signature!==s.signature?i.push({lo:s.lo,hi:s.hi,a:s.a,b:s.b,safe:s.safe,signature:s.signature,roomIds:s.roomIds,finalCm:s.finalCm}):(t.hi=s.hi,t.b=s.b)}return i};function bm(t,e,i,s,n){const o=i||[],a=Array.isArray(t?.partitions)?t.partitions:[],r=Array.isArray(t?.openings)?t.openings:[],l=Array.isArray(t?.room_drafts)?t.room_drafts:[],c={walls:o,partitions:a,openings:r,roomDrafts:l,partitionsReconciled:0,openingsRehosted:0,removedDrafts:0};if(!a.length&&!l.length)return c;const h=Math.max(2e-4*n.gridPitch,1e-9);let d=o,p=a,u=r;const _=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),m=((t,e,i,s)=>{const n=new Map(t.map(t=>[t.id,t])),o=new Set;for(const t of e){if(!n.get(t.id)||!Array.isArray(t.points)||t.points.length<2||t.segments.length!==t.points.length-1)continue;let e=!0;for(let n=0;n+10)){e=!1;break}const l=Math.hypot(a[0]-o[0],a[1]-o[1]);if(!(l>s)){e=!1;break}const c=i.flatMap(t=>{const e=t.cm>0?t.cm:ll;if(t.open||"outer"!==t.kind&&"shared"!==t.kind||e+st.lo-e.lo||t.hi-e.hi);let h=0;for(const t of c){if(t.lo>h+s)break;if(h=Math.max(h,t.hi),h>=l-s)break}h!m.has(t.id));let f=0,v=0;const y=new Map(e.partitions.map(t=>[t.id,t]));for(const t of[...a].sort((t,e)=>t.id.localeCompare(e.id))){if(!p.some(e=>e.id===t.id))continue;if(!um(t))continue;const i=y.get(t.id);if(!(i&&rm(i.a)&&rm(i.b)&&Number.isFinite(i.cm)&&i.cm>0))continue;const[o,a]=lm(i.a,i.b)<=0?[[i.a[0],i.a[1]],[i.b[0],i.b[1]]]:[[i.b[0],i.b[1]],[i.a[0],i.a[1]]],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>h))continue;const _=r/c,g=l/c,b=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),w=b.flatMap(t=>{if(t.open||"outer"!==t.kind&&"shared"!==t.kind)return[];const e=dm(o,a,t.a,t.b,h);return e?[{interval:t,range:e}]:[]});if(!w.length)continue;const k=u.filter(t=>"partition"===t.host?.kind&&t.host.id===i.id).map(t=>({opening:t,resolved:Sp(t,e.partitions,n.coordScale,n.cellCm,n.gridPitch).resolved}));if(k.some(t=>!t.resolved))continue;const x=[0,c];for(const{range:t}of w)x.push(t.lo,t.hi);const $=x.slice(),S=new Map;for(const{opening:t,resolved:e}of k){const i=hm(e.center,o,_,g),s={lo:i-e.length/2,hi:i+e.length/2};S.set(t.id,s),$.push(Math.max(0,s.lo),Math.min(c,s.hi))}const M=[...new Set($.filter(t=>Number.isFinite(t)&&t>=-h&&t<=c+h).map(t=>Math.max(0,Math.min(c,t)).toFixed(9)))].map(Number).sort((t,e)=>t-e),C=p.map(t=>fm(t,n.coordScale)).filter(t=>t.id!==i.id),D=e.room_drafts.filter(t=>!m.has(t.id)),P=[];for(let t=0;t+1h))continue;const r=cm(o,_,g,s),l=cm(o,_,g,a),c=w.filter(({range:t})=>t.lo<=s+h&&t.hi>=a-h).map(({interval:t})=>t),d=new Map;for(const t of c)d.set(t.roomId,t);const p=[...d.values()],u=new Set(p.map(t=>t.kind)),m=new Set(p.map(t=>t.cm>0?t.cm:ll)),f=p[0]?.kind,v=[...d.keys()].sort(),y=1===u.size&&1===m.size&&("outer"===f&&1===v.length||"shared"===f&&2===v.length),b={id:i.id,a:r,b:l,cm:i.cm},k=C.some(t=>!!dm(r,l,t.a,t.b,h)),x=D.some(t=>t.points.some((e,i)=>i+10?p[0].cm:ll:0,T=y?Math.max(S,i.cm):i.cm;P.push({lo:s,hi:a,a:r,b:l,safe:$,signature:$?`${f}|${v.join(",")}|${T}`:"",roomIds:v,roomCm:S,finalCm:T})}if(!P.some(t=>t.safe))continue;const T=new Map;for(const{opening:t,resolved:e}of k){const s=S.get(t.id),o=x.some(t=>t>s.lo+h&&tpm(t,s,h)),r=new Set(a.filter(t=>t.safe).map(t=>t.signature));if(!o&&a.length>0&&a.every(t=>t.safe)&&1===r.size&&Rp(e,b,h)){T.set(t.id,{resolved:e,signature:[...r][0]});continue}const l=xp(i,n.cellCm,n.gridPitch),c={lo:s.lo-l,hi:s.hi+l};for(const t of P)pm(t,c,h)&&(t.safe=!1,t.signature="")}let R=!0;for(;R;){R=!1;for(const[t,e]of[...T.entries()]){const s=S.get(t),o=P.filter(t=>pm(t,s,h));if(o.length>0&&o.every(t=>t.safe)&&o.every(t=>t.signature===e.signature))continue;T.delete(t);const a=xp(i,n.cellCm,n.gridPitch),r={lo:s.lo-a,hi:s.hi+a};for(const t of P)pm(t,r,h)&&(t.safe=!1,t.signature="");R=!0}}const I=ym(P,h),A=I.filter(t=>t.safe),z=I.filter(t=>!t.safe);if(!A.length)continue;if(p.length-1+z.length>2e3)continue;let F=d;for(const t of A){const[e,s]=lm(i.a,i.b)<=0?[t.a,t.b]:[t.b,t.a];F=Fl(F,e,s,t.finalCm,n.pitch,n.coordScale)}if(F=uc(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),F.length>500)continue;const E=new Set(p.map(t=>t.id));E.delete(i.id);const N=z.map((t,e)=>{const s=[t.a[0]/n.coordScale,t.a[1]/n.coordScale],o=[t.b[0]/n.coordScale,t.b[1]/n.coordScale],a=0===e?i.id:vm(i.id,s,o,E);return E.add(a),{id:a,a:s,b:o,cm:i.cm}}),O=p.findIndex(t=>t.id===i.id),L=p.slice();L.splice(O,1,...N);const H=L.map(t=>fm(t,n.coordScale)),B=new Map;let q=!0;for(const{opening:t,resolved:e}of k){const i=T.get(t.id);if(i){const e=Ip(t,i.resolved,n.coordScale),{host:s,...o}=e;B.set(t.id,o);continue}const s=S.get(t.id),o=N[z.findIndex(t=>t.lo<=s.lo+h&&t.hi>=s.hi-h)],a=o&&H.find(t=>t.id===o.id);if(!o||!a){q=!1;break}const r=a.b[0]-a.a[0],l=a.b[1]-a.a[1],c=Math.hypot(r,l),d=hm(e.center,a.a,r/c,l/c),p={...Ip(t,e,n.coordScale),host:{kind:"partition",id:o.id,t:d/c}};if(!Mp(p,H,n.coordScale,n.cellCm,n.gridPitch).resolved){q=!1;break}B.set(t.id,p)}if(!q)continue;const W=u.map(t=>B.get(t.id)||t),j=[...T.keys()].map(t=>B.get(t)),U=j.map(t=>mm(t,H,n));if(U.some(t=>!t))continue;let G=!1;for(let t=0;tt.id));for(const t of W){if(V.has(t.id))continue;const e=mm(t,H,n);e&&U.some(t=>gm(t,e,h))&&(G=!0)}if(G)continue;const K=Ec(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale);[...T.entries()].every(([t,e])=>{const i=B.get(t),s=Lc(K,{x:i.x*n.coordScale,y:i.y*n.coordScale,angle:i.angle,length:i.length*n.coordScale},!0),o=[s.negative,s.positive].filter(t=>!!t?.full),a=e.signature.split("|")[1].split(","),r=new Set(o.map(t=>t.roomId));return o.length===a.length&&r.size===a.length&&a.every(t=>r.has(t))})&&(d=F,p=L,u=W,f+=A.length,v+=T.size)}return{walls:d,partitions:p,openings:u,roomDrafts:g,partitionsReconciled:f,openingsRehosted:v,removedDrafts:m.size}}const wm=t=>JSON.parse(JSON.stringify(t)),km=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),xm=(t,e)=>e.length>0&&e.length<=35&&("space"===t?/^[a-z0-9_-]+$/.test(e):/^[A-Za-z0-9_-]+$/.test(e));function $m(t,e){let i=String(e??"");const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s}_(.+)_([0-9a-f]{8})$`);let o=0;for(;o<16;o++){const t=n.exec(i);if(!t)return{root:i,layers:o,bounded:!1};i=t[1]}return{root:i,layers:o,bounded:n.test(i)}}const Sm=(t,e,i)=>{const s=t.get(e)||[];s.push(i),t.set(e,s)};const Mm=1e-9;class Cm extends Error{constructor(t,e=""){super(e?`${t}: ${e}`:t),this.reason=t,this.name="WallSegmentModelError"}}const Dm=t=>JSON.parse(JSON.stringify(t)),Pm=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1])),Tm=t=>[Number(t[0]),Number(t[1])],Rm=t=>`${Number(t[0]).toFixed(12)},${Number(t[1]).toFixed(12)}`,Im=(t,e)=>{const i=Rm(t),s=Rm(e);return iRm(t)<=Rm(e)?[Tm(t),Tm(e)]:[Tm(e),Tm(t)],zm=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Fm=t=>{const e=[[Number(t.points[0][0]),Number(t.points[0][1])]],i=[];for(let s=1;s{const i=new Set,s=t=>{const e=Number(t);if(!Number.isFinite(e))return;const s=e/Th;Math.abs(s-Math.round(s))>=Ur&&i.add(e.toFixed(12))};for(const e of Array.isArray(t?.rooms)?t.rooms:[])for(const t of hi(e)||[])s(t[0]),s(t[1]);for(const e of[t?.wall_segments,t?.walls])for(const t of Array.isArray(e)?e:[])s(t?.a?.[0]),s(t?.a?.[1]),s(t?.b?.[0]),s(t?.b?.[1]);for(const t of e)s(t?.[0]),s(t?.[1]);return i.size},Nm=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;return o>1e-18?((t[0]-e[0])*s+(t[1]-e[1])*n)/o:0},Om=(t,e,i)=>{const s=Math.max(0,Math.min(1,Nm(t,e,i)));return Math.hypot(t[0]-(e[0]+(i[0]-e[0])*s),t[1]-(e[1]+(i[1]-e[1])*s))},Lm=(t,e,i,s,n=Mm)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(r<=n)return 0;const l=e=>Math.abs((e[0]-t[0])*a-(e[1]-t[1])*o)/r;if(l(i)>n||l(s)>n)return 0;const c=Nm(i,t,e),h=Nm(s,t,e);return Math.max(0,Math.min(1,Math.max(c,h))-Math.max(0,Math.min(c,h)))*r},Hm=t=>{const e=(new TextEncoder).encode(t),i=8*e.length,s=64*Math.ceil((e.length+9)/64),n=new Uint8Array(s);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(s-8,Math.floor(i/4294967296),!1),o.setUint32(s-4,i>>>0,!1);const a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(t,e)=>t>>>e|t<<32-e;for(let t=0;t>>3,n=c(i,17)^c(i,19)^i>>>10;l[t]=l[t-16]+s+l[t-7]+n>>>0}let[e,i,s,n,h,d,p,u]=r;for(let t=0;t<64;t++){const o=u+(c(h,6)^c(h,11)^c(h,25))+(h&d^~h&p)+a[t]+l[t]>>>0,r=e&i^e&s^i&s;u=p,p=d,d=h,h=n+o>>>0,n=s,s=i,i=e,e=o+((c(e,2)^c(e,13)^c(e,22))+r>>>0)>>>0}r[0]=r[0]+e>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+s>>>0,r[3]=r[3]+n>>>0,r[4]=r[4]+h>>>0,r[5]=r[5]+d>>>0,r[6]=r[6]+p>>>0,r[7]=r[7]+u>>>0}const h=new Uint8Array(32),d=new DataView(h.buffer);for(let t=0;t{const e="abcdefghijklmnopqrstuvwxyz234567";let i=0,s=0,n="";for(const o of t)for(s=s<<8|o,i+=8;i>=5;)n+=e[s>>>i-5&31],i-=5;return i&&(n+=e[s<<5-i&31]),n},qm=(t,e,i,s,n="")=>{const[o,a]=Am(e,i),r=`${t}|${Rm(o)}|${Rm(a)}|${[...s].sort().join(",")}${n}`;return`wall-${Bm(Hm(r)).slice(0,20)}`};let Wm=0;const jm=t=>{for(let e=0;e<1e3;e++){const e=globalThis.crypto?.randomUUID?.(),i=`wall-${e||Bm(Hm(`${Date.now()}|${Wm++}|${Math.random()}`)).slice(0,26)}`;if(!t.has(i))return i}throw new Cm("duplicate-id","id factory exhausted")},Um=t=>{const e=new Map;for(const i of Array.isArray(t?.wall_segments)?t.wall_segments:[])if(i&&"string"==typeof i.id&&Pm(i.a)&&Pm(i.b)){if(e.has(i.id))throw new Cm("duplicate-id",i.id);e.set(i.id,i)}return e},Gm=(t,e,i)=>{const s=(i,s)=>{const n=t[0]-i[0],o=t[1]-i[1];return Math.abs(e[0]-s[0]-n)<=Mm&&Math.abs(e[1]-s[1]-o)<=Mm?[n,o]:null};return s(i.a,i.b)||s(i.b,i.a)},Vm=(t,e)=>{const i=Array.isArray(t.rooms)?t.rooms:[],s=ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]),n=s.length?s:_d(i,null,1,.04*Th,!0),o=[];for(const t of i){const i=hi(t),s=Array.isArray(t?.wall_ids)?t.wall_ids:[];if(i&&s.length===i.length)for(let t=0;t"partition"!==t.host?.kind&&[Number(t.x),Number(t.y)].every(Number.isFinite)&&Number.isFinite(Number(t.angle))&&Number(t.length)>0&&n.some(e=>Om([Number(t.x),Number(t.y)],[e[0],e[1]],[e[2],e[3]])<=.04*Th)):[],l=r.map(t=>{const e=Number(t.angle)*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Number(t.length)/2,n=[Number(t.x),Number(t.y)];return{a:[n[0]-i[0]*s,n[1]-i[1]*s],b:[n[0]+i[0]*s,n[1]+i[1]*s]}}),c=(t,e)=>r.some(i=>{const s=[Number(i.x),Number(i.y)];if(!Rl(t,e,Number(i.angle)))return!1;if(Om(s,t,e)>.02*Th)return!1;const n=zm(t,e),o=Nm(s,t,e)*n,a=Number(i.length)/2;return o+a>=-Mm&&o-a<=n+Mm}),h=new Map,d=[];for(const s of i){const r=String(s?.id||""),p=hi(s);if(!r||!p||p.length<3)throw new Cm("invalid-room",r);const u=ec(i,r,a,Th,1,[...t.walls||[],...l]);if(!u||u.poly.length<3)throw new Cm("invalid-room",r);const _=Array.isArray(s.wall_ids)?s.wall_ids:[],m=_.length===p.length;let g=null,f=m;if(f)for(let t=0;tMm||Math.abs(s[1]-g[1])>Mm)){f=!1;break}g=s}const v=[];for(let t=0;t2)throw new Cm("third-owner",a);const d=m?_[u.parent[t]]:void 0;if("string"==typeof d&&d){const n=e.get(d);f||!n||Lm(i,s,n.a,n.b)>Mm?l.preferredIds.add(d):l.positionalIds.add(d),l.preferredCarriers.set(d,{a:Tm(p[u.parent[t]]),b:Tm(p[(u.parent[t]+1)%p.length])})}const g=u.parent[t];l.parentKeys.add(wl(p[g],p[(g+1)%p.length],Th));const y=[(i[0]+s[0])/2,(i[1]+s[1])/2],b=t=>t.some(t=>Om(y,[t[0],t[1]],[t[2],t[3]])<=.04*Th);l.zeroWall||=b(o)||b(n)&&!c(i,s),v.push(a)}const y={...s};delete y.wall_ids,d.push({...y,poly:u.poly.map(t=>[t[0],t[1]]),wall_ids:v})}return{atoms:[...h.values()].sort((t,e)=>t.key.localeCompare(e.key)),rooms:d}},Km=(t,e,i,s,n)=>{const o=new Map([...i.values()].map(t=>[Im(t.a,t.b),t])),a=(t=>{const e=new Map;for(const i of t)"wall"===i.host?.kind&&e.set(i.host.id,(e.get(i.host.id)||0)+1);return e})(t.openings||[]),r=new Map;for(const t of e){const e=n?.get(t.key);if(e){const s=i.get(e);if(!s)throw new Cm("duplicate-id",e);r.set(t,s);continue}if(t.preferredIds.size>1)throw new Cm("duplicate-id",[...t.preferredIds].sort().join(","));const s=[...t.preferredIds][0],l=s?i.get(s):void 0;if(l){r.set(t,l);continue}const c=s?t.preferredCarriers.get(s):void 0;if(s&&c){r.set(t,{id:s,a:c.a,b:c.b,cm:0});continue}const h=o.get(t.key);if(h){r.set(t,h);continue}const d=[...i.values()].filter(e=>Lm(t.a,t.b,e.a,e.b)>Mm),p=[...new Map(d.map(t=>[t.id,t])).values()];if(p.sort((t,e)=>(a.get(e.id)||0)-(a.get(t.id)||0)||zm(e.a,e.b)-zm(t.a,t.b)||t.id.localeCompare(e.id)),p[0])r.set(t,p[0]);else if(1===t.positionalIds.size){const e=i.get([...t.positionalIds][0]);e&&r.set(t,e)}}const l=new Map;for(const[t,e]of r){const i=l.get(e.id)||[];i.push(t),l.set(e.id,i)}for(const[t,e]of l){const s=i.get(t)||r.get(e[0]);if(!s)throw new Cm("duplicate-id",t);const n=[(s.a[0]+s.b[0])/2,(s.a[1]+s.b[1])/2];e.sort((t,e)=>{const i=Om(n,t.a,t.b)<=Mm?0:1,o=Om(n,e.a,e.b)<=Mm?0:1;if(i!==o)return i-o;return(Om(s.a,t.a,t.b)<=Mm?0:1)-(Om(s.a,e.a,e.b)<=Mm?0:1)||t.key.localeCompare(e.key)}),e[0].id=t}const c=(t=>{const e=new Set;for(const i of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns])for(const t of Array.isArray(i)?i:[])"string"==typeof t?.id&&t.id&&e.add(t.id);for(const i of Array.isArray(t.room_drafts)?t.room_drafts:[])for(const t of Array.isArray(i?.segments)?i.segments:[])"string"==typeof t?.id&&t.id&&e.add(t.id);return e})(t);for(const t of e)if(t.id){if(c.has(t.id))throw new Cm("duplicate-id",t.id);c.add(t.id)}const h=e.filter(t=>!t.id);if(s){const e=h.map(e=>{const[i,s]=Am(e.a,e.b),n=`${String(t.id||"")}|${Rm(i)}|${Rm(s)}|${[...e.owners].sort().join(",")}`,o=Bm(Hm(n));return{atom:e,seed:n,digest:o,base:`wall-${o.slice(0,20)}`}}).sort((t,e)=>t.digest.localeCompare(e.digest)||t.atom.key.localeCompare(e.atom.key)),i=new Map;for(const t of e){const e=i.get(t.digest);if(e&&e!==t.seed)throw new Cm("duplicate-id",t.digest);i.set(t.digest,t.seed);let s=1,n=t.base;for(;c.has(n);)n=`${t.base}-${++s}`;t.atom.id=n,c.add(n)}}else for(const t of h)t.id=jm(c),c.add(t.id)},Ym=(t,e)=>{if("partition"===t.host?.kind)return null;const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=e=>{if(!(Number(e.cm)>0))return!1;const s=Nm(i,e.a,e.b),n=zm(e.a,e.b),o=Number(t.length)/2;return s>=-Mm&&s<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(o)&&o>=0&&s*n-o>=-Mm&&s*n+o<=n+Mm},n="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null,o=n&&s(n)?[n]:e.filter(s);if(1!==o.length)return null;const a=o[0];return{kind:"wall",id:a.id,t:Math.max(0,Math.min(1,Nm(i,a.a,a.b)))}},Jm=(t,e)=>{const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=Number(t.length)/2,n=e.filter(e=>{if(!(Number(e.cm)>0))return!1;const n=Nm(i,e.a,e.b),o=zm(e.a,e.b);return n>=-Mm&&n<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(s)&&s>=0&&n*o-s>=-Mm&&n*o+s<=o+Mm}),o=(e=>{if(!e.length)return null;const s="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null;return s||[...e].sort((t,e)=>Om(i,t.a,t.b)-Om(i,e.a,e.b)||Number(e.cm)-Number(t.cm)||(t.ide.id?1:0))[0]})(n);return o?{kind:"wall",id:o.id,t:Math.max(0,Math.min(1,Nm(i,o.a,o.b)))}:null},Xm=(t,e,i)=>{const s=Um(t),{atoms:n,rooms:o}=Vm(t,s);Km(t,n,s,e,i);const a=n.map(e=>{const i=e.id?s.get(e.id):void 0,n=((t,e,i)=>{if(e.zeroWall)return 0;const s=Array.isArray(t.walls)?t.walls:[],n=wl(e.a,e.b,Th),o=s.filter(t=>Number(t.cm)>0&&(!(t.key!==n&&!e.parentKeys.has(t.key))||!(!Pm(t.a)||!Pm(t.b))&&Lm(e.a,e.b,t.a,t.b)>=zm(e.a,e.b)-Mm)).map(t=>Math.max(1,Math.min(100,Number(t.cm))));if(new Set(o.map(t=>t.toFixed(9))).size>1)throw new Cm("thickness-conflict",e.key);if(o.length)return o[0];const a=Pl(s,e.a,e.b,Th,1);return a>0?a:Number(i?.cm)>0?Number(i.cm):0})(t,e,i);return{...i||{},id:e.id,a:[...e.a],b:[...e.b],cm:n}}),r=new Map(n.map(t=>[t.key,t.id]));for(const t of o)t.wall_ids=t.wall_ids.map(t=>r.get(t));t.rooms=o,t.wall_segments=a,t.walls=a.filter(t=>t.cm>0).map(t=>({key:wl(t.a,t.b,Th),cm:t.cm,a:[...t.a],b:[...t.b]})),t.walls.length||delete t.walls,delete t.open_spans;for(const e of t.rooms)delete e.open_to;return((t,e)=>{const i=new Set;for(const e of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns,t.wall_segments])for(const t of Array.isArray(e)?e:[])"string"==typeof t?.id&&t.id&&i.add(t.id);for(const s of Array.isArray(t.room_drafts)?t.room_drafts:[]){const n=Array.isArray(s.segments)?s.segments:[];for(let o=0;o{const s=Array.isArray(t.openings)?t.openings:[];for(const t of s){if("partition"===t.host?.kind)continue;if(!t.host&&!i){const i=Ym(t,e);i&&(t.host=i);continue}const s=Ym(t,e)??(i?Jm(t,e):null);if(s)t.host=s;else{if(!i)throw new Cm("opening-host",t.id);delete t.host}}})(t,a,e),a.reduce((t,e)=>t+(s.has(e.id)?0:1),0)};function Zm(t,e={}){const i=JSON.stringify(t),s=Dm(t);rl(s);let n=0;const o=Number(s?.model_version||0)<9;for(const t of Array.isArray(s?.spaces)?s.spaces:[]){const i=e.lineageSpaceId===String(t?.id||"")?e.lineageHints:void 0;n+=Xm(t,o,i)}return s.model_version=9,rl(s),{config:s,changed:i!==JSON.stringify(s),migratedSegments:n}}const Qm=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tg(t,e){const i=(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){const s=new Map;for(const e of t)Qm(e)&&"string"==typeof e.id&&e.id&&s.set(e.id,e);const n=e.map((e,n)=>{if(Qm(e)&&"string"==typeof e.id&&e.id){const t=s.get(e.id);return t?i(t,e):Dm(e)}return n[e,e in t?i(t[e],s):Dm(s)]);for(const e of Object.keys(t))delete t[e];for(const[e,i]of s)t[e]=i;return t}return Dm(e)};return i(t,e)}const eg=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ig=(t,e,i)=>Math.min(i,Math.max(e,t)),sg=t=>Sh({spaces:[t]})[0],ng=(t,e,i)=>{const s=i>0?i:1,n=t=>`${(t[0]/s).toFixed(12)},${(t[1]/s).toFixed(12)}`,o=n(t),a=n(e);return o0?a:1,l=Math.max(s*r*.02,1e-9),c=[];for(const e of t||[])for(const t of hi(e)||[])c.push([t[0],t[1]]);const h=[];for(const t of i||[])Array.isArray(t)&&t.length>=4&&t.slice(0,4).every(Number.isFinite)&&h.push([t[0],t[1]],[t[2],t[3]]);const d=(t,e)=>e.some(e=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l),p=new Map;for(const a of t||[]){if(!a?.id)continue;const u=hc(t,a.id,e,i,s,n,o,r);if(u)for(let t=0;t0&&_>0&&a===m&&_!==a))continue;const g=u.poly[s],f=u.poly[(s+1)%u.poly.length],v=Math.hypot(f[0]-g[0],f[1]-g[1]);if(!(v>l&&v<.5*o-1e-9*o))continue;if(d(g,h)||d(f,h))continue;if(d(g,c)&&d(f,c))continue;const y=ng(g,f,r),b=p.get(y);b?b.targets.add(a):p.set(y,{a:[g[0],g[1]],b:[f[0],f[1]],targets:new Set([a])})}}}let u=e.slice();const _=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l,m=(t,e)=>{if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return!1;const i=[Number(t.a[0])*r,Number(t.a[1])*r],s=[Number(t.b[0])*r,Number(t.b[1])*r];return!![...i,...s].every(Number.isFinite)&&(_(i,e.a)&&_(s,e.b)||_(i,e.b)&&_(s,e.a))};for(const t of[...p.values()].filter(t=>1===t.targets.size).sort((t,e)=>ng(t.a,t.b,r).localeCompare(ng(e.a,e.b,r)))){const e=[...t.targets][0],i=u.filter(e=>m(e,t));if(new Set(i.map(t=>t.cm)).size>1)continue;let n=!1;u=u.map(i=>m(i,t)?(n=!0,i.cm===e?i:{...i,cm:e}):i),n||(u=Fl(u,t.a,t.b,e,s,r))}return u}const ag=t=>{const e=[];for(const i of t||[]){const t=hi(i);if(t?.length)for(let i=0;i"string"==typeof t?.id?t.id:"").filter(Boolean),h=new Set(c),d=new Map;for(const t of c){const e=$m("space",t);e.layers>0&&xm("space",e.root)&&Sm(d,e.root,t)}const p=new Map,u=new Map,_=new Map,m=new Map;for(const t of r){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i=new Map;for(const s of Array.isArray(t.rooms)?t.rooms:[]){const t="string"==typeof s?.id?s.id:"";if(!t)continue;const n=$m("room",t);n.layers>0&&xm("room",n.root)&&Sm(i,n.root,t),u.has(t)||u.set(t,e),_.has(t)||_.set(t,String(s.name||""));const o="string"==typeof s.area?s.area:"";if(o){const i=m.get(o)||[];i.push({spaceId:e,roomId:t}),m.set(o,i)}}p.set(e,i)}const g=new Set(u.keys()),f=new Map,v=new Map;for(const t of l)"string"==typeof t?.id&&t.id&&(!0===t.removed?v.set(t.id,t):f.set(t.id,t));const y={spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,positionsUnresolved:0,nestedRefsUnresolved:0,deadSpaceIds:[],orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0,removedPositions:[],liveMissingPositions:[],unverifiedPositions:[]},b=new Set,w=t=>h.has(t)?null:(()=>{const e=$m("space",t).root;if(!xm("space",e))return null;const i=d.get(e)||[];return 1===i.length?i[0]:null})(),k=(t,e)=>{const i=$m("room",t).root;if(!xm("room",i))return null;const s=p.get(e)?.get(i)||[];return 1===s.length?s[0]:null},x=t=>{const e=i.effectiveAreaByMarker?.[t]||"",s=e&&m.get(e)||[];return 1===s.length?s[0]:null},$=(t,e,i)=>{if("string"==typeof t.room_id&&t.room_id&&!g.has(t.room_id)){const s=e?k(t.room_id,e):null;s?(t.room_id=s,y.roomRefsRemapped++):i?(t.room_id=i.roomId,y.roomRefsRemapped++):!0!==t.removed&&delete t.room_id}const s=t.vacuum?.segment_map;if(s&&"object"==typeof s&&!Array.isArray(s))for(const t of Object.keys(s)){const i=s[t];if("string"!=typeof i||!i||g.has(i))continue;const n=e?k(i,e):null;n?(s[t]=n,y.roomRefsRemapped++):y.nestedRefsUnresolved++}};for(const t of l){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i="string"==typeof t.space?t.space:"",s=i&&!h.has(i),o=n[e],a="string"==typeof o?.s?o.s:"",r=a&&!h.has(a),l=!0===t.removed;let c=i&&h.has(i)?i:null,d=null,p=!1;if(s){const s=w(i);s?(t.space=s,c=s,p=!0,y.spaceRefsRemapped++):l||"virtual"===t.binding?l||(delete t.space,c=null,y.markersDetached++):(d=x(e),d?(t.space=d.spaceId,c=d.spaceId,y.spaceRefsRemapped++):(delete t.space,c=null,y.markersDetached++))}l&&!p||$(t,c,d),r&&p&&a===i&&c&&(n[e]={...o,s:c},y.positionsRemapped++,b.add(e))}for(const t of Object.keys(n)){if(b.has(t))continue;const e=n[t],i="string"==typeof e?.s?e.s:"";if(!i||h.has(i))continue;const s=w(i);if(s){if(t.startsWith("rl_")){const i=t.slice(3),o=k(i,s);if(o){const i=`rl_${o}`;km(n,i)||(n[i]={...e,s:s}),delete n[t],y.roomRefsRemapped++,y.positionsRemapped++;continue}}n[t]={...e,s:s},y.positionsRemapped++}}const S=i.ownerRoster,M=!0===S?.authoritative,C=new Set(S?.deviceIds||[]),D=new Set(S?.entityIds||[]),P=new Set(Array.isArray(s.settings?.known_devices)?s.settings.known_devices.filter(t=>"string"==typeof t):[]),T=(t,e="")=>{const i=String(S?.names?.[t]||e||"").trim();return i&&i!==t?i:""},R=(t,e,i,s="",n)=>({id:t,spaceId:e,kind:i,name:T(t,s),...n?{reason:n}:{}}),I=t=>{"room_label"===t?y.orphanRoomLabelsRemoved++:"group"===t?y.orphanGroupPositionsRemoved++:y.orphanDevicePositionsRemoved++},A=new Set;for(const[t,e]of Object.entries(n)){const s="string"==typeof e?.s?e.s:"";if(!s||h.has(s))continue;let o,a;const r=f.get(t),l=v.get(t);if(r)o=R(t,s,"device",String(r.name||"")),a="live";else if(l)o=R(t,s,"device",String(l.name||"")),a="absent";else if(t.startsWith("rl_")){const e=t.slice(3);o=R(t,s,"room_label",_.get(e)||""),a=g.has(e)?"live":"absent"}else if(t.startsWith("lg_")){const e=t.slice(3);o=R(t,s,"group"),a=D.has(e)?"live":M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")}else C.has(t)?(o=R(t,s,"device"),a="live"):P.has(t)?(o=R(t,s,"device"),a=M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")):(o=R(t,s,"unknown","","unknown_owner"),a="unverified");if("absent"!==a){if("live"===a){if(y.liveMissingPositions.push(o),!0===i.removeLiveMissingPositions){delete n[t],y.liveMissingPositionsRemoved++,I(o.kind),y.removedPositions.push(o);continue}}else y.unverifiedPositions.push(o);y.positionsUnresolved++,A.add(s)}else delete n[t],I(o.kind),y.removedPositions.push(o)}return y.deadSpaceIds=[...A].sort((t,e)=>t.localeCompare(e)),{config:s,layout:n,report:y,changed:JSON.stringify(s)!==o||JSON.stringify(n)!==a}}(t,e,i),a=o.config,r=nl(a,o.layout);rl(a),al(o.layout);const l=JSON.stringify(t||{}),c=JSON.stringify(e||{}),h=Number.isInteger(Number(a.model_version))?Number(a.model_version):0,d=(t=>{let e=0,i=0,s=0;for(const i of t.markers||[]){if("ripple"===i.display&&(i.display="icon_ripple",e++),Array.isArray(i.controls)){const t="string"==typeof i.binding&&i.binding.startsWith("entity:")?i.binding.slice(7):"",s=t?i.controls.filter(e=>e!==t):i.controls;JSON.stringify(s)!==JSON.stringify(i.controls)&&(i.controls=s.length?s:null,e++)}const t=i.vacuum;t&&eg(t,"trail")&&(["never","cleaning","always"].includes(t.trail_mode)||(t.trail_mode=!1===t.trail?"never":"cleaning"),delete t.trail,e++)}for(const n of t.spaces||[]){const t=n.settings;"glow"===t?.fill_mode&&("boolean"!=typeof t.glow_enabled&&(t.glow_enabled=!0),t.fill_mode="none",e++,i++);for(const t of n.rooms||[]){const i=t.settings;"glow"===i?.fill_mode&&("boolean"!=typeof i.glow&&(i.glow=!0),delete i.fill_mode,e++,s++)}if(eg(n,"segments")&&(delete n.segments,e++),eg(n,"plan_scale")){const t=Number(n.plan_scale);Number.isFinite(t)&&t>=wh&&t<=kh&&(eg(n,"plan_scale_x")||(n.plan_scale_x=t),eg(n,"plan_scale_y")||(n.plan_scale_y=t),delete n.plan_scale,e++)}const o=Number(n.cell_cm);eg(n,"cell_cm")&&(!Number.isFinite(o)||o<.1||o>1e3)&&(n.cell_cm=Number.isFinite(o)&&o>0?ig(o,.1,1e3):5,e++);const a=Number(n.cell_cm),r=Number.isFinite(a)&&a>0?a:5;for(const t of n.wall_columns||[])if("circle"===t.shape)eg(t,"angle")&&(delete t.angle,e++);else if("square"===t.shape&&eg(t,"angle")){const i=((Number(t.angle)||0)%90+90)%90;t.angle!==i&&(t.angle=i,e++)}for(const t of n.decor||[]){if(eg(t,"width")){const i=Number(t.width);(eg(t,"width_cm")||Number.isFinite(i))&&(eg(t,"width_cm")||(t.width_cm=Number(ig(i/Ph*r,.1,100).toFixed(6))),delete t.width,e++)}if("rect"!==t?.kind&&"ellipse"!==t?.kind||!0!==t.fill||(eg(t,"fill_color")||(t.fill_color=t.color||"#607d8b",e++),eg(t,"fill_opacity")||(t.fill_opacity=.25,e++)),"text"!==t?.kind)continue;void 0===t.size_cm?(t.size_cm=Number(ig(es*is(t)/Ph*r,.1,2e3).toFixed(6)),delete t.scale,delete t.size,e++):(eg(t,"scale")||eg(t,"size"))&&(delete t.scale,delete t.size,e++);let i=String(t.text??"");const s=[...i.matchAll(/\{([^{}\r\n]+)\}/g)].some(t=>!!Yi(t[1]));if(!(eg(t,"entity")||eg(t,"attr")||eg(t,"unit")))continue;const n=String(t.unit??"").trim(),o="state"===String(t.attr??"").trim().toLowerCase()?null:t.attr,a=s||n?"":Ji(t.entity,o);if(s||a){if(a){const e=i.indexOf("{}");i=e>=0?i.slice(0,e)+a+i.slice(e+2):`${i}${i?" ":""}${a}`,t.text=i}delete t.entity,delete t.attr,delete t.unit,e++}}}return{total:e,glowSpaces:i,glowRooms:s}})(a);let p=d.total;const u=(_=a.spaces||[],JSON.parse(JSON.stringify(_)));var _;const m=X_(a.spaces||[],o.layout);let g=0,f=0,v=0,y="";const b=m.spaces.map(t=>{const e=function(t){const e=JSON.parse(JSON.stringify(t||{}));let i=Array.isArray(e.rooms)?e.rooms:[];const s=new Map;for(const t of i){const e=hi(t);if(e)for(let t=0;tt.key.localeCompare(e.key))){let e=null;for(const s of $a(t,i)){const t=r.get(_a(s.from));if(t&&t!==_a(s.to))continue;const n=wa(i,s);if(ka(i,n,s)){e=s,i=n;break}}e?(r.set(_a(e.from),_a(e.to)),n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}e.rooms=i;for(const t of e.room_drafts||[]){if(!Array.isArray(t?.points)||t.points.length<2)continue;const e=t.points.map(t=>[...t]),i=e.slice(0,-1).flatMap((i,s)=>{const n=e[s+1],o=pa(i,n);return o?[{key:`${String(t.id||"")}:${s}`,a:[...i],b:[...n],axis:o.axis}]:[]});let s=e;for(const t of i){let e=null;for(const i of $a(t,[{poly:s}])){const t=s.map(t=>ba(t,i)),n=t.length>=4&&ma(t[0],t[t.length-1]),o=n?t.slice(0,-1):t;if(n?va(o):ya(o)){e=i,s=t;break}}e?(n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}t.points=s}for(const t of e.partitions||[]){if(!Array.isArray(t?.a)||!Array.isArray(t?.b))continue;const i=pa(t.a,t.b);if(!i)continue;const s={key:String(t.id||ga(t.a,t.b)),a:[...t.a],b:[...t.b],axis:i.axis};let r=null;for(const i of $a(s,[{poly:[t.a,t.b]}])){const s=ba(t.a,i),n=ba(t.b,i),o=Math.hypot(n[0]-s[0],n[1]-s[1]);if(!(o>0))continue;const a=(e.openings||[]).filter(e=>"partition"===e?.host?.kind&&e.host.id===t.id).every(t=>{const e=Number(t.host.t),i=Number(t.length);return Number.isFinite(e)&&e>=0&&e<=1&&Number.isFinite(i)&&i>0&&e*o-i/2>=-1e-12&&e*o+i/2<=o+1e-12});if(a){r=i,t.a=s,t.b=n;break}}r?(n++,a=Math.max(a,Math.hypot(r.to[0]-r.from[0],r.to[1]-r.from[1]))):o++}return{space:e,report:{wallsStraightened:n,wallsStraightenSkipped:o,maxStraightenShift:a},changed:n>0}}(t);g+=e.report.wallsStraightened,f+=e.report.wallsStraightenSkipped;const i=Number(t?.cell_cm)>0?Number(t.cell_cm):5,s=e.report.maxStraightenShift/Th*i;return s>v&&(v=s,y=String(t?.id||"")),e.space}),w=g?X_(b,m.layout):{...m,spaces:b};a.spaces=w.spaces;const k=g?{...m.report,moved:m.report.moved+w.report.moved,coordsCanonicalized:m.report.coordsCanonicalized+w.report.coordsCanonicalized,maxShift:Math.max(m.report.maxShift,w.report.maxShift),maxShiftCm:Math.max(m.report.maxShiftCm,w.report.maxShiftCm),maxSpace:w.report.maxShiftCm>m.report.maxShiftCm?w.report.maxSpace:m.report.maxSpace,rotated:m.report.rotated+w.report.rotated,removedDrafts:m.report.removedDrafts+w.report.removedDrafts}:{...m.report};let x=0,$=0,S=0,M=0,C=0,D=0,P=0,T=0;for(let t=0;t0===Number(t.cm)),walls:e.walls||[]}),o=sg(e),r=sg(i);if(!o||!r)continue;const l=ag(o.rooms),c=ag(r.rooms),h=.02*Ph,d=(e.wall_segments||[]).filter(t=>0===Number(t.cm)).map(t=>({...t,key:wl(t.a,t.b,Th),cm:0})),p=new Set(d.map(t=>t.key)),_=m_(e,o.rooms,yh,h);$+=_.length;for(const t of _){const e=[t[0]/yh,t[1]/yh],i=[t[2]/yh,t[3]/yh],s=wl(e,i,Th);p.has(s)||(p.add(s),d.push({key:s,a:e,b:i,cm:0}))}const m=d.length,g=Al(d,l,c,Th,yh),f=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(!(o>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))},v=g.filter(t=>{if(!Array.isArray(t.a)||!Array.isArray(t.b))return!1;const e=t.a.map(t=>t*yh),i=t.b.map(t=>t*yh);return c.some(([t,s])=>f(e,t,s)<=4*h&&f(i,t,s)<=4*h)});S+=Math.max(0,m-v.length);const y=(i.wall_segments||[]).filter(t=>Number(t.cm)>0);i.wall_segments=[...y,...v.map(({key:t,...e})=>e)];const b=v.map(t=>[t.a[0]*yh,t.a[1]*yh,t.b[0]*yh,t.b[1]*yh]),w=Array.isArray(e.walls)?e.walls.length:0;let k=Al(e.walls,l,c,Th,yh);k=og(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=uc(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=Tl(k,i.rooms||[],Th,1,b.map(t=>[t[0]/yh,t[1]/yh,t[2]/yh,t[3]/yh])),x+=Math.max(0,w-k.length),k.length?i.walls=k:delete i.walls;const R=nm(i.partitions||[],{pitch:Th,geometry:am(i)});R.merged&&(M+=R.merged,i.partitions=R.partitions,om(i.openings,i.partitions,R.openingMoves,{coordScale:yh,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph}));const I=sg(i);if(I){const t=n(i,I,i.walls||[],b,{pitch:Th,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph,coordScale:yh});t.partitionsReconciled&&(C+=t.partitionsReconciled,D+=t.openingsRehosted,t.partitions.length?i.partitions=t.partitions:delete i.partitions,t.openings.length?i.openings=t.openings:delete i.openings,t.walls.length?i.walls=t.walls:delete i.walls),t.removedDrafts&&(P+=t.removedDrafts,t.roomDrafts.length?i.room_drafts=t.roomDrafts:delete i.room_drafts)}JSON.stringify({zero:(i.wall_segments||[]).filter(t=>0===Number(t.cm)),walls:i.walls||[]})!==s&&T++}let R=0;h<=9&&(R=function(t){const e=Zm(t);return tg(t,e.config),{...e,config:t}}(a).migratedSegments);const I=rl(a),A=al(w.layout),z=JSON.stringify(I)!==l||JSON.stringify(A)!==c;h<9&&z&&(I.model_version=9);const F=JSON.stringify(I)!==l||JSON.stringify(A)!==c,E=Number.isInteger(Number(I.model_version))?Number(I.model_version):h,N=F?k:{...k,moved:0,coordsCanonicalized:0,maxShift:0,maxShiftCm:0,maxSpace:"",rotated:0,removedDrafts:0},O=F?o.report:{...o.report,spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0};return{config:I,layout:A,report:{...N,modelFrom:h,modelTo:E,migrated:F?p:0,glowSpacesMigrated:F?d.glowSpaces:0,glowRoomsMigrated:F?d.glowRooms:0,canonicalized:F?T:0,wallSegmentsMigrated:F?R:0,legacyZeroWallsMigrated:F?$:0,wallsMerged:F?x:0,spansMerged:F?S:0,partitionsMerged:F?M:0,partitionsReconciled:F?C:0,openingsRehosted:F?D:0,redundantDraftsRemoved:F?P:0,wallsStraightened:F?g:0,wallsStraightenSkipped:f,maxStraightenShiftCm:F?v:0,maxStraightenSpace:F?y:"",latticeCoordinatesCanonicalized:F?r.canonicalized:0,latticeCoordinatesFar:F?r.far:0,latticeMaxShift:F?r.maxShift:0,latticeMaxShiftCm:F?r.maxShiftCm:0,latticeSpaces:F?r.spaces:[],...O},changed:F}}function lg(t,e,i){const s=(t?.spaces||[]).find(t=>t?.id===i),n=new Set((s?.rooms||[]).map(t=>String(t?.id||"")).filter(Boolean)),o=[...new Set((t?.markers||[]).filter(t=>!0!==t?.removed&&"string"==typeof t?.id).filter(t=>t.space===i||"string"==typeof t.room_id&&n.has(t.room_id)||e?.[t.id]?.s===i).map(t=>t.id))].sort((t,e)=>t.localeCompare(e));return{markerIds:o,count:o.length}}function cg(t){return t instanceof Error?t.name||"Error":typeof t}function hg(t){return wd({id:t?.id??"",cell_cm:t?.cell_cm,rooms:t?.rooms||[],walls:t?.walls||[],wall_segments:t?.wall_segments||[],open_spans:t?.open_spans||[],openings:t?.openings||[],partitions:t?.partitions||[],room_drafts:t?.room_drafts||[],wall_columns:t?.wall_columns||[]})}function dg(t,e,i,s=Ph,n=1e3){return(Array.isArray(t?.openings)?t.openings:[]).flatMap(t=>{const o={...t,rx:Number(t.x)*n,ry:Number(t.y)*n,rlen:Number(t.length)*n};if(!t.host||"wall"===t.host.kind)return[o];const a=Sp(t,e.partitions,n,i,s);return a.resolved?[{...t,rx:a.resolved.center[0],ry:a.resolved.center[1],rlen:a.resolved.length,angle:a.resolved.angle,partitionHost:a.resolved}]:[]})}function pg(t,e=()=>!0){return t.flatMap(t=>t.host&&t.partitionHost&&e(t)?[Dp(t.partitionHost)]:[])}function ug(t,e,i,s,n,o,a=Ph,r=1e3){const l=dc(e.rooms,[...i],s,n,o,a,r);return t.flatMap(t=>{const e={x:t.rx,y:t.ry,angle:Number(t.angle)||0,length:t.rlen};return t.host&&"wall"!==t.host.kind?t.partitionHost&&Rp(t.partitionHost,l,2e-4*a)?[e]:[]:[e]})}function _g(t,e){const i=Th,s=Ph,n=yh,o=Number.isFinite(Number(e.cellCm))&&Number(e.cellCm)>0?Number(e.cellCm):5,a=Array.isArray(t?.walls)?t.walls:[],r=function(t,e,i=Ph,s=1e3){return _d(e.rooms,t?.open_spans,s,.02*i)}(t,e,s,n),l=function(t,e,i=Ph){if(!e.length)return[];const s=t.filter(t=>t?.id),n=.02*i,o=[];for(let t=0;t{const e=[(t[0]+t[2])/2,(t[1]+t[3])/2];return h.some(t=>Ls(e,t)<4*n)}).map(t=>[...t]);d.length&&o.push({a:a,b:r,segs:d})}return o}(e.rooms,r,s).flatMap(t=>t.segs),c=dg(t,e,o,s,n),h=pg(c),d=ih(e,o,s,2e-4*s,h).all;return{space:e,walls:a,openCuts:l,openings:c,roomOpenings:ug(c,e,a,l,i,o,s,n),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:s,coordScale:n}}function mg(t,e,i){const s="string"==typeof t?.title?t.title.trim():"",n=null==t?.id?"":String(t.id).trim();return{spaceId:n,displayName:s||n||i(e+1)}}function gg(t,e={}){const i=(e.fingerprint||wd)(t),s=Array.isArray(t?.spaces)?t.spaces:[],n=e.fallbackSpaceName||(t=>`Space ${t}`),o=e.prepareSpace||_g,a=e.wallPass||Rc,r=e.floorPass||Pc,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!p){l.push({...h,status:"not-applicable"});continue}let u=null;if(p){try{u=a(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(t){l.push({...h,status:"failed",reason:"wall-exception",detail:cg(t)});continue}if(null==u){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===u.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===u.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}e.captureWallGeometry?.(d,u)}if(d.space.rooms.length&&null==u?.paperGeom){let t;try{t=r(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(t){l.push({...h,status:"failed",reason:"floor-exception",detail:cg(t)});continue}if(null==t){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(t=>"failed"===t.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}class fg{constructor(t=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(t))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(t){this._undo.push(t),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const t=this._undo.pop()??null;return t&&this._redo.push(t),t}redo(){const t=this._redo.pop()??null;return t&&this._undo.push(t),t}clear(){this._undo=[],this._redo=[]}}const vg=new WeakMap;const yg=(t,e,i)=>255===t[i+3]&&e.every((e,s)=>Math.abs(t[i+s]-e)<=2);async function bg(t){const e=t.defaultView;if(!e||!e.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],s=[16,64,128],n=[9,19,29],o=`\n \n \n \n \n \n `,a=e.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((t,i)=>{const s=new e.Image,n=e.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);s.onload=()=>{e.clearTimeout(n),t(s)},s.onerror=()=>{e.clearTimeout(n),i(new Error("SVG blend probe failed"))},s.src=a}),r=t.createElement("canvas");r.width=4,r.height=1;const l=r.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return yg(c,i,0)&&yg(c,function(t,e){return[0,1,2].map(i=>Math.round(255-(255-t[i])*(255-e[i])/255))}(i,s),4)&&yg(c,s,8)&&yg(c,n,12)}catch{return!1}finally{e.URL.revokeObjectURL(a)}}const wg={now:()=>performance.now(),requestFrame:t=>requestAnimationFrame(t),cancelFrame:t=>cancelAnimationFrame(t)},kg=t=>Math.max(0,Math.min(1,t)),xg=(t,e,i)=>t+(e-t)*i,$g=(t,e,i)=>{const s=1-t;return 3*s*s*t*e+3*s*t*t*i+t*t*t};function Sg(t,e){return{centerX:t.x+t.w/2,centerY:t.y+t.h/2,pixelsPerUnit:e>0&&t.w>0?e/t.w:1,viewBox:{...t}}}function Mg(t,e,i){const s=Math.max(1e-9,t.pixelsPerUnit),n=Math.max(1e-9,e/s),o=Math.max(1e-9,i/s);return{x:t.centerX-n/2,y:t.centerY-o/2,w:n,h:o}}function Cg(t){const e=t.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(e);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const s=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(e)?.[1];return s?[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16),8===s.length?parseInt(s.slice(6,8),16)/255:1]:null}function Dg(t,e,i){const s=Cg(t),n=Cg(e);if(!s||!n)return i<.5?t:e;const o=kg(i);return`rgba(${Math.round(xg(s[0],n[0],o))}, ${Math.round(xg(s[1],n[1],o))}, ${Math.round(xg(s[2],n[2],o))}, ${xg(s[3],n[3],o).toFixed(3)})`}function Pg(t,e,i){const s=(t=>{const e=kg(t);if(0===e||1===e)return e;let i=0,s=1,n=e;for(let t=0;t<12;t++)n=(i+s)/2,$g(n,.2,.2){const e=this._state;if(!e||e.token!==n)return;const i=kg((t-e.startedAt)/e.duration);e.presented=i>=1?e.to:Pg(e.from,e.to,i),e.phase=i>=1?"settling":"running",this._hooks.frame(e),i<1?this._raf=this._clock.requestFrame(a):(this._raf=0,this._hooks.settled(e),this._state?.token===n&&(this._state=null))};return this._raf=this._clock.requestFrame(a),n}cancel(t=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const e=this._state;this._state=null,this._token++,e&&t&&(e.phase="settling",e.presented=e.to,this._hooks.frame(e),this._hooks.settled(e))}dispose(){this.cancel(!1)}}const Rg="houseplan_card_labs_v1",Ig=Object.freeze([Object.freeze({id:"iso",issue:89,since:"1.62.0",expires:"1.65.0",summary:"Volumetric plan renderer"})]);function Ag(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(String(t||"").trim());if(!e)return null;const i=e.slice(1).map(Number);return i.every(t=>Number.isSafeInteger(t))?i:null}function zg(t,e){for(let i=0;i<3;i++)if(t[i]!==e[i])return t[i]t.split(",")).map(t=>t.trim()).filter(Boolean)}function Hg(t,e,i,s=Ig){const n=function(t,e=Ig){const i=Ag(t),s=new Map;if(!i||!Eg(e))return s;for(const t of e){const e=Ag(t.since),n=Ag(t.expires);zg(i,e)>=0&&zg(i,n)<0&&s.set(t.id,t)}return s}(i,s),o=new Set(Eg(s)?s.map(t=>t.id):[]),a=new Set(function(t){if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}catch{return[]}}(e).filter(t=>n.has(t)));let r=!1;const l=t=>{if("off"===t)return a.clear(),void(r=!0);const e=t.startsWith("-"),i=e?t.slice(1):t;o.has(i)&&(r=!0,e||!n.has(i)?a.delete(i):a.add(i))};for(const e of Lg(new URLSearchParams(String(t.search||"").replace(/^\?/,""))))l(e);for(const e of Lg(Ng(t.hash)))l(e);const c=Object.freeze([...a].sort());return{active:c,space:Og(t.hash),persist:r?JSON.stringify(c):void 0,knownUrlOperation:r}}let Bg={active:Object.freeze([]),space:""},qg="",Wg=!1,jg="";const Ug=new Set;function Gg(){if("undefined"==typeof window)return Bg;const t=Hg(window.location,function(){try{return window.localStorage.getItem(Rg)}catch{return null}}(),qg);void 0!==t.persist&&function(t){try{window.localStorage.setItem(Rg,t)}catch{}}(t.persist),Bg={active:t.active,space:t.space},window.__hpLabs=t.active;for(const t of Ug)t(Bg);return Bg}function Vg(){Gg()}function Kg(t){return qg=t,"undefined"==typeof window?Bg:(Wg||(Wg=!0,window.addEventListener("hashchange",Vg),window.addEventListener("popstate",Vg)),Gg())}const Yg=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])});function Jg(t){return[t.rotDeg,t.tiltDeg,t.xyScale,t.zScale,t.origin[0],t.origin[1]].every(Number.isFinite)&&Math.abs(t.xyScale)>1e-12&&Math.abs(Math.cos(t.tiltDeg*Math.PI/180))>1e-12}function Xg(t,e,i=Yg){if(!(Jg(i)&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(e)))throw new Error("invalid isometric projection input");const s=i.rotDeg*Math.PI/180,n=i.tiltDeg*Math.PI/180,o=t[0]-i.origin[0],a=t[1]-i.origin[1],r=(o*Math.cos(s)-a*Math.sin(s))*i.xyScale,l=(o*Math.sin(s)+a*Math.cos(s))*i.xyScale;return[i.origin[0]+r,i.origin[1]+l*Math.cos(n)-e*i.zScale*Math.sin(n)]}function Zg(t,e=Yg){if(!Jg(e)||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new Error("invalid isometric projection input");const i=e.rotDeg*Math.PI/180,s=e.tiltDeg*Math.PI/180,n=(t[0]-e.origin[0])/e.xyScale,o=(t[1]-e.origin[1])/(e.xyScale*Math.cos(s));return[e.origin[0]+n*Math.cos(i)+o*Math.sin(i),e.origin[1]-n*Math.sin(i)+o*Math.cos(i)]}function Qg(t=Yg){return`matrix(${function(t=Yg){if(!Jg(t))throw new Error("invalid isometric camera");const e=t.rotDeg*Math.PI/180,i=t.tiltDeg*Math.PI/180,s=t.xyScale*Math.cos(e),n=-t.xyScale*Math.sin(e),o=t.xyScale*Math.sin(e)*Math.cos(i),a=t.xyScale*Math.cos(e)*Math.cos(i);return[s,o,n,a,t.origin[0]-s*t.origin[0]-n*t.origin[1],t.origin[1]-o*t.origin[0]-a*t.origin[1]]}(t).map(t=>Number(t.toFixed(12))).join(" ")})`}function tf(t,e=Yg){const{rect:i,wallHeight:s}=t,n=t.openingHeight??s,o=t.floorDepth??0;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(o)||s<0||n<0||o<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],r=Math.max(s,n),l=a.flatMap(t=>[Xg(t,-o,e),Xg(t,r,e)]),c=l.map(t=>t[0]),h=l.map(t=>t[1]),d=Math.min(...c),p=Math.min(...h);return{x:d,y:p,w:Math.max(...c)-d,h:Math.max(...h)-p}}const ef=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function sf(t){let e=0;for(let i=0;iArray.isArray(t)&&Number.isFinite(t[0])&&Number.isFinite(t[1])).map(t=>[Number(t[0]),Number(t[1])]),i=e[e.length-1];return e.length>1&&e[0][0]===i[0]&&e[0][1]===i[1]&&e.pop(),e}(t);if(i.length<3)return[];const s=!e;return sf(i)>0===s?i:[...i].reverse()}function of(t,e,i){return t.length?`M ${t.map(t=>ef(Xg(t,i,e))).join(" L ")} Z`:""}function af(t,e,i){const s=e[1]-t[1],n=-(e[0]-t[0]),o=i.rotDeg*Math.PI/180;return s*Math.sin(o)+n*Math.cos(o)}function rf(t,e,i=Yg){if(!Number.isFinite(e)||e<0)throw new Error("invalid floor edge height");const s=(t||[]).map(t=>(t||[]).map((t,e)=>function(t,e){const i=nf(t,e);if(!i.length)return i;let s=0;for(let t=1;t0)).filter(t=>t.length>=3&&Math.abs(sf(t))>=1e-9)).filter(t=>t.length&&sf(t[0])>0);s.sort((t,e)=>{const i=t[0][0],s=e[0][0];return i[0]-s[0]||i[1]-s[1]||Math.abs(sf(e[0]))-Math.abs(sf(t[0]))});const n=[],o=[];let a=0;for(let t=0;tt.depth-e.depth||t.component-e.component||t.edge-e.edge),{footprintPath:n.join(" "),sides:o,componentCount:s.length,edgeCount:a}}function lf(t,e){return t^=Math.round(64*(Number.isFinite(e)?e:0)),Math.imul(t,16777619)>>>0}const cf=t=>t.every(Number.isFinite);function hf(t,e,i,s){const n=t[0]*i,o=t[1]*s,a=e*Math.PI/180;return[n*Math.cos(a)-o*Math.sin(a),n*Math.sin(a)+o*Math.cos(a)]}function df(t,e,i,s,n,o,a){const r=t.flipH?-1:1,l="gate"===t.type?1:t.flipV?-1:1,c=(t.type,t.flipV,t.angle,t.face,{ox:0,oy:0}),h=function(t,e){return[t[0]+e[0],t[1]+e[1]]}([t.x+c.ox,t.y+c.oy],hf(i,t.angle,r,l));return{leaf:e,hinge:h,closedVector:hf(s,t.angle,r,l),quarterVector:hf([-s[1],s[0]],t.angle,r,l),turnDeg:n,bottom:o,top:a}}const pf=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function uf(t,e,i=Yg){const s=Math.max(0,Math.min(1,Number.isFinite(e)?e:0));return t.leaves.map(e=>{const n=function(t,e){const i=t.turnDeg*e*Math.PI/180;return[t.hinge[0]+t.closedVector[0]*Math.cos(i)+t.quarterVector[0]*Math.sin(i),t.hinge[1]+t.closedVector[1]*Math.cos(i)+t.quarterVector[1]*Math.sin(i)]}(e,s),o=Xg(e.hinge,e.bottom,i),a=Xg(n,e.bottom,i),r=Xg(n,e.top,i),l=Xg(e.hinge,e.top,i);return{id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${pf(o)} L ${pf(a)} L ${pf(r)} L ${pf(l)} Z`,shadowD:`M ${pf(Xg(e.hinge,0,i))} L ${pf(Xg(n,0,i))}`,depth:Math.max(o[1],a[1])}})}const _f={window:120,door:90,passage:90,gate:300};function mf(t){return _f[t]}function gf(t,e){const i=[t[0],t[1]],s=[e[0],e[1]];return function(t,e){return t[0]-e[0]||t[1]-e[1]}(i,s)<=0?{a:i,b:s}:{a:s,b:i}}function ff(t){const e=new Map;return t.forEach((t,i)=>{if(!t.kind||t.open)return;const s=gf(t.a,t.b);if(Math.hypot(s.b[0]-s.a[0],s.b[1]-s.a[1])<=1e-9)return;const n=function(t,e){const i=t=>(Math.abs(t)<=5e-10?0:Math.round(1e6*t)/1e6).toFixed(6);return`${i(t[0])},${i(t[1])}>${i(e[0])},${i(e[1])}`}(s.a,s.b),o=e.get(n);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,t.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(t.partitionHost&&(o.partitionHost&&o.partitionHost.id!==t.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=t.partitionHost));e.set(n,{segmentKey:n,a:s.a,b:s.b,physicalHalfWidth:Math.max(0,t.half||0),sourceOrder:i,...t.partitionHost?{partitionHost:t.partitionHost}:{}})}),[...e.values()]}function vf(t,e){if(Math.abs(t.distance-e.distance)>1e-9)return t.distance-e.distance;if(Math.abs(t.perpendicular-e.perpendicular)>1e-9)return t.perpendicular-e.perpendicular;return(t.target.segmentKeye.target.segmentKey?1:0)||t.target.sourceOrder-e.target.sourceOrder}function yf(t){const e=ff(t.intervals).map(e=>{const i=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,r=(t[0]-e.a[0])*o+(t[1]-e.a[1])*a,l=Math.max(0,Math.min(n,r)),c=e.a[0]+l*o,h=e.a[1]+l*a;return{along:l,length:n,x:c,y:h,distance:Math.hypot(t[0]-c,t[1]-h),perpendicular:Math.abs((t[0]-e.a[0])*a-(t[1]-e.a[1])*o)}}(t.pointer,e);return{target:e,...i,envelope:Math.max(t.baseTolerance,e.physicalHalfWidth+t.bodyPointerPadding)}}).filter(t=>t.distance<=t.envelope+1e-9).filter(e=>!function(t,e,i,s,n){const o=e.b[0]-e.a[0],a=e.b[1]-e.a[1],r=Math.hypot(o,a);if(!(r>1e-9))return!1;const l=o/r,c=a/r;for(const o of i){if(!o.open&&o.kind)continue;const i=gf(o.a,o.b),a=i.b[0]-i.a[0],r=i.b[1]-i.a[1],h=Math.hypot(a,r);if(!(h>1e-9))continue;const d=a/h,p=r/h;if(Math.abs(l*p-c*d)>1e-6)continue;if(Math.abs((i.a[0]-e.a[0])*c-(i.a[1]-e.a[1])*l)>n)continue;const u=(t[0]-i.a[0])*d+(t[1]-i.a[1])*p,_=1e-9;if(!(u<=_||u>=h-_)&&Math.abs((t[0]-i.a[0])*p-(t[1]-i.a[1])*d)<=s+1e-9)return!0}return!1}(t.pointer,e.target,t.intervals,e.envelope,Math.max(1e-9,Math.min(t.baseTolerance,.04*t.gridStep)))),i=e.filter(e=>!!e.target.partitionHost&&t.renderedLength+2*e.target.physicalHalfWidth>e.length+1e-9).sort(vf),s=e.filter(e=>!e.target.partitionHost||t.renderedLength+2*e.target.physicalHalfWidth<=e.length+1e-9).sort(vf);let n=s[0];if(!n)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=s.filter(t=>Math.abs(t.distance-n.distance)<=1e-9&&Math.abs(t.perpendicular-n.perpendicular)<=1e-9),a=o.filter(t=>t.target.partitionHost);if(a.length){if(1!==new Set(a.map(t=>t.target.partitionHost.id)).size||a.some(t=>t.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const t=a[0],e=t.target.b[0]-t.target.a[0],i=t.target.b[1]-t.target.a[1],s=Math.hypot(e,i),r=e/s,l=i/s,c=o.every(e=>{const i=e.target.b[0]-e.target.a[0],s=e.target.b[1]-e.target.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,c=Math.abs(r*a-l*o)<=1e-6,h=Math.abs((e.target.a[0]-t.target.a[0])*l-(e.target.a[1]-t.target.a[1])*r);return c&&h<=1e-9});if(!c)return{candidate:null,jambBlockedTarget:null};n=t}if(n.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:r,length:l}=n,c=r.b[0]-r.a[0],h=r.b[1]-r.a[1],d=c/l,p=h/l,u=r.partitionHost?r.physicalHalfWidth:0,_=Math.min(Math.max(0,t.renderedLength)/2+u,l/2);let m=n.along;const g=Math.max(t.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=r.a[0]+d*m,y=r.a[1]+p*m,b=Math.max(0,t.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),$=Math.max(0,l-k),S=[r.a[0]+d*(w-x/2),r.a[1]+p*(w-x/2)],M=[r.a[0]+d*(k+$/2),r.a[1]+p*(k+$/2)];let C=180*Math.atan2(h,c)/Math.PI;C>=90?C-=180:C<-90&&(C+=180);const D=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:t.preset.revision,geometryRevision:t.geometryRevision,pointer:[t.pointer[0],t.pointer[1]],type:t.preset.type,lengthCm:t.preset.lengthCm,flipH:t.preset.flipH,flipV:t.preset.flipV,x:v,y:y,angle:C,renderedLength:t.renderedLength,target:r,...r.partitionHost?{host:{...r.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:S},{distance:$,midpoint:M}],guide:D?{x:v,y:y,angle:C}:null}},jambBlockedTarget:null}}function bf(t,e,i,s,n=1e-6){return t.presetRevision===i&&t.geometryRevision===s&&Math.hypot(t.pointer[0]-e[0],t.pointer[1]-e[1])<=n}const wf=(t,e)=>t[0]*e[1]-t[1]*e[0],kf=(t,e)=>t[0]*e[0]+t[1]*e[1],xf=(t,e)=>[t[0]-e[0],t[1]-e[1]],$f=(t,e,i)=>[t[0]+e[0]*i,t[1]+e[1]*i];function Sf(t,e,i){return Math.abs(wf(t,e))<=i}function Mf(t,e,i){return Math.abs(wf(xf(t,e),i))}function Cf(t,e,i,s,n){const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n&&i>0))return[];const l=[o/r,a/r];return function(t,e,i){const s=e.map(([e,i])=>[Math.max(0,Math.min(e,i)),Math.min(t,Math.max(e,i))]).filter(([t,e])=>e>t+i).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),n=[];for(const t of s){const e=n[n.length-1];!e||t[0]>e[1]+i?n.push([...t]):e[1]=Math.max(e[1],t[1])}const o=[];let a=0;for(const[t,e]of n)t>a+i&&o.push([a,t]),a=Math.max(a,e);return t>a+i&&o.push([a,t]),o}(r,s.flatMap(e=>{const s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=Math.hypot(s,o);if(!(a>n&&Sf(l,[s/a,o/a],1e-6)))return[];if(Mf(e.a,t,l)>1.1*Math.max(i,n)||Mf(e.b,t,l)>1.1*Math.max(i,n))return[];return[[kf(xf(e.a,t),l),kf(xf(e.b,t),l)]]}),n).flatMap(([e,s])=>{const n=Ol({a:$f(t,l,e),b:$f(t,l,s),halfDepth:i});return n?[n]:[]})}function Df(t){const e=t.coordScale??1,i=Math.max(t.epsilon??2e-4*t.gridPitch,1e-9),s=[];for(const i of t.rooms||[]){if(!i?.id)continue;const n=hc(t.rooms,i.id,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e);if(!n||n.poly.length<3)continue;const o=Zl(n.poly,n.offsets);!o||o.length<3||s.push({roomId:i.id,profile:n,inner:o})}s.sort((t,e)=>t.roomId.localeCompare(e.roomId));const n=(t.roomOpenings||[]).map(t=>{const e=t.angle*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Math.max(0,t.length)/2;return{a:$f([t.x,t.y],i,-s),b:$f([t.x,t.y],i,s)}}),o=[];for(const s of zc(t.rooms,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e))for(const t of Cf(s.a,s.b,s.depthUnits/2,n,i))o.push({body:t});const a=new Map;for(const e of t.partitionCuts||[]){const t=a.get(e.hostId)||[];t.push(e),a.set(e.hostId,t)}for(const e of t.partitions||[]){const s=gl(e.cm,t.cellCm,t.gridPitch)/2;for(const t of Cf(e.a,e.b,s,a.get(e.id)||[],i))o.push({body:t,partitionId:e.id})}return{rooms:s,boundaries:o,epsilon:i}}function Pf(t,e,i,s){const n=t.profile.offsets[e];if(!(n>0))return null;const o=function(t,e){const i=t[e],s=t[(e+1)%t.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return function(t){let e=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t.profile.poly,e),a=$f(i.center,o,n),r=[];for(let e=0;es&&Sf(i.axis,[l[0]/c,l[1]/c],1e-6)))continue;if(Mf(n,a,i.axis)>s||Mf(o,a,i.axis)>s)continue;const h=kf(xf(n,a),i.axis),d=kf(xf(o,a),i.axis);r.push([Math.min(h,d),Math.max(h,d)])}const l=function(t,e){t.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);const i=[];for(const s of t){const t=i[i.length-1];!t||s[0]>t[1]+e?i.push([...s]):t[1]=Math.max(t[1],s[1])}return i}(r,s).find(([t,e])=>t<=s&&e>=-s);if(!l)return null;const[c,h]=l,d=$f(a,i.axis,-i.half),p=$f(a,i.axis,i.half),u=Math.max(0,-i.half-c),_=Math.max(0,h-i.half),m=u>0?$f(a,i.axis,c):d,g=_>0?$f(a,i.axis,h):p,f=kf(o,i.normal)>=0?1:-1,v=(e,s,n)=>({from:e,to:s,label:[(e[0]+s[0])/2,(e[1]+s[1])/2],axis:i.axis,labelNormal:o,distance:n,roomId:t.roomId,roomSide:f,source:"room-face"});return{left:v(d,m,u),right:v(p,g,_)}}function Tf(t){const e=$f(t.center,t.axis,-t.half),i=$f(t.center,t.axis,t.half),s=$f(t.center,t.axis,Math.min(-t.half,t.targetLo)),n=$f(t.center,t.axis,Math.max(t.half,t.targetHi)),o=(e,i)=>({from:e,to:i,label:[(e[0]+i[0])/2,(e[1]+i[1])/2],axis:t.axis,labelNormal:t.normal,distance:Math.hypot(i[0]-e[0],i[1]-e[1]),source:"host-end"});return[o(e,s),o(i,n)]}function Rf(t,e,i,s){const n=xf(i,e),o=kf(n,n);if(!(o>s*s))return Math.hypot(...xf(t,e))<=s;const a=kf(xf(t,e),n)/o;if(a<-s||a>1+s)return!1;const r=$f(e,n,Math.max(0,Math.min(1,a)));return Math.hypot(...xf(t,r))<=s}function If(t,e,i){let s=!1;for(let n=0,o=e.length-1;nt[1]!=c>t[1]&&t[0]<(l-a)*(t[1]-r)/(c-r)+a&&(s=!s)}return s}function Af(t,e,i,s,n,o){const a=xf(s,i),r=wf(e,a);if(Math.abs(r)<=o)return null;const l=xf(i,t),c=wf(l,a)/r,h=wf(l,e)/r;return c<-o||c>n+o||h<-o||h>1+o?null:Math.max(0,Math.min(n,c))}function zf(t,e,i){const s=Tf(i),n="partition"===t.host?.kind?t.host.id:void 0;return[{base:s[0],direction:[-i.axis[0],-i.axis[1]]},{base:s[1],direction:i.axis}].map(({base:t,direction:i})=>{const s=t.distance,o=function(t,e,i,s,n,o){let a=null;for(const r of s)if(!n||r.partitionId!==n){if(If(t,r.body,o))return 0;for(let s=0;skf(xf(t,n),i));return{center:n,axis:i,normal:s,half:Math.max(0,t.renderedLength)/2,targetLo:Math.min(...o),targetHi:Math.max(...o)}}(t),s=e.rooms.flatMap(t=>{const s=function(t,e,i){const{profile:s}=t;let n=null;for(let t=0;t0))continue;const o=s.poly[t],a=s.poly[(t+1)%s.poly.length],r=xf(a,o),l=Math.hypot(r[0],r[1]);if(!(l>i&&Sf(e.axis,[r[0]/l,r[1]/l],1e-6)))continue;if(Mf(o,e.center,e.axis)>i||Mf(a,e.center,e.axis)>i)continue;const c=kf(xf(o,e.center),e.axis),h=kf(xf(a,e.center),e.axis),d=Math.min(c,h),p=Math.max(c,h);if(d>-e.half+i||p0?d:p<0?-p:0);(!n||u2)return Tf(i);if(s.length){const t=s.map(({room:t,edge:s})=>Pf(t,s,i,e.epsilon));if(t.some(t=>!t))return Tf(i);const n=t;return[...n.map(t=>t.left),...n.map(t=>t.right)]}return zf(t,e,i)}function Ef(t){return!(!t.canEdit||t.kiosk||t.fixedFloor)&&("view"!==t.mode&&("mouse"===t.pointerType&&t.spaceCount>1))}const Nf="1.68.0",Of={badge:"display.badge",icon_ripple:"display.icon_ripple",value:"display.value",static_icon:"display.static_icon"},Lf={badge:"marker.display_hint_badge",icon_ripple:"marker.display_hint_icon_ripple",value:"marker.display_hint_value",static_icon:"marker.display_hint_static_icon"},Hf=2e3,Bf=1e3,qf=1500,Wf=t=>{const e=String(t??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return null;const i=Number(e);return Number.isFinite(i)?i:null},jf=(t,e)=>{if(!t.has(e))return{hit:!1};const i=t.get(e);return t.delete(e),t.set(e,i),{hit:!0,value:i}},Uf=(t,e,i,s)=>{for(t.delete(e),t.set(e,i);t.size>s;){const e=t.keys().next().value;if(void 0===e)break;t.delete(e)}},Gf=new Map;let Vf=0;const Kf=t=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(t??{})}`;let Yf=1e4;const Jf="houseplan_card_layout_v1",Xf="houseplan_card_cfg_v1",Zf="houseplan_card_zoom_v1",Qf="houseplan_card_nav_v1",tv="houseplan_card_kiosk_v1",ev="houseplan_card_view_v1",iv="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",sv=1e3,nv=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]],ov=(t,e)=>{const i=Math.min(t.x,e.x),s=Math.min(t.y,e.y);return{x:i,y:s,w:Math.max(t.x+t.w,e.x+e.w)-i,h:Math.max(t.y+t.h,e.y+e.h)-s}},av=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),rv=2e3,lv=(t,e,i)=>{const s=new Event(e,{bubbles:!0,composed:!0});s.detail=i??{},t.dispatchEvent(s)},cv=t=>{history.pushState(null,"",t),lv(window,"location-changed",{replace:!1})},hv=(t,e)=>{let i,s=null;const n=(...n)=>{clearTimeout(i),s=n,i=window.setTimeout(()=>{i=void 0;const e=s;s=null,e&&t(...e)},e)};return n.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const e=s;s=null,e&&t(...e)},n.cancel=()=>{clearTimeout(i),i=void 0,s=null},n.pending=()=>void 0!==i,n},dv=t=>{try{t.target?.setPointerCapture?.(t.pointerId)}catch{}};class pv extends ht{constructor(){super(...arguments),this._space="f1",this._layout={},this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._serverCfg=null,this._cfgRev=0,this._cfgContentFingerprint="",this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._layoutRev=0,this._layoutContentFingerprint="",this._virtualLights=mn(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._tip=null,this._hoverRoom=null,this._pointerModality=new N_(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...Rr},this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=t=>{this._reducedMotion=t.matches,this._cancelDevicePressFeedback(),t.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:t.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Tg({frame:t=>this._applyModeTransitionFrame(t),settled:t=>this._settleModeTransition(t)}),this._editorSecondary=new W_({root:()=>this.renderRoot,requestUpdate:()=>this.requestUpdate(),updateComplete:()=>this.updateComplete,clearTip:()=>{this._tip=null}}),this._editorSecondaryCopy={groupActive:(t,e)=>this._t("editor.group_active",{group:t,item:e}),openGroup:t=>this._t("editor.open_group",{group:t}),disabledAction:(t,e)=>this._t("editor.disabled_action",{action:t,reason:e})},this._tool="draw",this._geometryHistory=new fg(50),this._wallDialog=null,this._drawWallField=null,this._activeDraftId=null,this._resumeDraftBySpace={},this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowClipCache=new Map,this._glowGeometryWarnings=new Set,this._lightBarrierCache=null,this._glowFeatherUnits=null,this._glowRenderedSources=new Map,this._glowLastAppearance=new Map,this._glowEnteringSources=new Set,this._glowEnterRafs=new Map,this._glowFadeTimers=new Map,this._glowFeatherSuspendUntil=0,this._glowFeatherResumeTimer=0,this._glowSourceSeq=0,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszSel=null,this._rszDrag=null,this._rszEligibilityCache=null,this._rszPreview=null,this._rszLive=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._touchContacts=new Map,this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:t=>this._guardTouchGesture(t)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._alignDialog=null,this._settingsDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=t=>this._onKey(t),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++Vf,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=t=>{if(this._continuity.visibility(t),this._dayCycleVisibility(t),"hidden"===t.kind)return this._clearTransientHover(!0),this._cancelDevicePressFeedback(),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,!t.long){const t=Date.now();let e=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+I_)>t||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,e=!0);return void(e&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._lastTap=0,this._onLabsSnapshot=t=>{const e=this._effectiveProjection();this._labs=t;const i=this._effectiveProjection();this._convertProjectionView(e,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const t=this._hashSpace();if(t&&this._model.find(e=>e.id===t)&&t!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._onHaRegistryUpdate=()=>{const t=An(this.hass);t.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=t.revision,this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,function(t){const e=Cn(t);e&&(Tn(t,e),Rn(t,e))}(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new $d(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=hv(()=>{if(this._serverStorage){const t=[...this._dirtyPos];this._dirtyPos.clear();for(const e of t){const t=ol(this._layout[e]);t&&(this._layout={...this._layout,[e]:t},this._sentPos.set(e,t),this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t}).then(t=>this._noteLayoutRev(t)).catch(t=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))).finally(()=>{this._sentPos.get(e)===t&&this._sentPos.delete(e)}))}this._cacheSnapshot()}else this._layout=al(Gr(this._layout)),localStorage.setItem(Jf,JSON.stringify(this._layout))},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.undo();t&&(this._applyGeometryState(t.before,!0)?this._showToast(this._t("history.undone",{name:t.name})):this._geometryHistory.clear())},this._redoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.redo();t&&(this._applyGeometryState(t.after,!0)?this._showToast(this._t("history.redone",{name:t.name})):this._geometryHistory.clear())},this._saveConfigDebounced=hv(()=>{this._serverCfg&&this._writeConfig().catch(t=>{const e=!0===t?.physicalGeometryRolledBack;"geometry-unsafe"!==t?.code&&("wall_model_client_outdated"===t?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===t?.code?(this._showToast(this._t("toast.conflict")),e||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(t)})),e&&this._reloadRejectedPhysicalWrite())})},500),this._draftSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>{const t=this._physicalDialog,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=Wf(t.cm);if(null==s)return void this._showPhysicalRange("column"===t.kind?jc:100,"column"===t.kind?1:0);const n=this._imperial?2.54*s:s,o="column"===t.kind?jc:100,a="column"===t.kind?1:0;if(!Number.isFinite(n)||no)return void this._showPhysicalRange(o,a);if("column"===t.kind){const e=i.wall_columns.find(e=>e.id===t.id);if(!e)return;const s=Wf(t.angle||"0");if("circle"!==t.shape&&(null==s||s<0||s>=90))return void this._showToast(this._t("toast.physical_angle"));const o="circle"===t.shape?{id:t.id,shape:"circle",center:e.center,cm:n}:{id:t.id,shape:"square",center:e.center,cm:n,angle:s};if(i.wall_columns.some(e=>e.id!==t.id&&uh(e,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"))}const r=this._geometrySnapshot();if("partition"===t.kind){const i=(e.partitions||[]).find(e=>e.id===t.id);if(i&&0===n&&f_(e.openings,{kind:"partition",id:t.id}))return void this._showToast(this._t("toast.zero_wall_opening_conflict"));i&&(i.cm=n)}else if("column"===t.kind){const i=(e.wall_columns||[]).find(e=>e.id===t.id);i&&(i.cm=Gc(n),i.shape="circle"===t.shape?"circle":"square","square"===i.shape?i.angle=Wf(t.angle||"0"):delete i.angle)}else{const i=(e.room_drafts||[]).find(e=>e.id===t.id);i?.segments?.[t.segment||0]&&(i.segments[t.segment||0].cm=n)}const l=this._commitPhysicalGeometry(this._t("history.physical_edit"),r);this._physicalDialog=null,l||this.requestUpdate()},this._deletePhysicalSelection=()=>{const t=this._physicalSel,e=this._curSpaceCfg;if(!t||!e)return;if("draft"===t.kind)return void this._deleteDraftWhole();const i=this._geometrySnapshot();if("partition"===t.kind){const i=(e.openings||[]).filter(e=>"partition"===e.host?.kind&&e.host.id===t.id).sort((t,e)=>(t.host?.t||0)-(e.host?.t||0));if(i.length)return void(this._partitionDeleteDialog={id:t.id,openings:i.map(t=>JSON.parse(JSON.stringify(t)))})}const s="partition"===t.kind?"partitions":"column"===t.kind?"wall_columns":"room_drafts";e[s]=(e[s]||[]).filter(e=>e.id!==t.id),e[s].length||delete e[s],this._activeDraftId===t.id&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._confirmPartitionDelete=()=>{const t=this._partitionDeleteDialog,e=this._curSpaceCfg;if(!t||!e)return;const i=this._geometrySnapshot();e.partitions=(e.partitions||[]).filter(e=>e.id!==t.id),e.partitions.length||delete e.partitions,e.openings=(e.openings||[]).filter(e=>"partition"!==e.host?.kind||e.host.id!==t.id),e.openings.length||delete e.openings,this._partitionDeleteDialog=null,this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftWhole=()=>{const t="draft"===this._physicalDialog?.kind?this._physicalDialog.id:"draft"===this._physicalSel?.kind?this._physicalSel.id:null,e=this._curSpaceCfg;if(!t||!e||!confirm(this._t("confirm.delete_draft")))return;const i=this._geometrySnapshot();e.room_drafts=(e.room_drafts||[]).filter(e=>e.id!==t),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===t&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftSegment=()=>{const t=this._physicalDialog,e=this._curSpaceCfg;if(!t||"draft"!==t.kind||!e)return;if(!confirm(this._t("confirm.delete_draft_segment")))return;const i=(e.room_drafts||[]).findIndex(e=>e.id===t.id);if(i<0)return;const s=e.room_drafts[i],n=Math.max(0,Math.min(s.segments.length-1,t.segment||0)),o=[],a=s.points.slice(0,n+1),r=s.points.slice(n+1);if(a.length>=2&&o.push({id:s.id,points:a,segments:s.segments.slice(0,n)}),r.length>=2&&o.push({id:o.length?`${s.id}-${Date.now().toString(36)}`:s.id,points:r,segments:s.segments.slice(n+1)}),2===o.length&&e.room_drafts.length>=200)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot();e.room_drafts.splice(i,1,...o),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===s.id&&this._cancelPath(),this._physicalDialog=null,this._physicalSel=o.length?{kind:"draft",id:o[0].id}:null,this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),l)},this._confirmRoomDelete=t=>{const e=this._roomDeleteDialog,i=this._curSpaceCfg,s=this._spaceModel();if(!e||!i||!s)return;const n=s.rooms.find(t=>t.id===e.roomId);if(!n)return void(this._roomDeleteDialog=null);const o=this._openCuts(),a=$u(dc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv).filter(t=>t.roomId===n.id),s.partitions,this._openingsR.map(t=>({...t,x:t.rx,y:t.ry})),.02*this._gridPitch),r=new Set(a.materialize.filter(t=>!t.reusePartitionId).map(t=>t.interval.key)).size;if(t&&(i.partitions||[]).length+r>rv)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot(),c=pc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv);if(t){i.partitions||=[];const t=new Map,e=new Map,s=t=>{const e=(i.wall_segments||[]).find(e=>{const i=[Number(e.a?.[0])*sv,Number(e.a?.[1])*sv],s=[Number(e.b?.[0])*sv,Number(e.b?.[1])*sv];return this._samePt(t.a,i)&&this._samePt(t.b,s)||this._samePt(t.a,s)&&this._samePt(t.b,i)});return"string"==typeof e?.id&&e.id?e.id:null},n=Date.now().toString(36);for(const o of a.materialize){let a=o.reusePartitionId?i.partitions.find(t=>t.id===o.reusePartitionId):e.get(o.interval.key);a||(a={id:s(o.interval)||`partition-room-${n}-${e.size}`,a:[o.interval.a[0]/sv,o.interval.a[1]/sv],b:[o.interval.b[0]/sv,o.interval.b[1]/sv],cm:o.interval.cm},i.partitions.push(a),e.set(o.interval.key,a)),t.set(o.interval.key,a)}for(const e of i.openings||[]){const i=a.openingIntervals.get(e.id),s=i?t.get(i):null,n=this._openingsR.find(t=>t.id===e.id);if(!s||!n)continue;const o={a:[s.a[0]*sv,s.a[1]*sv],b:[s.b[0]*sv,s.b[1]*sv]};e.host={kind:"partition",id:s.id,t:Su([n.rx,n.ry],o)}}}else if(a.removeOpeningIds.length){const t=new Set(a.removeOpeningIds);i.openings=(i.openings||[]).filter(e=>!t.has(e.id)),i.openings.length||delete i.openings}i.rooms=i.rooms.filter(t=>t.id!==n.id),this._cfgEpoch++;const h=this._normalizeWalls(c,this._openCuts());h.length?i.walls=h:delete i.walls,this._roomDeleteDialog=null,this._commitPhysicalGeometry(this._t(t?"history.delete_room_keep_walls":"history.delete_room_with_walls"),l),this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate()},this._rebindPartitionOpening=()=>{const t=this._openingDialog;if(!t?.id)return;const e=t.id;this._activateMarkupTool("opening"),"opening"===this._tool&&(this._openingRebindId=e,this._openingPreset={type:t.type,lengthCm:t.lengthCm,flipH:t.flipH,flipV:t.flipV,revision:++this._openingPresetRevision},this._openingDialog=null,this._openingHoverCandidate=null)},this._keepClosedAsPartitions=()=>{if(this._wallFaceBatch)return void this._decideWallFace(!1);if(!this._contourClosed||this._pendingSplit||!this._curSpaceCfg)return;const t=this._curSpaceCfg,e=this._path.slice(0,-1);if((t.partitions||[]).length+e.length>rv)return void this._showToast(this._t("toast.physical_limit"));const i=this._geometrySnapshot(),s=Xp(e.length,[...this._draftSegmentCms,this._closingWallCm??void 0],this._drawWallCm,ll);t.partitions||=[];const n=Date.now().toString(36),o=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,a=this._draftSegmentsForPath(this._path,o,s);for(let i=0;it.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.contour_to_partitions"),i),this._roomDialog=!1,this._path=[],delete this._resumeDraftBySpace[this._space],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null},this._toggleServerPlans=async()=>{const t=this._spaceDialog;if(t)if(t.pickSaved)this._spaceDialog={...t,pickSaved:!1};else{this._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.hass.callWS({type:"houseplan/plans/list"}),e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:t?.plans||[],savedBusy:!1})}catch(t){const e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:[],savedBusy:!1}),this._showToast(this._t("toast.plans_list_failed",{err:this._errText(t)}))}}},this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const t=this._dayCycleState();if(!t)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const e=mr(t);e!==this._dayCycleClockKey&&(this._dayCycleClockKey=e,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(!this._norm)return;const t=this._glowRadiusCm,e=this._imperial?Math.round(t/30.48*10)/10:Math.round(t)/100;this._settingsDialog={colors:JSON.parse(JSON.stringify(this._fillColors)),glowRadius:e,bgColor:hs(this._settings,{bgColor:null})||null,northDeg:$r(this._settings,{}),bgMode:Sr(this._settings,{}),sunRays:Mr(this._settings,{}),busy:!1}},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._previewAlignDialog(!1),this._toggleOptimizeLivePositions=()=>{const t=this._alignDialog;t&&!t.busy&&t.report.liveMissingPositions.length&&this._previewAlignDialog(!t.removeLiveMissingPositions)},this._optimizeUndoBusy=!1,this._openBackupExport=()=>{this._settingsDialog=null,this._backupExportDialog={kind:"full",planOnly:!1,busy:!1,error:""}},this._openRulesDialog=()=>{if(!this._norm)return;const t=this._settings.icon_rules,e=(t&&t.length?t:Jt).map(t=>({...t}));this._rulesDialog={rules:e,test:"",busy:!1}},this._climateCache=null,this._gearPtCache=new WeakMap}get _canEdit(){return!!this._norm&&(!0===this._serverCanWrite||!1!==this._serverCanWrite&&!0===this.hass?.user?.is_admin)}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}_cssColor(t,e){const i=String(t||"").trim();if(!i)return e;const s=document.createElement("span");s.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(s);const n=getComputedStyle(s).color||e;return s.remove(),n}_currentModeVisual(t=this._mode){const e=this._modeTransition.presented||this._modeTransitionVisual;if(e)return{...e,viewport:{...e.viewport,viewBox:{...e.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const s=this.renderRoot.querySelector(".editorchrome"),n=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),a=this.renderRoot.querySelector(".hp-backdrop"),r=this.renderRoot.querySelector(".zoomwrap"),l=r?getComputedStyle(r).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:t,editorChromeHeight:"view"===t?0:s?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:Sg(n,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===t?.35:1,backdropOpacity:a&&Number(getComputedStyle(a).opacity)||1,viewWeight:"view"===t?1:0,editorWeight:"view"===t?0:1,toolbarContentOpacity:"view"===t?0:1}}_viewForModeTarget(t,e,i,s,n){const o=Ni(this._baseVb(),s/Math.max(1,n)),a=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),r=o.w/a,l=o.h/a,c=e??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-r/2,y:h-l/2,w:r,h:l},o)}_targetStageColor(t){return"view"!==t?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(t){return"view"===t&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(t){return 1}_applyModeTransitionFrame(t){t.targetMode===this._mode&&(this._modeTransitionVisual=t.presented,this._view={...t.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(t){if(t.targetMode!==this._mode)return;const e=this._modeTransitionRequest;this._view={...t.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[t.to.stageWidth,t.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._modeTransitionBusy||t.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-t.to.stageWidth)>.5||Math.abs(i.clientHeight-t.to.stageHeight)>.5)){const t=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,t?t.x+t.w/2:void 0,t?t.y+t.h/2:void 0),this.requestUpdate()}const s=this.renderRoot.activeElement;(!s||!s.isConnected||!!s.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(t=!0){const e=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(t),t&&e||(this._modeTransitionVisual=null)}_adoptMode(t){this._cancelModeTransition(!1),this._mode=t,"view"!==t&&(this._editorChromeMode=t)}_commitViewModeAtomic(t,e,i,s){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=e,t){const n=this._stageEl?.clientWidth||t.stageWidth,o=Math.max(1,t.stageHeight+t.editorChromeHeight);this._view=this._viewForModeTarget(e,i,s,n,o),this._lastValidStageSize=[n,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(t,e,i,s,n,o){this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._mode!==i)return void(t===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const a=this.renderRoot.querySelector(".editorchrome"),r=a?.querySelector(".editorchrome-inner"),l="view"===i?0:r?.scrollHeight||r?.getBoundingClientRect().height||0,c=Math.max(1,e.stageHeight+e.editorChromeHeight),h=Math.max(1,c-l),d=this._stageEl?.clientWidth||e.stageWidth;if(d<=0||h<=0)return this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._applyView(s,n,o),void this.requestUpdate();const p=this._viewForModeTarget(s,n,o,d,h),u={presentedMode:i,editorChromeHeight:l,stageWidth:d,stageHeight:h,viewport:Sg(p,d),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const _=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(e,u,i,this._reducedMotion||_?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(t=this._model,e=this._loadOk){const i=this._config?.floor,s=function(t){if(!t.hasFloor)return{kind:"absent"};const e=t.floor;if("string"==typeof e)return e.length?t.spaceIds.includes(e)?{kind:"valid",id:e,source:"id"}:{kind:"invalid",reason:"unknown-id",value:e}:{kind:"invalid",reason:"empty-id",value:e};if("number"==typeof e){if(!Number.isFinite(e))return{kind:"invalid",reason:"non-finite-index",value:e};if(!Number.isInteger(e))return{kind:"invalid",reason:"fractional-index",value:e};if(e<0)return{kind:"invalid",reason:"negative-index",value:e};const i=t.spaceIds[e];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:e}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:e}}({spaceIds:t.map(t=>t.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||e?s:"number"==typeof i?"valid"===s.kind||"invalid"===s.kind&&"out-of-range-index"===s.reason?{kind:"pending",value:i}:s:"valid"===s.kind||"invalid"===s.kind&&"unknown-id"!==s.reason?s:{kind:"pending",value:i}}_canCommitSpace(t,e=!1){if(e||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===t}_commitSpace(t,e=!1){return!!this._canCommitSpace(t,e)&&(t!==this._space&&(this._clearTransientHover(!0),this._cancelDevicePressFeedback()),this._space=t,!0)}_slideTo(t,e){if(t===this._space)return!0;if(!this._canCommitSpace(t))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),i||(this._slide=e,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(t,e){Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:t.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(dv(t),this._tabDragRelease=t=>this._tabPointerUp(t),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:e,pointerId:t.pointerId,x:t.clientX,y:t.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(t,e,i){const s=this._model.map(t=>t.id),n=s.indexOf(i);if(n<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const a of o){const o=a.dataset.id||"";if(!o||o===i)continue;const r=a.getBoundingClientRect();if(tr.right||er.bottom)continue;const l=s.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,s;const n=this._tabDropTargetAt(t.clientX,t.clientY,e.id);e.moved&&e.targetId===n?.targetId&&e.placement===n?.placement||(this._tabDrag={...e,moved:!0,targetId:n?.targetId||null,placement:n?.placement||null})}_tabPointerUp(t){const e=this._tabDrag;if(e&&e.pointerId!==t.pointerId)return;const i="pointerup"===t.type&&e?.moved?this._tabDropTargetAt(t.clientX,t.clientY,e.id):null;"pointerup"===t.type&&e?.moved&&this._suppressNextTabClick(),this._endTabDrag(),e?.moved&&i&&this._commitTabOrder(e.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(t){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(t)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(t,e){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const s=this._model.map(t=>t.id),n=function(t,e,i){const s=t.indexOf(e),n=t.indexOf(i);if(s<0||n<0||s===n)return t;const o=t.slice();return o.splice(s,1),o.splice(n,0,e),o}(s,t,e);if(n===s)return;const o=new Map(this._devices.map(t=>[String(t.id),String(t.area||"")])),a=function(t,e,i,s=()=>""){if(!i)return[];const n=[];for(const o of t){if(!o||!0===o.removed)continue;const t="string"==typeof o.id?o.id:"";if(!t)continue;if("string"==typeof o.space&&o.space)continue;const a=("string"==typeof o.area?o.area:"")||s(t)||"";a&&e[a]||n.push({id:t,space:i})}return n}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([t,e])=>[t,e.space])),s[0]||"",t=>o.get(t)||"");if(a.length){const t=new Map(a.map(t=>[t.id,t.space]));for(const e of i.markers||[]){const i=t.get(String(e.id));i&&(e.space=i)}}i.spaces=function(t,e){const i=new Map(e.map((t,e)=>[t,e]));return t.map((t,e)=>({space:t,index:e})).sort((t,e)=>(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)||t.index-e.index).map(t=>t.space)}(i.spaces||[],n),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(t){if(this._endTabDrag(),t===this._space)return;const e=this._model.map(t=>t.id),i=e.indexOf(this._space),s=e.indexOf(t);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(t,i>=0&&s0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const t=this._model.map(t=>t.id),e=t.indexOf(this._space);this._slideTo(t[(e+1)%t.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(t){this._wallUnionCacheValue=t,null===t&&this._wallUnionPool.clear()}_newContinuityController(){return new bd(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(ev,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(t){const e=this._view;if(!e)return null;const i=[e.x+e.w/2,e.y+e.h/2],s="iso"===t?Zg(i):i;return{x:s[0],y:s[1]}}_convertProjectionView(t,e){if(t===e)return;const i=this._logicalViewCenter(t);this._view=null;const s=i?"iso"===e?Xg([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,s?.[0],s?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(t){if(!this._labsIso||"view"!==this._mode)return;const e=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:t},"iso"===t){const t=this._isoSceneKey();t&&this._isoFallback.delete(t)}this._saveViewPreference();const i=this._effectiveProjection();this._convertProjectionView(e,i)}_hashSpace(){return Og(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const t=(e=this.ownerDocument,vg.get(e)?.resolved);var e;void 0!==t&&(this._glowScreenBlend=t),this._continuityUnsub?.(),this._continuityUnsub=vd(this.ownerDocument,this._pageVisibility),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(t=>{for(const e of t)for(const t of e.addedNodes)this._syncPointerHoverSubtree(t)}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),function(t){const e=vg.get(t);if(e)return e.promise;const i={promise:Promise.resolve(!1)};return i.promise=bg(t).catch(()=>!1).then(t=>(i.resolved=t,t)),vg.set(t,i),i.promise}(this.ownerDocument).then(t=>{t!==this._glowScreenBlend&&(this._glowScreenBlend=t,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>Is(this._serverCfg)),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(t,e){Ug.add(e);const i=Kg(t);return"undefined"==typeof window&&e(i),()=>{Ug.delete(e)}}(Nf,this._onLabsSnapshot),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const t of this._activityRt.values())clearTimeout(t.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),this._modeTransition.dispose(),this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer);for(const t of this._glowFadeTimers.values())clearTimeout(t);for(const t of this._glowEnterRafs.values())cancelAnimationFrame(t);clearTimeout(this._glowFeatherResumeTimer),this._glowFeatherResumeTimer=0,this._glowFeatherSuspendUntil=0,this._glowFadeTimers.clear(),this._glowEnterRafs.clear(),this._glowEnteringSources.clear(),this._glowRenderedSources.clear(),this._glowLastAppearance.clear(),this._glowSourceSeq=0,this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._touchContacts.clear(),this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(t){if("Escape"===t.key&&this._vacFit)return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void t.stopPropagation();if("Escape"===t.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm=null);if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._settingsDialog)return void(this._settingsDialog=null);if(this._markerDialog)return void(this._markerDialog=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary.hasOpenGroup)return t.preventDefault(),void this._editorSecondary.closeGroup(!0)}const e=t.composedPath?.()||[t.target],i=e.some(t=>t?.matches?.('input, textarea, select, [contenteditable="true"]')),s=e.some(t=>t?.classList?.contains?.("editor-secondary")),n=t.ctrlKey||t.metaKey,o=t.key.toLowerCase(),a=/^[a-z]$/.test(o),r="z"===o||!a&&"KeyZ"===t.code,l="y"===o||!a&&"KeyY"===t.code,c=n&&(r&&t.shiftKey||l),h=n&&r&&!t.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;return c?(t.preventDefault(),void this._redoGeometry()):h?(t.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry()):"Delete"!==t.key&&"Backspace"!==t.key||!this._decorSel||i||s?void("Escape"===t.key&&(t.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._furnPalette=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(t.preventDefault(),void this._decorDeleteSel())}if(this._markup&&(!h&&!c||!i)){if(("Delete"===t.key||"Backspace"===t.key)&&this._physicalSel&&!i&&!s)return t.preventDefault(),void this._deletePhysicalSelection();if(c)return t.preventDefault(),void this._redoGeometry();if(h)return t.preventDefault(),this._rszDrag?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===t.key)return this._physicalDrag||this._physicalRotate?(t.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(t.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(t.preventDefault(),void this._finishWallChain()):this._physicalSel?(t.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(t.preventDefault(),this._rszDrag?void this._rszCancelDrag():void(this._rszSel?this._rszSel=null:this._tool="draw")):"split"===this._tool?(t.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(t.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(t.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(t.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length){if(this._contourClosed)return this._path=this._path.slice(0,-1),void(this._closingWallCm=null);if(this._activeDraftId&&this._path.length>1&&this._curSpaceCfg){const t=this._geometrySnapshot();this._path=this._path.slice(0,-1),this._draftSegmentCms=this._draftSegmentCms.slice(0,-1);const e=this._curSpaceCfg,i=(e.room_drafts||[]).findIndex(t=>t.id===this._activeDraftId);if(i>=0){const s=Array.isArray(e.room_drafts[i]?.segments)?e.room_drafts[i].segments:[];this._path.length<2?(e.room_drafts.splice(i,1),e.room_drafts.length||delete e.room_drafts,this._activeDraftId=null):e.room_drafts[i]={id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentCms.map((t,e)=>({...s[e]||{},cm:t}))},this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),t)}return}this._path=this._path.slice(0,-1)}}_undoActiveDraftPoint(){const t=this._activeDraftId,e=this._path[0]?[...this._path[0]]:null,i=this._geometryHistory.undo();if(!i)return void this._undoPoint();if(!this._applyGeometryState(i.before,!0))return void this._geometryHistory.clear();const s=t?this._spaceModel()?.room_drafts.find(e=>e.id===t):null;s?(this._activeDraftId=s.id,this._path=s.points.map(t=>[...t]),this._draftSegmentCms=this._adoptDraftCms(this._path,s.segments.map(t=>t.cm),s.id),this._resumeDraftBySpace[this._space]=s.id):(this._activeDraftId=null,this._path=e?[e]:[],this._draftSegmentCms=[],t&&this._resumeDraftBySpace[this._space]===t&&delete this._resumeDraftBySpace[this._space]),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:i.name}))}static getConfigElement(){return document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(t){for(const t of Gf.values())for(const e of t)clearTimeout(e.evict);Gf.clear(),Yf=t&&t>0?t:1e4}static _warmBootStats(){let t=0,e=0;const i=[];for(const s of Gf.values())for(const n of s)t++,n.dlg&&(e++,i.push(n.dlg.kind));return{keys:Gf.size,slots:t,dlgs:e,drafts:i}}setConfig(t){const e=this._config,i=!!e&&Object.prototype.hasOwnProperty.call(e,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...t};(i!==this._hasFixedFloor||e?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&t.default_floor&&this._commitSpace(t.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(Zf)||"{}")||{}}catch{this._zoomBySpace={}}try{const t=JSON.parse(localStorage.getItem(ev)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(t).filter(t=>"flat"===t[1]||"iso"===t[1]))}catch{this._viewPreference={}}this._labs=Kg(Nf);try{const t=JSON.parse(localStorage.getItem(tv)||"null");this._kioskScale={icon:Es(t?.icon),font:Es(t?.font)}}catch{}try{const t=JSON.parse(localStorage.getItem(Xf)||"null");t&&t.config&&Array.isArray(t.config.spaces)&&(this._serverCfg=t.config,this._cfgEpoch++,this._cfgRev=t.rev||0,this._cfgContentFingerprint=t.config_fingerprint||wd(t.config),this._layout=t.layout||{},this._layoutRev=t.layout_rev||0,this._layoutContentFingerprint=t.layout_fingerprint||wd(this._layout),this._virtualLights=mn(t.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1)}_warmAdopt(){if(this._config?.kiosk)return;const t=Kf(this._config);if(this._warmKey===t&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const e=this.parentNode,i=this._warmIdx(e),s=Gf.get(t);if(!s||!s.length)return;const n=s.find(t=>t.owner===this._warmGen);if(n)return this._warmLongReturn=!!n.freed&&Date.now()-n.freed>=md,clearTimeout(n.evict),n.evict=0,n.freed=0,n.live=!0,this._warmSlot=n,this._warmKey=t,n.frameFingerprint&&this._continuity.adoptCompleteFrame(n.frameFingerprint),void(!this._devices.length&&n.devices?.length&&(this._devices=[...n.devices]));const{slot:o,sure:a}=((t,e,i,s)=>{const n=t=>{const e=!!i&&t.place?.deref()===i;return e&&t.idx===s?4:t.live?0:e?3:2};let o=null,a=0,r=0,l=null;for(const i of t){if(i.owner===e)continue;l=i;const t=n(i);t<=0||(t>a?(o=i,a=t,r=1):t===a&&r++)}return!o||r>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(s,this._warmGen,e,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=md,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),this._warmKey=t,a?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=e?new WeakRef(e):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},s.push(this._warmSlot),this._warmTrim(s)))}_warmIdx(t){const e=t?.children;if(!e)return-1;for(let t=0;t4;){const e=t.findIndex(t=>!t.live);if(e<0)break;clearTimeout(t[e].evict),t.splice(e,1)}}_warmScheduleEvict(t,e){if(clearTimeout(t.evict),!(t.dlg||t.vp&&"view"!==t.vp.mode))return;const i=t.freed,s=t.owner;t.evict=window.setTimeout(()=>{if(t.evict=0,t.freed!==i||t.owner!==s)return;var n;t.dlg=null,t.vp=(n=t.vp)&&"view"!==n.mode?{...n,mode:"view",zoom:n.snap?.space===n.space?n.snap.zoom:n.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:n,t.frameFingerprint="";const o=Gf.get(e);if(!t.live&&o&&o.length>1){const e=o.indexOf(t);e>=0&&o.splice(e,1)}},Yf+250)}_warmAdoptViewport(t){const e=this._warmVp;if(!e||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(t=>t.id===e.space)||"valid"===i.kind&&i.id!==e.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(e.space,!0),this._navApplied=!0,this._adoptMode("view"!==e.mode&&this._canEdit&&!t.kiosk?e.mode:"view"),this._pendingNavMode="view"===e.mode||this._canEdit||t.kiosk?null:e.mode,this._zoom=e.zoom;const s=this._effectiveProjection(),n=s===e.projection&&this._labsIso===e.activeLabsIso;if(this._view=n&&e.view?{...e.view}:null,this._viewModeSnap=n&&e.snap?{...e.snap}:null,!n&&e.logicalCenter){const t="iso"===s?Xg([e.logicalCenter.x,e.logicalCenter.y],0):[e.logicalCenter.x,e.logicalCenter.y];this._applyView(e.zoom,t[0],t[1])}var o;this._tool="opening"===(o=function(t){return"partition"===t?"draw":t}(o=e.tool))?"draw":"string"==typeof o&&av.has(o)?o:"draw",this._decorTool=e.decorTool,this._showHidden=e.showHidden,this._showFar!==e.showFar&&(this._showFar=e.showFar,this._frame=null),this._selId=e.selId,this._rszSel=e.rszSel,this._decorSel=e.decorSel,this._warmVpArmed=!0}_warmPatch(t,e=!1){if(this._config?.kiosk)return;const i=Kf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!e)return;const t=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:this._warmIdx(t),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const s=Gf.get(i)||[];for(s.push(this._warmSlot),Gf.set(i,s),this._warmTrim(s);Gf.size>8;){const t=Gf.keys().next().value;if(void 0===t||t===i)break;for(const e of Gf.get(t)||[])clearTimeout(e.evict);Gf.delete(t)}}Object.assign(this._warmSlot,t)}}_warmViewportState(){const t=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:t,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(t),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._rszSel,decorSel:this._decorSel}}_warmDialogState(){const t=(t,e)=>({kind:t,space:this._space,mode:this._mode,data:e});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?t("openingInfo",this._openingInfo.id):this._infoCard?t("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:t("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:t("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:t("marker",this._markerDialog):this._openingDialog?t("opening",this._openingDialog):this._backdropDialog?t("backdrop",this._backdropDialog):this._decorShapeDialog?t("decorShape",this._decorShapeDialog):this._decorTextDialog?t("decorText",this._decorTextDialog):this._roomDialog?t("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:t("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const t={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices};if(this._warmRevivePending||(t.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const e=this.parentNode;t.place=e?new WeakRef(e):null,t.idx=this._warmIdx(e)}this._warmPatch(t)}_warmReviveDialog(){this._warmRevivePending=!1;const t=this._warmSlot;if(this._warmReviveTimer=void 0,!t||!t.dlg)return;const e=t.dlg,i=t.freed;if(t.dlg=null,t.freed=0,clearTimeout(t.evict),t.evict=0,i&&!(Date.now()-i>Yf)&&e.space===this._space&&e.mode===this._mode){switch(e.kind){case"space":this._spaceDialog={...e.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...e.data,busy:!1};break;case"settings":this._settingsDialog={...e.data,busy:!1};break;case"rules":this._rulesDialog={...e.data,busy:!1};break;case"opening":this._openingDialog={...e.data};break;case"backdrop":this._backdropDialog={...e.data};break;case"decorShape":this._decorShapeDialog={...e.data};break;case"decorText":{this._decorTextDialog={...e.data};const t=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:t,end:t};break}case"room":{const t=e.data;this._roomEditId=t.editId,this._roomFill=t.fill,this._roomCustomFill=t.customFill||null,this._roomTempSrc=t.tempSrc,this._roomHumSrc=t.humSrc,this._roomSrcOpen=t.srcOpen,this._roomSrcFilter=t.srcFilter,this._roomNameScale=t.nameScale,this._roomLabelScale=t.labelScale,this._areaSel=t.areaSel,this._nameSel=t.nameSel,this._pendingSplit=t.pendingSplit,this._wallFaceBatch=t.wallFaceBatch||null,this._path=t.path,this._wallFaceBatch&&(this._activeDraftId=this._wallFaceBatch.activeDraftId,this._draftSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const t=this._devices.find(t=>t.id===e.data);t&&(this._infoCard=t);break}case"openingInfo":{const t=(this._curSpaceCfg?.openings||[]).find(t=>t.id===e.data);t&&(this._openingInfo=t);break}}this.requestUpdate()}}_cacheSnapshot(){if(this._serverCfg)try{this._cfgContentFingerprint=wd(this._serverCfg),this._layoutContentFingerprint=wd(this._layout),this._virtualLights=function(t,e,i){if(t.configRev===i)return t;const s=new Set((Array.isArray(e?.markers)?e.markers:[]).filter(yn).map(t=>t.id));return{...t,configRev:i,off:new Set([...t.off].filter(t=>s.has(t)))}}(this._virtualLights,this._serverCfg,this._cfgRev),localStorage.setItem(Xf,JSON.stringify({config:this._serverCfg,rev:this._cfgRev,config_fingerprint:this._cfgContentFingerprint,layout:this._layout,layout_rev:this._layoutRev,layout_fingerprint:this._layoutContentFingerprint,virtual_lights:fn(this._virtualLights)}))}catch{}}_beginContinuityCandidate(t,e,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=e,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(t,i))}_continuityStageValid(){const t=this._stageEl;return!!t&&t.clientWidth>0&&t.clientHeight>0}_continuityAssetsReady(){if(!this._model.length)return!1;const t=this._model.length?this._spaceModel():null;return!t?.bg?.href||this._signer.isReady(this.hass,t.bg.href)}_initialSpaceSelection(t,e=this._loadOk){const i=this._fixedFloorState(t,e);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(t){const e=new Set(t.spaceIds.filter(t=>!!t));if(!e.size)return{id:null,source:"none"};const i=[["hash",!1===t.acceptHash?null:t.hashSpace],["current",t.preserveCurrent?t.currentSpace:null],["saved",t.savedSpace],["default",t.defaultSpace],["first",t.spaceIds[0]]];for(const[t,s]of i)if(s&&e.has(s))return{id:s,source:t};return{id:null,source:"none"}}({spaceIds:t.map(t=>t.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(t,e=this._loadOk){const i=this._initialSpaceSelection(t,e);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(t,e=this._space){const i=Sh(t),s=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==s.kind)return"";const n=this._initialSpaceSelection(i,!0).id||(i.some(t=>t.id===e)?e:i[0]?.id);return i.find(t=>t.id===n)?.bg?.href||""}_visualFrameFingerprint(){const t=this._stageEl,e=t?[t.clientWidth,t.clientHeight]:[0,0];return kd([this._cfgRev,this._cfgContentFingerprint||wd(this._serverCfg),this._layoutRev,this._layoutContentFingerprint||wd(this._layout),this._space,this._mode,this._view,e,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const t=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==t)return this._stagedDeviceSnapshotToken=t,void this.requestUpdate();this._continuityPaintToken!==t&&(this._continuityPaintToken=t,this._continuity.candidateReady(t)&&this._continuity.commitAfterPaint(t,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(e=>{e&&t===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):t===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(t,e){this._signer.markLoaded(this.hass,t,e),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const t="connection"===this._continuity.recoveryReason;return W`
`}afterRender(){const t=this.host.root();this._blocked&&(this._openGroupId?this.closeGroup(!1):"palette"===this._currentModel?.kind&&this._currentModel.dismiss?.()),this._syncGlobalDismissListener();const e=t.querySelector(".editor-secondary"),i=this._renderedContext,s=e?.dataset.contextId||"";if(s&&i&&s!==i&&!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches&&(this._contentAnimation?.cancel(),this._contentAnimation=e?.querySelector(".editor-secondary-content")?.animate([{opacity:.35,transform:"translateY(-4px)"},{opacity:1,transform:"translateY(0)"}],{duration:100,easing:"ease-out"})),this._renderedContext=s,i&&s!==i&&this._focusOwned){const i=s?e?.querySelector('[tabindex="0"], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'):t.querySelector(".editbar-tools");i?.focus?.(),this._focusOwned=!!s}if("palette"===this._currentModel?.kind&&this._currentModel.launcherId){const e=[...t.querySelectorAll("[data-editor-palette]")].find(t=>t.dataset.editorPalette===this._currentModel?.launcherId);e&&null!==e.offsetParent||this._currentModel.dismiss?.()}if(!this._openGroupId)return;const n=[...t.querySelectorAll("[data-editor-group]")].find(t=>t.dataset.editorGroup===this._openGroupId);n&&null!==n.offsetParent||this.closeGroup(!0)}handleOutsideDismiss(t){if(q_(t,t=>t.hasAttribute("data-editor-navigation")))return"pointerdown"===t.type?this.closeForNavigation():"click"===t.type&&this._dismissPointerTarget&&this._clearDismissClick(),!1;if("click"===t.type&&this._dismissPointerTarget){return!!(t.composedPath?.()||[t.target]).includes(this._dismissPointerTarget)&&(this._clearDismissClick(),t.preventDefault(),t.stopImmediatePropagation(),!0)}const e=this._openGroupId||this._blocked||"palette"!==this._currentModel?.kind?null:this._currentModel;if("pointerdown"===t.type&&(this._openGroupId||e)){const i=q_(t,t=>t.classList.contains("editor-secondary")),s=q_(t,t=>!!t.dataset.editorGroup),n=q_(t,t=>!!t.dataset.editorPalette),o=q_(t,t=>t.classList.contains("stage"));if(!(i||s||n||"stay-open-on-canvas"===e?.dismissPolicy&&o))return t.preventDefault(),t.stopImmediatePropagation(),this._dismissPointerTarget=t.target,clearTimeout(this._dismissTimer),this._dismissTimer=window.setTimeout(()=>{this._clearDismissClick()},800),this._openGroupId?this.closeGroup(!1):e?.dismiss?.(),this._syncGlobalDismissListener(),!0}return!1}_activateGroupItem(t,e,i){if(t.id!==this._openGroupId)return;const s=t.items.find(t=>t.id===e);if(!s||s.disabled)return;const n="toggle"===s.role&&"stay-open"===s.closePolicy,o=0===i.detail;n||(this._openGroupId=null,this.host.requestUpdate(),this._syncGlobalDismissListener()),s.invoke(),!n&&o&&this.host.updateComplete().then(()=>{const e=[...this.host.root().querySelectorAll("[data-editor-group]")].find(e=>e.dataset.editorGroup===t.id&&null!==e.offsetParent);e?.focus()})}_groupKeydown(t){if(!["ArrowLeft","ArrowRight","Home","End"].includes(t.key))return;const e=[...t.currentTarget.querySelectorAll(".editor-group-item:not([disabled])")];if(!e.length)return;t.preventDefault();const i=e.indexOf(this.host.root().activeElement),s="Home"===t.key?0:"End"===t.key?e.length-1:"ArrowLeft"===t.key?i<=0?e.length-1:i-1:(i+1)%e.length;e[s]?.focus()}_clearDismissClick(){this._dismissPointerTarget=null,clearTimeout(this._dismissTimer),this._dismissTimer=void 0,this._syncGlobalDismissListener()}_syncGlobalDismissListener(){const t=!this._blocked&&"palette"===this._currentModel?.kind,e=!!this._openGroupId||t||!!this._dismissPointerTarget;e!==this._globalDismissListening&&(this._globalDismissListening=e,e?(window.addEventListener("pointerdown",this._globalDismissGuard,!0),window.addEventListener("click",this._globalDismissGuard,!0)):(window.removeEventListener("pointerdown",this._globalDismissGuard,!0),window.removeEventListener("click",this._globalDismissGuard,!0)))}}const j_=t=>t.stopPropagation(),U_=4.166666666666667e-9;function G_(t){return Number.isFinite(t)?Math.round(t/Th)*Th:t}const V_=(t,e,i,s)=>Math.hypot(i-t,s-e),K_=(t,e,i,s,n,o,a,r)=>Math.hypot(Math.max(Math.abs(n-t),Math.abs(n+a-(t+i))),Math.max(Math.abs(o-e),Math.abs(o+r-(e+s)))),Y_=(t,e,i,s,n,o,a)=>{const r=Math.max(Number(s)||0,0)/2,l=Math.PI/180,c=Math.cos(i*l)*r,h=Math.sin(i*l)*r,d=Math.cos(a*l)*r,p=Math.sin(a*l)*r,u=Math.max(V_(t+c,e+h,n+d,o+p),V_(t-c,e-h,n-d,o-p)),_=Math.max(V_(t+c,e+h,n-d,o-p),V_(t-c,e-h,n+d,o+p));return Math.min(u,_)},J_=t=>{const e=Number(t?.cell_cm);return e>0?e:5};function X_(t,e){const i=JSON.parse(JSON.stringify(t||[])),s=JSON.parse(JSON.stringify(e||{}));let n=0,o=0,a=0,r=0,l="",c=0,h=0,d=0;const p=(t,e)=>{Number.isFinite(t)&&Number.isFinite(e)&&t!==e&&Math.abs(e-t)<=U_&&h++},u=(t,e)=>{p(t[0],e[0]),p(t[1],e[1])},_={};let m=5;for(const t of i){const e=J_(t);null!=t?.id&&(_[String(t.id)]=e),e>m&&(m=e)}const g=(t,e,i,s=!1)=>{if(!(t>U_||s))return;n++,t>a&&(a=t);const o=t*Dh*e;o>r&&(r=o,l=i)};for(const t of i){const e=J_(t),i=null!=t?.id?String(t.id):"";for(const s of t.rooms||[]){o++;let t=0;if(s.poly?.length)s.poly=s.poly.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),u(e,i),i});else if(null!=s.x&&null!=s.y){const e=s.x,i=s.y,n=s.w||0,o=s.h||0,a=G_(e+n),r=G_(i+o),l=G_(e),c=G_(i),h=Math.max(Th,a-l),d=Math.max(Th,r-c);t=K_(e,i,n,o,l,c,h,d),s.x=l,s.y=c,s.w=h,s.h=d,p(e,l),p(i,c),p(e+n,l+h),p(i+o,c+d)}g(t,e,i)}for(const s of t.room_drafts||[]){o++;let t=0;const n=s.points||[],a=n.map(e=>{const i=[G_(e[0]),G_(e[1])];return t=Math.max(t,V_(e[0],e[1],i[0],i[1])),i}),r=a.length?[a[0]]:[],l=a.length?[[n[0],a[0]]]:[],c=[];for(let t=0;t+1=2)for(const[t,e]of l)u(t,e);g(t,e,i)}if(Array.isArray(t.room_drafts)){const e=t.room_drafts.length;t.room_drafts=t.room_drafts.filter(t=>t.points?.length>=2),d+=e-t.room_drafts.length,t.room_drafts.length||delete t.room_drafts}for(const s of t.partitions||[]){o++;const n=[s.a[0],s.a[1]],a=[s.b[0],s.b[1]],r=[G_(n[0]),G_(n[1])],l=[G_(a[0]),G_(a[1])];let c=Math.max(V_(n[0],n[1],r[0],r[1]),V_(a[0],a[1],l[0],l[1]));const h=V_(r[0],r[1],l[0],l[1]),d=(t.openings||[]).filter(t=>"partition"===t.host?.kind&&t.host.id===s.id).every(t=>{const e=Number(t.length),i=Number(t.host.t),s=i*h;return Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>=0&&i<=1&&s-e/2>=-U_&&s+e/2<=h+U_});h>U_&&d?(s.a=r,s.b=l,u(n,r),u(a,l)):c=0,g(c,e,i)}for(const s of t.wall_columns||[]){o++;const t=[s.center[0],s.center[1]],n=[G_(t[0]),G_(t[1])],a=V_(t[0],t[1],n[0],n[1]);s.center=n,u(t,n),g(a,e,i)}for(const s of t.decor||[]){o++;let t=0;if("line"===s.kind){const e=[s.x1,s.y1],i=[s.x2,s.y2],n=[G_(e[0]),G_(e[1])],o=[G_(i[0]),G_(i[1])];t=Math.max(V_(e[0],e[1],n[0],n[1]),V_(i[0],i[1],o[0],o[1])),s.x1=n[0],s.y1=n[1],s.x2=o[0],s.y2=o[1],u(e,n),u(i,o)}else{const e=s.x,i=s.y,n=s.w,o=s.h,a=G_(e),r=G_(i);if(null!=s.w&&null!=s.h){const l=G_(e+n),c=G_(i+o),h=Math.max(Th,l-a),d=Math.max(Th,c-r);t=K_(e,i,n,o,a,r,h,d),s.w=h,s.h=d,p(e+n,a+h),p(i+o,r+d)}else t=V_(e,i,a,r);s.x=a,s.y=r,p(e,a),p(i,r)}g(t,e,i)}for(const s of t.openings||[]){if(o++,"partition"===s.host?.kind){const n=(t.partitions||[]).find(t=>t.id===s.host.id),o=Number(s.host.t);if(!n||!Number.isFinite(o)||o<0||o>1)continue;const a=n.b[0]-n.a[0],r=n.b[1]-n.a[1];if(Math.hypot(a,r)<=U_)continue;const l=n.a[0]+a*o,h=n.a[1]+r*o;let d=180*Math.atan2(r,a)/Math.PI;d>=90?d-=180:d<-90&&(d+=180);const p=Number(s.angle),u=!(Number.isFinite(p)&&p===d),_=Y_(s.x,s.y,Number.isFinite(p)?p:d,Number(s.length)||0,l,h,d);s.x=l,s.y=h,s.angle=d,u&&c++,g(_,e,i,u);continue}const n=ui([s.x,s.y],t.rooms||[],.025,{step:Th,length:Number(s.length)||0});if(!n)continue;const a=Number(s.angle),r=!(Number.isFinite(a)&&a===n.angle),l=Y_(s.x,s.y,Number.isFinite(a)?a:n.angle,Number(s.length)||0,n.x,n.y,n.angle);s.x=n.x,s.y=n.y,s.angle=n.angle,r&&c++,g(l,e,i,r)}}for(const[t,e]of Object.entries(s)){if(!e||"object"!=typeof e)continue;const i=e;if("number"!=typeof i.x||"number"!=typeof i.y)continue;o++;const n=G_(i.x),a=G_(i.y),r=V_(i.x,i.y,n,a);s[t]={...i,x:n,y:a},p(i.x,n),p(i.y,a);const l="string"==typeof i.s?i.s:"";g(r,_[l]??m,l)}return{spaces:i,layout:s,report:{moved:n,coordsCanonicalized:h,total:o,maxShift:a,maxShiftCm:r,maxSpace:l,rotated:c,removedDrafts:d},changed:n>0||h>0}}function Z_(t,e){const i=e.base+t*e.span;return Math.min(1,Math.max(0,i))}const Q_=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),tm=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1]);function em(t,e,i){const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(o<=0)return tm(t,e);let a=((t[0]-e[0])*s+(t[1]-e[1])*n)/o;return a=Math.max(0,Math.min(1,a)),Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))}function im(t,e,i,s,n){for(const s of e)if(s&&!i.has(s.id)&&Q_(s.a)&&Q_(s.b)&&(tm(t,s.a)<=n||tm(t,s.b)<=n))return!0;for(const e of s?.roomPolygons||[])for(let i=0;i0&&r>0))return null;if(Math.abs(n[0]/a*(o[1]/r)-n[1]/a*(o[0]/r))>i)return null;for(const[i,n]of[[t.a,e.a],[t.a,e.b],[t.b,e.a],[t.b,e.b]])if(tm(i,n)<=s)return[(i[0]+n[0])/2,(i[1]+n[1])/2];return null}function nm(t,e){const i=.05*(Number(e.pitch)>0?Number(e.pitch):1),s=new Map;let n=(t||[]).filter(t=>!!t&&"string"==typeof t.id&&Q_(t.a)&&Q_(t.b));if(n.length<2)return{partitions:[...t||[]],merged:0,openingMoves:[]};const o=e.seedIds&&e.seedIds.length?new Set(e.seedIds):null;let a=0;for(let t=0;ttm(e,t.at)>i);let h=c[0]??r.a,d=c[c.length-1]??l.b;if(c.length<2&&(h=r.a,d=l.b),d[0]0?(d[0]-h[0])/u:0,m=u>0?(d[1]-h[1])/u:0,g=t=>u>0?((t[0]-h[0])*_+(t[1]-h[1])*m)/u:0;for(const t of[r,l]){const e=g(t.a),i=g(t.b)-e;for(const[n,o]of s)o.toId===t.id&&s.set(n,{fromId:o.fromId,toId:p.id,base:e+o.base*i,span:o.span*i});s.set(t.id,{fromId:t.id,toId:p.id,base:e,span:i})}o&&o.add(p.id),n=n.filter((e,i)=>i!==t.i&&i!==t.j),n.splice(t.i,0,p),a++}return{partitions:n,merged:a,openingMoves:[...s.values()]}}function om(t,e,i,s){if(!t?.length||!i.length)return 0;const n=new Map(i.map(t=>[t.fromId,t]));let o=0;for(const i of t){const t=i?.host;if(!t||"partition"!==t.kind)continue;const a=n.get(t.id);if(!a)continue;i.host={...t,id:a.toId,t:Z_(t.t,a)},o++;const r=Sp(i,e,s.coordScale,s.cellCm,s.gridPitch).resolved;r&&Object.assign(i,Ip(i,r,s.coordScale))}return o}function am(t,e){const i=e?.excludeDraftId||null;return{roomPolygons:(t?.rooms||[]).map(t=>hi(t)).filter(t=>!!t),columns:t?.wall_columns||[],draftEnds:(t?.room_drafts||[]).flatMap(t=>{if(i&&t?.id===i)return[];const e=t?.points||[];return e.length?[e[0],e[e.length-1]]:[]})}}const rm=t=>!!t&&t.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]),lm=(t,e)=>t[0]-e[0]||t[1]-e[1],cm=(t,e,i,s)=>[t[0]+e*s,t[1]+i*s],hm=(t,e,i,s)=>(t[0]-e[0])*i+(t[1]-e[1])*s,dm=(t,e,i,s,n)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n))return null;const l=o/r,c=a/r,h=e=>Math.abs((e[0]-t[0])*c-(e[1]-t[1])*l);if(h(i)>n||h(s)>n)return null;const d=hm(i,t,l,c),p=hm(s,t,l,c),u=Math.max(0,Math.min(d,p)),_=Math.min(r,Math.max(d,p));return _-u>n?{lo:u,hi:_}:null},pm=(t,e,i)=>Math.min(t.hi,e.hi)-Math.max(t.lo,e.lo)>i,um=t=>{const e=new Set(["id","a","b","cm"]);return Object.keys(t||{}).every(t=>e.has(t))},_m=(t,e,i,s)=>{const n=t.b[0]-t.a[0],o=t.b[1]-t.a[1],a=Math.hypot(n,o);if(!(a>s))return!0;const r=n/a,l=o/a,c=gl(t.cm,i.cellCm,i.gridPitch)/2;return e.some(e=>{const n=e?.center;if(!rm(n))return!0;const o=hm(n,t.a,r,l),h=Math.abs((n[0]-t.a[0])*l-(n[1]-t.a[1])*r),d=gl(Number(e.cm),i.cellCm,i.gridPitch)*("square"===e.shape?Math.SQRT1_2:.5);return!(Number.isFinite(d)&&d>0)||o>=-d-s&&o<=a+d+s&&h<=c+d+s})},mm=(t,e,i)=>{if(t.host){const s=Sp(t,e,i.coordScale,i.cellCm,i.gridPitch).resolved;return s?{center:s.center,angle:s.angle,length:s.length}:null}const s=Number(t.x)*i.coordScale,n=Number(t.y)*i.coordScale,o=Number(t.angle),a=Number(t.length)*i.coordScale;return[s,n,o,a].every(Number.isFinite)&&a>0?{center:[s,n],angle:o,length:a}:null},gm=(t,e,i)=>{const s=t.angle*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=e.angle*Math.PI/180,r=Math.cos(a),l=Math.sin(a);if(Math.abs(n*l-o*r)>1e-6)return!1;const c=e.center[0]-t.center[0],h=e.center[1]-t.center[1];if(Math.abs(c*o-h*n)>i)return!1;const d=c*n+h*o;return Math.max(-t.length/2,d-e.length/2)({...t,a:[t.a[0]*e,t.a[1]*e],b:[t.b[0]*e,t.b[1]*e]}),vm=(t,e,i,s)=>{const n=`~r-${(t=>{let e=2166136261;for(let i=0;i>>0;return e.toString(36)})(`${t}|${e[0].toFixed(9)},${e[1].toFixed(9)}|${i[0].toFixed(9)},${i[1].toFixed(9)}`)}`,o=`${t.slice(0,Math.max(1,64-n.length))}${n}`;let a=o;for(let t=2;s.has(a);t++){const e=`-${t}`;a=`${o.slice(0,64-e.length)}${e}`}return s.add(a),a},ym=(t,e)=>{const i=[];for(const s of t){const t=i[i.length-1];!(t&&Math.abs(t.hi-s.lo)<=e&&t.safe===s.safe)||s.safe&&t.signature!==s.signature?i.push({lo:s.lo,hi:s.hi,a:s.a,b:s.b,safe:s.safe,signature:s.signature,roomIds:s.roomIds,finalCm:s.finalCm}):(t.hi=s.hi,t.b=s.b)}return i};function bm(t,e,i,s,n){const o=i||[],a=Array.isArray(t?.partitions)?t.partitions:[],r=Array.isArray(t?.openings)?t.openings:[],l=Array.isArray(t?.room_drafts)?t.room_drafts:[],c={walls:o,partitions:a,openings:r,roomDrafts:l,partitionsReconciled:0,openingsRehosted:0,removedDrafts:0};if(!a.length&&!l.length)return c;const h=Math.max(2e-4*n.gridPitch,1e-9);let d=o,p=a,u=r;const _=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),m=((t,e,i,s)=>{const n=new Map(t.map(t=>[t.id,t])),o=new Set;for(const t of e){if(!n.get(t.id)||!Array.isArray(t.points)||t.points.length<2||t.segments.length!==t.points.length-1)continue;let e=!0;for(let n=0;n+10)){e=!1;break}const l=Math.hypot(a[0]-o[0],a[1]-o[1]);if(!(l>s)){e=!1;break}const c=i.flatMap(t=>{const e=t.cm>0?t.cm:ll;if(t.open||"outer"!==t.kind&&"shared"!==t.kind||e+st.lo-e.lo||t.hi-e.hi);let h=0;for(const t of c){if(t.lo>h+s)break;if(h=Math.max(h,t.hi),h>=l-s)break}h!m.has(t.id));let f=0,v=0;const y=new Map(e.partitions.map(t=>[t.id,t]));for(const t of[...a].sort((t,e)=>t.id.localeCompare(e.id))){if(!p.some(e=>e.id===t.id))continue;if(!um(t))continue;const i=y.get(t.id);if(!(i&&rm(i.a)&&rm(i.b)&&Number.isFinite(i.cm)&&i.cm>0))continue;const[o,a]=lm(i.a,i.b)<=0?[[i.a[0],i.a[1]],[i.b[0],i.b[1]]]:[[i.b[0],i.b[1]],[i.a[0],i.a[1]]],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>h))continue;const _=r/c,g=l/c,b=dc(e.rooms,d,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),w=b.flatMap(t=>{if(t.open||"outer"!==t.kind&&"shared"!==t.kind)return[];const e=dm(o,a,t.a,t.b,h);return e?[{interval:t,range:e}]:[]});if(!w.length)continue;const k=u.filter(t=>"partition"===t.host?.kind&&t.host.id===i.id).map(t=>({opening:t,resolved:Sp(t,e.partitions,n.coordScale,n.cellCm,n.gridPitch).resolved}));if(k.some(t=>!t.resolved))continue;const x=[0,c];for(const{range:t}of w)x.push(t.lo,t.hi);const $=x.slice(),S=new Map;for(const{opening:t,resolved:e}of k){const i=hm(e.center,o,_,g),s={lo:i-e.length/2,hi:i+e.length/2};S.set(t.id,s),$.push(Math.max(0,s.lo),Math.min(c,s.hi))}const M=[...new Set($.filter(t=>Number.isFinite(t)&&t>=-h&&t<=c+h).map(t=>Math.max(0,Math.min(c,t)).toFixed(9)))].map(Number).sort((t,e)=>t-e),C=p.map(t=>fm(t,n.coordScale)).filter(t=>t.id!==i.id),D=e.room_drafts.filter(t=>!m.has(t.id)),P=[];for(let t=0;t+1h))continue;const r=cm(o,_,g,s),l=cm(o,_,g,a),c=w.filter(({range:t})=>t.lo<=s+h&&t.hi>=a-h).map(({interval:t})=>t),d=new Map;for(const t of c)d.set(t.roomId,t);const p=[...d.values()],u=new Set(p.map(t=>t.kind)),m=new Set(p.map(t=>t.cm>0?t.cm:ll)),f=p[0]?.kind,v=[...d.keys()].sort(),y=1===u.size&&1===m.size&&("outer"===f&&1===v.length||"shared"===f&&2===v.length),b={id:i.id,a:r,b:l,cm:i.cm},k=C.some(t=>!!dm(r,l,t.a,t.b,h)),x=D.some(t=>t.points.some((e,i)=>i+10?p[0].cm:ll:0,T=y?Math.max(S,i.cm):i.cm;P.push({lo:s,hi:a,a:r,b:l,safe:$,signature:$?`${f}|${v.join(",")}|${T}`:"",roomIds:v,roomCm:S,finalCm:T})}if(!P.some(t=>t.safe))continue;const T=new Map;for(const{opening:t,resolved:e}of k){const s=S.get(t.id),o=x.some(t=>t>s.lo+h&&tpm(t,s,h)),r=new Set(a.filter(t=>t.safe).map(t=>t.signature));if(!o&&a.length>0&&a.every(t=>t.safe)&&1===r.size&&Rp(e,b,h)){T.set(t.id,{resolved:e,signature:[...r][0]});continue}const l=xp(i,n.cellCm,n.gridPitch),c={lo:s.lo-l,hi:s.hi+l};for(const t of P)pm(t,c,h)&&(t.safe=!1,t.signature="")}let R=!0;for(;R;){R=!1;for(const[t,e]of[...T.entries()]){const s=S.get(t),o=P.filter(t=>pm(t,s,h));if(o.length>0&&o.every(t=>t.safe)&&o.every(t=>t.signature===e.signature))continue;T.delete(t);const a=xp(i,n.cellCm,n.gridPitch),r={lo:s.lo-a,hi:s.hi+a};for(const t of P)pm(t,r,h)&&(t.safe=!1,t.signature="");R=!0}}const I=ym(P,h),A=I.filter(t=>t.safe),z=I.filter(t=>!t.safe);if(!A.length)continue;if(p.length-1+z.length>2e3)continue;let F=d;for(const t of A){const[e,s]=lm(i.a,i.b)<=0?[t.a,t.b]:[t.b,t.a];F=Fl(F,e,s,t.finalCm,n.pitch,n.coordScale)}if(F=uc(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale),F.length>500)continue;const E=new Set(p.map(t=>t.id));E.delete(i.id);const N=z.map((t,e)=>{const s=[t.a[0]/n.coordScale,t.a[1]/n.coordScale],o=[t.b[0]/n.coordScale,t.b[1]/n.coordScale],a=0===e?i.id:vm(i.id,s,o,E);return E.add(a),{id:a,a:s,b:o,cm:i.cm}}),O=p.findIndex(t=>t.id===i.id),L=p.slice();L.splice(O,1,...N);const H=L.map(t=>fm(t,n.coordScale)),B=new Map;let q=!0;for(const{opening:t,resolved:e}of k){const i=T.get(t.id);if(i){const e=Ip(t,i.resolved,n.coordScale),{host:s,...o}=e;B.set(t.id,o);continue}const s=S.get(t.id),o=N[z.findIndex(t=>t.lo<=s.lo+h&&t.hi>=s.hi-h)],a=o&&H.find(t=>t.id===o.id);if(!o||!a){q=!1;break}const r=a.b[0]-a.a[0],l=a.b[1]-a.a[1],c=Math.hypot(r,l),d=hm(e.center,a.a,r/c,l/c),p={...Ip(t,e,n.coordScale),host:{kind:"partition",id:o.id,t:d/c}};if(!Mp(p,H,n.coordScale,n.cellCm,n.gridPitch).resolved){q=!1;break}B.set(t.id,p)}if(!q)continue;const W=u.map(t=>B.get(t.id)||t),j=[...T.keys()].map(t=>B.get(t)),U=j.map(t=>mm(t,H,n));if(U.some(t=>!t))continue;let G=!1;for(let t=0;tt.id));for(const t of W){if(V.has(t.id))continue;const e=mm(t,H,n);e&&U.some(t=>gm(t,e,h))&&(G=!0)}if(G)continue;const K=Ec(e.rooms,F,s,n.pitch,n.cellCm,n.gridPitch,n.coordScale);[...T.entries()].every(([t,e])=>{const i=B.get(t),s=Lc(K,{x:i.x*n.coordScale,y:i.y*n.coordScale,angle:i.angle,length:i.length*n.coordScale},!0),o=[s.negative,s.positive].filter(t=>!!t?.full),a=e.signature.split("|")[1].split(","),r=new Set(o.map(t=>t.roomId));return o.length===a.length&&r.size===a.length&&a.every(t=>r.has(t))})&&(d=F,p=L,u=W,f+=A.length,v+=T.size)}return{walls:d,partitions:p,openings:u,roomDrafts:g,partitionsReconciled:f,openingsRehosted:v,removedDrafts:m.size}}const wm=t=>JSON.parse(JSON.stringify(t)),km=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),xm=(t,e)=>e.length>0&&e.length<=35&&("space"===t?/^[a-z0-9_-]+$/.test(e):/^[A-Za-z0-9_-]+$/.test(e));function $m(t,e){let i=String(e??"");const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s}_(.+)_([0-9a-f]{8})$`);let o=0;for(;o<16;o++){const t=n.exec(i);if(!t)return{root:i,layers:o,bounded:!1};i=t[1]}return{root:i,layers:o,bounded:n.test(i)}}const Sm=(t,e,i)=>{const s=t.get(e)||[];s.push(i),t.set(e,s)};const Mm=1e-9;class Cm extends Error{constructor(t,e=""){super(e?`${t}: ${e}`:t),this.reason=t,this.name="WallSegmentModelError"}}const Dm=t=>JSON.parse(JSON.stringify(t)),Pm=t=>Array.isArray(t)&&t.length>=2&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1])),Tm=t=>[Number(t[0]),Number(t[1])],Rm=t=>`${Number(t[0]).toFixed(12)},${Number(t[1]).toFixed(12)}`,Im=(t,e)=>{const i=Rm(t),s=Rm(e);return iRm(t)<=Rm(e)?[Tm(t),Tm(e)]:[Tm(e),Tm(t)],zm=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Fm=t=>{const e=[[Number(t.points[0][0]),Number(t.points[0][1])]],i=[];for(let s=1;s{const i=new Set,s=t=>{const e=Number(t);if(!Number.isFinite(e))return;const s=e/Th;Math.abs(s-Math.round(s))>=Ur&&i.add(e.toFixed(12))};for(const e of Array.isArray(t?.rooms)?t.rooms:[])for(const t of hi(e)||[])s(t[0]),s(t[1]);for(const e of[t?.wall_segments,t?.walls])for(const t of Array.isArray(e)?e:[])s(t?.a?.[0]),s(t?.a?.[1]),s(t?.b?.[0]),s(t?.b?.[1]);for(const t of e)s(t?.[0]),s(t?.[1]);return i.size},Nm=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;return o>1e-18?((t[0]-e[0])*s+(t[1]-e[1])*n)/o:0},Om=(t,e,i)=>{const s=Math.max(0,Math.min(1,Nm(t,e,i)));return Math.hypot(t[0]-(e[0]+(i[0]-e[0])*s),t[1]-(e[1]+(i[1]-e[1])*s))},Lm=(t,e,i,s,n=Mm)=>{const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(r<=n)return 0;const l=e=>Math.abs((e[0]-t[0])*a-(e[1]-t[1])*o)/r;if(l(i)>n||l(s)>n)return 0;const c=Nm(i,t,e),h=Nm(s,t,e);return Math.max(0,Math.min(1,Math.max(c,h))-Math.max(0,Math.min(c,h)))*r},Hm=t=>{const e=(new TextEncoder).encode(t),i=8*e.length,s=64*Math.ceil((e.length+9)/64),n=new Uint8Array(s);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(s-8,Math.floor(i/4294967296),!1),o.setUint32(s-4,i>>>0,!1);const a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(t,e)=>t>>>e|t<<32-e;for(let t=0;t>>3,n=c(i,17)^c(i,19)^i>>>10;l[t]=l[t-16]+s+l[t-7]+n>>>0}let[e,i,s,n,h,d,p,u]=r;for(let t=0;t<64;t++){const o=u+(c(h,6)^c(h,11)^c(h,25))+(h&d^~h&p)+a[t]+l[t]>>>0,r=e&i^e&s^i&s;u=p,p=d,d=h,h=n+o>>>0,n=s,s=i,i=e,e=o+((c(e,2)^c(e,13)^c(e,22))+r>>>0)>>>0}r[0]=r[0]+e>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+s>>>0,r[3]=r[3]+n>>>0,r[4]=r[4]+h>>>0,r[5]=r[5]+d>>>0,r[6]=r[6]+p>>>0,r[7]=r[7]+u>>>0}const h=new Uint8Array(32),d=new DataView(h.buffer);for(let t=0;t{const e="abcdefghijklmnopqrstuvwxyz234567";let i=0,s=0,n="";for(const o of t)for(s=s<<8|o,i+=8;i>=5;)n+=e[s>>>i-5&31],i-=5;return i&&(n+=e[s<<5-i&31]),n},qm=(t,e,i,s,n="")=>{const[o,a]=Am(e,i),r=`${t}|${Rm(o)}|${Rm(a)}|${[...s].sort().join(",")}${n}`;return`wall-${Bm(Hm(r)).slice(0,20)}`};let Wm=0;const jm=t=>{for(let e=0;e<1e3;e++){const e=globalThis.crypto?.randomUUID?.(),i=`wall-${e||Bm(Hm(`${Date.now()}|${Wm++}|${Math.random()}`)).slice(0,26)}`;if(!t.has(i))return i}throw new Cm("duplicate-id","id factory exhausted")},Um=t=>{const e=new Map;for(const i of Array.isArray(t?.wall_segments)?t.wall_segments:[])if(i&&"string"==typeof i.id&&Pm(i.a)&&Pm(i.b)){if(e.has(i.id))throw new Cm("duplicate-id",i.id);e.set(i.id,i)}return e},Gm=(t,e,i)=>{const s=(i,s)=>{const n=t[0]-i[0],o=t[1]-i[1];return Math.abs(e[0]-s[0]-n)<=Mm&&Math.abs(e[1]-s[1]-o)<=Mm?[n,o]:null};return s(i.a,i.b)||s(i.b,i.a)},Vm=(t,e)=>{const i=Array.isArray(t.rooms)?t.rooms:[],s=ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]),n=s.length?s:_d(i,null,1,.04*Th,!0),o=[];for(const t of i){const i=hi(t),s=Array.isArray(t?.wall_ids)?t.wall_ids:[];if(i&&s.length===i.length)for(let t=0;t"partition"!==t.host?.kind&&[Number(t.x),Number(t.y)].every(Number.isFinite)&&Number.isFinite(Number(t.angle))&&Number(t.length)>0&&n.some(e=>Om([Number(t.x),Number(t.y)],[e[0],e[1]],[e[2],e[3]])<=.04*Th)):[],l=r.map(t=>{const e=Number(t.angle)*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Number(t.length)/2,n=[Number(t.x),Number(t.y)];return{a:[n[0]-i[0]*s,n[1]-i[1]*s],b:[n[0]+i[0]*s,n[1]+i[1]*s]}}),c=(t,e)=>r.some(i=>{const s=[Number(i.x),Number(i.y)];if(!Rl(t,e,Number(i.angle)))return!1;if(Om(s,t,e)>.02*Th)return!1;const n=zm(t,e),o=Nm(s,t,e)*n,a=Number(i.length)/2;return o+a>=-Mm&&o-a<=n+Mm}),h=new Map,d=[];for(const s of i){const r=String(s?.id||""),p=hi(s);if(!r||!p||p.length<3)throw new Cm("invalid-room",r);const u=ec(i,r,a,Th,1,[...t.walls||[],...l]);if(!u||u.poly.length<3)throw new Cm("invalid-room",r);const _=Array.isArray(s.wall_ids)?s.wall_ids:[],m=_.length===p.length;let g=null,f=m;if(f)for(let t=0;tMm||Math.abs(s[1]-g[1])>Mm)){f=!1;break}g=s}const v=[];for(let t=0;t2)throw new Cm("third-owner",a);const d=m?_[u.parent[t]]:void 0;if("string"==typeof d&&d){const n=e.get(d);f||!n||Lm(i,s,n.a,n.b)>Mm?l.preferredIds.add(d):l.positionalIds.add(d),l.preferredCarriers.set(d,{a:Tm(p[u.parent[t]]),b:Tm(p[(u.parent[t]+1)%p.length])})}const g=u.parent[t];l.parentKeys.add(wl(p[g],p[(g+1)%p.length],Th));const y=[(i[0]+s[0])/2,(i[1]+s[1])/2],b=t=>t.some(t=>Om(y,[t[0],t[1]],[t[2],t[3]])<=.04*Th);l.zeroWall||=b(o)||b(n)&&!c(i,s),v.push(a)}const y={...s};delete y.wall_ids,d.push({...y,poly:u.poly.map(t=>[t[0],t[1]]),wall_ids:v})}return{atoms:[...h.values()].sort((t,e)=>t.key.localeCompare(e.key)),rooms:d}},Km=(t,e,i,s,n)=>{const o=new Map([...i.values()].map(t=>[Im(t.a,t.b),t])),a=(t=>{const e=new Map;for(const i of t)"wall"===i.host?.kind&&e.set(i.host.id,(e.get(i.host.id)||0)+1);return e})(t.openings||[]),r=new Map;for(const t of e){const e=n?.get(t.key);if(e){const s=i.get(e);if(!s)throw new Cm("duplicate-id",e);r.set(t,s);continue}if(t.preferredIds.size>1)throw new Cm("duplicate-id",[...t.preferredIds].sort().join(","));const s=[...t.preferredIds][0],l=s?i.get(s):void 0;if(l){r.set(t,l);continue}const c=s?t.preferredCarriers.get(s):void 0;if(s&&c){r.set(t,{id:s,a:c.a,b:c.b,cm:0});continue}const h=o.get(t.key);if(h){r.set(t,h);continue}const d=[...i.values()].filter(e=>Lm(t.a,t.b,e.a,e.b)>Mm),p=[...new Map(d.map(t=>[t.id,t])).values()];if(p.sort((t,e)=>(a.get(e.id)||0)-(a.get(t.id)||0)||zm(e.a,e.b)-zm(t.a,t.b)||t.id.localeCompare(e.id)),p[0])r.set(t,p[0]);else if(1===t.positionalIds.size){const e=i.get([...t.positionalIds][0]);e&&r.set(t,e)}}const l=new Map;for(const[t,e]of r){const i=l.get(e.id)||[];i.push(t),l.set(e.id,i)}for(const[t,e]of l){const s=i.get(t)||r.get(e[0]);if(!s)throw new Cm("duplicate-id",t);const n=[(s.a[0]+s.b[0])/2,(s.a[1]+s.b[1])/2];e.sort((t,e)=>{const i=Om(n,t.a,t.b)<=Mm?0:1,o=Om(n,e.a,e.b)<=Mm?0:1;if(i!==o)return i-o;return(Om(s.a,t.a,t.b)<=Mm?0:1)-(Om(s.a,e.a,e.b)<=Mm?0:1)||t.key.localeCompare(e.key)}),e[0].id=t}const c=(t=>{const e=new Set;for(const i of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns])for(const t of Array.isArray(i)?i:[])"string"==typeof t?.id&&t.id&&e.add(t.id);for(const i of Array.isArray(t.room_drafts)?t.room_drafts:[])for(const t of Array.isArray(i?.segments)?i.segments:[])"string"==typeof t?.id&&t.id&&e.add(t.id);return e})(t);for(const t of e)if(t.id){if(c.has(t.id))throw new Cm("duplicate-id",t.id);c.add(t.id)}const h=e.filter(t=>!t.id);if(s){const e=h.map(e=>{const[i,s]=Am(e.a,e.b),n=`${String(t.id||"")}|${Rm(i)}|${Rm(s)}|${[...e.owners].sort().join(",")}`,o=Bm(Hm(n));return{atom:e,seed:n,digest:o,base:`wall-${o.slice(0,20)}`}}).sort((t,e)=>t.digest.localeCompare(e.digest)||t.atom.key.localeCompare(e.atom.key)),i=new Map;for(const t of e){const e=i.get(t.digest);if(e&&e!==t.seed)throw new Cm("duplicate-id",t.digest);i.set(t.digest,t.seed);let s=1,n=t.base;for(;c.has(n);)n=`${t.base}-${++s}`;t.atom.id=n,c.add(n)}}else for(const t of h)t.id=jm(c),c.add(t.id)},Ym=(t,e)=>{if("partition"===t.host?.kind)return null;const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=e=>{if(!(Number(e.cm)>0))return!1;const s=Nm(i,e.a,e.b),n=zm(e.a,e.b),o=Number(t.length)/2;return s>=-Mm&&s<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(o)&&o>=0&&s*n-o>=-Mm&&s*n+o<=n+Mm},n="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null,o=n&&s(n)?[n]:e.filter(s);if(1!==o.length)return null;const a=o[0];return{kind:"wall",id:a.id,t:Math.max(0,Math.min(1,Nm(i,a.a,a.b)))}},Jm=(t,e)=>{const i=[Number(t.x),Number(t.y)];if(!i.every(Number.isFinite))return null;const s=Number(t.length)/2,n=e.filter(e=>{if(!(Number(e.cm)>0))return!1;const n=Nm(i,e.a,e.b),o=zm(e.a,e.b);return n>=-Mm&&n<=1+Mm&&Om(i,e.a,e.b)<=.02*Th&&Rl(e.a,e.b,Number(t.angle))&&Number.isFinite(s)&&s>=0&&n*o-s>=-Mm&&n*o+s<=o+Mm}),o=(e=>{if(!e.length)return null;const s="wall"===t.host?.kind?e.find(e=>e.id===t.host.id):null;return s||[...e].sort((t,e)=>Om(i,t.a,t.b)-Om(i,e.a,e.b)||Number(e.cm)-Number(t.cm)||(t.ide.id?1:0))[0]})(n);return o?{kind:"wall",id:o.id,t:Math.max(0,Math.min(1,Nm(i,o.a,o.b)))}:null},Xm=(t,e,i)=>{const s=Um(t),{atoms:n,rooms:o}=Vm(t,s);Km(t,n,s,e,i);const a=n.map(e=>{const i=e.id?s.get(e.id):void 0,n=((t,e,i)=>{if(e.zeroWall)return 0;const s=Array.isArray(t.walls)?t.walls:[],n=wl(e.a,e.b,Th),o=s.filter(t=>Number(t.cm)>0&&(!(t.key!==n&&!e.parentKeys.has(t.key))||!(!Pm(t.a)||!Pm(t.b))&&Lm(e.a,e.b,t.a,t.b)>=zm(e.a,e.b)-Mm)).map(t=>Math.max(1,Math.min(100,Number(t.cm))));if(new Set(o.map(t=>t.toFixed(9))).size>1)throw new Cm("thickness-conflict",e.key);if(o.length)return o[0];const a=Pl(s,e.a,e.b,Th,1);return a>0?a:Number(i?.cm)>0?Number(i.cm):0})(t,e,i);return{...i||{},id:e.id,a:[...e.a],b:[...e.b],cm:n}}),r=new Map(n.map(t=>[t.key,t.id]));for(const t of o)t.wall_ids=t.wall_ids.map(t=>r.get(t));t.rooms=o,t.wall_segments=a,t.walls=a.filter(t=>t.cm>0).map(t=>({key:wl(t.a,t.b,Th),cm:t.cm,a:[...t.a],b:[...t.b]})),t.walls.length||delete t.walls,delete t.open_spans;for(const e of t.rooms)delete e.open_to;return((t,e)=>{const i=new Set;for(const e of[t.rooms,t.openings,t.decor,t.room_drafts,t.partitions,t.wall_columns,t.wall_segments])for(const t of Array.isArray(e)?e:[])"string"==typeof t?.id&&t.id&&i.add(t.id);for(const s of Array.isArray(t.room_drafts)?t.room_drafts:[]){const n=Array.isArray(s.segments)?s.segments:[];for(let o=0;o{const s=Array.isArray(t.openings)?t.openings:[];for(const t of s){if("partition"===t.host?.kind)continue;if(!t.host&&!i){const i=Ym(t,e);i&&(t.host=i);continue}const s=Ym(t,e)??(i?Jm(t,e):null);if(s)t.host=s;else{if(!i)throw new Cm("opening-host",t.id);delete t.host}}})(t,a,e),a.reduce((t,e)=>t+(s.has(e.id)?0:1),0)};function Zm(t,e={}){const i=JSON.stringify(t),s=Dm(t);rl(s);let n=0;const o=Number(s?.model_version||0)<9;for(const t of Array.isArray(s?.spaces)?s.spaces:[]){const i=e.lineageSpaceId===String(t?.id||"")?e.lineageHints:void 0;n+=Xm(t,o,i)}return s.model_version=9,rl(s),{config:s,changed:i!==JSON.stringify(s),migratedSegments:n}}const Qm=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tg(t,e){const i=(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){const s=new Map;for(const e of t)Qm(e)&&"string"==typeof e.id&&e.id&&s.set(e.id,e);const n=e.map((e,n)=>{if(Qm(e)&&"string"==typeof e.id&&e.id){const t=s.get(e.id);return t?i(t,e):Dm(e)}return n[e,e in t?i(t[e],s):Dm(s)]);for(const e of Object.keys(t))delete t[e];for(const[e,i]of s)t[e]=i;return t}return Dm(e)};return i(t,e)}const eg=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ig=(t,e,i)=>Math.min(i,Math.max(e,t)),sg=t=>Sh({spaces:[t]})[0],ng=(t,e,i)=>{const s=i>0?i:1,n=t=>`${(t[0]/s).toFixed(12)},${(t[1]/s).toFixed(12)}`,o=n(t),a=n(e);return o0?a:1,l=Math.max(s*r*.02,1e-9),c=[];for(const e of t||[])for(const t of hi(e)||[])c.push([t[0],t[1]]);const h=[];for(const t of i||[])Array.isArray(t)&&t.length>=4&&t.slice(0,4).every(Number.isFinite)&&h.push([t[0],t[1]],[t[2],t[3]]);const d=(t,e)=>e.some(e=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l),p=new Map;for(const a of t||[]){if(!a?.id)continue;const u=hc(t,a.id,e,i,s,n,o,r);if(u)for(let t=0;t0&&_>0&&a===m&&_!==a))continue;const g=u.poly[s],f=u.poly[(s+1)%u.poly.length],v=Math.hypot(f[0]-g[0],f[1]-g[1]);if(!(v>l&&v<.5*o-1e-9*o))continue;if(d(g,h)||d(f,h))continue;if(d(g,c)&&d(f,c))continue;const y=ng(g,f,r),b=p.get(y);b?b.targets.add(a):p.set(y,{a:[g[0],g[1]],b:[f[0],f[1]],targets:new Set([a])})}}}let u=e.slice();const _=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1])<=2*l,m=(t,e)=>{if(!Array.isArray(t.a)||!Array.isArray(t.b)||t.a.length<2||t.b.length<2)return!1;const i=[Number(t.a[0])*r,Number(t.a[1])*r],s=[Number(t.b[0])*r,Number(t.b[1])*r];return!![...i,...s].every(Number.isFinite)&&(_(i,e.a)&&_(s,e.b)||_(i,e.b)&&_(s,e.a))};for(const t of[...p.values()].filter(t=>1===t.targets.size).sort((t,e)=>ng(t.a,t.b,r).localeCompare(ng(e.a,e.b,r)))){const e=[...t.targets][0],i=u.filter(e=>m(e,t));if(new Set(i.map(t=>t.cm)).size>1)continue;let n=!1;u=u.map(i=>m(i,t)?(n=!0,i.cm===e?i:{...i,cm:e}):i),n||(u=Fl(u,t.a,t.b,e,s,r))}return u}const ag=t=>{const e=[];for(const i of t||[]){const t=hi(i);if(t?.length)for(let i=0;i"string"==typeof t?.id?t.id:"").filter(Boolean),h=new Set(c),d=new Map;for(const t of c){const e=$m("space",t);e.layers>0&&xm("space",e.root)&&Sm(d,e.root,t)}const p=new Map,u=new Map,_=new Map,m=new Map;for(const t of r){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i=new Map;for(const s of Array.isArray(t.rooms)?t.rooms:[]){const t="string"==typeof s?.id?s.id:"";if(!t)continue;const n=$m("room",t);n.layers>0&&xm("room",n.root)&&Sm(i,n.root,t),u.has(t)||u.set(t,e),_.has(t)||_.set(t,String(s.name||""));const o="string"==typeof s.area?s.area:"";if(o){const i=m.get(o)||[];i.push({spaceId:e,roomId:t}),m.set(o,i)}}p.set(e,i)}const g=new Set(u.keys()),f=new Map,v=new Map;for(const t of l)"string"==typeof t?.id&&t.id&&(!0===t.removed?v.set(t.id,t):f.set(t.id,t));const y={spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,positionsUnresolved:0,nestedRefsUnresolved:0,deadSpaceIds:[],orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0,removedPositions:[],liveMissingPositions:[],unverifiedPositions:[]},b=new Set,w=t=>h.has(t)?null:(()=>{const e=$m("space",t).root;if(!xm("space",e))return null;const i=d.get(e)||[];return 1===i.length?i[0]:null})(),k=(t,e)=>{const i=$m("room",t).root;if(!xm("room",i))return null;const s=p.get(e)?.get(i)||[];return 1===s.length?s[0]:null},x=t=>{const e=i.effectiveAreaByMarker?.[t]||"",s=e&&m.get(e)||[];return 1===s.length?s[0]:null},$=(t,e,i)=>{if("string"==typeof t.room_id&&t.room_id&&!g.has(t.room_id)){const s=e?k(t.room_id,e):null;s?(t.room_id=s,y.roomRefsRemapped++):i?(t.room_id=i.roomId,y.roomRefsRemapped++):!0!==t.removed&&delete t.room_id}const s=t.vacuum?.segment_map;if(s&&"object"==typeof s&&!Array.isArray(s))for(const t of Object.keys(s)){const i=s[t];if("string"!=typeof i||!i||g.has(i))continue;const n=e?k(i,e):null;n?(s[t]=n,y.roomRefsRemapped++):y.nestedRefsUnresolved++}};for(const t of l){const e="string"==typeof t?.id?t.id:"";if(!e)continue;const i="string"==typeof t.space?t.space:"",s=i&&!h.has(i),o=n[e],a="string"==typeof o?.s?o.s:"",r=a&&!h.has(a),l=!0===t.removed;let c=i&&h.has(i)?i:null,d=null,p=!1;if(s){const s=w(i);s?(t.space=s,c=s,p=!0,y.spaceRefsRemapped++):l||"virtual"===t.binding?l||(delete t.space,c=null,y.markersDetached++):(d=x(e),d?(t.space=d.spaceId,c=d.spaceId,y.spaceRefsRemapped++):(delete t.space,c=null,y.markersDetached++))}l&&!p||$(t,c,d),r&&p&&a===i&&c&&(n[e]={...o,s:c},y.positionsRemapped++,b.add(e))}for(const t of Object.keys(n)){if(b.has(t))continue;const e=n[t],i="string"==typeof e?.s?e.s:"";if(!i||h.has(i))continue;const s=w(i);if(s){if(t.startsWith("rl_")){const i=t.slice(3),o=k(i,s);if(o){const i=`rl_${o}`;km(n,i)||(n[i]={...e,s:s}),delete n[t],y.roomRefsRemapped++,y.positionsRemapped++;continue}}n[t]={...e,s:s},y.positionsRemapped++}}const S=i.ownerRoster,M=!0===S?.authoritative,C=new Set(S?.deviceIds||[]),D=new Set(S?.entityIds||[]),P=new Set(Array.isArray(s.settings?.known_devices)?s.settings.known_devices.filter(t=>"string"==typeof t):[]),T=(t,e="")=>{const i=String(S?.names?.[t]||e||"").trim();return i&&i!==t?i:""},R=(t,e,i,s="",n)=>({id:t,spaceId:e,kind:i,name:T(t,s),...n?{reason:n}:{}}),I=t=>{"room_label"===t?y.orphanRoomLabelsRemoved++:"group"===t?y.orphanGroupPositionsRemoved++:y.orphanDevicePositionsRemoved++},A=new Set;for(const[t,e]of Object.entries(n)){const s="string"==typeof e?.s?e.s:"";if(!s||h.has(s))continue;let o,a;const r=f.get(t),l=v.get(t);if(r)o=R(t,s,"device",String(r.name||"")),a="live";else if(l)o=R(t,s,"device",String(l.name||"")),a="absent";else if(t.startsWith("rl_")){const e=t.slice(3);o=R(t,s,"room_label",_.get(e)||""),a=g.has(e)?"live":"absent"}else if(t.startsWith("lg_")){const e=t.slice(3);o=R(t,s,"group"),a=D.has(e)?"live":M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")}else C.has(t)?(o=R(t,s,"device"),a="live"):P.has(t)?(o=R(t,s,"device"),a=M?"absent":"unverified","unverified"===a&&(o.reason="registry_unavailable")):(o=R(t,s,"unknown","","unknown_owner"),a="unverified");if("absent"!==a){if("live"===a){if(y.liveMissingPositions.push(o),!0===i.removeLiveMissingPositions){delete n[t],y.liveMissingPositionsRemoved++,I(o.kind),y.removedPositions.push(o);continue}}else y.unverifiedPositions.push(o);y.positionsUnresolved++,A.add(s)}else delete n[t],I(o.kind),y.removedPositions.push(o)}return y.deadSpaceIds=[...A].sort((t,e)=>t.localeCompare(e)),{config:s,layout:n,report:y,changed:JSON.stringify(s)!==o||JSON.stringify(n)!==a}}(t,e,i),a=o.config,r=nl(a,o.layout);rl(a),al(o.layout);const l=JSON.stringify(t||{}),c=JSON.stringify(e||{}),h=Number.isInteger(Number(a.model_version))?Number(a.model_version):0,d=(t=>{let e=0,i=0,s=0;for(const i of t.markers||[]){if("ripple"===i.display&&(i.display="icon_ripple",e++),Array.isArray(i.controls)){const t="string"==typeof i.binding&&i.binding.startsWith("entity:")?i.binding.slice(7):"",s=t?i.controls.filter(e=>e!==t):i.controls;JSON.stringify(s)!==JSON.stringify(i.controls)&&(i.controls=s.length?s:null,e++)}const t=i.vacuum;t&&eg(t,"trail")&&(["never","cleaning","always"].includes(t.trail_mode)||(t.trail_mode=!1===t.trail?"never":"cleaning"),delete t.trail,e++)}for(const n of t.spaces||[]){const t=n.settings;"glow"===t?.fill_mode&&("boolean"!=typeof t.glow_enabled&&(t.glow_enabled=!0),t.fill_mode="none",e++,i++);for(const t of n.rooms||[]){const i=t.settings;"glow"===i?.fill_mode&&("boolean"!=typeof i.glow&&(i.glow=!0),delete i.fill_mode,e++,s++)}if(eg(n,"segments")&&(delete n.segments,e++),eg(n,"plan_scale")){const t=Number(n.plan_scale);Number.isFinite(t)&&t>=wh&&t<=kh&&(eg(n,"plan_scale_x")||(n.plan_scale_x=t),eg(n,"plan_scale_y")||(n.plan_scale_y=t),delete n.plan_scale,e++)}const o=Number(n.cell_cm);eg(n,"cell_cm")&&(!Number.isFinite(o)||o<.1||o>1e3)&&(n.cell_cm=Number.isFinite(o)&&o>0?ig(o,.1,1e3):5,e++);const a=Number(n.cell_cm),r=Number.isFinite(a)&&a>0?a:5;for(const t of n.wall_columns||[])if("circle"===t.shape)eg(t,"angle")&&(delete t.angle,e++);else if("square"===t.shape&&eg(t,"angle")){const i=((Number(t.angle)||0)%90+90)%90;t.angle!==i&&(t.angle=i,e++)}for(const t of n.decor||[]){if(eg(t,"width")){const i=Number(t.width);(eg(t,"width_cm")||Number.isFinite(i))&&(eg(t,"width_cm")||(t.width_cm=Number(ig(i/Ph*r,.1,100).toFixed(6))),delete t.width,e++)}if("rect"!==t?.kind&&"ellipse"!==t?.kind||!0!==t.fill||(eg(t,"fill_color")||(t.fill_color=t.color||"#607d8b",e++),eg(t,"fill_opacity")||(t.fill_opacity=.25,e++)),"text"!==t?.kind)continue;void 0===t.size_cm?(t.size_cm=Number(ig(es*is(t)/Ph*r,.1,2e3).toFixed(6)),delete t.scale,delete t.size,e++):(eg(t,"scale")||eg(t,"size"))&&(delete t.scale,delete t.size,e++);let i=String(t.text??"");const s=[...i.matchAll(/\{([^{}\r\n]+)\}/g)].some(t=>!!Yi(t[1]));if(!(eg(t,"entity")||eg(t,"attr")||eg(t,"unit")))continue;const n=String(t.unit??"").trim(),o="state"===String(t.attr??"").trim().toLowerCase()?null:t.attr,a=s||n?"":Ji(t.entity,o);if(s||a){if(a){const e=i.indexOf("{}");i=e>=0?i.slice(0,e)+a+i.slice(e+2):`${i}${i?" ":""}${a}`,t.text=i}delete t.entity,delete t.attr,delete t.unit,e++}}}return{total:e,glowSpaces:i,glowRooms:s}})(a);let p=d.total;const u=(_=a.spaces||[],JSON.parse(JSON.stringify(_)));var _;const m=X_(a.spaces||[],o.layout);let g=0,f=0,v=0,y="";const b=m.spaces.map(t=>{const e=function(t){const e=JSON.parse(JSON.stringify(t||{}));let i=Array.isArray(e.rooms)?e.rooms:[];const s=new Map;for(const t of i){const e=hi(t);if(e)for(let t=0;tt.key.localeCompare(e.key))){let e=null;for(const s of $a(t,i)){const t=r.get(_a(s.from));if(t&&t!==_a(s.to))continue;const n=wa(i,s);if(ka(i,n,s)){e=s,i=n;break}}e?(r.set(_a(e.from),_a(e.to)),n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}e.rooms=i;for(const t of e.room_drafts||[]){if(!Array.isArray(t?.points)||t.points.length<2)continue;const e=t.points.map(t=>[...t]),i=e.slice(0,-1).flatMap((i,s)=>{const n=e[s+1],o=pa(i,n);return o?[{key:`${String(t.id||"")}:${s}`,a:[...i],b:[...n],axis:o.axis}]:[]});let s=e;for(const t of i){let e=null;for(const i of $a(t,[{poly:s}])){const t=s.map(t=>ba(t,i)),n=t.length>=4&&ma(t[0],t[t.length-1]),o=n?t.slice(0,-1):t;if(n?va(o):ya(o)){e=i,s=t;break}}e?(n++,a=Math.max(a,Math.hypot(e.to[0]-e.from[0],e.to[1]-e.from[1]))):o++}t.points=s}for(const t of e.partitions||[]){if(!Array.isArray(t?.a)||!Array.isArray(t?.b))continue;const i=pa(t.a,t.b);if(!i)continue;const s={key:String(t.id||ga(t.a,t.b)),a:[...t.a],b:[...t.b],axis:i.axis};let r=null;for(const i of $a(s,[{poly:[t.a,t.b]}])){const s=ba(t.a,i),n=ba(t.b,i),o=Math.hypot(n[0]-s[0],n[1]-s[1]);if(!(o>0))continue;const a=(e.openings||[]).filter(e=>"partition"===e?.host?.kind&&e.host.id===t.id).every(t=>{const e=Number(t.host.t),i=Number(t.length);return Number.isFinite(e)&&e>=0&&e<=1&&Number.isFinite(i)&&i>0&&e*o-i/2>=-1e-12&&e*o+i/2<=o+1e-12});if(a){r=i,t.a=s,t.b=n;break}}r?(n++,a=Math.max(a,Math.hypot(r.to[0]-r.from[0],r.to[1]-r.from[1]))):o++}return{space:e,report:{wallsStraightened:n,wallsStraightenSkipped:o,maxStraightenShift:a},changed:n>0}}(t);g+=e.report.wallsStraightened,f+=e.report.wallsStraightenSkipped;const i=Number(t?.cell_cm)>0?Number(t.cell_cm):5,s=e.report.maxStraightenShift/Th*i;return s>v&&(v=s,y=String(t?.id||"")),e.space}),w=g?X_(b,m.layout):{...m,spaces:b};a.spaces=w.spaces;const k=g?{...m.report,moved:m.report.moved+w.report.moved,coordsCanonicalized:m.report.coordsCanonicalized+w.report.coordsCanonicalized,maxShift:Math.max(m.report.maxShift,w.report.maxShift),maxShiftCm:Math.max(m.report.maxShiftCm,w.report.maxShiftCm),maxSpace:w.report.maxShiftCm>m.report.maxShiftCm?w.report.maxSpace:m.report.maxSpace,rotated:m.report.rotated+w.report.rotated,removedDrafts:m.report.removedDrafts+w.report.removedDrafts}:{...m.report};let x=0,$=0,S=0,M=0,C=0,D=0,P=0,T=0;for(let t=0;t0===Number(t.cm)),walls:e.walls||[]}),o=sg(e),r=sg(i);if(!o||!r)continue;const l=ag(o.rooms),c=ag(r.rooms),h=.02*Ph,d=(e.wall_segments||[]).filter(t=>0===Number(t.cm)).map(t=>({...t,key:wl(t.a,t.b,Th),cm:0})),p=new Set(d.map(t=>t.key)),_=m_(e,o.rooms,yh,h);$+=_.length;for(const t of _){const e=[t[0]/yh,t[1]/yh],i=[t[2]/yh,t[3]/yh],s=wl(e,i,Th);p.has(s)||(p.add(s),d.push({key:s,a:e,b:i,cm:0}))}const m=d.length,g=Al(d,l,c,Th,yh),f=(t,e,i)=>{const s=i[0]-e[0],n=i[1]-e[1],o=s*s+n*n;if(!(o>0))return Math.hypot(t[0]-e[0],t[1]-e[1]);const a=Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*n)/o));return Math.hypot(t[0]-(e[0]+s*a),t[1]-(e[1]+n*a))},v=g.filter(t=>{if(!Array.isArray(t.a)||!Array.isArray(t.b))return!1;const e=t.a.map(t=>t*yh),i=t.b.map(t=>t*yh);return c.some(([t,s])=>f(e,t,s)<=4*h&&f(i,t,s)<=4*h)});S+=Math.max(0,m-v.length);const y=(i.wall_segments||[]).filter(t=>Number(t.cm)>0);i.wall_segments=[...y,...v.map(({key:t,...e})=>e)];const b=v.map(t=>[t.a[0]*yh,t.a[1]*yh,t.b[0]*yh,t.b[1]*yh]),w=Array.isArray(e.walls)?e.walls.length:0;let k=Al(e.walls,l,c,Th,yh);k=og(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=uc(r.rooms,k,b,Th,Number(i.cell_cm)>0?Number(i.cell_cm):5,Ph,yh),k=Tl(k,i.rooms||[],Th,1,b.map(t=>[t[0]/yh,t[1]/yh,t[2]/yh,t[3]/yh])),x+=Math.max(0,w-k.length),k.length?i.walls=k:delete i.walls;const R=nm(i.partitions||[],{pitch:Th,geometry:am(i)});R.merged&&(M+=R.merged,i.partitions=R.partitions,om(i.openings,i.partitions,R.openingMoves,{coordScale:yh,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph}));const I=sg(i);if(I){const t=n(i,I,i.walls||[],b,{pitch:Th,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,gridPitch:Ph,coordScale:yh});t.partitionsReconciled&&(C+=t.partitionsReconciled,D+=t.openingsRehosted,t.partitions.length?i.partitions=t.partitions:delete i.partitions,t.openings.length?i.openings=t.openings:delete i.openings,t.walls.length?i.walls=t.walls:delete i.walls),t.removedDrafts&&(P+=t.removedDrafts,t.roomDrafts.length?i.room_drafts=t.roomDrafts:delete i.room_drafts)}JSON.stringify({zero:(i.wall_segments||[]).filter(t=>0===Number(t.cm)),walls:i.walls||[]})!==s&&T++}let R=0;h<=9&&(R=function(t){const e=Zm(t);return tg(t,e.config),{...e,config:t}}(a).migratedSegments);const I=rl(a),A=al(w.layout),z=JSON.stringify(I)!==l||JSON.stringify(A)!==c;h<9&&z&&(I.model_version=9);const F=JSON.stringify(I)!==l||JSON.stringify(A)!==c,E=Number.isInteger(Number(I.model_version))?Number(I.model_version):h,N=F?k:{...k,moved:0,coordsCanonicalized:0,maxShift:0,maxShiftCm:0,maxSpace:"",rotated:0,removedDrafts:0},O=F?o.report:{...o.report,spaceRefsRemapped:0,roomRefsRemapped:0,positionsRemapped:0,markersDetached:0,orphanRoomLabelsRemoved:0,orphanDevicePositionsRemoved:0,orphanGroupPositionsRemoved:0,liveMissingPositionsRemoved:0};return{config:I,layout:A,report:{...N,modelFrom:h,modelTo:E,migrated:F?p:0,glowSpacesMigrated:F?d.glowSpaces:0,glowRoomsMigrated:F?d.glowRooms:0,canonicalized:F?T:0,wallSegmentsMigrated:F?R:0,legacyZeroWallsMigrated:F?$:0,wallsMerged:F?x:0,spansMerged:F?S:0,partitionsMerged:F?M:0,partitionsReconciled:F?C:0,openingsRehosted:F?D:0,redundantDraftsRemoved:F?P:0,wallsStraightened:F?g:0,wallsStraightenSkipped:f,maxStraightenShiftCm:F?v:0,maxStraightenSpace:F?y:"",latticeCoordinatesCanonicalized:F?r.canonicalized:0,latticeCoordinatesFar:F?r.far:0,latticeMaxShift:F?r.maxShift:0,latticeMaxShiftCm:F?r.maxShiftCm:0,latticeSpaces:F?r.spaces:[],...O},changed:F}}function lg(t,e,i){const s=(t?.spaces||[]).find(t=>t?.id===i),n=new Set((s?.rooms||[]).map(t=>String(t?.id||"")).filter(Boolean)),o=[...new Set((t?.markers||[]).filter(t=>!0!==t?.removed&&"string"==typeof t?.id).filter(t=>t.space===i||"string"==typeof t.room_id&&n.has(t.room_id)||e?.[t.id]?.s===i).map(t=>t.id))].sort((t,e)=>t.localeCompare(e));return{markerIds:o,count:o.length}}function cg(t){return t instanceof Error?t.name||"Error":typeof t}function hg(t){return wd({id:t?.id??"",cell_cm:t?.cell_cm,rooms:t?.rooms||[],walls:t?.walls||[],wall_segments:t?.wall_segments||[],open_spans:t?.open_spans||[],openings:t?.openings||[],partitions:t?.partitions||[],room_drafts:t?.room_drafts||[],wall_columns:t?.wall_columns||[]})}function dg(t,e,i,s=Ph,n=1e3){return(Array.isArray(t?.openings)?t.openings:[]).flatMap(t=>{const o={...t,rx:Number(t.x)*n,ry:Number(t.y)*n,rlen:Number(t.length)*n};if(!t.host||"wall"===t.host.kind)return[o];const a=Sp(t,e.partitions,n,i,s);return a.resolved?[{...t,rx:a.resolved.center[0],ry:a.resolved.center[1],rlen:a.resolved.length,angle:a.resolved.angle,partitionHost:a.resolved}]:[]})}function pg(t,e=()=>!0){return t.flatMap(t=>t.host&&t.partitionHost&&e(t)?[Dp(t.partitionHost)]:[])}function ug(t,e,i,s,n,o,a=Ph,r=1e3){const l=dc(e.rooms,[...i],s,n,o,a,r);return t.flatMap(t=>{const e={x:t.rx,y:t.ry,angle:Number(t.angle)||0,length:t.rlen};return t.host&&"wall"!==t.host.kind?t.partitionHost&&Rp(t.partitionHost,l,2e-4*a)?[e]:[]:[e]})}function _g(t,e){const i=Th,s=Ph,n=yh,o=Number.isFinite(Number(e.cellCm))&&Number(e.cellCm)>0?Number(e.cellCm):5,a=Array.isArray(t?.walls)?t.walls:[],r=function(t,e,i=Ph,s=1e3){return _d(e.rooms,t?.open_spans,s,.02*i)}(t,e,s,n),l=function(t,e,i=Ph){if(!e.length)return[];const s=t.filter(t=>t?.id),n=.02*i,o=[];for(let t=0;t{const e=[(t[0]+t[2])/2,(t[1]+t[3])/2];return h.some(t=>Ls(e,t)<4*n)}).map(t=>[...t]);d.length&&o.push({a:a,b:r,segs:d})}return o}(e.rooms,r,s).flatMap(t=>t.segs),c=dg(t,e,o,s,n),h=pg(c),d=ih(e,o,s,2e-4*s,h).all;return{space:e,walls:a,openCuts:l,openings:c,roomOpenings:ug(c,e,a,l,i,o,s,n),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:s,coordScale:n}}function mg(t,e,i){const s="string"==typeof t?.title?t.title.trim():"",n=null==t?.id?"":String(t.id).trim();return{spaceId:n,displayName:s||n||i(e+1)}}function gg(t,e={}){const i=(e.fingerprint||wd)(t),s=Array.isArray(t?.spaces)?t.spaces:[],n=e.fallbackSpaceName||(t=>`Space ${t}`),o=e.prepareSpace||_g,a=e.wallPass||Rc,r=e.floorPass||Pc,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!p){l.push({...h,status:"not-applicable"});continue}let u=null;if(p){try{u=a(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(t){l.push({...h,status:"failed",reason:"wall-exception",detail:cg(t)});continue}if(null==u){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===u.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===u.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}e.captureWallGeometry?.(d,u)}if(d.space.rooms.length&&null==u?.paperGeom){let t;try{t=r(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(t){l.push({...h,status:"failed",reason:"floor-exception",detail:cg(t)});continue}if(null==t){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(t=>"failed"===t.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}class fg{constructor(t=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(t))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(t){this._undo.push(t),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const t=this._undo.pop()??null;return t&&this._redo.push(t),t}redo(){const t=this._redo.pop()??null;return t&&this._undo.push(t),t}clear(){this._undo=[],this._redo=[]}}const vg=new WeakMap;const yg=(t,e,i)=>255===t[i+3]&&e.every((e,s)=>Math.abs(t[i+s]-e)<=2);async function bg(t){const e=t.defaultView;if(!e||!e.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],s=[16,64,128],n=[9,19,29],o=`\n \n \n \n \n \n `,a=e.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((t,i)=>{const s=new e.Image,n=e.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);s.onload=()=>{e.clearTimeout(n),t(s)},s.onerror=()=>{e.clearTimeout(n),i(new Error("SVG blend probe failed"))},s.src=a}),r=t.createElement("canvas");r.width=4,r.height=1;const l=r.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return yg(c,i,0)&&yg(c,function(t,e){return[0,1,2].map(i=>Math.round(255-(255-t[i])*(255-e[i])/255))}(i,s),4)&&yg(c,s,8)&&yg(c,n,12)}catch{return!1}finally{e.URL.revokeObjectURL(a)}}const wg={now:()=>performance.now(),requestFrame:t=>requestAnimationFrame(t),cancelFrame:t=>cancelAnimationFrame(t)},kg=t=>Math.max(0,Math.min(1,t)),xg=(t,e,i)=>t+(e-t)*i,$g=(t,e,i)=>{const s=1-t;return 3*s*s*t*e+3*s*t*t*i+t*t*t};function Sg(t,e){return{centerX:t.x+t.w/2,centerY:t.y+t.h/2,pixelsPerUnit:e>0&&t.w>0?e/t.w:1,viewBox:{...t}}}function Mg(t,e,i){const s=Math.max(1e-9,t.pixelsPerUnit),n=Math.max(1e-9,e/s),o=Math.max(1e-9,i/s);return{x:t.centerX-n/2,y:t.centerY-o/2,w:n,h:o}}function Cg(t){const e=t.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(e);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const s=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(e)?.[1];return s?[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16),8===s.length?parseInt(s.slice(6,8),16)/255:1]:null}function Dg(t,e,i){const s=Cg(t),n=Cg(e);if(!s||!n)return i<.5?t:e;const o=kg(i);return`rgba(${Math.round(xg(s[0],n[0],o))}, ${Math.round(xg(s[1],n[1],o))}, ${Math.round(xg(s[2],n[2],o))}, ${xg(s[3],n[3],o).toFixed(3)})`}function Pg(t,e,i){const s=(t=>{const e=kg(t);if(0===e||1===e)return e;let i=0,s=1,n=e;for(let t=0;t<12;t++)n=(i+s)/2,$g(n,.2,.2){const e=this._state;if(!e||e.token!==n)return;const i=kg((t-e.startedAt)/e.duration);e.presented=i>=1?e.to:Pg(e.from,e.to,i),e.phase=i>=1?"settling":"running",this._hooks.frame(e),i<1?this._raf=this._clock.requestFrame(a):(this._raf=0,this._hooks.settled(e),this._state?.token===n&&(this._state=null))};return this._raf=this._clock.requestFrame(a),n}cancel(t=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const e=this._state;this._state=null,this._token++,e&&t&&(e.phase="settling",e.presented=e.to,this._hooks.frame(e),this._hooks.settled(e))}dispose(){this.cancel(!1)}}const Rg="houseplan_card_labs_v1",Ig=Object.freeze([Object.freeze({id:"iso",issue:89,since:"1.62.0",expires:"1.65.0",summary:"Volumetric plan renderer"})]);function Ag(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(String(t||"").trim());if(!e)return null;const i=e.slice(1).map(Number);return i.every(t=>Number.isSafeInteger(t))?i:null}function zg(t,e){for(let i=0;i<3;i++)if(t[i]!==e[i])return t[i]t.split(",")).map(t=>t.trim()).filter(Boolean)}function Hg(t,e,i,s=Ig){const n=function(t,e=Ig){const i=Ag(t),s=new Map;if(!i||!Eg(e))return s;for(const t of e){const e=Ag(t.since),n=Ag(t.expires);zg(i,e)>=0&&zg(i,n)<0&&s.set(t.id,t)}return s}(i,s),o=new Set(Eg(s)?s.map(t=>t.id):[]),a=new Set(function(t){if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}catch{return[]}}(e).filter(t=>n.has(t)));let r=!1;const l=t=>{if("off"===t)return a.clear(),void(r=!0);const e=t.startsWith("-"),i=e?t.slice(1):t;o.has(i)&&(r=!0,e||!n.has(i)?a.delete(i):a.add(i))};for(const e of Lg(new URLSearchParams(String(t.search||"").replace(/^\?/,""))))l(e);for(const e of Lg(Ng(t.hash)))l(e);const c=Object.freeze([...a].sort());return{active:c,space:Og(t.hash),persist:r?JSON.stringify(c):void 0,knownUrlOperation:r}}let Bg={active:Object.freeze([]),space:""},qg="",Wg=!1,jg="";const Ug=new Set;function Gg(){if("undefined"==typeof window)return Bg;const t=Hg(window.location,function(){try{return window.localStorage.getItem(Rg)}catch{return null}}(),qg);void 0!==t.persist&&function(t){try{window.localStorage.setItem(Rg,t)}catch{}}(t.persist),Bg={active:t.active,space:t.space},window.__hpLabs=t.active;for(const t of Ug)t(Bg);return Bg}function Vg(){Gg()}function Kg(t){return qg=t,"undefined"==typeof window?Bg:(Wg||(Wg=!0,window.addEventListener("hashchange",Vg),window.addEventListener("popstate",Vg)),Gg())}const Yg=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])});function Jg(t){return[t.rotDeg,t.tiltDeg,t.xyScale,t.zScale,t.origin[0],t.origin[1]].every(Number.isFinite)&&Math.abs(t.xyScale)>1e-12&&Math.abs(Math.cos(t.tiltDeg*Math.PI/180))>1e-12}function Xg(t,e,i=Yg){if(!(Jg(i)&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(e)))throw new Error("invalid isometric projection input");const s=i.rotDeg*Math.PI/180,n=i.tiltDeg*Math.PI/180,o=t[0]-i.origin[0],a=t[1]-i.origin[1],r=(o*Math.cos(s)-a*Math.sin(s))*i.xyScale,l=(o*Math.sin(s)+a*Math.cos(s))*i.xyScale;return[i.origin[0]+r,i.origin[1]+l*Math.cos(n)-e*i.zScale*Math.sin(n)]}function Zg(t,e=Yg){if(!Jg(e)||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new Error("invalid isometric projection input");const i=e.rotDeg*Math.PI/180,s=e.tiltDeg*Math.PI/180,n=(t[0]-e.origin[0])/e.xyScale,o=(t[1]-e.origin[1])/(e.xyScale*Math.cos(s));return[e.origin[0]+n*Math.cos(i)+o*Math.sin(i),e.origin[1]-n*Math.sin(i)+o*Math.cos(i)]}function Qg(t=Yg){return`matrix(${function(t=Yg){if(!Jg(t))throw new Error("invalid isometric camera");const e=t.rotDeg*Math.PI/180,i=t.tiltDeg*Math.PI/180,s=t.xyScale*Math.cos(e),n=-t.xyScale*Math.sin(e),o=t.xyScale*Math.sin(e)*Math.cos(i),a=t.xyScale*Math.cos(e)*Math.cos(i);return[s,o,n,a,t.origin[0]-s*t.origin[0]-n*t.origin[1],t.origin[1]-o*t.origin[0]-a*t.origin[1]]}(t).map(t=>Number(t.toFixed(12))).join(" ")})`}function tf(t,e=Yg){const{rect:i,wallHeight:s}=t,n=t.openingHeight??s,o=t.floorDepth??0;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(o)||s<0||n<0||o<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],r=Math.max(s,n),l=a.flatMap(t=>[Xg(t,-o,e),Xg(t,r,e)]),c=l.map(t=>t[0]),h=l.map(t=>t[1]),d=Math.min(...c),p=Math.min(...h);return{x:d,y:p,w:Math.max(...c)-d,h:Math.max(...h)-p}}const ef=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function sf(t){let e=0;for(let i=0;iArray.isArray(t)&&Number.isFinite(t[0])&&Number.isFinite(t[1])).map(t=>[Number(t[0]),Number(t[1])]),i=e[e.length-1];return e.length>1&&e[0][0]===i[0]&&e[0][1]===i[1]&&e.pop(),e}(t);if(i.length<3)return[];const s=!e;return sf(i)>0===s?i:[...i].reverse()}function of(t,e,i){return t.length?`M ${t.map(t=>ef(Xg(t,i,e))).join(" L ")} Z`:""}function af(t,e,i){const s=e[1]-t[1],n=-(e[0]-t[0]),o=i.rotDeg*Math.PI/180;return s*Math.sin(o)+n*Math.cos(o)}function rf(t,e,i=Yg){if(!Number.isFinite(e)||e<0)throw new Error("invalid floor edge height");const s=(t||[]).map(t=>(t||[]).map((t,e)=>function(t,e){const i=nf(t,e);if(!i.length)return i;let s=0;for(let t=1;t0)).filter(t=>t.length>=3&&Math.abs(sf(t))>=1e-9)).filter(t=>t.length&&sf(t[0])>0);s.sort((t,e)=>{const i=t[0][0],s=e[0][0];return i[0]-s[0]||i[1]-s[1]||Math.abs(sf(e[0]))-Math.abs(sf(t[0]))});const n=[],o=[];let a=0;for(let t=0;tt.depth-e.depth||t.component-e.component||t.edge-e.edge),{footprintPath:n.join(" "),sides:o,componentCount:s.length,edgeCount:a}}function lf(t,e){return t^=Math.round(64*(Number.isFinite(e)?e:0)),Math.imul(t,16777619)>>>0}const cf=t=>t.every(Number.isFinite);function hf(t,e,i,s){const n=t[0]*i,o=t[1]*s,a=e*Math.PI/180;return[n*Math.cos(a)-o*Math.sin(a),n*Math.sin(a)+o*Math.cos(a)]}function df(t,e,i,s,n,o,a){const r=t.flipH?-1:1,l="gate"===t.type?1:t.flipV?-1:1,c=(t.type,t.flipV,t.angle,t.face,{ox:0,oy:0}),h=function(t,e){return[t[0]+e[0],t[1]+e[1]]}([t.x+c.ox,t.y+c.oy],hf(i,t.angle,r,l));return{leaf:e,hinge:h,closedVector:hf(s,t.angle,r,l),quarterVector:hf([-s[1],s[0]],t.angle,r,l),turnDeg:n,bottom:o,top:a}}const pf=t=>`${Number(t[0].toFixed(4))} ${Number(t[1].toFixed(4))}`;function uf(t,e,i=Yg){const s=Math.max(0,Math.min(1,Number.isFinite(e)?e:0));return t.leaves.map(e=>{const n=function(t,e){const i=t.turnDeg*e*Math.PI/180;return[t.hinge[0]+t.closedVector[0]*Math.cos(i)+t.quarterVector[0]*Math.sin(i),t.hinge[1]+t.closedVector[1]*Math.cos(i)+t.quarterVector[1]*Math.sin(i)]}(e,s),o=Xg(e.hinge,e.bottom,i),a=Xg(n,e.bottom,i),r=Xg(n,e.top,i),l=Xg(e.hinge,e.top,i);return{id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${pf(o)} L ${pf(a)} L ${pf(r)} L ${pf(l)} Z`,shadowD:`M ${pf(Xg(e.hinge,0,i))} L ${pf(Xg(n,0,i))}`,depth:Math.max(o[1],a[1])}})}const _f={window:120,door:90,passage:90,gate:300};function mf(t){return _f[t]}function gf(t,e){const i=[t[0],t[1]],s=[e[0],e[1]];return function(t,e){return t[0]-e[0]||t[1]-e[1]}(i,s)<=0?{a:i,b:s}:{a:s,b:i}}function ff(t){const e=new Map;return t.forEach((t,i)=>{if(!t.kind||t.open)return;const s=gf(t.a,t.b);if(Math.hypot(s.b[0]-s.a[0],s.b[1]-s.a[1])<=1e-9)return;const n=function(t,e){const i=t=>(Math.abs(t)<=5e-10?0:Math.round(1e6*t)/1e6).toFixed(6);return`${i(t[0])},${i(t[1])}>${i(e[0])},${i(e[1])}`}(s.a,s.b),o=e.get(n);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,t.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(t.partitionHost&&(o.partitionHost&&o.partitionHost.id!==t.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=t.partitionHost));e.set(n,{segmentKey:n,a:s.a,b:s.b,physicalHalfWidth:Math.max(0,t.half||0),sourceOrder:i,...t.partitionHost?{partitionHost:t.partitionHost}:{}})}),[...e.values()]}function vf(t,e){if(Math.abs(t.distance-e.distance)>1e-9)return t.distance-e.distance;if(Math.abs(t.perpendicular-e.perpendicular)>1e-9)return t.perpendicular-e.perpendicular;return(t.target.segmentKeye.target.segmentKey?1:0)||t.target.sourceOrder-e.target.sourceOrder}function yf(t){const e=ff(t.intervals).map(e=>{const i=function(t,e){const i=e.b[0]-e.a[0],s=e.b[1]-e.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,r=(t[0]-e.a[0])*o+(t[1]-e.a[1])*a,l=Math.max(0,Math.min(n,r)),c=e.a[0]+l*o,h=e.a[1]+l*a;return{along:l,length:n,x:c,y:h,distance:Math.hypot(t[0]-c,t[1]-h),perpendicular:Math.abs((t[0]-e.a[0])*a-(t[1]-e.a[1])*o)}}(t.pointer,e);return{target:e,...i,envelope:Math.max(t.baseTolerance,e.physicalHalfWidth+t.bodyPointerPadding)}}).filter(t=>t.distance<=t.envelope+1e-9).filter(e=>!function(t,e,i,s,n){const o=e.b[0]-e.a[0],a=e.b[1]-e.a[1],r=Math.hypot(o,a);if(!(r>1e-9))return!1;const l=o/r,c=a/r;for(const o of i){if(!o.open&&o.kind)continue;const i=gf(o.a,o.b),a=i.b[0]-i.a[0],r=i.b[1]-i.a[1],h=Math.hypot(a,r);if(!(h>1e-9))continue;const d=a/h,p=r/h;if(Math.abs(l*p-c*d)>1e-6)continue;if(Math.abs((i.a[0]-e.a[0])*c-(i.a[1]-e.a[1])*l)>n)continue;const u=(t[0]-i.a[0])*d+(t[1]-i.a[1])*p,_=1e-9;if(!(u<=_||u>=h-_)&&Math.abs((t[0]-i.a[0])*p-(t[1]-i.a[1])*d)<=s+1e-9)return!0}return!1}(t.pointer,e.target,t.intervals,e.envelope,Math.max(1e-9,Math.min(t.baseTolerance,.04*t.gridStep)))),i=e.filter(e=>!!e.target.partitionHost&&t.renderedLength+2*e.target.physicalHalfWidth>e.length+1e-9).sort(vf),s=e.filter(e=>!e.target.partitionHost||t.renderedLength+2*e.target.physicalHalfWidth<=e.length+1e-9).sort(vf);let n=s[0];if(!n)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=s.filter(t=>Math.abs(t.distance-n.distance)<=1e-9&&Math.abs(t.perpendicular-n.perpendicular)<=1e-9),a=o.filter(t=>t.target.partitionHost);if(a.length){if(1!==new Set(a.map(t=>t.target.partitionHost.id)).size||a.some(t=>t.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const t=a[0],e=t.target.b[0]-t.target.a[0],i=t.target.b[1]-t.target.a[1],s=Math.hypot(e,i),r=e/s,l=i/s,c=o.every(e=>{const i=e.target.b[0]-e.target.a[0],s=e.target.b[1]-e.target.a[1],n=Math.hypot(i,s),o=i/n,a=s/n,c=Math.abs(r*a-l*o)<=1e-6,h=Math.abs((e.target.a[0]-t.target.a[0])*l-(e.target.a[1]-t.target.a[1])*r);return c&&h<=1e-9});if(!c)return{candidate:null,jambBlockedTarget:null};n=t}if(n.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:r,length:l}=n,c=r.b[0]-r.a[0],h=r.b[1]-r.a[1],d=c/l,p=h/l,u=r.partitionHost?r.physicalHalfWidth:0,_=Math.min(Math.max(0,t.renderedLength)/2+u,l/2);let m=n.along;const g=Math.max(t.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=r.a[0]+d*m,y=r.a[1]+p*m,b=Math.max(0,t.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),$=Math.max(0,l-k),S=[r.a[0]+d*(w-x/2),r.a[1]+p*(w-x/2)],M=[r.a[0]+d*(k+$/2),r.a[1]+p*(k+$/2)];let C=180*Math.atan2(h,c)/Math.PI;C>=90?C-=180:C<-90&&(C+=180);const D=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:t.preset.revision,geometryRevision:t.geometryRevision,pointer:[t.pointer[0],t.pointer[1]],type:t.preset.type,lengthCm:t.preset.lengthCm,flipH:t.preset.flipH,flipV:t.preset.flipV,x:v,y:y,angle:C,renderedLength:t.renderedLength,target:r,...r.partitionHost?{host:{...r.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:S},{distance:$,midpoint:M}],guide:D?{x:v,y:y,angle:C}:null}},jambBlockedTarget:null}}function bf(t,e,i,s,n=1e-6){return t.presetRevision===i&&t.geometryRevision===s&&Math.hypot(t.pointer[0]-e[0],t.pointer[1]-e[1])<=n}const wf=(t,e)=>t[0]*e[1]-t[1]*e[0],kf=(t,e)=>t[0]*e[0]+t[1]*e[1],xf=(t,e)=>[t[0]-e[0],t[1]-e[1]],$f=(t,e,i)=>[t[0]+e[0]*i,t[1]+e[1]*i];function Sf(t,e,i){return Math.abs(wf(t,e))<=i}function Mf(t,e,i){return Math.abs(wf(xf(t,e),i))}function Cf(t,e,i,s,n){const o=e[0]-t[0],a=e[1]-t[1],r=Math.hypot(o,a);if(!(r>n&&i>0))return[];const l=[o/r,a/r];return function(t,e,i){const s=e.map(([e,i])=>[Math.max(0,Math.min(e,i)),Math.min(t,Math.max(e,i))]).filter(([t,e])=>e>t+i).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),n=[];for(const t of s){const e=n[n.length-1];!e||t[0]>e[1]+i?n.push([...t]):e[1]=Math.max(e[1],t[1])}const o=[];let a=0;for(const[t,e]of n)t>a+i&&o.push([a,t]),a=Math.max(a,e);return t>a+i&&o.push([a,t]),o}(r,s.flatMap(e=>{const s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=Math.hypot(s,o);if(!(a>n&&Sf(l,[s/a,o/a],1e-6)))return[];if(Mf(e.a,t,l)>1.1*Math.max(i,n)||Mf(e.b,t,l)>1.1*Math.max(i,n))return[];return[[kf(xf(e.a,t),l),kf(xf(e.b,t),l)]]}),n).flatMap(([e,s])=>{const n=Ol({a:$f(t,l,e),b:$f(t,l,s),halfDepth:i});return n?[n]:[]})}function Df(t){const e=t.coordScale??1,i=Math.max(t.epsilon??2e-4*t.gridPitch,1e-9),s=[];for(const i of t.rooms||[]){if(!i?.id)continue;const n=hc(t.rooms,i.id,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e);if(!n||n.poly.length<3)continue;const o=Zl(n.poly,n.offsets);!o||o.length<3||s.push({roomId:i.id,profile:n,inner:o})}s.sort((t,e)=>t.roomId.localeCompare(e.roomId));const n=(t.roomOpenings||[]).map(t=>{const e=t.angle*Math.PI/180,i=[Math.cos(e),Math.sin(e)],s=Math.max(0,t.length)/2;return{a:$f([t.x,t.y],i,-s),b:$f([t.x,t.y],i,s)}}),o=[];for(const s of zc(t.rooms,t.walls,t.openCuts,t.pitch,t.cellCm,t.gridPitch,e))for(const t of Cf(s.a,s.b,s.depthUnits/2,n,i))o.push({body:t});const a=new Map;for(const e of t.partitionCuts||[]){const t=a.get(e.hostId)||[];t.push(e),a.set(e.hostId,t)}for(const e of t.partitions||[]){const s=gl(e.cm,t.cellCm,t.gridPitch)/2;for(const t of Cf(e.a,e.b,s,a.get(e.id)||[],i))o.push({body:t,partitionId:e.id})}return{rooms:s,boundaries:o,epsilon:i}}function Pf(t,e,i,s){const n=t.profile.offsets[e];if(!(n>0))return null;const o=function(t,e){const i=t[e],s=t[(e+1)%t.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return function(t){let e=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t.profile.poly,e),a=$f(i.center,o,n),r=[];for(let e=0;es&&Sf(i.axis,[l[0]/c,l[1]/c],1e-6)))continue;if(Mf(n,a,i.axis)>s||Mf(o,a,i.axis)>s)continue;const h=kf(xf(n,a),i.axis),d=kf(xf(o,a),i.axis);r.push([Math.min(h,d),Math.max(h,d)])}const l=function(t,e){t.sort((t,e)=>t[0]-e[0]||t[1]-e[1]);const i=[];for(const s of t){const t=i[i.length-1];!t||s[0]>t[1]+e?i.push([...s]):t[1]=Math.max(t[1],s[1])}return i}(r,s).find(([t,e])=>t<=s&&e>=-s);if(!l)return null;const[c,h]=l,d=$f(a,i.axis,-i.half),p=$f(a,i.axis,i.half),u=Math.max(0,-i.half-c),_=Math.max(0,h-i.half),m=u>0?$f(a,i.axis,c):d,g=_>0?$f(a,i.axis,h):p,f=kf(o,i.normal)>=0?1:-1,v=(e,s,n)=>({from:e,to:s,label:[(e[0]+s[0])/2,(e[1]+s[1])/2],axis:i.axis,labelNormal:o,distance:n,roomId:t.roomId,roomSide:f,source:"room-face"});return{left:v(d,m,u),right:v(p,g,_)}}function Tf(t){const e=$f(t.center,t.axis,-t.half),i=$f(t.center,t.axis,t.half),s=$f(t.center,t.axis,Math.min(-t.half,t.targetLo)),n=$f(t.center,t.axis,Math.max(t.half,t.targetHi)),o=(e,i)=>({from:e,to:i,label:[(e[0]+i[0])/2,(e[1]+i[1])/2],axis:t.axis,labelNormal:t.normal,distance:Math.hypot(i[0]-e[0],i[1]-e[1]),source:"host-end"});return[o(e,s),o(i,n)]}function Rf(t,e,i,s){const n=xf(i,e),o=kf(n,n);if(!(o>s*s))return Math.hypot(...xf(t,e))<=s;const a=kf(xf(t,e),n)/o;if(a<-s||a>1+s)return!1;const r=$f(e,n,Math.max(0,Math.min(1,a)));return Math.hypot(...xf(t,r))<=s}function If(t,e,i){let s=!1;for(let n=0,o=e.length-1;nt[1]!=c>t[1]&&t[0]<(l-a)*(t[1]-r)/(c-r)+a&&(s=!s)}return s}function Af(t,e,i,s,n,o){const a=xf(s,i),r=wf(e,a);if(Math.abs(r)<=o)return null;const l=xf(i,t),c=wf(l,a)/r,h=wf(l,e)/r;return c<-o||c>n+o||h<-o||h>1+o?null:Math.max(0,Math.min(n,c))}function zf(t,e,i){const s=Tf(i),n="partition"===t.host?.kind?t.host.id:void 0;return[{base:s[0],direction:[-i.axis[0],-i.axis[1]]},{base:s[1],direction:i.axis}].map(({base:t,direction:i})=>{const s=t.distance,o=function(t,e,i,s,n,o){let a=null;for(const r of s)if(!n||r.partitionId!==n){if(If(t,r.body,o))return 0;for(let s=0;skf(xf(t,n),i));return{center:n,axis:i,normal:s,half:Math.max(0,t.renderedLength)/2,targetLo:Math.min(...o),targetHi:Math.max(...o)}}(t),s=e.rooms.flatMap(t=>{const s=function(t,e,i){const{profile:s}=t;let n=null;for(let t=0;t0))continue;const o=s.poly[t],a=s.poly[(t+1)%s.poly.length],r=xf(a,o),l=Math.hypot(r[0],r[1]);if(!(l>i&&Sf(e.axis,[r[0]/l,r[1]/l],1e-6)))continue;if(Mf(o,e.center,e.axis)>i||Mf(a,e.center,e.axis)>i)continue;const c=kf(xf(o,e.center),e.axis),h=kf(xf(a,e.center),e.axis),d=Math.min(c,h),p=Math.max(c,h);if(d>-e.half+i||p0?d:p<0?-p:0);(!n||u2)return Tf(i);if(s.length){const t=s.map(({room:t,edge:s})=>Pf(t,s,i,e.epsilon));if(t.some(t=>!t))return Tf(i);const n=t;return[...n.map(t=>t.left),...n.map(t=>t.right)]}return zf(t,e,i)}function Ef(t){return!(!t.canEdit||t.kiosk||t.fixedFloor)&&("view"!==t.mode&&("mouse"===t.pointerType&&t.spaceCount>1))}const Nf="1.68.0",Of={badge:"display.badge",icon_ripple:"display.icon_ripple",value:"display.value",static_icon:"display.static_icon"},Lf={badge:"marker.display_hint_badge",icon_ripple:"marker.display_hint_icon_ripple",value:"marker.display_hint_value",static_icon:"marker.display_hint_static_icon"},Hf=2e3,Bf=1e3,qf=1500,Wf=t=>{const e=String(t??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return null;const i=Number(e);return Number.isFinite(i)?i:null},jf=(t,e)=>{if(!t.has(e))return{hit:!1};const i=t.get(e);return t.delete(e),t.set(e,i),{hit:!0,value:i}},Uf=(t,e,i,s)=>{for(t.delete(e),t.set(e,i);t.size>s;){const e=t.keys().next().value;if(void 0===e)break;t.delete(e)}},Gf=new Map;let Vf=0;const Kf=t=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(t??{})}`;let Yf=1e4;const Jf="houseplan_card_layout_v1",Xf="houseplan_card_cfg_v1",Zf="houseplan_card_zoom_v1",Qf="houseplan_card_nav_v1",tv="houseplan_card_kiosk_v1",ev="houseplan_card_view_v1",iv="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",sv=1e3,nv=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]],ov=(t,e)=>{const i=Math.min(t.x,e.x),s=Math.min(t.y,e.y);return{x:i,y:s,w:Math.max(t.x+t.w,e.x+e.w)-i,h:Math.max(t.y+t.h,e.y+e.h)-s}},av=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),rv=2e3,lv=(t,e,i)=>{const s=new Event(e,{bubbles:!0,composed:!0});s.detail=i??{},t.dispatchEvent(s)},cv=t=>{history.pushState(null,"",t),lv(window,"location-changed",{replace:!1})},hv=(t,e)=>{let i,s=null;const n=(...n)=>{clearTimeout(i),s=n,i=window.setTimeout(()=>{i=void 0;const e=s;s=null,e&&t(...e)},e)};return n.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const e=s;s=null,e&&t(...e)},n.cancel=()=>{clearTimeout(i),i=void 0,s=null},n.pending=()=>void 0!==i,n},dv=t=>{try{t.target?.setPointerCapture?.(t.pointerId)}catch{}};class pv extends ht{constructor(){super(...arguments),this._space="f1",this._layout={},this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._serverCfg=null,this._cfgRev=0,this._cfgContentFingerprint="",this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._layoutRev=0,this._layoutContentFingerprint="",this._virtualLights=mn(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._tip=null,this._hoverRoom=null,this._pointerModality=new N_(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...Rr},this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=t=>{this._reducedMotion=t.matches,this._cancelDevicePressFeedback(),t.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:t.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Tg({frame:t=>this._applyModeTransitionFrame(t),settled:t=>this._settleModeTransition(t)}),this._editorSecondary=new W_({root:()=>this.renderRoot,requestUpdate:()=>this.requestUpdate(),updateComplete:()=>this.updateComplete,clearTip:()=>{this._tip=null}}),this._editorSecondaryCopy={groupActive:(t,e)=>this._t("editor.group_active",{group:t,item:e}),openGroup:t=>this._t("editor.open_group",{group:t}),disabledAction:(t,e)=>this._t("editor.disabled_action",{action:t,reason:e})},this._tool="draw",this._geometryHistory=new fg(50),this._wallDialog=null,this._drawWallField=null,this._activeDraftId=null,this._resumeDraftBySpace={},this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowClipCache=new Map,this._glowGeometryWarnings=new Set,this._lightBarrierCache=null,this._lightBarrierPool=new Map,this._glowFeatherUnits=null,this._glowRenderedSources=new Map,this._glowLastAppearance=new Map,this._glowEnteringSources=new Set,this._glowEnterRafs=new Map,this._glowFadeTimers=new Map,this._glowFeatherSuspendUntil=0,this._glowFeatherResumeTimer=0,this._glowSourceSeq=0,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszSel=null,this._rszDrag=null,this._rszEligibilityCache=null,this._rszPreview=null,this._rszLive=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._touchContacts=new Map,this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:t=>this._guardTouchGesture(t)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._alignDialog=null,this._settingsDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=t=>this._onKey(t),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++Vf,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=t=>{if(this._continuity.visibility(t),this._dayCycleVisibility(t),"hidden"===t.kind)return this._clearTransientHover(!0),this._cancelDevicePressFeedback(),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,!t.long){const t=Date.now();let e=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+I_)>t||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,e=!0);return void(e&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._lastTap=0,this._onLabsSnapshot=t=>{const e=this._effectiveProjection();this._labs=t;const i=this._effectiveProjection();this._convertProjectionView(e,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const t=this._hashSpace();if(t&&this._model.find(e=>e.id===t)&&t!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._onHaRegistryUpdate=()=>{const t=An(this.hass);t.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=t.revision,this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,function(t){const e=Cn(t);e&&(Tn(t,e),Rn(t,e))}(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new $d(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=hv(()=>{if(this._serverStorage){const t=[...this._dirtyPos];this._dirtyPos.clear();for(const e of t){const t=ol(this._layout[e]);t&&(this._layout={...this._layout,[e]:t},this._sentPos.set(e,t),this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t}).then(t=>this._noteLayoutRev(t)).catch(t=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))).finally(()=>{this._sentPos.get(e)===t&&this._sentPos.delete(e)}))}this._cacheSnapshot()}else this._layout=al(Gr(this._layout)),localStorage.setItem(Jf,JSON.stringify(this._layout))},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.undo();t&&(this._applyGeometryState(t.before,!0)?this._showToast(this._t("history.undone",{name:t.name})):this._geometryHistory.clear())},this._redoGeometry=()=>{if(this._physicalDrag||this._physicalRotate)return void this._cancelPhysicalGesture();if(this._decorDraft)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove||this._dtDrag||this._bdDrag)return void this._cancelDecorGesture();if(this._rszDrag)return void this._rszCancelDrag();const t=this._geometryHistory.redo();t&&(this._applyGeometryState(t.after,!0)?this._showToast(this._t("history.redone",{name:t.name})):this._geometryHistory.clear())},this._saveConfigDebounced=hv(()=>{this._serverCfg&&this._writeConfig().catch(t=>{const e=!0===t?.physicalGeometryRolledBack;"geometry-unsafe"!==t?.code&&("wall_model_client_outdated"===t?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===t?.code?(this._showToast(this._t("toast.conflict")),e||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(t)})),e&&this._reloadRejectedPhysicalWrite())})},500),this._draftSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>{const t=this._physicalDialog,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=Wf(t.cm);if(null==s)return void this._showPhysicalRange("column"===t.kind?jc:100,"column"===t.kind?1:0);const n=this._imperial?2.54*s:s,o="column"===t.kind?jc:100,a="column"===t.kind?1:0;if(!Number.isFinite(n)||no)return void this._showPhysicalRange(o,a);if("column"===t.kind){const e=i.wall_columns.find(e=>e.id===t.id);if(!e)return;const s=Wf(t.angle||"0");if("circle"!==t.shape&&(null==s||s<0||s>=90))return void this._showToast(this._t("toast.physical_angle"));const o="circle"===t.shape?{id:t.id,shape:"circle",center:e.center,cm:n}:{id:t.id,shape:"square",center:e.center,cm:n,angle:s};if(i.wall_columns.some(e=>e.id!==t.id&&uh(e,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"))}const r=this._geometrySnapshot();if("partition"===t.kind){const i=(e.partitions||[]).find(e=>e.id===t.id);if(i&&0===n&&f_(e.openings,{kind:"partition",id:t.id}))return void this._showToast(this._t("toast.zero_wall_opening_conflict"));i&&(i.cm=n)}else if("column"===t.kind){const i=(e.wall_columns||[]).find(e=>e.id===t.id);i&&(i.cm=Gc(n),i.shape="circle"===t.shape?"circle":"square","square"===i.shape?i.angle=Wf(t.angle||"0"):delete i.angle)}else{const i=(e.room_drafts||[]).find(e=>e.id===t.id);i?.segments?.[t.segment||0]&&(i.segments[t.segment||0].cm=n)}const l=this._commitPhysicalGeometry(this._t("history.physical_edit"),r);this._physicalDialog=null,l||this.requestUpdate()},this._deletePhysicalSelection=()=>{const t=this._physicalSel,e=this._curSpaceCfg;if(!t||!e)return;if("draft"===t.kind)return void this._deleteDraftWhole();const i=this._geometrySnapshot();if("partition"===t.kind){const i=(e.openings||[]).filter(e=>"partition"===e.host?.kind&&e.host.id===t.id).sort((t,e)=>(t.host?.t||0)-(e.host?.t||0));if(i.length)return void(this._partitionDeleteDialog={id:t.id,openings:i.map(t=>JSON.parse(JSON.stringify(t)))})}const s="partition"===t.kind?"partitions":"column"===t.kind?"wall_columns":"room_drafts";e[s]=(e[s]||[]).filter(e=>e.id!==t.id),e[s].length||delete e[s],this._activeDraftId===t.id&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._confirmPartitionDelete=()=>{const t=this._partitionDeleteDialog,e=this._curSpaceCfg;if(!t||!e)return;const i=this._geometrySnapshot();e.partitions=(e.partitions||[]).filter(e=>e.id!==t.id),e.partitions.length||delete e.partitions,e.openings=(e.openings||[]).filter(e=>"partition"!==e.host?.kind||e.host.id!==t.id),e.openings.length||delete e.openings,this._partitionDeleteDialog=null,this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftWhole=()=>{const t="draft"===this._physicalDialog?.kind?this._physicalDialog.id:"draft"===this._physicalSel?.kind?this._physicalSel.id:null,e=this._curSpaceCfg;if(!t||!e||!confirm(this._t("confirm.delete_draft")))return;const i=this._geometrySnapshot();e.room_drafts=(e.room_drafts||[]).filter(e=>e.id!==t),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===t&&this._cancelPath(),this._physicalSel=null,this._physicalDialog=null,this._commitPhysicalGeometry(this._t("history.physical_delete"),i)},this._deleteDraftSegment=()=>{const t=this._physicalDialog,e=this._curSpaceCfg;if(!t||"draft"!==t.kind||!e)return;if(!confirm(this._t("confirm.delete_draft_segment")))return;const i=(e.room_drafts||[]).findIndex(e=>e.id===t.id);if(i<0)return;const s=e.room_drafts[i],n=Math.max(0,Math.min(s.segments.length-1,t.segment||0)),o=[],a=s.points.slice(0,n+1),r=s.points.slice(n+1);if(a.length>=2&&o.push({id:s.id,points:a,segments:s.segments.slice(0,n)}),r.length>=2&&o.push({id:o.length?`${s.id}-${Date.now().toString(36)}`:s.id,points:r,segments:s.segments.slice(n+1)}),2===o.length&&e.room_drafts.length>=200)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot();e.room_drafts.splice(i,1,...o),e.room_drafts.length||delete e.room_drafts,this._activeDraftId===s.id&&this._cancelPath(),this._physicalDialog=null,this._physicalSel=o.length?{kind:"draft",id:o[0].id}:null,this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),l)},this._confirmRoomDelete=t=>{const e=this._roomDeleteDialog,i=this._curSpaceCfg,s=this._spaceModel();if(!e||!i||!s)return;const n=s.rooms.find(t=>t.id===e.roomId);if(!n)return void(this._roomDeleteDialog=null);const o=this._openCuts(),a=$u(dc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv).filter(t=>t.roomId===n.id),s.partitions,this._openingsR.map(t=>({...t,x:t.rx,y:t.ry})),.02*this._gridPitch),r=new Set(a.materialize.filter(t=>!t.reusePartitionId).map(t=>t.interval.key)).size;if(t&&(i.partitions||[]).length+r>rv)return void this._showToast(this._t("toast.physical_limit"));const l=this._geometrySnapshot(),c=pc(s.rooms,this._spaceWalls,o,this._wallKeyPitch,this._cellCm,this._gridPitch,sv);if(t){i.partitions||=[];const t=new Map,e=new Map,s=t=>{const e=(i.wall_segments||[]).find(e=>{const i=[Number(e.a?.[0])*sv,Number(e.a?.[1])*sv],s=[Number(e.b?.[0])*sv,Number(e.b?.[1])*sv];return this._samePt(t.a,i)&&this._samePt(t.b,s)||this._samePt(t.a,s)&&this._samePt(t.b,i)});return"string"==typeof e?.id&&e.id?e.id:null},n=Date.now().toString(36);for(const o of a.materialize){let a=o.reusePartitionId?i.partitions.find(t=>t.id===o.reusePartitionId):e.get(o.interval.key);a||(a={id:s(o.interval)||`partition-room-${n}-${e.size}`,a:[o.interval.a[0]/sv,o.interval.a[1]/sv],b:[o.interval.b[0]/sv,o.interval.b[1]/sv],cm:o.interval.cm},i.partitions.push(a),e.set(o.interval.key,a)),t.set(o.interval.key,a)}for(const e of i.openings||[]){const i=a.openingIntervals.get(e.id),s=i?t.get(i):null,n=this._openingsR.find(t=>t.id===e.id);if(!s||!n)continue;const o={a:[s.a[0]*sv,s.a[1]*sv],b:[s.b[0]*sv,s.b[1]*sv]};e.host={kind:"partition",id:s.id,t:Su([n.rx,n.ry],o)}}}else if(a.removeOpeningIds.length){const t=new Set(a.removeOpeningIds);i.openings=(i.openings||[]).filter(e=>!t.has(e.id)),i.openings.length||delete i.openings}i.rooms=i.rooms.filter(t=>t.id!==n.id),this._cfgEpoch++;const h=this._normalizeWalls(c,this._openCuts());h.length?i.walls=h:delete i.walls,this._roomDeleteDialog=null,this._commitPhysicalGeometry(this._t(t?"history.delete_room_keep_walls":"history.delete_room_with_walls"),l),this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate()},this._rebindPartitionOpening=()=>{const t=this._openingDialog;if(!t?.id)return;const e=t.id;this._activateMarkupTool("opening"),"opening"===this._tool&&(this._openingRebindId=e,this._openingPreset={type:t.type,lengthCm:t.lengthCm,flipH:t.flipH,flipV:t.flipV,revision:++this._openingPresetRevision},this._openingDialog=null,this._openingHoverCandidate=null)},this._keepClosedAsPartitions=()=>{if(this._wallFaceBatch)return void this._decideWallFace(!1);if(!this._contourClosed||this._pendingSplit||!this._curSpaceCfg)return;const t=this._curSpaceCfg,e=this._path.slice(0,-1);if((t.partitions||[]).length+e.length>rv)return void this._showToast(this._t("toast.physical_limit"));const i=this._geometrySnapshot(),s=Xp(e.length,[...this._draftSegmentCms,this._closingWallCm??void 0],this._drawWallCm,ll);t.partitions||=[];const n=Date.now().toString(36),o=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,a=this._draftSegmentsForPath(this._path,o,s);for(let i=0;it.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.contour_to_partitions"),i),this._roomDialog=!1,this._path=[],delete this._resumeDraftBySpace[this._space],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null},this._toggleServerPlans=async()=>{const t=this._spaceDialog;if(t)if(t.pickSaved)this._spaceDialog={...t,pickSaved:!1};else{this._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.hass.callWS({type:"houseplan/plans/list"}),e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:t?.plans||[],savedBusy:!1})}catch(t){const e=this._spaceDialog;e&&(this._spaceDialog={...e,saved:[],savedBusy:!1}),this._showToast(this._t("toast.plans_list_failed",{err:this._errText(t)}))}}},this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const t=this._dayCycleState();if(!t)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const e=mr(t);e!==this._dayCycleClockKey&&(this._dayCycleClockKey=e,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(!this._norm)return;const t=this._glowRadiusCm,e=this._imperial?Math.round(t/30.48*10)/10:Math.round(t)/100;this._settingsDialog={colors:JSON.parse(JSON.stringify(this._fillColors)),glowRadius:e,bgColor:hs(this._settings,{bgColor:null})||null,northDeg:$r(this._settings,{}),bgMode:Sr(this._settings,{}),sunRays:Mr(this._settings,{}),busy:!1}},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._previewAlignDialog(!1),this._toggleOptimizeLivePositions=()=>{const t=this._alignDialog;t&&!t.busy&&t.report.liveMissingPositions.length&&this._previewAlignDialog(!t.removeLiveMissingPositions)},this._optimizeUndoBusy=!1,this._openBackupExport=()=>{this._settingsDialog=null,this._backupExportDialog={kind:"full",planOnly:!1,busy:!1,error:""}},this._openRulesDialog=()=>{if(!this._norm)return;const t=this._settings.icon_rules,e=(t&&t.length?t:Jt).map(t=>({...t}));this._rulesDialog={rules:e,test:"",busy:!1}},this._climateCache=null,this._gearPtCache=new WeakMap}get _canEdit(){return!!this._norm&&(!0===this._serverCanWrite||!1!==this._serverCanWrite&&!0===this.hass?.user?.is_admin)}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}_cssColor(t,e){const i=String(t||"").trim();if(!i)return e;const s=document.createElement("span");s.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(s);const n=getComputedStyle(s).color||e;return s.remove(),n}_currentModeVisual(t=this._mode){const e=this._modeTransition.presented||this._modeTransitionVisual;if(e)return{...e,viewport:{...e.viewport,viewBox:{...e.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const s=this.renderRoot.querySelector(".editorchrome"),n=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),a=this.renderRoot.querySelector(".hp-backdrop"),r=this.renderRoot.querySelector(".zoomwrap"),l=r?getComputedStyle(r).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:t,editorChromeHeight:"view"===t?0:s?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:Sg(n,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===t?.35:1,backdropOpacity:a&&Number(getComputedStyle(a).opacity)||1,viewWeight:"view"===t?1:0,editorWeight:"view"===t?0:1,toolbarContentOpacity:"view"===t?0:1}}_viewForModeTarget(t,e,i,s,n){const o=Ni(this._baseVb(),s/Math.max(1,n)),a=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),r=o.w/a,l=o.h/a,c=e??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-r/2,y:h-l/2,w:r,h:l},o)}_targetStageColor(t){return"view"!==t?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(t){return"view"===t&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(t){return 1}_applyModeTransitionFrame(t){t.targetMode===this._mode&&(this._modeTransitionVisual=t.presented,this._view={...t.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(t){if(t.targetMode!==this._mode)return;const e=this._modeTransitionRequest;this._view={...t.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[t.to.stageWidth,t.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._modeTransitionBusy||t.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-t.to.stageWidth)>.5||Math.abs(i.clientHeight-t.to.stageHeight)>.5)){const t=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,t?t.x+t.w/2:void 0,t?t.y+t.h/2:void 0),this.requestUpdate()}const s=this.renderRoot.activeElement;(!s||!s.isConnected||!!s.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(t=!0){const e=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(t),t&&e||(this._modeTransitionVisual=null)}_adoptMode(t){this._cancelModeTransition(!1),this._mode=t,"view"!==t&&(this._editorChromeMode=t)}_commitViewModeAtomic(t,e,i,s){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=e,t){const n=this._stageEl?.clientWidth||t.stageWidth,o=Math.max(1,t.stageHeight+t.editorChromeHeight);this._view=this._viewForModeTarget(e,i,s,n,o),this._lastValidStageSize=[n,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(t,e,i,s,n,o){this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._mode!==i)return void(t===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const a=this.renderRoot.querySelector(".editorchrome"),r=a?.querySelector(".editorchrome-inner"),l="view"===i?0:r?.scrollHeight||r?.getBoundingClientRect().height||0,c=Math.max(1,e.stageHeight+e.editorChromeHeight),h=Math.max(1,c-l),d=this._stageEl?.clientWidth||e.stageWidth;if(d<=0||h<=0)return this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._applyView(s,n,o),void this.requestUpdate();const p=this._viewForModeTarget(s,n,o,d,h),u={presentedMode:i,editorChromeHeight:l,stageWidth:d,stageHeight:h,viewport:Sg(p,d),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const _=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(e,u,i,this._reducedMotion||_?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(t=this._model,e=this._loadOk){const i=this._config?.floor,s=function(t){if(!t.hasFloor)return{kind:"absent"};const e=t.floor;if("string"==typeof e)return e.length?t.spaceIds.includes(e)?{kind:"valid",id:e,source:"id"}:{kind:"invalid",reason:"unknown-id",value:e}:{kind:"invalid",reason:"empty-id",value:e};if("number"==typeof e){if(!Number.isFinite(e))return{kind:"invalid",reason:"non-finite-index",value:e};if(!Number.isInteger(e))return{kind:"invalid",reason:"fractional-index",value:e};if(e<0)return{kind:"invalid",reason:"negative-index",value:e};const i=t.spaceIds[e];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:e}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:e}}({spaceIds:t.map(t=>t.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||e?s:"number"==typeof i?"valid"===s.kind||"invalid"===s.kind&&"out-of-range-index"===s.reason?{kind:"pending",value:i}:s:"valid"===s.kind||"invalid"===s.kind&&"unknown-id"!==s.reason?s:{kind:"pending",value:i}}_canCommitSpace(t,e=!1){if(e||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===t}_commitSpace(t,e=!1){return!!this._canCommitSpace(t,e)&&(t!==this._space&&(this._clearTransientHover(!0),this._cancelDevicePressFeedback()),this._space=t,!0)}_slideTo(t,e){if(t===this._space)return!0;if(!this._canCommitSpace(t))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._commitSpace(t),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,"plan"===this._mode&&"draw"===this._tool&&this._resumeLastDraft(),this._restoreZoom(),i||(this._slide=e,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(t,e){Ef({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:t.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(dv(t),this._tabDragRelease=t=>this._tabPointerUp(t),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:e,pointerId:t.pointerId,x:t.clientX,y:t.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(t,e,i){const s=this._model.map(t=>t.id),n=s.indexOf(i);if(n<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const a of o){const o=a.dataset.id||"";if(!o||o===i)continue;const r=a.getBoundingClientRect();if(tr.right||er.bottom)continue;const l=s.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,s;const n=this._tabDropTargetAt(t.clientX,t.clientY,e.id);e.moved&&e.targetId===n?.targetId&&e.placement===n?.placement||(this._tabDrag={...e,moved:!0,targetId:n?.targetId||null,placement:n?.placement||null})}_tabPointerUp(t){const e=this._tabDrag;if(e&&e.pointerId!==t.pointerId)return;const i="pointerup"===t.type&&e?.moved?this._tabDropTargetAt(t.clientX,t.clientY,e.id):null;"pointerup"===t.type&&e?.moved&&this._suppressNextTabClick(),this._endTabDrag(),e?.moved&&i&&this._commitTabOrder(e.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(t){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(t)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(t,e){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const s=this._model.map(t=>t.id),n=function(t,e,i){const s=t.indexOf(e),n=t.indexOf(i);if(s<0||n<0||s===n)return t;const o=t.slice();return o.splice(s,1),o.splice(n,0,e),o}(s,t,e);if(n===s)return;const o=new Map(this._devices.map(t=>[String(t.id),String(t.area||"")])),a=function(t,e,i,s=()=>""){if(!i)return[];const n=[];for(const o of t){if(!o||!0===o.removed)continue;const t="string"==typeof o.id?o.id:"";if(!t)continue;if("string"==typeof o.space&&o.space)continue;const a=("string"==typeof o.area?o.area:"")||s(t)||"";a&&e[a]||n.push({id:t,space:i})}return n}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([t,e])=>[t,e.space])),s[0]||"",t=>o.get(t)||"");if(a.length){const t=new Map(a.map(t=>[t.id,t.space]));for(const e of i.markers||[]){const i=t.get(String(e.id));i&&(e.space=i)}}i.spaces=function(t,e){const i=new Map(e.map((t,e)=>[t,e]));return t.map((t,e)=>({space:t,index:e})).sort((t,e)=>(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)||t.index-e.index).map(t=>t.space)}(i.spaces||[],n),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(t){if(this._endTabDrag(),t===this._space)return;const e=this._model.map(t=>t.id),i=e.indexOf(this._space),s=e.indexOf(t);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(t,i>=0&&s0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const t=this._model.map(t=>t.id),e=t.indexOf(this._space);this._slideTo(t[(e+1)%t.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(t){this._wallUnionCacheValue=t,null===t&&this._wallUnionPool.clear()}_newContinuityController(){return new bd(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(ev,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(t){const e=this._view;if(!e)return null;const i=[e.x+e.w/2,e.y+e.h/2],s="iso"===t?Zg(i):i;return{x:s[0],y:s[1]}}_convertProjectionView(t,e){if(t===e)return;const i=this._logicalViewCenter(t);this._view=null;const s=i?"iso"===e?Xg([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,s?.[0],s?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(t){if(!this._labsIso||"view"!==this._mode)return;const e=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:t},"iso"===t){const t=this._isoSceneKey();t&&this._isoFallback.delete(t)}this._saveViewPreference();const i=this._effectiveProjection();this._convertProjectionView(e,i)}_hashSpace(){return Og(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const t=(e=this.ownerDocument,vg.get(e)?.resolved);var e;void 0!==t&&(this._glowScreenBlend=t),this._continuityUnsub?.(),this._continuityUnsub=vd(this.ownerDocument,this._pageVisibility),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(t=>{for(const e of t)for(const t of e.addedNodes)this._syncPointerHoverSubtree(t)}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),function(t){const e=vg.get(t);if(e)return e.promise;const i={promise:Promise.resolve(!1)};return i.promise=bg(t).catch(()=>!1).then(t=>(i.resolved=t,t)),vg.set(t,i),i.promise}(this.ownerDocument).then(t=>{t!==this._glowScreenBlend&&(this._glowScreenBlend=t,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>Is(this._serverCfg)),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(t,e){Ug.add(e);const i=Kg(t);return"undefined"==typeof window&&e(i),()=>{Ug.delete(e)}}(Nf,this._onLabsSnapshot),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const t of this._activityRt.values())clearTimeout(t.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),this._modeTransition.dispose(),this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer);for(const t of this._glowFadeTimers.values())clearTimeout(t);for(const t of this._glowEnterRafs.values())cancelAnimationFrame(t);clearTimeout(this._glowFeatherResumeTimer),this._glowFeatherResumeTimer=0,this._glowFeatherSuspendUntil=0,this._glowFadeTimers.clear(),this._glowEnterRafs.clear(),this._glowEnteringSources.clear(),this._glowRenderedSources.clear(),this._glowLastAppearance.clear(),this._glowSourceSeq=0,this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._touchContacts.clear(),this._touchSequenceMultitouch=!1,this._touchClickBlockUntil=0,this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(t){if("Escape"===t.key&&this._vacFit)return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void t.stopPropagation();if("Escape"===t.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm=null);if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._settingsDialog)return void(this._settingsDialog=null);if(this._markerDialog)return void(this._markerDialog=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary.hasOpenGroup)return t.preventDefault(),void this._editorSecondary.closeGroup(!0)}const e=t.composedPath?.()||[t.target],i=e.some(t=>t?.matches?.('input, textarea, select, [contenteditable="true"]')),s=e.some(t=>t?.classList?.contains?.("editor-secondary")),n=t.ctrlKey||t.metaKey,o=t.key.toLowerCase(),a=/^[a-z]$/.test(o),r="z"===o||!a&&"KeyZ"===t.code,l="y"===o||!a&&"KeyY"===t.code,c=n&&(r&&t.shiftKey||l),h=n&&r&&!t.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;return c?(t.preventDefault(),void this._redoGeometry()):h?(t.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry()):"Delete"!==t.key&&"Backspace"!==t.key||!this._decorSel||i||s?void("Escape"===t.key&&(t.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._furnPalette=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(t.preventDefault(),void this._decorDeleteSel())}if(this._markup&&(!h&&!c||!i)){if(("Delete"===t.key||"Backspace"===t.key)&&this._physicalSel&&!i&&!s)return t.preventDefault(),void this._deletePhysicalSelection();if(c)return t.preventDefault(),void this._redoGeometry();if(h)return t.preventDefault(),this._rszDrag?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeDraftId&&this._path.length>1?this._undoActiveDraftPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===t.key)return this._physicalDrag||this._physicalRotate?(t.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(t.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(t.preventDefault(),void this._finishWallChain()):this._physicalSel?(t.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(t.preventDefault(),this._rszDrag?void this._rszCancelDrag():void(this._rszSel?this._rszSel=null:this._tool="draw")):"split"===this._tool?(t.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(t.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(t.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(t.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length){if(this._contourClosed)return this._path=this._path.slice(0,-1),void(this._closingWallCm=null);if(this._activeDraftId&&this._path.length>1&&this._curSpaceCfg){const t=this._geometrySnapshot();this._path=this._path.slice(0,-1),this._draftSegmentCms=this._draftSegmentCms.slice(0,-1);const e=this._curSpaceCfg,i=(e.room_drafts||[]).findIndex(t=>t.id===this._activeDraftId);if(i>=0){const s=Array.isArray(e.room_drafts[i]?.segments)?e.room_drafts[i].segments:[];this._path.length<2?(e.room_drafts.splice(i,1),e.room_drafts.length||delete e.room_drafts,this._activeDraftId=null):e.room_drafts[i]={id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentCms.map((t,e)=>({...s[e]||{},cm:t}))},this._commitPhysicalGeometry(this._t("history.draft_segment_delete"),t)}return}this._path=this._path.slice(0,-1)}}_undoActiveDraftPoint(){const t=this._activeDraftId,e=this._path[0]?[...this._path[0]]:null,i=this._geometryHistory.undo();if(!i)return void this._undoPoint();if(!this._applyGeometryState(i.before,!0))return void this._geometryHistory.clear();const s=t?this._spaceModel()?.room_drafts.find(e=>e.id===t):null;s?(this._activeDraftId=s.id,this._path=s.points.map(t=>[...t]),this._draftSegmentCms=this._adoptDraftCms(this._path,s.segments.map(t=>t.cm),s.id),this._resumeDraftBySpace[this._space]=s.id):(this._activeDraftId=null,this._path=e?[e]:[],this._draftSegmentCms=[],t&&this._resumeDraftBySpace[this._space]===t&&delete this._resumeDraftBySpace[this._space]),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:i.name}))}static getConfigElement(){return document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(t){for(const t of Gf.values())for(const e of t)clearTimeout(e.evict);Gf.clear(),Yf=t&&t>0?t:1e4}static _warmBootStats(){let t=0,e=0;const i=[];for(const s of Gf.values())for(const n of s)t++,n.dlg&&(e++,i.push(n.dlg.kind));return{keys:Gf.size,slots:t,dlgs:e,drafts:i}}setConfig(t){const e=this._config,i=!!e&&Object.prototype.hasOwnProperty.call(e,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...t};(i!==this._hasFixedFloor||e?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&t.default_floor&&this._commitSpace(t.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(Zf)||"{}")||{}}catch{this._zoomBySpace={}}try{const t=JSON.parse(localStorage.getItem(ev)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(t).filter(t=>"flat"===t[1]||"iso"===t[1]))}catch{this._viewPreference={}}this._labs=Kg(Nf);try{const t=JSON.parse(localStorage.getItem(tv)||"null");this._kioskScale={icon:Es(t?.icon),font:Es(t?.font)}}catch{}try{const t=JSON.parse(localStorage.getItem(Xf)||"null");t&&t.config&&Array.isArray(t.config.spaces)&&(this._serverCfg=t.config,this._cfgEpoch++,this._cfgRev=t.rev||0,this._cfgContentFingerprint=t.config_fingerprint||wd(t.config),this._layout=t.layout||{},this._layoutRev=t.layout_rev||0,this._layoutContentFingerprint=t.layout_fingerprint||wd(this._layout),this._virtualLights=mn(t.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1)}_warmAdopt(){if(this._config?.kiosk)return;const t=Kf(this._config);if(this._warmKey===t&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const e=this.parentNode,i=this._warmIdx(e),s=Gf.get(t);if(!s||!s.length)return;const n=s.find(t=>t.owner===this._warmGen);if(n)return this._warmLongReturn=!!n.freed&&Date.now()-n.freed>=md,clearTimeout(n.evict),n.evict=0,n.freed=0,n.live=!0,this._warmSlot=n,this._warmKey=t,n.frameFingerprint&&this._continuity.adoptCompleteFrame(n.frameFingerprint),void(!this._devices.length&&n.devices?.length&&(this._devices=[...n.devices]));const{slot:o,sure:a}=((t,e,i,s)=>{const n=t=>{const e=!!i&&t.place?.deref()===i;return e&&t.idx===s?4:t.live?0:e?3:2};let o=null,a=0,r=0,l=null;for(const i of t){if(i.owner===e)continue;l=i;const t=n(i);t<=0||(t>a?(o=i,a=t,r=1):t===a&&r++)}return!o||r>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(s,this._warmGen,e,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=md,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)),this._warmKey=t,a?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=e?new WeakRef(e):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},s.push(this._warmSlot),this._warmTrim(s)))}_warmIdx(t){const e=t?.children;if(!e)return-1;for(let t=0;t4;){const e=t.findIndex(t=>!t.live);if(e<0)break;clearTimeout(t[e].evict),t.splice(e,1)}}_warmScheduleEvict(t,e){if(clearTimeout(t.evict),!(t.dlg||t.vp&&"view"!==t.vp.mode))return;const i=t.freed,s=t.owner;t.evict=window.setTimeout(()=>{if(t.evict=0,t.freed!==i||t.owner!==s)return;var n;t.dlg=null,t.vp=(n=t.vp)&&"view"!==n.mode?{...n,mode:"view",zoom:n.snap?.space===n.space?n.snap.zoom:n.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:n,t.frameFingerprint="";const o=Gf.get(e);if(!t.live&&o&&o.length>1){const e=o.indexOf(t);e>=0&&o.splice(e,1)}},Yf+250)}_warmAdoptViewport(t){const e=this._warmVp;if(!e||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(t=>t.id===e.space)||"valid"===i.kind&&i.id!==e.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(e.space,!0),this._navApplied=!0,this._adoptMode("view"!==e.mode&&this._canEdit&&!t.kiosk?e.mode:"view"),this._pendingNavMode="view"===e.mode||this._canEdit||t.kiosk?null:e.mode,this._zoom=e.zoom;const s=this._effectiveProjection(),n=s===e.projection&&this._labsIso===e.activeLabsIso;if(this._view=n&&e.view?{...e.view}:null,this._viewModeSnap=n&&e.snap?{...e.snap}:null,!n&&e.logicalCenter){const t="iso"===s?Xg([e.logicalCenter.x,e.logicalCenter.y],0):[e.logicalCenter.x,e.logicalCenter.y];this._applyView(e.zoom,t[0],t[1])}var o;this._tool="opening"===(o=function(t){return"partition"===t?"draw":t}(o=e.tool))?"draw":"string"==typeof o&&av.has(o)?o:"draw",this._decorTool=e.decorTool,this._showHidden=e.showHidden,this._showFar!==e.showFar&&(this._showFar=e.showFar,this._frame=null),this._selId=e.selId,this._rszSel=e.rszSel,this._decorSel=e.decorSel,this._warmVpArmed=!0}_warmPatch(t,e=!1){if(this._config?.kiosk)return;const i=Kf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!e)return;const t=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:this._warmIdx(t),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const s=Gf.get(i)||[];for(s.push(this._warmSlot),Gf.set(i,s),this._warmTrim(s);Gf.size>8;){const t=Gf.keys().next().value;if(void 0===t||t===i)break;for(const e of Gf.get(t)||[])clearTimeout(e.evict);Gf.delete(t)}}Object.assign(this._warmSlot,t)}}_warmViewportState(){const t=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:t,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(t),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._rszSel,decorSel:this._decorSel}}_warmDialogState(){const t=(t,e)=>({kind:t,space:this._space,mode:this._mode,data:e});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?t("openingInfo",this._openingInfo.id):this._infoCard?t("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:t("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:t("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:t("marker",this._markerDialog):this._openingDialog?t("opening",this._openingDialog):this._backdropDialog?t("backdrop",this._backdropDialog):this._decorShapeDialog?t("decorShape",this._decorShapeDialog):this._decorTextDialog?t("decorText",this._decorTextDialog):this._roomDialog?t("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:t("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const t={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices};if(this._warmRevivePending||(t.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const e=this.parentNode;t.place=e?new WeakRef(e):null,t.idx=this._warmIdx(e)}this._warmPatch(t)}_warmReviveDialog(){this._warmRevivePending=!1;const t=this._warmSlot;if(this._warmReviveTimer=void 0,!t||!t.dlg)return;const e=t.dlg,i=t.freed;if(t.dlg=null,t.freed=0,clearTimeout(t.evict),t.evict=0,i&&!(Date.now()-i>Yf)&&e.space===this._space&&e.mode===this._mode){switch(e.kind){case"space":this._spaceDialog={...e.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...e.data,busy:!1};break;case"settings":this._settingsDialog={...e.data,busy:!1};break;case"rules":this._rulesDialog={...e.data,busy:!1};break;case"opening":this._openingDialog={...e.data};break;case"backdrop":this._backdropDialog={...e.data};break;case"decorShape":this._decorShapeDialog={...e.data};break;case"decorText":{this._decorTextDialog={...e.data};const t=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:t,end:t};break}case"room":{const t=e.data;this._roomEditId=t.editId,this._roomFill=t.fill,this._roomCustomFill=t.customFill||null,this._roomTempSrc=t.tempSrc,this._roomHumSrc=t.humSrc,this._roomSrcOpen=t.srcOpen,this._roomSrcFilter=t.srcFilter,this._roomNameScale=t.nameScale,this._roomLabelScale=t.labelScale,this._areaSel=t.areaSel,this._nameSel=t.nameSel,this._pendingSplit=t.pendingSplit,this._wallFaceBatch=t.wallFaceBatch||null,this._path=t.path,this._wallFaceBatch&&(this._activeDraftId=this._wallFaceBatch.activeDraftId,this._draftSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const t=this._devices.find(t=>t.id===e.data);t&&(this._infoCard=t);break}case"openingInfo":{const t=(this._curSpaceCfg?.openings||[]).find(t=>t.id===e.data);t&&(this._openingInfo=t);break}}this.requestUpdate()}}_cacheSnapshot(){if(this._serverCfg)try{this._cfgContentFingerprint=wd(this._serverCfg),this._layoutContentFingerprint=wd(this._layout),this._virtualLights=function(t,e,i){if(t.configRev===i)return t;const s=new Set((Array.isArray(e?.markers)?e.markers:[]).filter(yn).map(t=>t.id));return{...t,configRev:i,off:new Set([...t.off].filter(t=>s.has(t)))}}(this._virtualLights,this._serverCfg,this._cfgRev),localStorage.setItem(Xf,JSON.stringify({config:this._serverCfg,rev:this._cfgRev,config_fingerprint:this._cfgContentFingerprint,layout:this._layout,layout_rev:this._layoutRev,layout_fingerprint:this._layoutContentFingerprint,virtual_lights:fn(this._virtualLights)}))}catch{}}_beginContinuityCandidate(t,e,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=e,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(t,i))}_continuityStageValid(){const t=this._stageEl;return!!t&&t.clientWidth>0&&t.clientHeight>0}_continuityAssetsReady(){if(!this._model.length)return!1;const t=this._model.length?this._spaceModel():null;return!t?.bg?.href||this._signer.isReady(this.hass,t.bg.href)}_initialSpaceSelection(t,e=this._loadOk){const i=this._fixedFloorState(t,e);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(t){const e=new Set(t.spaceIds.filter(t=>!!t));if(!e.size)return{id:null,source:"none"};const i=[["hash",!1===t.acceptHash?null:t.hashSpace],["current",t.preserveCurrent?t.currentSpace:null],["saved",t.savedSpace],["default",t.defaultSpace],["first",t.spaceIds[0]]];for(const[t,s]of i)if(s&&e.has(s))return{id:s,source:t};return{id:null,source:"none"}}({spaceIds:t.map(t=>t.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(t,e=this._loadOk){const i=this._initialSpaceSelection(t,e);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(t,e=this._space){const i=Sh(t),s=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==s.kind)return"";const n=this._initialSpaceSelection(i,!0).id||(i.some(t=>t.id===e)?e:i[0]?.id);return i.find(t=>t.id===n)?.bg?.href||""}_visualFrameFingerprint(){const t=this._stageEl,e=t?[t.clientWidth,t.clientHeight]:[0,0];return kd([this._cfgRev,this._cfgContentFingerprint||wd(this._serverCfg),this._layoutRev,this._layoutContentFingerprint||wd(this._layout),this._space,this._mode,this._view,e,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const t=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==t)return this._stagedDeviceSnapshotToken=t,void this.requestUpdate();this._continuityPaintToken!==t&&(this._continuityPaintToken=t,this._continuity.candidateReady(t)&&this._continuity.commitAfterPaint(t,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(e=>{e&&t===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):t===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(t,e){this._signer.markLoaded(this.hass,t,e),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const t="connection"===this._continuity.recoveryReason;return W`
t.stopPropagation()} @click=${t=>t.stopPropagation()} @@ -4983,7 +4983,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="d77b8f7b11118fb07d4858dfe45d94e740fd style="left:${r.toFixed(1)}%;top:${l.toFixed(1)}%" @click=${t=>{t.stopPropagation(),this._fitAll()}}> - `}_stageAspect(){const t=this._stageEl,e=this._baseVb();return t&&t.clientHeight?t.clientWidth/t.clientHeight:e[2]/e[3]}_viewOr(t){return this._view&&this._view.w?this._view:Ni(t,this._stageAspect())}_roomLabelReferenceViewWidth(t){if(!this._markup)return t.w;const e=this._stageEl,i=this.renderRoot.querySelector(".editorchrome");if(!e||e.clientWidth<=0||e.clientHeight<=0)return t.w;const s=e.clientHeight+(i?.getBoundingClientRect().height||0);return s<=0?t.w:this._viewForModeTarget(this._zoom,void 0,void 0,e.clientWidth,s).w}_screenToVb(t,e){const i=this._stageEl,s=this._viewOr(this._baseVb()),n=i?.clientWidth||1,o=i?.clientHeight||1;return[s.x+t/n*s.w,s.y+e/o*s.h]}_clampView(t,e){const i=(t,e,i,s)=>{const n=1*Math.max(e,s),o=i-n,a=i+s-e+n;return Math.max(Math.min(o,a),Math.min(Math.max(o,a),t))};return{w:t.w,h:t.h,x:i(t.x,t.w,e.x,e.w),y:i(t.y,t.h,e.y,e.h)}}_applyView(t,e,i){const s=this._baseVb(),n=Ni(s,this._stageAspect()),o=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,t)),a=n.w/o,r=n.h/o,l=this._viewOr(s),c=e??l.x+l.w/2,h=i??l.y+l.h/2,d=this._clampView({x:c-a/2,y:h-r/2,w:a,h:r},n);return!(this._view&&Math.abs(this._zoom-o)<1e-9&&Math.abs(this._view.x-d.x)<1e-6&&Math.abs(this._view.y-d.y)<1e-6&&Math.abs(this._view.w-d.w)<1e-6&&Math.abs(this._view.h-d.h)<1e-6)&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=o,this._view=d,!0)}_bootWatch(){clearTimeout(this._bootTimer),this._bootStart=Date.now(),this._bootLastH=-1,this._bootLastChange=this._bootStart;const t=()=>{if(!this._booting)return;const e=Date.now(),i=this._stageEl?this._stageEl.clientHeight:0;i!==this._bootLastH&&(this._bootLastH=i,this._bootLastChange=e);const s=e-this._bootStart;s>=1200||s>=700&&i>0&&e-this._bootLastChange>=250?this._bootSettled():this._bootTimer=window.setTimeout(t,100)};this._bootTimer=window.setTimeout(t,100)}_bootSettled(){this._booting&&!this._bootSettling&&(this._bootSettling=!0,this._refitView(),this._bootSettleRaf=requestAnimationFrame(()=>{this._bootSettleRaf=0,this._finishBootSettled()}))}_finishBootSettled(){if(!this._booting)return;this._refitView(),this._booting=!1,this._bootSettling=!1;const t=this._stageEl?.clientHeight??0;!this._config?.kiosk&&t>0&&this._warmPatch({hdrH:this._hdrH,stageH:t,vp:this._warmViewportState()},!0),this._bootFading=!0,this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220),this._bootSoft=!0,clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},qf)}_bootSoftCancel(){this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoft=!1)}_beginResumeSettle(){this._booting||this._resumeSettling||(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0),this._viewportInvalidAt=0,this._beginContinuityCandidate("warm-resume",!1),this._loading?this.requestUpdate():this._loadFromServer())}_refitView(){if(this._modeTransitionBusy)return;const t=this._stageEl;if(!t||"visible"!==document.visibilityState||t.clientWidth<=0||t.clientHeight<=0)return void(this._viewportInvalidAt||(this._viewportInvalidAt=Date.now()));const e=[t.clientWidth,t.clientHeight],i=this._lastValidStageSize,s=!!i&&Math.abs(i[0]-e[0])<=.5&&Math.abs(i[1]-e[1])<=.5,n=this._viewportInvalidAt?Date.now()-this._viewportInvalidAt:0;if(this._viewportInvalidAt=0,!i)return this._lastValidStageSize=e,void(this._view||this._applyView(this._zoom));s?this._pendingRefitSize=null:(this._pendingRefitSize=e,this._refitRaf||(this._refitRaf=requestAnimationFrame(()=>{this._refitRaf=0;const t=this._pendingRefitSize;this._pendingRefitSize=null;const e=this._stageEl;if(!t||!e||e.clientWidth<=0||e.clientHeight<=0)return;if(Math.abs(e.clientWidth-t[0])>.5||Math.abs(e.clientHeight-t[1])>.5)return void this._refitView();const i=this._lastValidStageSize;if(i&&Math.abs(i[0]-t[0])<=.5&&Math.abs(i[1]-t[1])<=.5)return;this._lastValidStageSize=t;const s=this._view;n>=md?this._beginContinuityCandidate("stage-size-restored",!0,"stage-size"):this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._applyView(this._zoom,s?s.x+s.w/2:void 0,s?s.y+s.h/2:void 0)})))}_zoomAt(t,e,i){const s=this._stageEl;if(!s)return;const n=Ni(this._baseVb(),this._stageAspect()),o=Math.min(pv.ZOOM_MAX,Math.max(pv.ZOOM_MIN,i));"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1));const a=s.clientWidth,r=s.clientHeight,l=this._screenToVb(t,e),c=n.w/o,h=n.h/o;this._zoom=o,this._view=this._clampView({x:l[0]-t/a*c,y:l[1]-e/r*h,w:c,h:h},n)}_onWheel(t){const e=this._stageEl;if(!e)return;t.preventDefault();const i=e.getBoundingClientRect(),s=t.deltaY<0?1.15:1/1.15;this._zoomAt(t.clientX-i.left,t.clientY-i.top,this._zoom*s),this._saveZoom()}_stepZoom(t){const e=this._stageEl;e&&(this._zoomAt(e.clientWidth/2,e.clientHeight/2,this._zoom*(t>0?1.4:1/1.4)),this._saveZoom())}_resetZoom(){const t=this._baseVb();"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=1,this._view=Ni(t,this._stageAspect()),this._saveZoom()}_saveZoom(){if("view"===this._mode){this._zoomBySpace={...this._zoomBySpace,[this._space]:this._zoom};try{localStorage.setItem(Zf,JSON.stringify(this._zoomBySpace))}catch{}}}_restoreZoom(){const t=this._zoomBySpace[this._space]||1;this._zoom=t;const e=this._stageEl;if(e&&e.clientHeight){const e=this._baseVb();return this._applyView(t,e[0]+e[2]/2,e[1]+e[3]/2),void this.requestUpdate()}this._view=null,requestAnimationFrame(()=>{if(!this._stageEl)return;const e=this._baseVb();this._applyView(t,e[0]+e[2]/2,e[1]+e[3]/2),this.requestUpdate()})}_stagePointerDown(t){if(this._vacFit)return;if(this._kiosk&&(this._cyclePausedUntil=Date.now()+6e4,0===this._pointers.size?(this._swipeStart={x:t.clientX,y:t.clientY,id:t.pointerId},t.target.closest?.(".dev, .roomlabel, .oplock")||(clearTimeout(this._kioskHoldTimer),this._kioskHoldTimer=window.setTimeout(()=>{this._kioskDialog=!0,this._swipeStart=null},3e3))):(this._swipeStart=null,clearTimeout(this._kioskHoldTimer))),this._drag)return;if(this._markup&&t.target.closest?.(".roomlabel, .rlhandle, .rszhandle, .dev, .oplock, .op-hit, button"))return;if("devices"===this._mode&&t.target.closest(".dev"))return;if("decor"===this._mode&&this._decorPointerDown(t))return;this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY});const e=this._viewOr(this._baseVb());if(1===this._pointers.size)this._panStart={sx:t.clientX,sy:t.clientY,vx:e.x,vy:e.y},this._panLock=null,this._suppressClick=!1;else if(2===this._pointers.size){"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const t=[...this._pointers.values()],e=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y);this._pinchStart={dist:e,zoom:this._zoom},this._panStart=null,this._panLock=null}}get _swipeZone(){return!this._hasFixedFloor&&this._kiosk&&this._zoom<=1.001&&this._model.length>1}_stagePointerMove(t){if(this._physicalRotate?.pid!==t.pointerId)if(this._physicalDrag?.pid!==t.pointerId)if(this._dtDrag?.pid!==t.pointerId)if(this._bdDrag?.pid!==t.pointerId){if(this._decorDraft?.pid===t.pointerId){const e=this._decorDraft;let i=this._decorSnap(this._svgPoint(t),t.pointerType);if(t.shiftKey&&("rect"===e.kind||"ellipse"===e.kind)){const t=i[0]-e.a[0],s=i[1]-e.a[1],n=Math.max(Math.abs(t),Math.abs(s));i=this._snap([e.a[0]+(t<0?-n:n),e.a[1]+(s<0?-n:n)])}return void(this._decorDraft={...e,b:i})}if(this._decorMove?.pid!==t.pointerId)if(this._pointers.has(t.pointerId)){if(this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this._markup&&1===this._pointers.size&&this._markupMove(t),this._pinchStart&&this._pointers.size>=2){"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const t=[...this._pointers.values()],e=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y)/(this._pinchStart.dist||1),i=this._stageEl.getBoundingClientRect(),s=(t[0].x+t[1].x)/2-i.left,n=(t[0].y+t[1].y)/2-i.top;this._zoomAt(s,n,this._pinchStart.zoom*e),this._suppressClick=!0,this._saveZoom()}else if(this._panStart){const e=t.clientX-this._panStart.sx,i=t.clientY-this._panStart.sy;Math.abs(e)+Math.abs(i)>4&&(this._suppressClick=!0,clearTimeout(this._holdTimer),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover()),null===this._panLock&&Math.abs(e)+Math.abs(i)>8&&(this._panLock=this._swipeZone&&Math.abs(e)>1.5*Math.abs(i)?"swipe":"pan");const s=this._stageEl;if("pan"===this._panLock&&s){const t=this._baseVb(),n=this._viewOr(t),o=Ni(t,this._stageAspect());this._view=this._clampView({x:this._panStart.vx-e/(s.clientWidth||1)*n.w,y:this._panStart.vy-i/(s.clientHeight||1)*n.h,w:n.w,h:n.h},o)}}}else this._markupMove(t);else this._decorMoveUpdate(t)}else this._bdMove(t);else this._dtMove(t);else this._physicalMove(t);else this._physicalRotateMove(t)}_stagePointerLeave(t){this._markup&&("opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover())}_stagePointerUp(t){if(this._kiosk){clearTimeout(this._kioskHoldTimer);const e=this._swipeStart;if(this._swipeStart=null,e&&e.id===t.pointerId){const i=t.clientX-e.x,s=t.clientY-e.y;if(Math.abs(i)+Math.abs(s)<8){const t=Date.now();t-this._lastTap<350&&this._resetZoom(),this._lastTap=t}const n="pan"===this._panLock?null:function(t,e,i,s,n,o=60){if(i>1.001||s.length<2)return null;if(Math.abs(t)t.id),this._space);n&&this._slideTo(n,i<0?"left":"right")&&(this._saveNav(),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._showKioskDots())}}if(this._physicalDrag?.pid===t.pointerId)return void this._physicalUp(t);if(this._physicalRotate?.pid===t.pointerId)return void this._physicalRotateUp(t);if(this._dtDrag?.pid===t.pointerId)return void this._dtUp();if(this._bdDrag?.pid===t.pointerId)return void this._bdUp();if(this._decorDraft?.pid===t.pointerId)return void this._decorCommitDraft();if(this._decorMove?.pid===t.pointerId)return this._decorMove.moved&&(this._recordGeometry(this._t("history.decor_move"),this._decorMove.before),this._saveConfig()),void(this._decorMove=null);const e=!!this._pinchStart||!!this._panStart;this._pointers.delete(t.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,setTimeout(()=>this._suppressClick=!1,0)),e&&0===this._pointers.size&&this.requestUpdate()}_clickRoom(t){!this._suppressClick&&t.area&&cv("/config/areas/area/"+t.area)}_pointerDown(t,e){if("plan"===this._mode)return;if("view"===this._mode){this._holdFired=!1,clearTimeout(this._holdTimer);const i=t.pointerId,s=t.currentTarget;return void(this._holdTimer=window.setTimeout(()=>{this._holdFired=!0,this._interruptViewGesture(i,s),this._infoCard=e},600))}if("ha_disabled"===e.bindingStatus?.kind)return;t.preventDefault();const i=this._pos(e);this._drag={id:e.id,sx:t.clientX,sy:t.clientY,ox:i.x,oy:i.y,moved:!1},dv(t),this._tip=null}_pointerMove(t,e){if(!this._drag||this._drag.id!==e.id)return;const i=this.renderRoot.querySelector(".stage");if(!i)return;const s=this._baseVb(),n=i.getBoundingClientRect(),o=this._viewOr(s),a=(t.clientX-this._drag.sx)/n.width*o.w,r=(t.clientY-this._drag.sy)/n.height*o.h;Math.abs(t.clientX-this._drag.sx)+Math.abs(t.clientY-this._drag.sy)>3&&(this._drag.moved=!0,clearTimeout(this._holdTimer));const l=Ah(this._drag.ox+a),c=Ah(this._drag.oy+r);this._savePos(e,l,c)}_pointerUp(t,e){if(clearTimeout(this._holdTimer),!this._drag||this._drag.id!==e.id)return;const i=this._drag.moved;this._drag=i?this._drag:null,i&&(this._selId=e.id,window.setTimeout(()=>this._drag=null,0))}_showToast(t){for(const t of this.renderRoot.querySelectorAll("hp-dialog"))t.closeTransientOverlays("toast");this._toast=t,clearTimeout(this._toastTimer),this._toastTimer=window.setTimeout(()=>{this._toast=""},3500)}_syncPointerHoverTargets(){const t=this._pointerModality.hoverEnabled;for(const e of this.renderRoot.querySelectorAll(iv))e.toggleAttribute("data-pointer-hover",t)}_syncPointerHoverSubtree(t){if(t.nodeType!==Node.ELEMENT_NODE)return;const e=t,i=this._pointerModality.hoverEnabled;e.matches(iv)&&e.toggleAttribute("data-pointer-hover",i);for(const t of e.querySelectorAll(iv))t.toggleAttribute("data-pointer-hover",i)}_clearTransientHover(t=!1){t&&this._pointerModality.suspend(),this._tip&&(this._tip=null),this._hoverRoom&&(this._hoverRoom=null)}_notePointer(t){const e=this._pointerModality.modality,i=this._pointerModality.note(t);"touch"!==i&&"pen"!==i||e===i&&!this._tip&&!this._hoverRoom||this._clearTransientHover()}_guardTouchGesture(t){if(this._editorSecondary.handleOutsideDismiss(t))return;if("click"===t.type){if(!this._suppressClick&&!this._touchSequenceMultitouch&&Date.now()>this._touchClickBlockUntil)return;return t.preventDefault(),void t.stopImmediatePropagation()}const e=t;if(this._notePointer(e),"touch"===e.pointerType)if("pointerdown"!==t.type){if("pointermove"===t.type){const t=this._touchContacts.get(e.pointerId);if(!t)return;const i={...t,x:e.clientX,y:e.clientY};if(this._touchContacts.set(e.pointerId,i),this._touchSequenceMultitouch&&"view"===this._mode&&!this._vacFit&&this._pinchStart&&[...this._touchContacts.values()].every(t=>t.inStage)){this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const t=[...this._touchContacts.values()];if(t.length>=2&&this._stageEl){const[e,i]=t,s=Math.hypot(e.x-i.x,e.y-i.y)/(this._pinchStart.dist||1),n=this._stageEl.getBoundingClientRect();this._zoomAt((e.x+i.x)/2-n.left,(e.y+i.y)/2-n.top,this._pinchStart.zoom*s),this._saveZoom()}}return}if("pointerup"===t.type||"pointercancel"===t.type||"lostpointercapture"===t.type){if(this._clearTransientHover(),this._touchContacts.delete(e.pointerId),this._touchSequenceMultitouch){if(this._touchClickBlockUntil=Date.now()+500,this._pointers.delete(e.pointerId),!this._vacFit&&this._pointers.size>=2){const[t,e]=[...this._pointers.values()];this._pinchStart={dist:Math.hypot(t.x-e.x,t.y-e.y),zoom:this._zoom}}else this._pinchStart=null;0===this._pointers.size&&(this._panStart=null,this._panLock=null)}0===this._touchContacts.size&&(this._touchSequenceMultitouch=!1)}}else if(this._touchContacts.set(e.pointerId,{x:e.clientX,y:e.clientY,inStage:!!e.target?.closest?.(".stage")}),this._touchContacts.size>=2){this._clearTransientHover(),this._touchSequenceMultitouch=!0,this._touchClickBlockUntil=Number.POSITIVE_INFINITY,clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),this._swipeStart=null;const t=[...this._touchContacts.values()];if("view"===this._mode&&!this._vacFit&&t.every(t=>t.inStage)){this._pointers=new Map([...this._touchContacts].map(([t,e])=>[t,{x:e.x,y:e.y}]));const[e,i]=t;this._pinchStart={dist:Math.hypot(e.x-i.x,e.y-i.y),zoom:this._zoom},this._panStart=null,this._panLock=null}else this._vacFit&&(this._pointers.clear(),this._pinchStart=null,this._panStart=null,this._panLock=null)}}_showTip(t,e,i,s,n,o){this._notePointer(t),this._pointerModality.hoverEnabled&&(this._drag||(this._tip={x:t.clientX,y:t.clientY,title:e,meta:i,lqi:s,temp:n,hum:o}))}get _gridPitch(){return Ph}get _cellCm(){const t=Number(this._curSpaceCfg?.cell_cm);return Number.isFinite(t)&&t>0?t:5}_fmtLen(t,e){const i=function(t,e,i,s){return Math.hypot(e[0]-t[0],e[1]-t[1])/i*s}(t,e,this._gridPitch,this._cellCm);return li(i,"mi"===this.hass?.config?.unit_system?.length)}get _curSpaceCfg(){const t=this._rszPreview;return t&&t.space===this._space?t.sp:this._serverCfg?.spaces.find(t=>t.id===this._space)}get _renderCfg(){const t=this._rszPreview;return t&&this._serverCfg?{...this._serverCfg,spaces:this._serverCfg.spaces.map(e=>e.id===t.space?t.sp:e)}:this._serverCfg}get _spaceH(){return this._curSpaceCfg,sv}get _segments(){const t=this._curSpaceCfg,e=this._spaceH;return pi(t?.rooms||[]).map(t=>[t[0]*sv,t[1]*e,t[2]*sv,t[3]*e])}_savedNav(){if(this._hasFixedFloor)return null;try{return JSON.parse(localStorage.getItem(Qf)||"null")}catch{return null}}_saveNav(){if(!this._hasFixedFloor)try{localStorage.setItem(Qf,JSON.stringify({space:this._space}))}catch{}}_leaveCardRoute(){if(this._routeDepartureHandled)return;this._routeDepartureHandled=!0,"view"!==this._mode&&this._setMode("view",!1),this._pendingNavMode=null,this._geometryHistory.clear(),this._activeDraftId=null,this._resumeDraftBySpace={},this._draftSegmentCms=[],this._closingWallCm=null,this._drawWallField=null,this._showHidden=!1,this._tapConfirm=null,this._vacCalConfirm=null,this._decorEraseConfirm=null,this._openingInfo=null,this._closeInfoCard(),this._rulesDialog=null,this._alignDialog=null,this._preflightClipboardFallback=null,this._backupImportDialog=null,this._backupExportDialog=null,this._settingsDialog=null,this._markerDialog=null,this._openingDialog=null,this._physicalDialog=null,this._wallDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._mergeDialog=null,this._roomDialog=!1,this._spaceDialog=null,this._importDialog=null;const t=this._warmSlot;t?.owner===this._warmGen&&(t.vp=this._warmViewportState(),t.dlg=null,t.frameFingerprint="",clearTimeout(t.evict),t.evict=0),this._saveNav()}_setMode(t,e=!0){this._endTabDrag(),this._pendingNavMode=null;const i=this._spaceModel();if(!i)return this._cancelModeTransition(!1),void(this._mode="view");if(this._kiosk&&"view"!==t)return;if(this._mode===t){if(!e&&"view"===t&&this._modeTransitionBusy){const e=this._currentModeVisual(t),i=this._modeTransitionTargetZoom,s=this._modeTransitionTargetCenterX,n=this._modeTransitionTargetCenterY;this._cancelModeTransition(!1),this._commitViewModeAtomic(e,i,s,n)}return}if(this._bootSoftCancel(),("plan"===t||"decor"===t)&&!this._norm)return void this._showToast(this._t("toast.markup_needs_server"));if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._clearTransientHover(!0),this._cancelDevicePressFeedback();const s=this._mode,n=this._effectiveProjection(),o=this._currentModeVisual(s),a=this._modeTransitionBusy,r=o&&"view"!==s&&"view"!==t?{...o,toolbarContentOpacity:this._reducedMotion?1:.35}:o;this._cancelModeTransition(!1),this._editorSecondary.closeForNavigation(),(this._decorMove||this._dtDrag||this._bdDrag)&&this._cancelDecorGesture();const l=!i.bg&&"view"===t!=("view"===s),c=a&&"view"===s&&"view"!==t?this._modeTransitionEditorCamera:null;let h=c?.zoom??(a?this._modeTransitionTargetZoom:this._zoom),d=c?c.centerX:a?this._modeTransitionTargetCenterX:r?.viewport.centerX,p=c?c.centerY:a?this._modeTransitionTargetCenterY:r?.viewport.centerY;if("view"===s&&"view"!==t&&!a){const e=this._view;if(this._viewModeSnap={space:this._space,zoom:this._zoom,cx:e?this._logicalViewCenter(n)?.x:void 0,cy:e?this._logicalViewCenter(n)?.y:void 0},"iso"===n){const e=this._logicalViewCenter("iso");d=e?.x,p=e?.y,this._view=null,this._mode=t,this._applyView(this._zoom,e?.x,e?.y)}l&&(h=1,d=void 0,p=void 0)}if("plan"===s&&this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._mode=t,this._editorChromeMode="view"===t?s:t,"view"===t){"view"===s||a||(this._modeTransitionEditorCamera={zoom:this._zoom,centerX:r?.viewport.centerX,centerY:r?.viewport.centerY});const t=this._viewModeSnap;if(t&&t.space===this._space){h=t.zoom;const e=this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat",i=null!=t.cx&&null!=t.cy&&"iso"===e?Xg([t.cx,t.cy],0):null;d=i?.[0]??t.cx,p=i?.[1]??t.cy}else t&&(h=this._zoomBySpace[this._space]||1,d=void 0,p=void 0)}else this._modeTransitionEditorCamera={zoom:h,centerX:d,centerY:p};this._modeTransitionTargetZoom=h,this._modeTransitionTargetCenterX=d,this._modeTransitionTargetCenterY=p,("iso"===n||"view"===t&&this._labsIso&&"iso"===this._viewPreference[this._space])&&(this._modeTransitionForceAtomic=!0);const u=++this._modeTransitionRequest;e?r?(this._modeTransitionPreparing=!0,this._modeTransitionVisual=r,this._prepareModeTransition(u,r,t,h,d,p)):(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._zoom=h,this._view=null,requestAnimationFrame(()=>{this.isConnected&&u===this._modeTransitionRequest&&this._mode===t&&(this._applyView(h,d,p),"view"===t&&(this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate())})):"view"===t&&this._commitViewModeAtomic(r,h,d,p),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._selId=null,this._physicalSel=null,this._physicalDialog=null,this._physicalDrag=null,this._rszSel=null,this._rszDrag=null,this._rszLive=null,this._rszPreview=null,this._tip=null,this._hoverRoom=null,this._decorDraft=null,this._decorSel=null,this._decorMove=null,this._backdropDialog=null,this._decorTool="select",this._bdDrag=null,this._dtDrag=null,this._dtBox=null,"plan"===t&&(this._primeDrawWallField(),this._resumeLastDraft()),this._saveNav()}_primeDrawWallField(){null===this._drawWallField&&(this._drawWallField=ml(ll,this._imperial))}get _drawWallFieldValue(){return null===this._drawWallField?ml(ll,this._imperial):this._drawWallField}get _drawWallCm(){const t=Wf(this._drawWallFieldValue);if(null==t||t<0)return null;const e=this._imperial?2.54*t:t,i="column"===this._tool?jc:100;return e>=("column"===this._tool?1:0)&&e<=i?e:null}get _drawWallMaxCm(){return"column"===this._tool?jc:100}_showPhysicalRange(t=this._drawWallMaxCm,e=0){this._showToast(this._t("toast.physical_range",{min:ml(e,this._imperial),max:ml(t,this._imperial),unit:this._t(this._imperial?"wallthick.unit_in":"wallthick.unit_cm")}))}_draftSegmentCount(t=this._curSpaceCfg){return(t?.room_drafts||[]).reduce((t,e)=>t+(Array.isArray(e.segments)?e.segments.length:0),0)}_mergeSpacePartitions(t,e){const i=t?.partitions||[];if(i.length<2)return 0;const s=nm(i,{pitch:Th,seedIds:e,geometry:am(t,{excludeDraftId:this._activeDraftId})});return s.merged?(t.partitions=s.partitions,om(t.openings,t.partitions,s.openingMoves,{coordScale:sv,cellCm:this._cellCm,gridPitch:this._gridPitch}),s.merged):0}_finishWallChain(){if("draw"!==this._tool||this._wallFaceBatch||this._roomDialog)return!0;const t=this._curSpaceCfg;if(!t||this._path.length<2)return this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._clearPlanSnapHover(),!0;const e=Zp(this._path,Xp(this._path.length-1,this._draftSegmentCms,this._drawWallCm,ll)),i=e.length;if((t.partitions||[]).length+i>rv)return this._showToast(this._t("toast.physical_limit")),!1;const s=this._geometrySnapshot();t.partitions||=[];const n=Date.now().toString(36),o=[],a=this._activeDraftId?(t.room_drafts||[]).find(t=>t.id===this._activeDraftId):null,r=this._draftSegmentsForPath(this._path,a,e.map(t=>t.cm));for(let s=0;st.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),this._commitPhysicalGeometry(this._t("history.wall_chain_finish"),s),delete this._resumeDraftBySpace[this._space],this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._clearPlanSnapHover(),!0}_activateMarkupTool(t){t!==this._tool&&(this._wallFaceBatch&&this._roomDialogCancel(),("draw"!==this._tool||this._finishWallChain())&&(this._cancelPath(),this._tool=t,"draw"===t&&this._resumeLastDraft(),"resize"===t&&(this._rszSel=null),"wallthick"===t&&(this._wallDialog=null)))}_limitReached(t){const e=this._curSpaceCfg;if(!e)return!0;const i="draft"===t?(e.room_drafts||[]).length>=200:"partition"===t?(e.partitions||[]).length>=rv:(e.wall_columns||[]).length>=500;return i&&this._showToast(this._t("toast.physical_limit")),i}_svgPoint(t){const e=this.renderRoot.querySelector(".stage").getBoundingClientRect();return this._screenToVb(t.clientX-e.left,t.clientY-e.top)}_snap(t){const e=this._gridPitch;return[Ah(ri(t[0],e)),Ah(ri(t[1],e))]}_snapDrawPoint(t,e=!1){const i=this._path[this._path.length-1],s=e&&i?function(t,e,i,s=1/0){if(!(i>0&&t?.every(Number.isFinite)&&e?.every(Number.isFinite)))return[e[0],e[1]];const n=e[0]-t[0],o=e[1]-t[1];if(Math.abs(n)+Math.abs(o)<=1e-12)return[t[0],t[1]];const a=Math.PI/4;let r=Math.atan2(o,n);r<0&&(r+=2*Math.PI);const l=Math.floor(r/a+.5)%8,[c,h]=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]][l],d=c*c+h*h;let p=Math.max(0,Math.round((n*c+o*h)/(i*d)));if(Number.isFinite(s)&&s>=0){const e=(t,e)=>{if(!e)return 1/0;const n=e>0?s-t:t+s;return Math.max(0,Math.floor((n+1e-9*i)/i))};p=Math.min(p,e(t[0],c),e(t[1],h))}return[t[0]+c*p*i,t[1]+h*p*i]}(i,t,this._gridPitch,Ch):t;return this._snap(s)}_planSnapOpeningCuts(t,e){if(!this._openingsR.length)return[];const i=this._openingWallIndexFor(t,e).value,s=[];for(const e of this._roomWallOpeningInputs(this._openingsR,t)){const t=Lc(i,e);if(!t.negative&&!t.positive)continue;const n=e.angle*Math.PI/180,o=Math.cos(n)*e.length/2,a=Math.sin(n)*e.length/2;s.push([e.x-o,e.y-a,e.x+o,e.y+a])}return s}_planSnapGeometrySnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|empty`,value:{segments:[],endpoints:[]}};const e=[this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._planSnapGeometryCache?.key===e)return this._planSnapGeometryCache;const i=this._openCuts(),s=Wp({space:t,activeDraftId:this._activeDraftId,roomCuts:this._planSnapOpeningCuts(t,i),partitionCuts:this._partitionOpeningCuts(t),epsilon:2e-4*this._gridPitch});return this._planSnapGeometryCache={key:e,value:s},this._planSnapGeometryCache}_hiddenWallDiagnosticSnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|hidden-empty`,value:{segments:[],endpoints:[]}};const e=["hidden",this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._hiddenWallDiagnosticCache?.key===e)return this._hiddenWallDiagnosticCache;const i=qp({space:t,activeDraftId:this._activeDraftId,epsilon:2e-4*this._gridPitch});return this._hiddenWallDiagnosticCache={key:e,value:i},this._hiddenWallDiagnosticCache}_planStructuralGeometrySnapshot(){const t=this._spaceModel();if(!t)return{key:`${this._space}|structural-empty`,value:{segments:[],endpoints:[]}};const e=["structural",this._space,this._cfgEpoch,this._activeDraftId||"",t.rooms.length,t.room_drafts.length,t.partitions.length].join("|");if(this._planStructuralGeometryCache?.key===e)return this._planStructuralGeometryCache;const i=Wp({space:t,activeDraftId:this._activeDraftId,epsilon:2e-4*this._gridPitch});return this._planStructuralGeometryCache={key:e,value:i},this._planStructuralGeometryCache}_planSnapContextKey(t){const e=this._path[0],i=this._path[this._path.length-1];return[t,this._tool,this._path.length,e?`${e[0]},${e[1]}`:"",i?`${i[0]},${i[1]}`:""].join("|")}_resolvePlanDrawPoint(t,e){const i=this._planSnapGeometrySnapshot(),s=this._path[this._path.length-1],n="draw"===this._tool&&this._path.length>=3?[{point:this._path[0],key:"closure:first-point"}]:[],o={tolerance:this._cssPxToRender(12),distinguishTolerance:this._cssPxToRender(8),gridStep:this._gridPitch,excludePoints:s?[s]:[],extraEndpoints:n,epsilon:2e-4*this._gridPitch},a=e&&s?Yp(i.value,t,{...o,anchor:s}):function(t,e,i){if(!(zp(e)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Ap,n=i.excludePoints||[],o=Vp(Gp(t,e,i),i.distinguishTolerance||0);if(o)return o;let a=null;for(const o of t.segments){const t=[o.a[0],o.a[1],o.b[0],o.b[1]],r=Ls([e[0],e[1]],t);if(r>i.tolerance)continue;const l=Kp(o,e,i.gridStep);!jp(l,n,s)&&Up(r,o.key,a)&&(a={kind:"line",point:l,key:o.key,distance:r,segment:o})}return a?{kind:"resolved",candidate:a,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}(i.value,t,o),r="resolved"===a.kind?a.candidate:null,l=r?[...r.point]:this._snapDrawPoint(t,e),c=s?ua(s,l):l;return{point:c,candidate:r&&fi(c,r.point)?r:null,conflicts:"ambiguous"===a.kind?a.conflicts:[],ambiguous:"ambiguous"===a.kind,contextKey:this._planSnapContextKey(i.key)}}get _activePlanSnapCandidate(){if(!this._markup||"draw"!==this._tool)return null;const t=this._planSnapHover;if(!t)return null;const e=this._planSnapGeometrySnapshot();return t.contextKey===this._planSnapContextKey(e.key)?t.candidate:null}get _activePlanSnapConflicts(){if(!this._markup||"draw"!==this._tool)return[];const t=this._planSnapHover;if(!t)return[];const e=this._planSnapGeometrySnapshot();return t.contextKey===this._planSnapContextKey(e.key)?t.conflicts:[]}_clearPlanSnapHover(t=!0){this._planSnapHover=null,this._syncPlanSnapActiveMarker(null),this._syncPlanSnapConflictMarkers([]),t&&(this._cursorPt=null)}_samePt(t,e){return fi(t,e)}_dropLegacySegments(){for(const t of this._serverCfg?.markers||[])"ripple"===t.display&&(t.display="icon_ripple");for(const t of this._serverCfg?.spaces||[]){delete t.segments;const e=new Set,i=t=>"string"==typeof t&&t.length>=1&&t.length<=64&&!e.has(t),s=t=>(e.add(t),!0),n=t=>Array.isArray(t)&&2===t.length&&t.every(t=>Number.isFinite(Number(t))&&Math.abs(Number(t))<=Mh);if(Array.isArray(t.partitions)&&(t.partitions=t.partitions.filter(t=>t&&i(t.id)&&n(t.a)&&n(t.b)&&Math.hypot(t.a[0]-t.b[0],t.a[1]-t.b[1])>1e-9&&s(t.id)).map(t=>({...t,cm:Number.isFinite(Number(t.cm))?Math.max(0,Math.min(100,Number(t.cm))):15})),t.partitions.length||delete t.partitions),Array.isArray(t.wall_columns)&&(t.wall_columns=t.wall_columns.filter(t=>t&&i(t.id)&&n(t.center)&&s(t.id)).map(t=>({id:t.id,shape:"circle"===t.shape?"circle":"square",center:[Number(t.center[0]),Number(t.center[1])],cm:Gc(Number(t.cm)||15),..."circle"===t.shape?{}:{angle:Vc(t.angle)}})),t.wall_columns.length||delete t.wall_columns),Array.isArray(t.room_drafts)&&(t.room_drafts=t.room_drafts.filter(t=>t&&i(t.id)&&Array.isArray(t.points)&&t.points.length>=2&&t.points.every(n)&&s(t.id)).map(t=>{const e=Fm(t);return{id:t.id,...e}}).filter(t=>t.points.length>=2),t.room_drafts.length||delete t.room_drafts),Array.isArray(t.walls)){const e=Sd(Sh({spaces:[t]}),t.id),i=e?g_(t,e,sv,.02*Ph).contour.map(t=>t.map(t=>t/sv)):ud(t.open_spans).map(t=>[t.a[0],t.a[1],t.b[0],t.b[1]]);t.walls=Tl(t.walls,t.rooms||[],Th,1,i),t.walls.length||delete t.walls}}}_rollbackRejectedPhysicalWrites(t){if(!this._serverCfg||!t.length)return!1;let e=!1;for(const[i]of t){const t=this._pendingPhysicalWrites.get(i);t&&(e=this._restoreGeometryStateInConfig(this._serverCfg,t.before)||e,this._pendingPhysicalWrites.delete(i))}return!!e&&(this._clearGeometryGesture(),this._geometryHistory.clear(),this._cfgEpoch++,this._modelCache=null,this._wallUnionCache=null,this._physicalBodiesCache=null,this._frame=null,this._regSignature="",this._cfgContentFingerprint=wd(this._serverCfg),this._maybeRebuildDevices(),this.requestUpdate(),!0)}async _reloadRejectedPhysicalWrite(){const t=this._writeChain;await t.catch(()=>{}),await this._reloadConfigOnly(!0)}get _cfgWriting(){return this._writesPending>0}_writeConfig(){var t,e;this._writesPending++,this._writeChain=(t=this._writeChain,e=async()=>{if(!this._serverCfg)return;this._dropLegacySegments();const t=rl(Gr(this._serverCfg)),e=wd(t),i=[...this._pendingPhysicalWrites.entries()];for(const[e,s]of i){const i=hg(t.spaces.find(t=>t.id===e));if(i===s.fingerprint)continue;let n=!1;try{n=this._checkSpacePhysicalGeometry(t,e).ok}catch{n=!1}if(!n)throw this._restoreGeometryStateLocal(s.before),this._pendingPhysicalWrites.delete(e),this._geometryHistory.clear(),this._showToast(this._t("toast.geometry_unsafe")),Object.assign(new Error("unsafe wall geometry"),{code:"geometry-unsafe"});s.fingerprint=i}let s;e!==wd(this._serverCfg)&&(this._serverCfg=t),this._cfgContentFingerprint=e;try{s=await this.hass.callWS({type:"houseplan/config/set",config:t,expected_rev:this._cfgRev})}catch(t){if(!this._rollbackRejectedPhysicalWrites(i))throw t;const e=t&&"object"==typeof t?t:Object.assign(new Error(String(t)),{cause:t});throw e.physicalGeometryRolledBack=!0,e}this._cfgRev=s?.rev??this._cfgRev+1;for(const[t,e]of i)this._pendingPhysicalWrites.get(t)?.fingerprint===e.fingerprint&&this._pendingPhysicalWrites.delete(t)},t.catch(()=>{}).then(e));return this._writeChain.finally(()=>{this._writesPending--})}_saveConfig(){this._cfgEpoch++,this._saveConfigDebounced()}_geometrySnapshotFromConfig(t,e){const i=t?.spaces?.find(t=>t.id===e);if(!i)return null;const s=t=>JSON.parse(JSON.stringify(t)),n={};for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])void 0!==i[t]&&(n[t]=i[t]);return{spaceId:e,rooms:s(i.rooms||[]),...Array.isArray(i.openings)?{openings:s(i.openings)}:{},...Array.isArray(i.walls)?{walls:s(i.walls)}:{},...Array.isArray(i.wall_segments)?{wall_segments:s(i.wall_segments)}:{},...Array.isArray(i.open_spans)?{open_spans:s(i.open_spans)}:{},...Array.isArray(i.room_drafts)?{room_drafts:s(i.room_drafts)}:{},...Array.isArray(i.partitions)?{partitions:s(i.partitions)}:{},...Array.isArray(i.wall_columns)?{wall_columns:s(i.wall_columns)}:{},...Array.isArray(i.decor)?{decor:s(i.decor)}:{},plan_transform:n}}_geometrySnapshot(t=this._space){return this._geometrySnapshotFromConfig(this._serverCfg,t)}_recordGeometry(t,e){if(!e)return;const i=this._geometrySnapshot(e.spaceId);i&&JSON.stringify(e)!==JSON.stringify(i)&&(this._geometryHistory.push({name:t,before:e,after:i}),this.requestUpdate())}_restoreGeometryStateInConfig(t,e,i=!1){const s=t?.spaces?.find(t=>t.id===e.spaceId);if(!s)return!1;const n=t=>JSON.parse(JSON.stringify(t)),o=new Map((s.rooms||[]).map(t=>[t.id,t]));if(s.rooms=n(e.rooms),i)for(const t of s.rooms){const e=o.get(t.id);!Array.isArray(t.wall_ids)&&Array.isArray(e?.wall_ids)&&e.wall_ids.length===t.poly?.length&&(t.wall_ids=n(e.wall_ids))}const a=(t,e)=>{void 0!==e?s[t]=n(e):i&&"wall_segments"===t||delete s[t]},r=new Map((s.openings||[]).map(t=>[t.id,t])),l=new Map((s.room_drafts||[]).map(t=>[t.id,t]));if(a("openings",e.openings),a("walls",e.walls),a("wall_segments",e.wall_segments),a("open_spans",e.open_spans),a("room_drafts",e.room_drafts),a("partitions",e.partitions),a("wall_columns",e.wall_columns),a("decor",e.decor),i){for(const t of s.openings||[]){const e=r.get(t.id);t.host||"wall"!==e?.host?.kind||(t.host=n(e.host))}for(const t of s.room_drafts||[]){const e=l.get(t.id);for(let i=0;i<(t.segments||[]).length;i++)!t.segments[i]?.id&&e?.segments?.[i]?.id&&(t.segments[i].id=e.segments[i].id)}}for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])delete s[t];return Object.assign(s,n(e.plan_transform||{})),!0}_restoreGeometryStateLocal(t){return!!this._restoreGeometryStateInConfig(this._serverCfg,t)&&(this._cfgEpoch++,this._modelCache=null,this._wallUnionCache=null,this._physicalBodiesCache=null,this._frame=null,this.requestUpdate(),!0)}_wallModelBlockerLabel(t){const e=t instanceof Cm?t.reason:"invalid-room";return this._t(`wall_model.reason.${e}`)}_hasLegacyZeroWallFields(t=this._serverCfg){return(t?.spaces||[]).some(t=>Array.isArray(t?.open_spans)&&t.open_spans.length>0||(t?.rooms||[]).some(t=>Array.isArray(t?.open_to)&&t.open_to.length>0))}_showWallModelMigrationBlocked(t){const e=this._hasLegacyZeroWallFields()?"toast.zero_wall_migration_blocked":"toast.wall_model_migration_blocked";this._showToast(this._t(e,{reason:this._wallModelBlockerLabel(t)}))}_commitPhysicalGeometry(t,e,i=[]){if(!e||!this._serverCfg)return!1;const s=this._serverCfg,n=this._geometrySnapshotFromConfig(s,e.spaceId),o=s.spaces.find(t=>t.id===e.spaceId);if(!o||hg(e)===hg(o))return!1;let a,r=!1;try{r=this._checkSpacePhysicalGeometry(s,e.spaceId).ok}catch{r=!1}if(!r)return this._clearGeometryGesture(),this._restoreGeometryStateLocal(e),this._showToast(this._t("toast.geometry_unsafe")),!1;let l=e;try{if(Number(s.model_version||0)<9){const t=JSON.parse(JSON.stringify(s));if(!this._restoreGeometryStateInConfig(t,e))throw new Cm("invalid-room",e.spaceId);const i=Zm(t).config;l=this._geometrySnapshotFromConfig(i,e.spaceId)||e;const o=JSON.parse(JSON.stringify(i));if(!n||!this._restoreGeometryStateInConfig(o,n,!0))throw new Cm("invalid-room",e.spaceId);const r=i.spaces.find(t=>t.id===e.spaceId),c=o.spaces.find(t=>t.id===e.spaceId);if(!Array.isArray(n.wall_segments)&&JSON.stringify(e.rooms)===JSON.stringify(n.rooms))for(const t of c?.wall_segments||[])t.cm=Pl(n.walls,t.a,t.b,Th,1);const h=((t,e,i)=>{const s=new Map,n=new Map((t?.rooms||[]).map(t=>[t.id,t])),o=new Map((e||[]).map(t=>[t.id,t])),{rooms:a}=Vm(i,Um(t));for(const t of a){const e=o.get(t.id),a=n.get(t.id),r=hi(e),l=hi((i.rooms||[]).find(e=>e.id===t.id)),c=hi(a);if(r&&l&&c&&r.length===l.length&&c.length===a?.wall_ids?.length&&t.poly.length===t.wall_ids.length)for(let e=0;e{const n=[];for(let o=0;oMm||Om(r,i,s)>Mm)continue;const l=Nm(a,i,s),c=Nm(r,i,s);l<-Mm||c>1+Mm||c<=l+Mm||n.push({start:l,id:e[o]})}return n.sort((t,e)=>t.start-e.start)},n=i(c,a.wall_ids,r[e],r[(e+1)%r.length]),o=i(t.poly,t.wall_ids,l[e],l[(e+1)%l.length]);if(n.length&&n.length===o.length)for(let t=0;tt.id===e.spaceId),s=this._path.length>=2?this._path.map(t=>[t[0]/sv,t[1]/sv]):[];s.push(...i.map(t=>[t[0],t[1]])),c=Em(t)<=Em(l,s)&&this._checkSpacePhysicalGeometry(a,e.spaceId).ok}catch{c=!1}if(!c)return this._clearGeometryGesture(),this._restoreGeometryStateLocal(e),this._showToast(this._t("toast.geometry_unsafe")),!1;tg(s,a),this._recordGeometry(t,l);const h=s.spaces.find(t=>t.id===e.spaceId),d=this._pendingPhysicalWrites.get(e.spaceId);return this._pendingPhysicalWrites.set(e.spaceId,{before:d?.before||l,fingerprint:hg(h)}),this._saveConfig(),!0}_clearGeometryGesture(){this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!1),this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._roomDeleteDialog=null,this._wallDialog=null,this._physicalDialog=null,this._physicalSel=null,this._physicalDrag=null,this._physicalRotate=null,this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._openingDialog=null,this._rszSel=null,this._rszDrag=null,this._rszPreview=null,this._rszLive=null,this._decorDraft=null,this._decorMove=null,this._dtDrag=null,this._bdDrag=null}_stagePointerCancel(t){if(clearTimeout(this._kioskHoldTimer),this._swipeStart?.id===t.pointerId&&(this._swipeStart=null),this._physicalDrag?.pid===t.pointerId||this._physicalRotate?.pid===t.pointerId)return void this._cancelPhysicalGesture();if(this._decorDraft?.pid===t.pointerId)return this._decorDraft=null,void this.requestUpdate();if(this._decorMove?.pid===t.pointerId||this._dtDrag?.pid===t.pointerId||this._bdDrag?.pid===t.pointerId)return void this._cancelDecorGesture();"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=!!this._pinchStart||!!this._panStart;this._pointers.delete(t.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null),e&&0===this._pointers.size&&this.requestUpdate()}_applyGeometryState(t,e=!1){if(!this._canCommitSpace(t.spaceId))return!1;const i=this._geometrySnapshot(t.spaceId);if(!i||!this._restoreGeometryStateLocal(t))return!1;const s=this._serverCfg,n=hg(i)!==hg(t);if(n){let n=!1;try{const i=s?this._checkSpacePhysicalGeometry(s,t.spaceId):null;n=!!i?.ok||!(!e||"wall-degraded-extra"!==i?.reason)}catch{n=!1}if(!n)return this._restoreGeometryStateLocal(i),this._showToast(this._t("toast.geometry_unsafe")),!1}let o;try{o=Zm(s).config}catch(t){return this._restoreGeometryStateLocal(i),this._showWallModelMigrationBlocked(t),!1}if(n){let n=!1;try{const i=o?this._checkSpacePhysicalGeometry(o,t.spaceId):null;n=!!i?.ok||!(!e||"wall-degraded-extra"!==i?.reason)}catch{n=!1}if(!n)return this._restoreGeometryStateLocal(i),this._showToast(this._t("toast.geometry_unsafe")),!1;tg(s,o);const a=s?.spaces.find(e=>e.id===t.spaceId),r=this._pendingPhysicalWrites.get(t.spaceId);this._pendingPhysicalWrites.set(t.spaceId,{before:r?.before||i,fingerprint:hg(a)})}else tg(s,o);return this._clearGeometryGesture(),this._space!==t.spaceId&&(this._commitSpace(t.spaceId),this._saveNav(),this._restoreZoom()),this._modelCache=null,this._frame=null,this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate(),!0}_roomAt(t){return this._spaceModel()?.rooms.find(e=>{const i=hi(e);return!!i&&wi(t,i)})}_overlapRoom(t){return this._spaceModel()?.rooms.find(e=>{const i=hi(e);return!!i&&Di(t,i)})}_pointInRoom(t,e){return e.poly?vi(t,e.poly):null!=e.x&&t[0]>=e.x&&t[0]<=e.x+e.w&&t[1]>=e.y&&t[1]<=e.y+e.h}_contourSelfIntersects(t){if(!Ia(t))return!0;const e=t.length,i=.001;for(let s=0;s=500)return this._showToast(this._t("toast.physical_limit")),!1;const t=this._curSpaceCfg;return!(!this._activeDraftId&&(t?.room_drafts||[]).length>=200||this._draftSegmentCount(t)>=2e3||(t?.partitions||[]).length+this._path.length>rv)||(this._showToast(this._t("toast.physical_limit")),!1)}_markupClick(t){if(this._vacFit)return;if(!this._markup)return;const e=this._spaceModel();if(!e)return void this._clearGeometryGesture();if(this._suppressClick)return;if(this._drag||this._rlResize)return;const i=t.composedPath?.()||[];if(i.some(t=>t?.classList?.contains?.("roomlabel")||t?.classList?.contains?.("rlhandle")))return;if(i.some(t=>t?.classList?.contains?.("physical-hit")))return;const s=this._svgPoint(t);if("select"===this._tool)return void(this._physicalSel=null);if("resize"===this._tool){if(this._rszDrag||i.some(t=>t?.classList?.contains?.("rszhandle")))return;const t=[...e.rooms].reverse().find(t=>this._pointInRoom(s,t));return void(this._rszSel=t?.id||null)}if("delroom"===this._tool)return void this._deleteRoomClick(s);if("opening"===this._tool)return void this._openingClick(s);if("merge"===this._tool)return void this._mergeClick(s);if("wallthick"===this._tool)return void this._wallThickClick(s);if("split"===this._tool)return void this._splitClick(s);if("column"===this._tool)return void this._columnClick(s);this._wallRepairDiagnostic=null;const n=this._resolvePlanDrawPoint(s,t.shiftKey);if(n.ambiguous)return this._planSnapHover={contextKey:n.contextKey,candidate:null,conflicts:n.conflicts},this._syncPlanSnapActiveMarker(null),this._syncPlanSnapConflictMarkers(n.conflicts),void this._showToast(this._t("toast.plan_snap_ambiguous"));let o=n.point;if(t.ctrlKey||t.metaKey){if(t.preventDefault(),this._path.length<3)return;o=ua(this._path[this._path.length-1],this._path[0])}if(!this._path.length){if(!t.shiftKey&&!n.candidate&&this._offerExistingWallFace(s))return;const e=this._draftEndAt(o);return e?(this._activeDraftId=e.draft.id,this._resumeDraftBySpace[this._space]=e.draft.id,this._path=e.reverse?[...e.draft.points].reverse().map(t=>[...t]):e.draft.points.map(t=>[...t]),void(this._draftSegmentCms=this._adoptDraftCms(this._path,e.reverse?[...e.draft.segments].reverse().map(t=>t.cm):e.draft.segments.map(t=>t.cm),e.draft.id))):(this._activeDraftId=null,this._draftSegmentCms=[],void(this._path=[o]))}const a=this._path[this._path.length-1];if(this._samePt(o,a))return;const r=this._draftEndAt(o,this._activeDraftId||void 0);if(r)return void this._mergeDraftEndpoint(r);if(!this._canAppendRoomDraftPoint())return;const l=this._drawWallCm;if(null==l)return void this._showPhysicalRange(100);const c=this._path.map(t=>[...t]);this._path=[...this._path,o],this._draftSegmentCms=[...this._draftSegmentCms,l],this._persistActiveDraftSegment(),this._offerWallFaces(c)}_draftEndAt(t,e){const i=this._spaceModel();if(!i)return null;const s=this._viewOr(this._baseVb()),n=Math.max(.15*this._gridPitch,this._stageEl?.clientWidth?s.w/this._stageEl.clientWidth*12:0);for(const s of i.room_drafts||[]){if(s.id===e)continue;if(s.points.length<2)continue;const i=s.points[0],o=s.points[s.points.length-1];if(Math.hypot(t[0]-o[0],t[1]-o[1])<=n)return{draft:s,reverse:!1};if(Math.hypot(t[0]-i[0],t[1]-i[1])<=n)return{draft:s,reverse:!0}}return null}_mergeDraftEndpoint(t){const e=this._curSpaceCfg;if(!e||!this._path.length)return;const i=this._path.map(t=>[...t]),s=this._wallGraphSources(i),n=Array.isArray(e.room_drafts)?e.room_drafts:[],o=this._activeDraftId?n.find(t=>t.id===this._activeDraftId):null,a=n.find(e=>e.id===t.draft.id);if(!a)return;const r=t.reverse?t.draft.points.map(t=>[...t]):[...t.draft.points].reverse().map(t=>[...t]),l=t.reverse?(a.segments||[]).map(t=>({...t})):[...a.segments||[]].reverse().map(t=>({...t})),c=this._path[this._path.length-1],h=this._samePt(c,r[0]),d=h?null:this._drawWallCm;if(!h&&null==d)return void this._showPhysicalRange(100);const p=this._draftSegmentsForPath(this._path,o,this._draftSegmentCms),u=[...this._path.map(t=>[...t]),...h?r.slice(1):r],_=[...p,...null==d?[]:[{cm:d}],...l],m=u.length>=4&&this._samePt(u[0],u[u.length-1]),g=u,f=_;if(g.length>500)return void this._showToast(this._t("toast.physical_limit"));const v=(o?.segments?.length||0)+(a.segments?.length||0);if(this._draftSegmentCount(e)-v+f.length>2e3)return void this._showToast(this._t("toast.physical_limit"));if(m){const t=g.slice(0,-1);if(this._contourSelfIntersects(t)||Ti(t)<=1e-6)return void this._showToast(this._t("toast.contour_cannot_close"));const e=this._overlapRoom(t);if(e)return void this._showToast(this._t("toast.room_overlap",{name:e.name||""}))}const y=this._geometrySnapshot(),b=this._activeDraftId||t.draft.id,w={...o||a,id:b,points:g.map(t=>[t[0]/sv,t[1]/sv]),segments:f};e.room_drafts=n.filter(e=>e.id!==t.draft.id&&(!this._activeDraftId||e.id!==this._activeDraftId)),e.room_drafts.push(w),this._activeDraftId=b,this._resumeDraftBySpace[this._space]=b,this._path=g,this._draftSegmentCms=this._adoptDraftCms(g,f.map(t=>Number(t.cm)),b),this._physicalSel=null,this._commitPhysicalGeometry(this._t("history.draft_merge"),y),null!=d&&this._offerWallFaces(i,i.length-1,s)}_adoptDraftCms(t,e,i){const s=Math.max(0,t.length-1),n=Xp(s,e,this._drawWallCm,ll);return e.length!==s&&console.debug(`[houseplan] draft ${i??"?"}: восстановлено толщин ${s-e.length} (#234)`),n}_draftSegmentsForPath(t,e,i){const s=Array.isArray(e?.points)?e.points.map(t=>[Number(t?.[0])*sv,Number(t?.[1])*sv]):[],n=Array.isArray(e?.segments)?e.segments:[];return Xp(Math.max(0,t.length-1),i,this._drawWallCm,ll).map((e,i)=>{const o=t[i],a=t[i+1],r=s.findIndex((t,e)=>{if(e+1>=s.length)return!1;const i=s[e+1];return this._samePt(o,t)&&this._samePt(a,i)||this._samePt(o,i)&&this._samePt(a,t)});return{...r>=0?n[r]:{},cm:e}})}_persistActiveDraftSegment(){if(this._path.length<2||!this._curSpaceCfg)return;const t=this._geometrySnapshot(),e=this._curSpaceCfg;e.room_drafts||=[],this._activeDraftId||(this._activeDraftId="draft-"+Date.now().toString(36)),this._resumeDraftBySpace[this._space]=this._activeDraftId;const i=e.room_drafts.findIndex(t=>t.id===this._activeDraftId),s={...i>=0?e.room_drafts[i]:{},id:this._activeDraftId,points:this._path.map(t=>[t[0]/sv,t[1]/sv]),segments:this._draftSegmentsForPath(this._path,i>=0?e.room_drafts[i]:null,this._draftSegmentCms)};i>=0?e.room_drafts[i]=s:e.room_drafts.push(s),this._commitPhysicalGeometry(this._t("history.draft_segment"),t)}_activeWallSourceKey(t){return`active:${this._activeDraftId||"session"}:${t}`}_wallGraphSources(t){const e=this._planStructuralGeometrySnapshot().value.segments.map(t=>({a:t.a,b:t.b,key:`static:${t.key}`}));for(let i=0;i+1t.key===i);if(s>=0){const[t]=this._wallFaceGraphCache.splice(s,1);return this._wallFaceGraphCache.push(t),t.value}const n=bu(t,e);return this._wallFaceGraphCache.push({key:i,value:n}),this._wallFaceGraphCache.length>4&&this._wallFaceGraphCache.shift(),n}_offerWallFaces(t,e=this._path.length-2,i){if(this._path.length<2||this._wallFaceBatch||this._roomDialog)return;const s=this._spaceModel();if(!s)return;const n=this._activeWallSourceKey(e),o=2e-4*this._gridPitch;let a,r;try{const e=i||this._wallGraphSources(t);r=this._wallGraphSources(this._path),a=function(t,e,i){const s=new Set(t.faces.map(t=>t.key));return e.faces.filter(t=>!s.has(t.key)&&t.sourceKeys.includes(i))}(this._wallFaceGraph(e,o),this._wallFaceGraph(r,o),n)}catch{return}if(!a.length){const t=Iu(r,{requiredSourceKey:n,maxDistance:gl(2,this._cellCm,this._gridPitch),gridStep:this._gridPitch,epsilon:o});return"ambiguous"===t.kind?(this._wallRepairDiagnostic=t.proposals[0]||null,void this._showToast(this._t(0===this._drawWallCm?"toast.zero_wall_ambiguous":"toast.wall_repair_ambiguous"))):void("repair"!==t.kind||this._overlapRoom(t.face.ring)||this._beginWallFaceBatch([{...t.face,repair:t.proposal}]))}for(const t of s.rooms){const e=hi(t);if(!t.id||!e)continue;const i=zi(e,this._path,.02*this._gridPitch);if(!i)continue;const[s,n]=i,o=Ti(s)>=Ti(n)?s:n,r=o===s?n:s,l=[...a].sort((t,e)=>Math.abs(t.area-Ti(r))-Math.abs(e.area-Ti(r))||t.key.localeCompare(e.key))[0];if(!l)return;return void this._beginWallFaceBatch([{...l,ring:r.map(t=>[t[0],t[1]]),split:{roomId:t.id,mainPoly:o,newPoly:r},consumeAllActive:!0}])}const l=a.filter(t=>!(t.ring.length<3||this._contourSelfIntersects(t.ring))&&!this._overlapRoom(t.ring));l.length&&this._beginWallFaceBatch(l)}_beginWallFaceBatch(t){this._wallRepairDiagnostic=null,this._wallFaceBatch={candidates:[...t].sort((t,e)=>t.area-e.area||t.key.localeCompare(e.key)),index:0,decisions:[],activePath:this._path.map(t=>[...t]),activeCms:[...this._draftSegmentCms],activeDraftId:this._activeDraftId},this._clearPlanSnapHover(),this._nameSel="",this._areaSel="",this._resetRoomDialogFields(),this._roomDialog=!0}_offerExistingWallFace(t){if(this._path.length||this._wallFaceBatch||this._roomDialog)return!1;const e=2e-4*this._gridPitch;try{let i,s=wu(this._wallFaceGraph(this._wallGraphSources([]),e),t,e);if(!s){const n=Iu(this._wallGraphSources([]),{point:t,maxDistance:gl(2,this._cellCm,this._gridPitch),gridStep:this._gridPitch,epsilon:e});if("ambiguous"===n.kind)return this._wallRepairDiagnostic=n.proposals[0]||null,this._showToast(this._t(0===this._drawWallCm?"toast.zero_wall_ambiguous":"toast.wall_repair_ambiguous")),!0;if("repair"===n.kind)s=n.face,i=n.proposal;else if("none"===n.kind){const i=Iu(this._wallGraphSources([]),{point:t,maxDistance:this._cssPxToRender(12),gridStep:this._gridPitch,epsilon:e});if("repair"===i.kind)return this._wallRepairDiagnostic=i.proposal,this._showToast(this._t("toast.wall_repair_too_large")),!0}}return!(!s||s.ring.length<3||this._contourSelfIntersects(s.ring)||this._overlapRoom(s.ring))&&(this._beginWallFaceBatch([{...s,existing:!i,repair:i}]),!0)}catch{return!1}}_columnClick(t){const e=this._snap(t),i=this._drawWallCm;if(null==i)return void this._showPhysicalRange(jc,1);if(!this._curSpaceCfg||this._limitReached("column"))return;const s=this._spaceModel();if(!s)return;const n={id:"column-"+Date.now().toString(36),shape:"square",center:e,cm:Gc(i),angle:0},o=(s.wall_columns||[]).find(t=>uh(t,n,.02*this._gridPitch));if(o)return clearTimeout(this._duplicateColumnTimer),this._duplicateColumnId=o.id,this._duplicateColumnTimer=window.setTimeout(()=>{this._duplicateColumnId=null},900),void this._showToast(this._t("toast.column_duplicate"));const a=this._geometrySnapshot(),r=this._curSpaceCfg;r.wall_columns||=[],r.wall_columns.push({...n,center:[e[0]/sv,e[1]/sv]}),this._commitPhysicalGeometry(this._t("history.column_add"),a)}_openPhysicalDialog(t,e,i){const s=this._spaceModel();if(s)if("partition"===t){const i=s.partitions.find(t=>t.id===e);i&&(this._physicalDialog={kind:t,id:e,cm:ml(i.cm,this._imperial),length:this._fmtLen(i.a,i.b)})}else if("column"===t){const i=s.wall_columns.find(t=>t.id===e);i&&(this._physicalDialog={kind:t,id:e,cm:ml(i.cm,this._imperial),shape:i.shape,angle:this._angleField("square"===i.shape?Vc(i.angle):0)})}else{const n=s.room_drafts.find(t=>t.id===e),o=Math.max(0,Math.min(n?.segments.length?n.segments.length-1:0,i||0));n?.segments[o]&&(this._physicalDialog={kind:t,id:e,segment:o,cm:ml(n.segments[o].cm,this._imperial),length:this._fmtLen(n.points[o],n.points[o+1])})}}_physicalDown(t,e,i){const s=this._spaceModel();if(!s)return;t.stopPropagation(),dv(t);const n=this._svgPoint(t),o=[];for(const t of[...s.wall_columns].reverse())dh(n,Qc(t,this._cellCm,this._gridPitch))&&o.push({kind:"column",id:t.id});for(const t of[...s.partitions].reverse()){const e=Zc(t.a,t.b,t.cm,this._cellCm,this._gridPitch);e&&dh(n,e)&&o.push({kind:"partition",id:t.id})}o.some(t=>t.kind===e&&t.id===i)||o.unshift({kind:e,id:i});const a=o.map(t=>`${t.kind}:${t.id}`).sort().join("|"),r=performance.now(),l=this._physicalPickCycle,c=o.length>1&&l?.signature===a&&r-l.at>380&&r-l.at<=1200&&Math.hypot(t.clientX-l.x,t.clientY-l.y)<=10?(l.index+1)%o.length:Math.max(0,o.findIndex(t=>t.kind===e&&t.id===i));this._physicalPickCycle={signature:a,index:c,x:t.clientX,y:t.clientY,at:r},e=o[c].kind,i=o[c].id;const h="partition"===e?s.partitions.find(t=>t.id===i):s.wall_columns.find(t=>t.id===i);h&&(this._physicalSel={kind:e,id:i},this._physicalDrag={pid:t.pointerId,kind:e,id:i,start:this._svgPoint(t),startClient:[t.clientX,t.clientY],before:this._geometrySnapshot(),moved:!1,base:JSON.parse(JSON.stringify(h)),delta:[0,0]})}_clampPhysicalDelta(t,e,i){const s="partition"===t?[e.a,e.b]:[e.center],n=s.map(t=>t[0]),o=s.map(t=>t[1]);return[Math.max(-Mh*sv-Math.min(...n),Math.min(Mh*sv-Math.max(...n),i[0])),Math.max(-Mh*sv-Math.min(...o),Math.min(Mh*sv-Math.max(...o),i[1]))]}_physicalMove(t){const e=this._physicalDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._svgPoint(t),s="partition"===e.kind?e.base.a:e.base.center,n=this._snap([s[0]+i[0]-e.start[0],s[1]+i[1]-e.start[1]]),o=this._clampPhysicalDelta(e.kind,e.base,[n[0]-s[0],n[1]-s[1]]);this._physicalDrag={...e,delta:o,moved:e.moved||Math.hypot(t.clientX-e.startClient[0],t.clientY-e.startClient[1])>=5}}_physicalUp(t){const e=this._physicalDrag;if(!e||e.pid!==t.pointerId)return;if(t.stopPropagation(),this._physicalDrag=null,!e.moved)return void this._registerPhysicalTap(e.kind,e.id);const i=this._spaceModel();if(!this._curSpaceCfg||!i)return;const s=this._curSpaceCfg;if("partition"===e.kind){const t=(s.partitions||[]).find(t=>t.id===e.id),i=e.base;if(t){const n={...i,a:[i.a[0]+e.delta[0],i.a[1]+e.delta[1]],b:[i.b[0]+e.delta[0],i.b[1]+e.delta[1]]};t.a=[n.a[0]/sv,n.a[1]/sv],t.b=[n.b[0]/sv,n.b[1]/sv];for(const t of s.openings||[]){if("partition"!==t.host?.kind||t.host.id!==e.id)continue;const i=Sp(t,[n],sv,this._cellCm,this._gridPitch).resolved;i&&Object.assign(t,Ip(t,i,sv))}}}else{const t=(s.wall_columns||[]).find(t=>t.id===e.id),n=e.base,o={...n,center:[n.center[0]+e.delta[0],n.center[1]+e.delta[1]]};if(i.wall_columns.some(t=>t.id!==e.id&&uh(t,o,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"));t&&(t.center=[(n.center[0]+e.delta[0])/sv,(n.center[1]+e.delta[1])/sv])}this._commitPhysicalGeometry(this._t("history.physical_move"),e.before)}_registerPhysicalTap(t,e,i){const s=performance.now(),n=this._physicalLastTap?.kind===t&&this._physicalLastTap.id===e&&this._physicalLastTap.segment===i&&s-this._physicalLastTap.at<=360;this._physicalLastTap={kind:t,id:e,segment:i,at:s},n&&(this._physicalLastTap=null,this._openPhysicalDialog(t,e,i))}_cancelPhysicalGesture(){this._physicalDrag=null,this._physicalRotate=null,this.requestUpdate()}_physicalRotateDown(t,e){if("square"!==e.shape||!this._spaceModel())return;t.preventDefault(),t.stopPropagation(),dv(t);const i=this._svgPoint(t);this._physicalSel={kind:"column",id:e.id},this._physicalRotate={pid:t.pointerId,id:e.id,center:[...e.center],startAngle:180*Math.atan2(i[1]-e.center[1],i[0]-e.center[0])/Math.PI,baseAngle:Vc(e.angle),angle:Vc(e.angle),before:this._geometrySnapshot(),moved:!1}}_physicalRotateMove(t){const e=this._physicalRotate;if(!e||e.pid!==t.pointerId)return;t.preventDefault(),t.stopPropagation();const i=this._svgPoint(t),s=180*Math.atan2(i[1]-e.center[1],i[0]-e.center[0])/Math.PI,n=e.baseAngle+s-e.startAngle,o=Vc(t.shiftKey?n:5*Math.round(n/5));this._physicalRotate={...e,angle:o,moved:e.moved||Math.abs(n-e.baseAngle)>=.5}}_physicalRotateUp(t){const e=this._physicalRotate;if(!e||e.pid!==t.pointerId)return;t.preventDefault(),t.stopPropagation(),this._physicalRotate=null;const i=this._spaceModel();if(!e.moved||!this._curSpaceCfg||!i)return;const s=i.wall_columns.find(t=>t.id===e.id);if(!s||"square"!==s.shape)return;const n={...s,angle:e.angle};if(i.wall_columns.some(t=>t.id!==e.id&&uh(t,n,.02*this._gridPitch)))return void this._showToast(this._t("toast.column_duplicate"));const o=this._curSpaceCfg.wall_columns?.find(t=>t.id===e.id);o&&(o.angle=e.angle,this._commitPhysicalGeometry(this._t("history.physical_edit"),e.before))}_rszRooms(){const t=[],e=this._spaceModel();if(!e)return t;for(const i of e.rooms){const e=i.id?hi(i):null;e&&t.push({id:i.id,poly:e,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0})}return i=t,s=Math.max(1e-12,1e-12*this._gridPitch),i.map(t=>{if(!Array.isArray(t.wall_ids)||t.wall_ids.length!==t.poly.length)return{...t,poly:t.poly.map(t=>[...t])};const e=t.poly.map(t=>[...t]);let i=!0;for(;i&&e.length>3;){i=!1;for(let t=0;t0){e.splice(t,1),i=!0;break}}}return{...t,poly:e}});var i,s}_rszOpenings(){return this._openingsR.map(t=>({id:t.id,x:t.rx,y:t.ry,length:t.rlen,hosted:!!t.host,angle:t.angle,type:t.type}))}_rszObstacles(){const t=this._spaceModel();if(!t)return[];const e=[];for(const i of t.partitions||[])e.push({kind:"segment",a:[...i.a],b:[...i.b],half:gl(i.cm,this._cellCm,this._gridPitch)/2});for(const i of t.room_drafts||[])for(let t=0;t+1Array.isArray(t.a)&&Array.isArray(t.b)&&t.a.length>=2&&t.b.length>=2).map(t=>({wall:t,a:[t.a[0]*sv,t.a[1]*this._spaceH],b:[t.b[0]*sv,t.b[1]*this._spaceH]})),n=Math.abs(t[0]-e[0])<=.05*this._gridPitch?"v":Math.abs(t[1]-e[1])<=.05*this._gridPitch?"h":null,o=s.filter(i=>!!n&&("h"===n?!(Math.abs(i.a[1]-t[1])>.05*this._gridPitch||Math.abs(i.b[1]-t[1])>.05*this._gridPitch)&&Math.min(Math.max(t[0],e[0]),Math.max(i.a[0],i.b[0]))-Math.max(Math.min(t[0],e[0]),Math.min(i.a[0],i.b[0]))>.05*this._gridPitch:!(Math.abs(i.a[0]-t[0])>.05*this._gridPitch||Math.abs(i.b[0]-t[0])>.05*this._gridPitch)&&Math.min(Math.max(t[1],e[1]),Math.max(i.a[1],i.b[1]))-Math.max(Math.min(t[1],e[1]),Math.min(i.a[1],i.b[1]))>.05*this._gridPitch)),a=new Set(o.map(t=>Number(t.wall.cm)).filter(t=>t>0));return{minDim:this._cmToUnits(30),eps:.05*this._gridPitch,step:this._gridPitch,movingHalf:i>0?gl(i,this._cellCm,this._gridPitch)/2:0,obstacles:this._rszObstacles(),thicknessConflict:a.size>1}}_rszResolution(t,e,i){const s=this._rszDrag?.snap||i||this._rszSnapshot(),n=`${this._space}|${this._cellCm}|${this._gridPitch}|${s}`;this._rszEligibilityCache&&this._rszEligibilityCache.key===n||(this._rszEligibilityCache={key:n,values:new Map});const o=`${t}:${e}`,a=this._rszEligibilityCache.values.get(o);if(a)return a;const r=this._rszDrag?.rooms||this._rszRooms(),l=r.find(e=>e.id===t),c=l?.poly?.[e]||[0,0],h=l?.poly?.[(e+1)%(l?.poly?.length||1)]||[0,0],d=function(t,e,i,s,n){const{eps:o}=n,a=t.find(t=>t.id===i);if(!a||s<0||s>=(a.poly?.length||0)||a.poly.length<4||!Ia(a.poly))return{enabled:!1,reason:"invalid-geometry"};const r=a.poly[s],l=a.poly[(s+1)%a.poly.length],c=Ea(r,l,o);if(!c)return{enabled:!1,reason:"diagonal"};if(!Ha(a.poly,s,c,o))return{enabled:!1,reason:"side-angle"};if(n.thicknessConflict)return{enabled:!1,reason:"thickness-conflict"};for(const t of n.obstacles||[])if(Wa(t,r,l,n))return{enabled:!1,reason:"duplicate-physical-wall"};const h=Da(Sa(l,r)),d=[],p=new Set;let u=!1,_=!1;for(const e of t)if(e.id!==i)for(let t=0;t1||d.length>1)return{enabled:!1,reason:"multiple-rooms"};const m={[i]:s},g=[i];if(1===d.length){const t=d[0];if(!Ia(t.room.poly))return{enabled:!1,reason:"invalid-geometry"};if(!Ha(t.room.poly,t.edge,c,o))return{enabled:!1,reason:"side-angle"};g.push(t.room.id),m[t.room.id]=t.edge}const f=[];for(const t of e)if(!(Ta([t.x,t.y],r,l)>2*o)){if(t.hosted||t.length>h+2*o)return{enabled:!1,reason:"opening-conflict"};f.push(t.id)}const v=Object.fromEntries(g.map(e=>[e,t.find(t=>t.id===e).poly.length])),y=[];for(const e of g){const i=t.find(t=>t.id===e),s=m[e],n=(s-1+i.poly.length)%i.poly.length,a=(s+1)%i.poly.length,r=Ga(t,e,n,1,o),l=Ga(t,e,a,0,o);if(!r||!l)return{enabled:!1,reason:"partial-shared"};y.push(r,l)}const b={roomId:i,edge:s,a:[...r],b:[...l],n:Ra(a.poly,s),roomIds:g,edgeByRoom:m,topology:v,movingOpeningIds:f,sideOwnership:y};if(!Qa(t,e,b,0,n))return{enabled:!1,reason:"invalid-geometry"};const w=Math.abs(Number(n.step));if(Number.isFinite(w)&&w>o){const i=[-w,w];if(!i.some(i=>Qa(t,e,b,i,n))){if(!i.some(i=>Ya(Ja(t,e,b,i),b,o)))return{enabled:!1,reason:"partial-shared"};const s={...n,obstacles:[]};return i.some(i=>Qa(t,e,b,i,s))?{enabled:!1,reason:"duplicate-physical-wall"}:e.length&&i.some(e=>Qa(t,[],b,e,n))?{enabled:!1,reason:"opening-conflict"}:{enabled:!1,reason:"invalid-geometry"}}}return{enabled:!0,plan:b}}(r,this._rszDrag?.openings||this._rszOpenings(),t,e,this._rszOptsFor(c,h));return this._rszEligibilityCache.values.set(o,d),d}_rszSnapshot(){return JSON.stringify(this._geometrySnapshot()||{spaceId:this._space,rooms:[],openings:[],walls:[],open_spans:[]})}_rszApplyPreview(t,e){const i=this._rszDrag,s=this._serverCfg?.spaces.find(t=>t.id===this._space);if(!i||!s||!this._serverCfg)return{ok:!1,reason:"missing-context"};const n=JSON.parse(i.snap),o={...s,rooms:n.rooms,openings:n.openings||[]};for(const t of["walls","wall_segments","open_spans","room_drafts","partitions","wall_columns","decor"])void 0!==n[t]?o[t]=n[t]:delete o[t];for(const t of["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"])void 0!==n.plan_transform?.[t]?o[t]=n.plan_transform[t]:delete o[t];const a=this._spaceH;for(const[e,i]of Object.entries(t)){const t=o.rooms.find(t=>t.id===e);t&&(t.poly=i.map(t=>[t[0]/sv,t[1]/a]),delete t.x,delete t.y,delete t.w,delete t.h)}for(const[t,i]of Object.entries(e)){const e=(o.openings||[]).find(e=>e.id===t);e&&(e.x=i[0]/sv,e.y=i[1]/a)}const r=[],l=[];for(const t of i.changed){const e=i.rooms.find(e=>e.id===t),s=o.rooms.find(e=>e.id===t);if(!e||!s?.poly)continue;const n=s.poly.map(t=>[t[0]*sv,t[1]*a]);if(e.poly.length!==n.length)continue;const c=Array.isArray(e.wall_ids)?e.wall_ids:[];for(let t=0;tt.id===i):null;s&&(s.a=[n[t][0]/sv,n[t][1]/sv],s.b=[n[(t+1)%n.length][0]/sv,n[(t+1)%n.length][1]/sv])}}if(r.length&&Array.isArray(o.walls)&&o.walls.length){const t=function(t,e,i,s,n=1,o="fixed-topology"){let a=!1;const r=Il(t,e,i,s,n,o,()=>{a=!0});return{walls:a?(t||[]).map(t=>({...t})):r,rejected:a}}(o.walls,r,l,this._wallKeyPitch,sv,"fixed-topology");if(t.rejected)return{ok:!1,reason:"wall-metadata"};o.walls=t.walls}const c=t=>t.map(t=>Number(t.cm)).sort((t,e)=>t-e),h=c(n.walls||[]),d=c(o.walls||[]);if(JSON.stringify(h)!==JSON.stringify(d))return{ok:!1,reason:"wall-metadata"};const p=[];for(const t of o.rooms||[]){const e=hi(t);if(e&&!(e.length<2))for(let t=0;tJSON.stringify([t?.key,t?.cm,t?.a,t?.b]),_=new Map;for(const t of n.walls||[]){const e=u(t);_.set(e,(_.get(e)||0)+1)}const m=[];for(const t of o.walls||[]){const e=u(t),i=_.get(e)||0;i?_.set(e,i-1):m.push(t)}if(zl(m,p,this._wallKeyPitch,sv,n.walls||[]).length)return{ok:!1,reason:"wall-metadata"};const g=this._rszSpaceCandidateGeometry(this._space,o);if(!g.ok)return{ok:!1,reason:"physical-geometry"};if(this._rszPreview={space:this._space,sp:o},this._cfgEpoch++,g.wallGeometry){const t=Ac(g.wallGeometry);if(t){const e=`${this._space}|${this._cfgEpoch}|${o.rooms.length}`,i={key:e,value:t};Uf(this._wallUnionPool,e,i,8),this._wallUnionCache=i}}return{ok:!0}}_rszSpaceCandidateGeometry(t,e){if(!this._serverCfg)return{ok:!1,wallGeometry:null};const i={...this._serverCfg,spaces:this._serverCfg.spaces.map(i=>i.id===t?e:i)};let s=null;try{return{ok:this._checkSpacePhysicalGeometry(i,t,t=>{s=t}).ok,wallGeometry:s}}catch{return{ok:!1,wallGeometry:null}}}_rszSpaceCandidateRenderable(t,e){if(!this._serverCfg)return!1;try{const i={...this._serverCfg,spaces:this._serverCfg.spaces.map(i=>i.id===t?e:i)};return this._checkSpacePhysicalGeometry(i,t).ok}catch{return!1}}_rszCandidateRenderable(t){return!!t&&t.space===this._space&&this._rszPreview===t&&this._rszSpaceCandidateRenderable(t.space,t.sp)}_rszEdgeDown(t,e,i){if("resize"!==this._tool||this._rszDrag)return;t.stopPropagation(),t.preventDefault();const s=this._rszRooms(),n=this._rszResolution(e,i);if(!n.enabled)return void this._showToast(this._rszReasonText(n.reason));dv(t);const o=n.plan,a=this._svgPoint(t);this._rszDrag={pid:t.pointerId,start:[a[0],a[1]],roomId:e,plan:o,opts:this._rszOptsFor(o.a,o.b),rooms:s,openings:this._rszOpenings(),snap:this._rszSnapshot(),moved:!1,d:0,changed:[...o.roomIds],rejectNotified:!1}}_rszReasonText(t){return this._t(`resize.disabled.${t}`)}_rszDisabledActivate(t,e){t.stopPropagation(),t.preventDefault(),this._showToast(this._rszReasonText(e))}_rszDisabledKey(t,e){"Enter"!==t.key&&" "!==t.key||this._rszDisabledActivate(t,e)}_rszMove(t){const e=this._rszDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._svgPoint(t),s=e.plan,n=(o=e.start,a=i,r=s.n,[o?.[0],o?.[1],a?.[0],a?.[1],r?.[0],r?.[1]].every(Number.isFinite)?(a[0]-o[0])*r[0]+(a[1]-o[1])*r[1]:0);var o,a,r;const l=this._snap([s.a[0]+s.n[0]*n,s.a[1]+s.n[1]*n]),c=(l[0]-s.a[0])*s.n[0]+(l[1]-s.a[1])*s.n[1];let h=function(t,e,i,s,n,o){if(!Number.isFinite(s)||Math.abs(s)<1e-9)return 0;const a=Math.sign(s),r=Math.abs(s),l=Math.max(Math.abs(n),1e-6);let c=tr.get(i);c&&c.opts===o||(c={opts:o,values:new Map},tr.set(i,c));const h=c.values;let d=0;for(let s=Math.min(l,r),n=0;n<4096&&s<=r+1e-9;n++,s=Math.min(r,s+l)){const n=a*s,c=`${n.toFixed(9)}|${l.toFixed(9)}`;let p=h.get(c);if(void 0===p&&(p=Qa(t,e,i,n,o),h.size<4096&&h.set(c,p)),!p)break;if(d=n,Math.abs(s-r)<=1e-9)break}return d}(e.rooms,e.openings,s,c,this._gridPitch,e.opts);if(h===e.d&&e.moved)return;const d=this._rszPreview,p=this._rszLive,u=e.d;let _=Ja(e.rooms,e.openings,s,h);if(!this._rszApplyPreview(_.polys,_.openings).ok)return this._rszPreview=d,this._rszLive=p,e.d=u,e.rejectNotified||(e.rejectNotified=!0,this._showToast(this._t("resize.preview_failed"))),void this.requestUpdate();e.moved=!0,e.changed=[...s.roomIds],e.d=h,this._rszLive=this._rszEdgeLabels(_,s),this.requestUpdate()}_rszUp(t){const e=this._rszDrag;if(!e||e.pid!==t.pointerId)return;t.stopPropagation();const i=this._rszPreview,s=e.moved&&Math.abs(e.d)>1e-9,n=this._rszSnapshot()===e.snap,o=Qa(e.rooms,e.openings,e.plan,e.d,e.opts),a=this._rszCandidateRenderable(i);if(this._rszDrag=null,this._rszLive=null,this._rszPreview=null,!s||!i)return this._cfgEpoch++,void this.requestUpdate();if(!n||!o||!a)return this._cfgEpoch++,this._showToast(this._t("resize.commit_failed")),void this.requestUpdate();const r=JSON.parse(e.snap),l=this._curSpaceCfg;l&&(l.rooms=i.sp.rooms,l.openings=i.sp.openings,Array.isArray(i.sp.walls)&&(i.sp.walls.length?l.walls=i.sp.walls:delete l.walls),Array.isArray(i.sp.wall_segments)&&(l.wall_segments=i.sp.wall_segments)),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._commitPhysicalGeometry(this._t("history.resize_room"),r),this._rszEligibilityCache=null,this.requestUpdate()}_rszCancelDrag(){this._rszDrag&&(this._rszDrag=null,this._rszLive=null,this._rszPreview=null,this._cfgEpoch++,this.requestUpdate())}_rszPointerCancel(t){const e=this._rszDrag;e&&e.pid===t.pointerId&&(t.stopPropagation(),this._rszCancelDrag())}_rszEdgeLabels(t,e){const i=this._rszDrag,s=[],n=t.polys[e.roomId]||i.rooms.find(t=>t.id===e.roomId).poly,o=n.length,a=this._rszInnerSpanCms(e.roomId,n,t.polys);for(const t of function(t,e){const i=t.length;return[(e-1+i)%i,(e+1)%i]}(n,e.edge)){const e=n[t],i=n[(t+1)%o],r=a?.[t];s.push({kind:"length",x:(e[0]+i[0])/2,y:(e[1]+i[1])/2,text:null==r?this._fmtLen(e,i):li(r,"mi"===this.hass?.config?.unit_system?.length),edge:{a:[e[0],e[1]],b:[i[0],i[1]]}})}const r="mi"===this.hass?.config?.unit_system?.length,l=e.roomIds,c=this._spaceWalls,h=this._physicalBodiesR(),d=this._baseVb(),p=this._view&&this._view.w>0&&this._view.h>0?this._view:{x:d[0],y:d[1],w:d[2],h:d[3]},[u,_]=this._lastValidStageSize||[p.w,p.h],m={...p,stageWidth:Math.max(1,u),stageHeight:Math.max(1,_)},g=this._spaceModel(),f=this._config?.icon_size??2.5,v=g?Vh(f>8?2.5:f,g,p.w,this._kiosk?this._kioskScale.icon:1)*m.stageWidth/100:24,y=Math.max(10,.77*v),b=this._t("room.settings_short"),w=y*(1.457+.66*Math.max(1,b.length)*.42);for(const n of l){const o=t.polys[n]||i.rooms.find(t=>t.id===n).poly,a=c.length&&g&&this._innerRoomContour(g,n)||o,l=ir(h.length?lh(rh(a,h))*Math.pow(this._cellCm/this._gridPitch,2)/1e4:er(a,this._gridPitch,this._cellCm),r),d=nr({poly:o,edge:e.edgeByRoom[n],text:l,view:m,gearCenter:$i(o),gearWidthPx:w,gearHeightPx:y});s.push({kind:"area",roomId:n,x:d.anchor[0],y:d.anchor[1],text:l,placement:d})}return s}_rszInnerSpanCms(t,e,i){const s=Object.keys(i).length?Object.entries(i).map(([t,e])=>({id:t,poly:e})):this._spaceModel()?.rooms;if(!s?.length)return null;const n=this._spaceWalls;if(!n.length)return null;const o=function(t,e,i,s,n,o,a,r=1){const l=(t||[]).find(t=>t?.id===e),c=hi(l);if(!c||c.length<3)return null;const h=hc(t,e,i,s,n,o,a,r);if(!h)return c.map(()=>0);const d=4*Vl(n,r);return c.map((t,e)=>{const i=c[(e+1)%c.length],s=[(t[0]+i[0])/2,(t[1]+i[1])/2];for(let t=0;tfunction(t,e,i){const s=t?.length||0;if(s<3||!Array.isArray(i)||i.length!==s)return 0;const n=(Math.trunc(e)%s+s)%s,o=t[n],a=t[(n+1)%s],r=a[0]-o[0],l=a[1]-o[1],c=Math.hypot(r,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[n])||0);if(!(h>0))return c;const d=[r/c,l/c],p=Yl(t,n),u=[o[0]+p[0]*h,o[1]+p[1]*h],_=e=>{const n=Math.max(0,Number(i[e])||0);if(!(n>0))return null;const a=t[e],r=t[(e+1)%s],l=r[0]-a[0],c=r[1]-a[1],h=Math.hypot(l,c);if(!(h>0))return null;const p=Yl(t,e),_=Xl(u,d,[a[0]+p[0]*n,a[1]+p[1]*n],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((n-1+s)%s)??0,g=(_((n+1)%s)??c)-m;return g>0?g:0}(e,i,o)*a)}_renderResizeMeasurements(){if(!this._rszLive?.length)return G;const t=this._rszLive.filter(t=>"length"===t.kind),e=this._rszLive.filter(t=>"area"===t.kind);return j`
`}get _glowRadiusCm(){const t=Number(this._settings.glow_radius_cm);return Number.isFinite(t)&&t>0?t:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const t=this._glowRadiusCm;return this._imperial?String(Math.round(t/30.48*10)/10):String(t/100)}_glowTransition(t,e){let i=this._glowRenderedSources.get(t);if(e){const e=this._glowFadeTimers.get(t);if(null!=e&&(clearTimeout(e),this._glowFadeTimers.delete(t)),null==i){this._suspendGlowFeatherForTransition(),i=++this._glowSourceSeq,this._glowRenderedSources.set(t,i),this._glowEnteringSources.add(t);const e=requestAnimationFrame(()=>{this._glowEnterRafs.get(t)===e&&(this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),this.isConnected&&this.requestUpdate())});this._glowEnterRafs.set(t,e)}return{domId:i,entering:this._glowEnteringSources.has(t),leaving:!1}}if(null==i)return null;const s=this._glowEnterRafs.get(t);if(null!=s&&cancelAnimationFrame(s),this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),!this._glowFadeTimers.has(t)){this._suspendGlowFeatherForTransition();const e=window.setTimeout(()=>{this._glowFadeTimers.get(t)===e&&(this._glowFadeTimers.delete(t),this._glowRenderedSources.delete(t),this._glowLastAppearance.delete(t),this.isConnected&&this.requestUpdate())},534);this._glowFadeTimers.set(t,e)}return{domId:i,entering:!1,leaving:!0}}_suspendGlowFeatherForTransition(){if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;this._glowFeatherSuspendUntil=Math.max(this._glowFeatherSuspendUntil,Date.now()+500),clearTimeout(this._glowFeatherResumeTimer);const t=Math.max(0,this._glowFeatherSuspendUntil-Date.now())+17,e=()=>{this._glowFeatherResumeTimer=0,Date.now()=128){const t=this._glowGeometryWarnings.values().next().value;t&&this._glowGeometryWarnings.delete(t)}this._glowGeometryWarnings.add(n),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${i}, phase ${s}`)}}_lightBarriers(t,e){const i=this._zeroWalls(),s=this._openCuts(),n=[...i.transmissive],o=Math.max(this._cmToUnits(10),.5*this._gridPitch),a=t=>e.some(e=>this._pointInRoom(t,e.r)),r=this._openingsR.filter(t=>{if("door"!==(e=String(t.type))&&"gate"!==e&&"passage"!==e)return!1;var e;const i=t.angle*Math.PI/180,s=-Math.sin(i),n=Math.cos(i);return a([t.rx+s*o,t.ry+n*o])&&a([t.rx-s*o,t.ry-n*o])}),l=this._roomWallOpeningInputs(r,t);for(const t of l){const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,s=Math.sin(e)*t.length/2;n.push([t.x-i,t.y-s,t.x+i,t.y+s])}const c=new Set(r.filter(t=>t.partitionHost).map(t=>t.id)),h=[t.id,this._cfgEpoch,this._cellCm,this._gridPitch,[...c].sort().join(",")].join("|");this._lightPhysicalBodiesCache?.key!==h&&(this._lightPhysicalBodiesCache={key:h,all:ih(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t,t=>c.has(t.id))).all});const d=this._lightPhysicalBodiesCache.all;let p=2166136261;const u=t=>{p^=Math.round(64*(Number.isFinite(t)?t:0)),p=Math.imul(p,16777619)>>>0},_=this._spaceWalls;u(this._cellCm),u(this._gridPitch),u(this._wallKeyPitch);for(const{poly:t}of e){u(t.length);for(const e of t)u(e[0]),u(e[1])}for(const t of n)for(const e of t)u(e);u("solid"===i.style?1:0);for(const t of i.barriers)for(const e of t)u(e);for(const t of d){u(t.length);for(const e of t)u(e[0]),u(e[1])}for(const t of _)u(t.cm),u(t.a?.[0]??0),u(t.a?.[1]??0),u(t.b?.[0]??0),u(t.b?.[1]??0);const m=p.toString(36),g=`${t.id}|${m}`;if(this._lightBarrierCache?.key===g)return this._lightBarrierCache.value;const f=.02*this._gridPitch,v=[],y=_.length||d.length?Rc(t.rooms,_,s,l,this._wallKeyPitch,this._cellCm,this._gridPitch,sv,d):null;if(!y||"ok"!==y.status&&"degraded-extra"!==y.status)for(const t of d)v.push(...Fu(t));else for(const t of y.components)for(const e of ch(t.geom))v.push(...Fu(e));for(const{poly:t}of e)for(const e of n.length?Ps(t,n,f):Fu(t))v.push(e);for(const t of i.barriers)v.push(t);const b={occluders:zu(v),floor:e.map(t=>t.poly),fingerprint:m,masonryGeometry:!y||"ok"!==y.status&&"degraded-extra"!==y.status?[]:y.components.flatMap(t=>t.geom),opaqueBodies:d};return this._lightBarrierCache={key:g,value:b},b}_renderGlowLayer(t,e){const i=this._fillColors,s=this._glowRadiusCm/this._cellCm*this._gridPitch,n=t.rooms.map(t=>({r:t,poly:hi(t)})).filter(t=>!!t.poly),o=n.filter(({r:t})=>Fs(e.glow,t));if(!o.length)return this._forgetGlowSpace(t.id),j``;const{occluders:a,floor:r,fingerprint:l,masonryGeometry:c,opaqueBodies:h}=this._lightBarriers(t,n),d=ho(this._renderPlanHass,this._renderDevices,null,this._virtualLights).filter(e=>e.device.space===t.id),p=new Map;for(const t of d){if(!t.device.id)continue;const e=p.get(t.device.id)||[];e.push(t),p.set(t.device.id,e)}const u=[],_=new Set;for(const e of this._renderDevices){if(e.space!==t.id)continue;const o=po(p.get(e.id)||[]);if(!o)continue;const d=`${t.id}|${e.id}`;_.add(d);const m=$s(o.passive?{state:o.on?"on":"off",attributes:{}}:this._renderPlanHass.states[o.eid],e.marker?.glow_color,i.glow_light.c),g=Number(e.marker?.glow_radius_cm),f=Number.isFinite(g)&&g>0?g/this._cellCm*this._gridPitch:s,v=this._pos(e);if(ph([v.x,v.y],c,h)){this._forgetGlowSource(d);continue}const y=this._glowTransition(d,!!m);if(!y)continue;m&&this._glowLastAppearance.set(d,{c:m.c,alpha:Ss(m.bri,i.glow_light.a)});const b=this._glowLastAppearance.get(d);if(!b)continue;let w=null;const k=`${t.id}|${l}|${v.x.toFixed(4)},${v.y.toFixed(4)}|${f.toFixed(4)}`,x=jf(this._glowClipCache,k);if(x.hit)w=x.value;else{const e=Ou([v.x,v.y],f,a,96);w={lit:e.length>=3?ah([e],r,{onBoundsFailure:({boundIndex:e,phase:i})=>{const s=n[e]?.r;this._warnGlowGeometryFallback(t.id,l,s?.id||`#${e}`,i)}}):[]},Uf(this._glowClipCache,k,w,256)}u.push({key:d,sourceEid:o.eid,domId:y.domId,entering:y.entering,leaving:y.leaving,pos:v,c:b.c,alpha:b.alpha,geometry:w,r:f})}const m=`${t.id}|`;for(const t of this._glowRenderedSources.keys())t.startsWith(m)&&!_.has(t)&&this._forgetGlowSource(t);if(!u.length)return j``;const g=this._spaceWalls,f=o.length===n.length?[]:this._openCuts(),v=this._wallUnionGeometry()?.roomGeom,y=o.length===n.length?null:o.map(({r:e,poly:i})=>{const s=g.length&&e.id&&this._innerRoomContour(t,e.id,f,v)||i,o=this._cleanFloor(e,s,t).path,a=Pi(s,n.filter(t=>t.r!==e).map(t=>t.poly)),r=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z";return[o||r(s),...a.map(r)].join(" ")}),b=this._viewOr(this._baseVb()),w=this._stageEl?.clientWidth&&b.w?this._stageEl.clientWidth/b.w:1,k=1/(w>0?w:1),x=!this._pinchStart&&!this._panStart&&Date.now()>=this._glowFeatherSuspendUntil;(null==this._glowFeatherUnits||x)&&(this._glowFeatherUnits=k);const $=this._glowFeatherUnits??k,S=4*$,M=u.reduce((t,e)=>({x:Math.min(t.x,e.pos.x-e.r-S),y:Math.min(t.y,e.pos.y-e.r-S),maxX:Math.max(t.maxX,e.pos.x+e.r+S),maxY:Math.max(t.maxY,e.pos.y+e.r+S),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});return M.w=M.maxX-M.x,M.h=M.maxY-M.y,j` +
`}get _glowRadiusCm(){const t=Number(this._settings.glow_radius_cm);return Number.isFinite(t)&&t>0?t:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const t=this._glowRadiusCm;return this._imperial?String(Math.round(t/30.48*10)/10):String(t/100)}_glowTransition(t,e){let i=this._glowRenderedSources.get(t);if(e){const e=this._glowFadeTimers.get(t);if(null!=e&&(clearTimeout(e),this._glowFadeTimers.delete(t)),null==i){this._suspendGlowFeatherForTransition(),i=++this._glowSourceSeq,this._glowRenderedSources.set(t,i),this._glowEnteringSources.add(t);const e=requestAnimationFrame(()=>{this._glowEnterRafs.get(t)===e&&(this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),this.isConnected&&this.requestUpdate())});this._glowEnterRafs.set(t,e)}return{domId:i,entering:this._glowEnteringSources.has(t),leaving:!1}}if(null==i)return null;const s=this._glowEnterRafs.get(t);if(null!=s&&cancelAnimationFrame(s),this._glowEnterRafs.delete(t),this._glowEnteringSources.delete(t),!this._glowFadeTimers.has(t)){this._suspendGlowFeatherForTransition();const e=window.setTimeout(()=>{this._glowFadeTimers.get(t)===e&&(this._glowFadeTimers.delete(t),this._glowRenderedSources.delete(t),this._glowLastAppearance.delete(t),this.isConnected&&this.requestUpdate())},534);this._glowFadeTimers.set(t,e)}return{domId:i,entering:!1,leaving:!0}}_suspendGlowFeatherForTransition(){if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;this._glowFeatherSuspendUntil=Math.max(this._glowFeatherSuspendUntil,Date.now()+500),clearTimeout(this._glowFeatherResumeTimer);const t=Math.max(0,this._glowFeatherSuspendUntil-Date.now())+17,e=()=>{this._glowFeatherResumeTimer=0,Date.now()=128){const t=this._glowGeometryWarnings.values().next().value;t&&this._glowGeometryWarnings.delete(t)}this._glowGeometryWarnings.add(n),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${i}, phase ${s}`)}}_lightBarriers(t,e){const i=wd([this._curSpaceCfg,this._cellCm,this._gridPitch]),s=`${t.id}|${i}`,n=jf(this._lightBarrierPool,s);if(n.hit)return this._lightBarrierCache=n.value,n.value.value;const o=this._zeroWalls(),a=this._openCuts(),r=[...o.transmissive],l=Math.max(this._cmToUnits(10),.5*this._gridPitch),c=t=>e.some(e=>this._pointInRoom(t,e.r)),h=this._openingsR.filter(t=>{if("door"!==(e=String(t.type))&&"gate"!==e&&"passage"!==e)return!1;var e;const i=t.angle*Math.PI/180,s=-Math.sin(i),n=Math.cos(i);return c([t.rx+s*l,t.ry+n*l])&&c([t.rx-s*l,t.ry-n*l])}),d=this._roomWallOpeningInputs(h,t);for(const t of d){const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,s=Math.sin(e)*t.length/2;r.push([t.x-i,t.y-s,t.x+i,t.y+s])}const p=new Set(h.filter(t=>t.partitionHost).map(t=>t.id)),u=[t.id,this._cfgEpoch,this._cellCm,this._gridPitch,[...p].sort().join(",")].join("|");this._lightPhysicalBodiesCache?.key!==u&&(this._lightPhysicalBodiesCache={key:u,all:ih(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t,t=>p.has(t.id))).all});const _=this._lightPhysicalBodiesCache.all,m=this._spaceWalls,g=.02*this._gridPitch,f=[],v=this._wallUnionGeometry(),y=v?.sourceFingerprint,b=v&&y===i?function(t,e=[],i=[],s={}){if("failed-core"===t.status||"not-applicable"===t.status)return null;const n=t.roomComponents?.length?t.roomComponents:yc(t.roomGeom)?[{id:"room-primary",geom:t.roomGeom}]:[];let o=n[0]?.geom||null;const a=n.slice(1).map(t=>({...t}));try{for(const i of e){if(!(i.length>0&&t.openingIndex))continue;const e=Lc(t.openingIndex,i,!0);if(!e.negative&&!e.positive)continue;const s=i.angle*Math.PI/180,n=Math.cos(s),r=Math.sin(s),l=-r,c=n,h=i.length/2,d=t.openingPadUnits??1.25*Math.max(t.depthUnits,1),p=vc([[i.x-n*h-l*d,i.y-r*h-c*d],[i.x+n*h-l*d,i.y+r*h-c*d],[i.x+n*h+l*d,i.y+r*h+c*d],[i.x-n*h+l*d,i.y-r*h+c*d]]);o&&(o=oi(o,p));for(const t of a)t.geom=oi(t.geom,p)}const n=[...a];let r=a.length;const l=s.mergeExtra||((t,e)=>t?si(t,e):e);for(let t=0;tt.length>=2&&Number.isFinite(t[0])&&Number.isFinite(t[1]))||Math.abs(Ti(e))<=1e-9){r++;continue}const s=[vc(e)];try{const e=l(o,s,t);if(!yc(e))throw new Error("invalid extra union");o=e}catch{r++,yc(s)&&n.push({id:`policy-extra-${t}`,geom:s})}}n.sort((t,e)=>Tc(t.geom).localeCompare(Tc(e.geom)));const c=o||[];return{status:r?"degraded-extra":"ok",geom:c,components:[...yc(c)?[{id:"primary",geom:c}]:[],...n.map((t,e)=>({...t,id:`isolated-${e}`}))]}}catch{return null}}(v,d,_):null,w=b||(m.length||_.length?Rc(t.rooms,m,a,d,this._wallKeyPitch,this._cellCm,this._gridPitch,sv,_):null);if(!w||"ok"!==w.status&&"degraded-extra"!==w.status)for(const t of _)f.push(...Fu(t));else for(const t of w.components)for(const e of ch(t.geom))f.push(...Fu(e));for(const{poly:t}of e)for(const e of r.length?Ps(t,r,g):Fu(t))f.push(e);for(const t of o.barriers)f.push(t);const k={occluders:zu(f),floor:e.map(t=>t.poly),fingerprint:i,masonryGeometry:!w||"ok"!==w.status&&"degraded-extra"!==w.status?[]:w.components.flatMap(t=>t.geom),opaqueBodies:_},x={key:s,value:k};return Uf(this._lightBarrierPool,s,x,8),this._lightBarrierCache=x,k}_renderGlowLayer(t,e){const i=this._fillColors,s=this._glowRadiusCm/this._cellCm*this._gridPitch,n=t.rooms.map(t=>({r:t,poly:hi(t)})).filter(t=>!!t.poly),o=n.filter(({r:t})=>Fs(e.glow,t));if(!o.length)return this._forgetGlowSpace(t.id),j``;const{occluders:a,floor:r,fingerprint:l,masonryGeometry:c,opaqueBodies:h}=this._lightBarriers(t,n),d=ho(this._renderPlanHass,this._renderDevices,null,this._virtualLights).filter(e=>e.device.space===t.id),p=new Map;for(const t of d){if(!t.device.id)continue;const e=p.get(t.device.id)||[];e.push(t),p.set(t.device.id,e)}const u=[],_=new Set;for(const e of this._renderDevices){if(e.space!==t.id)continue;const o=po(p.get(e.id)||[]);if(!o)continue;const d=`${t.id}|${e.id}`;_.add(d);const m=$s(o.passive?{state:o.on?"on":"off",attributes:{}}:this._renderPlanHass.states[o.eid],e.marker?.glow_color,i.glow_light.c),g=Number(e.marker?.glow_radius_cm),f=Number.isFinite(g)&&g>0?g/this._cellCm*this._gridPitch:s,v=this._pos(e);if(ph([v.x,v.y],c,h)){this._forgetGlowSource(d);continue}const y=this._glowTransition(d,!!m);if(!y)continue;m&&this._glowLastAppearance.set(d,{c:m.c,alpha:Ss(m.bri,i.glow_light.a)});const b=this._glowLastAppearance.get(d);if(!b)continue;let w=null;const k=`${t.id}|${l}|${v.x.toFixed(4)},${v.y.toFixed(4)}|${f.toFixed(4)}`,x=jf(this._glowClipCache,k);if(x.hit)w=x.value;else{const e=Ou([v.x,v.y],f,a,96);w={lit:e.length>=3?ah([e],r,{onBoundsFailure:({boundIndex:e,phase:i})=>{const s=n[e]?.r;this._warnGlowGeometryFallback(t.id,l,s?.id||`#${e}`,i)}}):[]},Uf(this._glowClipCache,k,w,256)}u.push({key:d,sourceEid:o.eid,domId:y.domId,entering:y.entering,leaving:y.leaving,pos:v,c:b.c,alpha:b.alpha,geometry:w,r:f})}const m=`${t.id}|`;for(const t of this._glowRenderedSources.keys())t.startsWith(m)&&!_.has(t)&&this._forgetGlowSource(t);if(!u.length)return j``;const g=this._spaceWalls,f=o.length===n.length?[]:this._openCuts(),v=this._wallUnionGeometry()?.roomGeom,y=o.length===n.length?null:o.map(({r:e,poly:i})=>{const s=g.length&&e.id&&this._innerRoomContour(t,e.id,f,v)||i,o=this._cleanFloor(e,s,t).path,a=Pi(s,n.filter(t=>t.r!==e).map(t=>t.poly)),r=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z";return[o||r(s),...a.map(r)].join(" ")}),b=this._viewOr(this._baseVb()),w=this._stageEl?.clientWidth&&b.w?this._stageEl.clientWidth/b.w:1,k=1/(w>0?w:1),x=!this._pinchStart&&!this._panStart&&Date.now()>=this._glowFeatherSuspendUntil;(null==this._glowFeatherUnits||x)&&(this._glowFeatherUnits=k);const $=this._glowFeatherUnits??k,S=4*$,M=u.reduce((t,e)=>({x:Math.min(t.x,e.pos.x-e.r-S),y:Math.min(t.y,e.pos.y-e.r-S),maxX:Math.max(t.maxX,e.pos.x+e.r+S),maxY:Math.max(t.maxY,e.pos.y+e.r+S),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});return M.w=M.maxX-M.x,M.h=M.maxY-M.y,j` ${Mt(u,t=>t.key,t=>{const e=t.domId,i=t.geometry;return j` ${""} >(); /** Freeze the SVG blur while a pinch/pan emits animation frames, then adopt * the final screen-space value after the gesture. */ private _glowFeatherUnits: number | null = null; @@ -8944,6 +8948,10 @@ class HouseplanCard extends LitElement { const projected = wallBodiesGeometryPath(preflight.wallGeometry); if (projected) { const key = `${this._space}|${this._cfgEpoch}|${sp.rooms.length}`; + Object.defineProperty(projected, 'sourceFingerprint', { + value: contentFingerprint([sp, this._cellCm, this._gridPitch]), + enumerable: false, + }); const entry = { key, value: projected }; lruWrite(this._wallUnionPool, key, entry, 8); this._wallUnionCache = entry; @@ -11615,19 +11623,27 @@ class HouseplanCard extends LitElement { const walls = this._spaceWalls; const extras = this._physicalBodiesR(); if (!walls.length && !extras.length) return null; - const openCuts = this._openCuts(); - const openings = this._roomWallOpeningInputs(); const unionKey = `${this._space}|${this._cfgEpoch}|${space.rooms.length}`; if (!this._wallUnionCache || this._wallUnionCache.key !== unionKey) { const cached = lruRead(this._wallUnionPool, unionKey); if (cached.hit) this._wallUnionCache = cached.value; else { + // Opening association and physical-body extraction are structural + // work. Do them only for a real cache miss; this method is intentionally + // called by many room consumers in one render. + const openCuts = this._openCuts(); + const openings = this._roomWallOpeningInputs(); + const value = wallBodiesUnionPath( + space.rooms, walls, openCuts, openings, + this._wallKeyPitch, this._cellCm, this._gridPitch, NORM_W, extras, + ); + if (value) Object.defineProperty(value, 'sourceFingerprint', { + value: contentFingerprint([this._curSpaceCfg, this._cellCm, this._gridPitch]), + enumerable: false, + }); const entry = { key: unionKey, - value: wallBodiesUnionPath( - space.rooms, walls, openCuts, openings, - this._wallKeyPitch, this._cellCm, this._gridPitch, NORM_W, extras, - ), + value, }; lruWrite(this._wallUnionPool, unionKey, entry, 8); this._wallUnionCache = entry; @@ -16499,6 +16515,19 @@ class HouseplanCard extends LitElement { occluders: LightSegment[]; floor: number[][][]; fingerprint: string; masonryGeometry: any; opaqueBodies: number[][][]; } { + const raw = this._curSpaceCfg; + // Exact content identity keeps the old in-place-mutation protection while + // moving the cache lookup ahead of passage classification, physical-body + // booleans and wall topology. `_cfgEpoch` alone is deliberately not used: + // old editor paths and third-party harnesses can still mutate a structure + // before advancing it. + const fingerprint = contentFingerprint([raw, this._cellCm, this._gridPitch]); + const cacheKey = `${space.id}|${fingerprint}`; + const pooled = lruRead(this._lightBarrierPool, cacheKey); + if (pooled.hit) { + this._lightBarrierCache = pooled.value; + return pooled.value.value; + } // Gates are door-like: their different symbol must not change how light // crosses the clear opening. const zeroWalls = this._zeroWalls(); @@ -16552,47 +16581,27 @@ class HouseplanCard extends LitElement { }; } const lightPhysical = this._lightPhysicalBodiesCache.all; - // Keyed by what it is made of, never by `_cfgEpoch`: geometry edited in - // place leaves the epoch behind, and a stale barrier set is invisible — - // the plan simply keeps lighting through a wall that now exists. - let hash = 0x811c9dc5; - const mix = (value: number) => { - hash ^= Math.round((Number.isFinite(value) ? value : 0) * 64); - hash = Math.imul(hash, 0x01000193) >>> 0; - }; const walls = this._spaceWalls; - mix(this._cellCm); - mix(this._gridPitch); - mix(this._wallKeyPitch); - for (const { poly } of polys) { mix(poly.length); for (const p of poly) { mix(p[0]); mix(p[1]); } } - for (const cut of cuts) for (const value of cut) mix(value); - mix(zeroWalls.style === 'solid' ? 1 : 0); - for (const barrier of zeroWalls.barriers) for (const value of barrier) mix(value); - for (const body of lightPhysical) { - mix(body.length); - for (const point of body) { mix(point[0]); mix(point[1]); } - } - for (const wall of walls) { - mix(wall.cm); - mix(wall.a?.[0] ?? 0); mix(wall.a?.[1] ?? 0); - mix(wall.b?.[0] ?? 0); mix(wall.b?.[1] ?? 0); - } - const fingerprint = hash.toString(36); - const cacheKey = `${space.id}|${fingerprint}`; - if (this._lightBarrierCache?.key === cacheKey) return this._lightBarrierCache.value; const eps = this._gridPitch * 0.02; const occluders: LightSegment[] = []; // The masonry the plan draws, cut by passages only — real thickness, real // jamb faces. Treating a wall as its centreline let light bleed half a wall // deep (a bright bar at every opening) and started every shadow half a wall // away from the corner that casts it. - const masonry = walls.length || lightPhysical.length - ? wallBodiesGeometry( - space.rooms, walls, openCuts, - roomPassages, - this._wallKeyPitch, this._cellCm, this._gridPitch, NORM_W, lightPhysical, - ) + const sharedWallGeometry = this._wallUnionGeometry(); + const sharedFingerprint = (sharedWallGeometry as unknown as { + sourceFingerprint?: string; + } | null)?.sourceFingerprint; + const recut = sharedWallGeometry && sharedFingerprint === fingerprint + ? recutWallBodiesGeometry(sharedWallGeometry, roomPassages, lightPhysical) : null; + const masonry = recut || (walls.length || lightPhysical.length + ? wallBodiesGeometry( + space.rooms, walls, openCuts, + roomPassages, + this._wallKeyPitch, this._cellCm, this._gridPitch, NORM_W, lightPhysical, + ) + : null); if (masonry && (masonry.status === 'ok' || masonry.status === 'degraded-extra')) { for (const component of masonry.components) { for (const ring of geometryAllRings(component.geom)) occluders.push(...polygonSegments(ring)); @@ -16627,7 +16636,9 @@ class HouseplanCard extends LitElement { // doors, and therefore cannot be used when the boolean geometry is empty. opaqueBodies: lightPhysical, }; - this._lightBarrierCache = { key: cacheKey, value }; + const entry = { key: cacheKey, value }; + lruWrite(this._lightBarrierPool, cacheKey, entry, 8); + this._lightBarrierCache = entry; return value; } diff --git a/src/wall-thickness.ts b/src/wall-thickness.ts index 1ba32a4a..38273274 100644 --- a/src/wall-thickness.ts +++ b/src/wall-thickness.ts @@ -38,8 +38,13 @@ export interface WallBodiesGeometryResult { components: readonly WallGeometryComponent[]; /** Canonical room masonry before independent bodies. */ roomGeom: any; + /** Uncut room-masonry components. Usually one primary component; a rare + * boolean fallback keeps an isolated exterior shell here as well. */ + roomComponents?: readonly WallGeometryComponent[]; paperGeom: any; depthUnits: number; + /** Exact transverse slot padding used by the opening-cut pass. */ + openingPadUnits?: number; openingIndex: OpeningWallIndex | null; /** Canonical junction topology reused by per-room inner contours. */ multiWallNodes: MultiWallNodeMap | null; @@ -3606,6 +3611,7 @@ export function wallBodiesGeometry( ): WallBodiesGeometryResult { if (!walls?.length && !extraBodies.length) return { status: 'not-applicable', geom: [], components: [], roomGeom: [], paperGeom: [], + roomComponents: [], depthUnits: 0, openingIndex: null, multiWallNodes: null, degradedExtraCount: 0, }; const roomRings: MultiWallRoomRing[] = []; @@ -3774,6 +3780,14 @@ export function wallBodiesGeometry( body = dropDegenerateRings(body, Math.max(multiWallNodes.epsilon, 1e-9) ** 2); } const roomGeom = body || []; + const roomComponents: WallGeometryComponent[] = [ + ...(structurallyValidWallGeometry(roomGeom) + ? [{ id: 'room-primary', geom: roomGeom }] + : []), + ...isolatedCore.map((component, index) => ({ + id: `room-isolated-${index}`, geom: component.geom, + })), + ]; // cut opening tunnels (axis-aligned to opening angle) corePhase = 'openings'; for (const o of openings) { @@ -3835,14 +3849,17 @@ export function wallBodiesGeometry( ]; return { status: degradedExtraCount || degradedCoreCount ? 'degraded-extra' : 'ok', - geom: primary, components, roomGeom, paperGeom, - depthUnits: maxDepth, openingIndex, multiWallNodes, + geom: primary, components, roomGeom, roomComponents, paperGeom, + depthUnits: maxDepth, + openingPadUnits: Math.max(maxDepth, pitch * coordScale) * 1.25, + openingIndex, multiWallNodes, degradedExtraCount: degradedExtraCount + degradedCoreCount, }; } catch { operations.onCoreFailure?.(corePhase); return { status: 'failed-core', geom: [], components: [], roomGeom: [], paperGeom: [], + roomComponents: [], depthUnits: maxDepth, openingIndex: null, multiWallNodes, degradedExtraCount: 0, }; } @@ -3867,9 +3884,12 @@ export function wallBodiesUnionPath( paths: readonly { id: string; d: string; fillRule: 'evenodd' }[]; components: readonly WallGeometryComponent[]; roomGeom: any; + roomComponents: readonly WallGeometryComponent[]; + openingIndex: OpeningWallIndex | null; multiWallNodes: MultiWallNodeMap | null; paperD: string; depthUnits: number; + openingPadUnits?: number; fillRule: 'evenodd' | 'nonzero'; } | null { if (!walls?.length && !extraBodies.length) return null; @@ -3889,9 +3909,12 @@ export function wallBodiesGeometryPath( paths: readonly { id: string; d: string; fillRule: 'evenodd' }[]; components: readonly WallGeometryComponent[]; roomGeom: any; + roomComponents: readonly WallGeometryComponent[]; + openingIndex: OpeningWallIndex | null; multiWallNodes: MultiWallNodeMap | null; paperD: string; depthUnits: number; + openingPadUnits?: number; fillRule: 'evenodd' | 'nonzero'; } | null { if (united.status === 'failed-core' || united.status === 'not-applicable') return null; @@ -3900,11 +3923,25 @@ export function wallBodiesGeometryPath( })).filter((component) => !!component.d); const d = paths[0]?.d || ''; const paperD = polyclipToPathD(united.paperGeom); - if (paths.length) return { - status: united.status, d, paths, components: united.components, - roomGeom: united.roomGeom, multiWallNodes: united.multiWallNodes, paperD, - depthUnits: united.depthUnits, fillRule: 'evenodd', - }; + if (paths.length) { + const projected = { + status: united.status, d, paths, components: united.components, + roomGeom: united.roomGeom, + multiWallNodes: united.multiWallNodes, paperD, + depthUnits: united.depthUnits, + fillRule: 'evenodd', + } as unknown as NonNullable>; + // Retained topology is an internal acceleration seam, not part of the + // enumerable SVG projection contract. Keeping it non-enumerable preserves + // structural equality and serialization for callers that compare path + // payloads while still allowing a second opening policy to reuse it. + Object.defineProperties(projected, { + roomComponents: { value: united.roomComponents || [], enumerable: false }, + openingIndex: { value: united.openingIndex, enumerable: false }, + openingPadUnits: { value: united.openingPadUnits, enumerable: false }, + }); + return projected; + } // successful empty result: do not resurrect raw rings // Fail closed. The old raw per-room-ring fallback is the exact algorithm // that creates an exterior tooth at a corner Split, so resurrecting it after @@ -3912,6 +3949,93 @@ export function wallBodiesGeometryPath( return null; } +/** + * Recut an already-built room masonry pass for another opening policy. + * + * Plan drawing and light transport share the expensive room topology but not + * their cuts: every visual opening cuts the plan, while only an interior + * door/gate transmits light. Rebuilding all room rings, junctions and the + * exterior envelope for that second policy dominated first paint. This helper + * starts from the immutable uncut components retained by wallBodiesGeometry, + * applies the alternate slots, and then merges the policy-specific independent + * bodies. Any unexpected core failure returns null so callers can fall back to + * a completely independent canonical pass. + */ +export function recutWallBodiesGeometry( + base: Pick, + openings: Array<{ x: number; y: number; angle: number; length: number }> = [], + extraBodies: number[][][] = [], + operations: WallGeometryOperations = {}, +): { status: 'ok' | 'degraded-extra'; geom: any; components: readonly WallGeometryComponent[] } | null { + if (base.status === 'failed-core' || base.status === 'not-applicable') return null; + const retained = base.roomComponents?.length + ? base.roomComponents + : (structurallyValidWallGeometry(base.roomGeom) + ? [{ id: 'room-primary', geom: base.roomGeom }] + : []); + let body: any = retained[0]?.geom || null; + const isolatedCore: WallGeometryComponent[] = retained.slice(1) + .map((component) => ({ ...component })); + try { + for (const opening of openings) { + if (!(opening.length > 0) || !base.openingIndex) continue; + const association = resolveOpeningWallAssociation(base.openingIndex, opening, true); + if (!association.negative && !association.positive) continue; + const rad = (opening.angle * Math.PI) / 180; + const ux = Math.cos(rad), uy = Math.sin(rad); + const nx = -uy, ny = ux; + const half = opening.length / 2; + const pad = base.openingPadUnits ?? Math.max(base.depthUnits, 1) * 1.25; + const slot = closedRing([ + [opening.x - ux * half - nx * pad, opening.y - uy * half - ny * pad], + [opening.x + ux * half - nx * pad, opening.y + uy * half - ny * pad], + [opening.x + ux * half + nx * pad, opening.y + uy * half + ny * pad], + [opening.x - ux * half + nx * pad, opening.y - uy * half + ny * pad], + ]) as any; + if (body) body = difference(body, slot); + for (const component of isolatedCore) component.geom = difference(component.geom, slot); + } + const isolated: WallGeometryComponent[] = [...isolatedCore]; + let degradedExtraCount = isolatedCore.length; + const mergeExtra = operations.mergeExtra + || ((primary: any, extra: any) => primary ? union(primary, extra) : extra); + for (let index = 0; index < extraBodies.length; index++) { + const extra = extraBodies[index]; + if (extra.length < 3 || !extra.every((point) => point.length >= 2 + && Number.isFinite(point[0]) && Number.isFinite(point[1])) + || Math.abs(polygonArea(extra)) <= 1e-9) { + degradedExtraCount++; + continue; + } + const standalone: any = [closedRing(extra)]; + try { + const merged = mergeExtra(body, standalone, index); + if (!structurallyValidWallGeometry(merged)) throw new Error('invalid extra union'); + body = merged; + } catch { + degradedExtraCount++; + if (structurallyValidWallGeometry(standalone)) { + isolated.push({ id: `policy-extra-${index}`, geom: standalone }); + } + } + } + isolated.sort((left, right) => polyclipToPathD(left.geom).localeCompare(polyclipToPathD(right.geom))); + const primary = body || []; + return { + status: degradedExtraCount ? 'degraded-extra' : 'ok', + geom: primary, + components: [ + ...(structurallyValidWallGeometry(primary) ? [{ id: 'primary', geom: primary }] : []), + ...isolated.map((component, index) => ({ ...component, id: `isolated-${index}` })), + ], + }; + } catch { + return null; + } +} + /** * Per-edge wall quads for styling hooks and thick-cut suppression — one body * per unique wall key. Shared and outer walls both grow ±½ from the diff --git a/test/golden-matrix.test.mjs b/test/golden-matrix.test.mjs index 48aef7de..74ef645c 100644 --- a/test/golden-matrix.test.mjs +++ b/test/golden-matrix.test.mjs @@ -764,11 +764,11 @@ test('a light source paints exactly one region: the floor it can see', () => { // Barriers are keyed by their own content: `_cfgEpoch` lags behind geometry // edited in place, and a stale barrier set lights straight through a wall. assert.doesNotMatch(glow, /_cfgEpoch/); - assert.match(source, /const fingerprint = hash\.toString\(36\)/); - assert.match(source, /for \(const point of body\) \{ mix\(point\[0\]\); mix\(point\[1\]\); \}/); - assert.match(source, /mix\(wall\.b\?\.\[0\] \?\? 0\); mix\(wall\.b\?\.\[1\] \?\? 0\)/); + assert.match(source, /const fingerprint = contentFingerprint\(\[/); + assert.match(source, /contentFingerprint\(\[raw, this\._cellCm, this\._gridPitch\]\)/); assert.match(source, /const cacheKey = `\$\{space\.id\}\|\$\{fingerprint\}`/); - assert.match(source, /mix\(this\._cellCm\)[\s\S]*mix\(this\._gridPitch\)/); + assert.match(source, /sharedFingerprint === fingerprint/, + 'an in-place edit must never recut stale shared masonry'); }); test('all destructive editor dialogs use the medium shell and shared responsive footer groups', () => { diff --git a/test/performance-contract.test.mjs b/test/performance-contract.test.mjs index c8ceb9ac..464e9b1c 100644 --- a/test/performance-contract.test.mjs +++ b/test/performance-contract.test.mjs @@ -111,3 +111,31 @@ test('room inner faces are structurally cached and shared by both fill layers', assert.equal([...viewRooms.matchAll(/innerContourForRoom\(/g)].length, 0); assert.match(viewRooms, /this\._innerRoomContour\(space, r\.id, allZeroCuts, roomWallGeometry\)/); }); + +test('wall and light geometry reuse bounded caches before structural work', () => { + const source = readFileSync(new URL('../src/houseplan-card.ts', import.meta.url), 'utf8'); + + const unionStart = source.indexOf('private _wallUnionGeometry()'); + const unionEnd = source.indexOf('\n /** Thick-wall spans', unionStart); + assert.ok(unionStart >= 0 && unionEnd > unionStart, 'wall-union helper is present'); + const union = source.slice(unionStart, unionEnd); + assert.ok( + union.indexOf('lruRead(this._wallUnionPool, unionKey)') + < union.indexOf('const openCuts = this._openCuts();'), + 'a cached wall union must avoid resolving openings', + ); + assert.match(union, /lruWrite\(this\._wallUnionPool, unionKey, entry, 8\)/); + + const lightStart = source.indexOf('private _lightBarriers('); + const lightEnd = source.indexOf('\n /** Light pools', lightStart); + assert.ok(lightStart >= 0 && lightEnd > lightStart, 'light-barrier helper is present'); + const light = source.slice(lightStart, lightEnd); + assert.ok( + light.indexOf('lruRead(this._lightBarrierPool, cacheKey)') + < light.indexOf('const zeroWalls = this._zeroWalls();'), + 'a cached light barrier must return before geometry classification', + ); + assert.match(light, /contentFingerprint\(\[/); + assert.match(light, /recutWallBodiesGeometry\(sharedWallGeometry, roomPassages, lightPhysical\)/); + assert.match(light, /lruWrite\(this\._lightBarrierPool, cacheKey, entry, 8\)/); +}); diff --git a/test/wall-thickness.test.mjs b/test/wall-thickness.test.mjs index 04459776..d938213e 100644 --- a/test/wall-thickness.test.mjs +++ b/test/wall-thickness.test.mjs @@ -10,7 +10,8 @@ import { drawWallPreviewD, linearWallBody, linearWallJoinPatches, DRAW_WALL_DEFAULT_CM, clampWallCm, cmToField, fieldToCm, wallCmToUnits, insetContour, outsetContour, inwardNormal, edgeKinds, wallEdgeBodies, - wallBodyRings, wallBodiesGeometry, wallBodiesUnionPath, floorFootprintGeometry, + wallBodyRings, wallBodiesGeometry, wallBodiesUnionPath, recutWallBodiesGeometry, + floorFootprintGeometry, virtualJunctionPatches, stableJunctionPatch, unionJunctionPatches, innerContourForRoom, innerEdgeSpan, ownEdgeOffsets, paperRoomShapesWithWalls, WALL_MIN_CM, WALL_MAX_CM, MITRE_LIMIT, VISUAL_MITRE_LIMIT, @@ -138,6 +139,36 @@ test('#278 rejects degraded extras in strict preflight while render geometry rem assert.equal(result.roomGeom.length, 0, 'independent bodies never enter room area masonry'); }); +test('alternate opening policy recuts the retained room masonry exactly', () => { + const rooms = [ + { id: 'left', poly: [[0, 0], [100, 0], [100, 100], [0, 100]] }, + { id: 'right', poly: [[100, 0], [200, 0], [200, 100], [100, 100]] }, + ]; + const unique = new Map(); + for (const room of rooms) for (let index = 0; index < room.poly.length; index++) { + const a = room.poly[index], b = room.poly[(index + 1) % room.poly.length]; + const key = wallKey(a, b, 1); + if (!unique.has(key)) unique.set(key, { key, a, b, cm: 20 }); + } + const walls = [...unique.values()]; + const interiorDoor = { x: 100, y: 50, angle: 90, length: 30 }; + const exteriorWindow = { x: 50, y: 0, angle: 0, length: 24 }; + const extras = [[[130, 35], [150, 35], [150, 45], [130, 45]]]; + const visual = wallBodiesGeometry( + rooms, walls, [], [interiorDoor, exteriorWindow], 1, 5, 5, 1, extras, + ); + const directLight = wallBodiesGeometry( + rooms, walls, [], [interiorDoor], 1, 5, 5, 1, extras, + ); + const recutLight = recutWallBodiesGeometry(visual, [interiorDoor], extras); + assert.equal(visual.status, 'ok'); + assert.ok(visual.roomComponents?.length, 'uncut room masonry is retained'); + assert.equal(directLight.status, 'ok'); + assert.equal(recutLight?.status, 'ok'); + closeTo(geometryDifferenceArea(directLight.geom, recutLight.geom), 0, 1e-6); + closeTo(geometryDifferenceArea(recutLight.geom, directLight.geom), 0, 1e-6); +}); + const enclosedLocalHoleRings = (geometry, node) => { const radius = MITRE_LIMIT * node.halfDepth + 1e-6; return (geometry || []).flatMap((polygon) => (polygon || []).slice(1)).filter((ring) =>