0?xa(e,this._cellCm,this._gridPitch):3*this._gridPitch,s=Math.max(i/2,1.25*this._gridPitch);let n="";for(const e of t.segs)n+=(n?" ":"")+Ga([[e[0],e[1]],[e[2],e[3]]],s,!1);return{segs:t.segs,open:t.open,d:n}}_wallThickClick(t){const e=this._wallThickHit(t);if(!e)return void this._showToast(this._t("toast.wallthick_pick"));if(e.open)return void this._showToast(this._t("toast.wallthick_open"));const i=e.cm,s=this._viewOr(this._baseVb()),n=(e.a[0]+e.b[0])/2,o=(e.a[1]+e.b[1])/2;this._wallDialog={a:e.a,b:e.b,value:ka(i,this._imperial),roomId:e.roomId,sx:(n-s.x)/s.w*100,sy:(o-s.y)/s.h*100}}_wallThickApply(t){const e=this._wallDialog;if(!e)return;const i=this._curSpaceCfg,s=this._spaceModel();if(!i||!s)return;const n=e.value.trim(),o=n?mg(n):0;if(null==o)return void this._showPhysicalRange(100);const r=this._imperial?2.54*o:o;if(n&&(!Number.isFinite(r)||r<0||r>0&&r<1||r>100))return void this._showPhysicalRange(100);const a=this._geometrySnapshot(),l=n&&r>0?r:null,c=this._openCuts();let h;h=t&&e.roomId?Ha(i.walls,s.rooms,e.roomId,l,this._wallKeyPitch,c,Pg):Na(i.walls,e.a,e.b,l,this._wallKeyPitch,Pg),h=this._normalizeWalls(h,c),h.length?i.walls=h:delete i.walls,this._wallDialog=null,this._showToast(this._t(null==l?"toast.wallthick_cleared":"toast.wallthick_set")),this._recordGeometry(this._t("history.wall_thickness"),a),this._saveConfig(),this.requestUpdate()}_wallHatchDefs(t){if(!this._spaceWalls.length&&!this._physicalBodiesR().length&&!this._markup)return j``;const e=ya(this._cellCm);return j`
`}_resolvedRoomFills(t,e){const i=new Map,s=new Map;for(const n of t.rooms){const t=this._roomDialog&&n.id===this._roomEditId?this._roomFill||e.fill:Fs(e.fill,n),o=this._roomDialog&&n.id===this._roomEditId?this._roomCustomFill||e.customFill:ls(e.customFill,n),r=_s(t,"lqi"===t&&n.area?this._roomLqi(n.area):null,"light"===t?po(ho(this._renderPlanHass,this._renderDevices,n,this._virtualLights)):"none","temp"===t?this._roomTemp(n):null,e.tempMin,e.tempMax,this._fillColors,o);i.set(n,r),n.id&&s.set(n.id,r)}return{byRoom:i,byId:s}}_spaceDisplayForRender(){const t=cs(this._curSpaceCfg),e=this._spaceDialog;return e&&"edit"===e.mode&&e.spaceId===this._space?{...t,showBorders:e.showBorders,showNames:e.showNames,hideDecor:e.hideDecor,hideOpenings:e.hideOpenings,color:e.roomColor,opacity:e.roomOpacity,fill:e.fillMode,customFill:e.customFill?as(e.customFill):rs,glow:e.glowEnabled,tempMin:e.tempMin,tempMax:e.tempMax,showLqi:e.showLqi,cardFontScale:e.cardFontScale,labelTemp:e.labelTemp,labelHum:e.labelHum,labelLqi:e.labelLqi,labelLight:e.labelLight}:t}_openingWallIndexFor(t,e){const i=t.rooms.map(t=>`${t.id}:${t.poly?.map(t=>t.join(",")).join("/")||`${t.x},${t.y},${t.w},${t.h}`}`).join(";"),s=this._spaceWalls.map(t=>`${t.key}:${t.a?.join(",")||""}:${t.b?.join(",")||""}:${t.cm}`).join(";"),n=e.map(t=>t.join(",")).join(";"),o=[t.id,this._cfgEpoch,this._wallKeyPitch,this._cellCm,this._gridPitch,i,s,n].join("|");let r=this._openingWallIndexCache.get(o);return r||(r=wl(t.rooms,this._spaceWalls,e,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)),vg(this._openingWallIndexCache,o,r,4),{key:o,value:r}}_renderOpeningTunnelFills(t,e,i="data"){if(this._markup||!this._spaceWalls.length||!this._openingsR.length)return j``;if("glow-base"===i&&![...e.byRoom.values()].some(Boolean))return j``;const s=this._openPairs().flatMap(t=>t.segs),n=this._openingsR.map(t=>({x:t.rx,y:t.ry,angle:t.angle,length:t.rlen})),o=n.map(t=>`${t.x},${t.y},${t.angle},${t.length}`).join(";"),r=this._openingWallIndexFor(t,s),a=`${r.key}|${o}`;return this._openingTunnelCache&&this._openingTunnelCache.key===a||(this._openingTunnelCache={key:a,value:Dl(r.value,n)}),Vu({openings:this._openingsR,geometries:this._openingTunnelCache.value,fillsByRoomId:e.byId,idPrefix:`${t.id}-${i}`,groupClass:"data"===i?"opening-tunnels":"opening-tunnels glow-base-tunnels",dataLayer:i})}_resolvedGlowBase(t,e,i){const s=new Map,n=new Map,o=this._fillColors.glow_base;for(const r of t.rooms){const t=i.byRoom.get(r),a=Es(e.glow,r)&&(!t||t.opacity<=0)?{color:o.c,opacity:o.a,mode:"glow"}:null;s.set(r,a),r.id&&n.set(r.id,a)}return{byRoom:s,byId:n}}_renderGlowBaseRooms(t,e){if(this._markup||![...e.byRoom.values()].some(Boolean))return j``;const i=new Map(t.rooms.map(t=>[t,hi(t)])),s=this._openPairs().flatMap(t=>t.segs),n=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z",o=t.rooms.map(o=>{const r=e.byRoom.get(o)||null,a=i.get(o)||null;if(!r||!a)return G;const l=this._spaceWalls.length&&o.id&&hl(t.rooms,o.id,this._spaceWalls,s,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)||a,c=Ti(l,t.rooms.filter(t=>t!==o).map(t=>i.get(t)).filter(t=>!!t)),h=this._cleanFloor(o,l,t).path;return h||c.length?j` `:o.poly||l!==a?j` `:j` `});return j`${o} `}_renderWallBodies(t){if("iso"===this._renderProjection)return j``;if(t&&!t.showBorders&&("view"===this._mode||"devices"===this._mode))return j``;const e=this._wallUnionGeometry();if(!e)return j``;const i=this._stageEl,s=this._viewOr(this._baseVb()),n=i&&i.clientWidth&&s.w?i.clientWidth/s.w:1,o=t?.color||"#607d8b",r=va(e.depthUnits,n)||ba(ya(this._cellCm),n),a=this._fillColors.wall_fill;return j`
`}_isoDecorationLayers(t){const e="undefined"==typeof CSS||"function"!=typeof CSS.supports||CSS.supports("filter","blur(1px)"),i="function"==typeof matchMedia&&matchMedia("(forced-colors: active)").matches;return function(t){const e=!!t.showBorders;return{structural:e,panels:e&&!t.hideOpenings,shadows:e&&t.filtersSupported&&!t.forcedColors,materialNuance:e&&!t.forcedColors,floorSymbols:!t.hideOpenings&&!e}}({showBorders:t.showBorders,hideOpenings:t.hideOpenings,filtersSupported:e,forcedColors:i})}_isoOpeningPanels(t){if(!t.panels)return[];const e=this._isoScene();if(!e)return[];return e.openings.flatMap(t=>{const e=this._openingsR[t.sourceIndex];return e?L_(t,this._openingAmt(e)):[]}).sort((t,e)=>t.depth-e.depth||t.sourceIndex-e.sourceIndex||t.leaf-e.leaf)}_renderIsoDefs(t,e){return j`
${"walls"===e&&t.materialNuance?j`
`:G}
${"underlay"===e&&t.shadows?j`
`:G}
${"shadows"===e&&t.shadows?j`
`:G}
`}_renderIsoUnderlay(t){if(!t.structural)return j``;const e=this._isoScene()?.floor;return e?j`
${this._renderIsoDefs(t,"underlay")}
${t.shadows&&e.footprintPath?j` `:G}
${e.sides.map(t=>j` `)}
`:j``}_renderIsoShadows(t,e){if(!t.shadows)return j``;const i=this._isoScene()?.geometry;return i?j`
${this._renderIsoDefs(t,"shadows")}
${e.map(t=>j` `)}
`:j``}_renderIsoWalls(t,e){if("iso"!==this._renderProjection)return j``;if(!t.structural)return j``;const i=this._isoScene();return i?j`
${this._renderIsoDefs(t,"walls")}
${i.geometry.sides.map(t=>j` `)}
${t.panels?j`${e.map(t=>j` `)} `:G}
`:j``}_roomHoverPaths(t){const e=this._hoverRoom;if("view"!==this._mode||!e||e.space!==t.id)return null;const i=t.rooms.find(t=>t===e.room||!!t.id&&t.id===e.room.id);if(!i)return null;const s=hi(i);if(!s)return null;const n=t.rooms.filter(t=>t!==i).map(t=>({room:t,poly:hi(t)})).filter(t=>!!t.poly),o=Ti(s,n.map(t=>t.poly)),r=this._openPairs(),a=r.flatMap(t=>t.segs),l=i.id?r.filter(t=>t.a.id===i.id||t.b.id===i.id).flatMap(t=>t.segs):r.flatMap(t=>t.segs),c=this._spaceWalls,h=c.length&&i.id&&hl(t.rooms,i.id,c,a,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)||s,d=[{axis:s,face:h}];for(const e of o){const i=n.find(t=>t.poly===e)?.room;let s=e;if(c.length&&i?.id){const n=nl(t.rooms,i.id,c,a,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg);n&&(s=bl(n.poly,n.offsets)||e)}d.push({axis:e,face:s})}const u=this._roomWallOpeningInputs(this._openingsR,t).map(t=>{const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,s=Math.sin(e)*t.length/2;return[t.x-i,t.y-s,t.x+i,t.y+s]}),p=.02*this._gridPitch,_=l.concat(u),g=d.map(({axis:t,face:e})=>{const i=_.map(i=>((t,e,i)=>{const s=t[2]-t[0],n=t[3]-t[1],o=Math.hypot(s,n);if(o.05)&&Hs([l,c],[i[0],i[1],s[0],s[1]])<=4*p){h=!0;break}}if(!h)return null;let d=null;for(let t=0;t.05)continue;const u=Hs([l,c],[e[0],e[1],s[0],s[1]]);(!d||u!!t);return i.length?Ts(e,i,p).map(t=>`M ${t[0]} ${t[1]} L ${t[2]} ${t[3]}`).join(" "):`M ${e.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`}).filter(Boolean).join(" ");if(!g)return null;const m=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`;return{fillD:[this._cleanFloor(i,h,t).path||m(h),...o.map(m)].join(" "),outlineD:g}}_renderRoomHoverFill(t){return t?j`
`:j``}_renderRoomHoverOutline(t){return t?j`
`:j``}_renderWallThickUi(){const t=this._wallThickHover;return t&&t.d?j` `:j``}_renderWallThickDialog(){const t=this._wallDialog;return t?W`t.stopPropagation()}>
${this._t("wallthick.field")}
{this._wallDialog={...t,value:e.target.value}}}
@keydown=${t=>{"Enter"===t.key&&(t.preventDefault(),this._wallThickApply(!1))}} />
${this._t(this._imperial?"wallthick.unit_in":"wallthick.unit_cm")}
this._wallThickApply(!0)}>
${this._t("wallthick.apply_room")}
this._wallThickApply(!1)}>
`:W``}_openingAt(t){if(!this._openingsR.length)return null;const e=this._openingsR.flatMap(e=>{const i=e.angle*Math.PI/180,s=t[0]-e.rx,n=t[1]-e.ry,o=s*Math.cos(i)+n*Math.sin(i);return Math.abs(o)>e.rlen/2+12?[]:[{o:e,localY:-s*Math.sin(i)+n*Math.cos(i)}]});if(!e.length)return null;const i=this._spaceModel();if(!i)return null;const s=this._openPairs().flatMap(t=>t.segs),n=this._openingWallIndexFor(i,s).value;return e.find(({o:t,localY:e})=>{const i="gate"===t.type?!t.flip_v:t.flip_v,s=t.partitionHost||this._spaceWalls.length||"gate"===t.type?this._openingFace(t,n,!!i):{ox:0,oy:0,cm:0,side:-1},o=Cu({type:t.type,length:t.rlen,angle:t.angle,amount:this._openingAmt(t),flipH:!!t.flip_h,flipV:!!t.flip_v,cellCm:this._cellCm,gridPitch:this._gridPitch,face:s});return Math.abs(e)<=o.hitHalf})?.o||null}_resolveOpeningPlacement(t){const e=this._openingPreset;if("opening"!==this._tool||!e)return null;const i=this._spaceModel();if(!i)return null;const s=this._openCuts(),n=this._openingWallIndexFor(i,s),o=`${n.key}|partitions:${this._cfgEpoch}`;var r,a,l;this._openingPlacementIntervalsCache&&this._openingPlacementIntervalsCache.key===o||(this._openingPlacementIntervalsCache={key:o,value:[...ol(i.rooms,this._spaceWalls,s,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg),...(r=i.partitions,a=this._cellCm,l=this._gridPitch,r.flatMap(t=>!ud(t.a)||!ud(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:xa(t.cm,a,l)/2,partitionHost:{kind:"partition",id:t.id}}]))]}),this._openingDimensionContextCache&&this._openingDimensionContextCache.key===o||(this._openingDimensionContextCache={key:o,value:eg({rooms:i.rooms,walls:this._spaceWalls,openCuts:s,partitions:i.partitions,roomOpenings:this._roomWallOpeningInputs(),partitionCuts:this._partitionOpeningCuts(i),pitch:this._wallKeyPitch,cellCm:this._cellCm,gridPitch:this._gridPitch,coordScale:Pg,epsilon:2e-4*this._gridPitch})});const c=G_({pointer:[t[0],t[1]],preset:e,geometryRevision:this._cfgEpoch,renderedLength:this._cmToUnits(e.lengthCm),intervals:this._openingPlacementIntervalsCache.value,baseTolerance:1.5*this._gridPitch,bodyPointerPadding:this._cssPxToRender(this._boundaryCoarse?10:6),gridStep:this._gridPitch});this._openingJambBlockCm=c.jambBlockedTarget?c.jambBlockedTarget.physicalHalfWidth/this._gridPitch*this._cellCm:null;const h=c.candidate;if(!h)return null;const d="gate"===h.type?!h.flipV:h.flipV;let u;if(h.host){const t=gd({id:"preview",type:h.type,x:h.x/Pg,y:h.y/Pg,angle:h.angle,length:h.renderedLength/Pg,host:h.host},i.partitions,Pg,this._cellCm,this._gridPitch).resolved;u=t?yd(t,d):{ox:0,oy:0,cm:0,side:-1}}else u=Sl(n.value,{x:h.x,y:h.y,angle:h.angle,length:h.renderedLength,flip_v:d});const p="mi"===this.hass?.config?.unit_system?.length,_=lg(h,this._openingDimensionContextCache.value).map(t=>({x:t.label[0],y:t.label[1],text:li(t.distance/this._gridPitch*this._cellCm,p),dimension:t}));return{...h,face:u,measure:{labels:_,guide:h.measure.guide}}}_activateOpeningPlacement(t){this._activateMarkupTool("opening"),"opening"===this._tool&&(this._openingPreset=function(t,e){return{type:t,lengthCm:q_(t),flipH:!1,flipV:!1,revision:e}}(t,++this._openingPresetRevision),this._openingHoverCandidate=null,this._cursorPt=null)}_clearOpeningPlacement(t){this._openingHoverCandidate=null,this._openingJambBlockCm=null,t&&(this._openingPreset=null,this._openingRebindId=null)}_openingClick(t){const e=this._spaceModel();if(!e)return;const i=this._openingRebindId?null:this._openingAt(t);if(i)return void this._editOpening(i);const s=this._openingPreset;if(!s)return;const n=this._openingHoverCandidate,o=n&&V_(n,[t[0],t[1]],s.revision,this._cfgEpoch)?n:this._resolveOpeningPlacement(t);if(!o){if(null!=this._openingJambBlockCm)return void this._showToast(this._t("opening.partition_jamb_margin",{distance:li(this._openingJambBlockCm,this._imperial)}));const i=1.5*this._gridPitch,s=pi(t,e.rooms,i);return s&&function(t,e,i,s,n){for(const o of s)if(!(Hs([t,e],o)>n)&&za([o[0],o[1]],[o[2],o[3]],i))return!0;return!1}(s.x,s.y,s.angle,this._openCuts(),i)?void this._showToast(this._t("toast.opening_on_virtual")):void this._showToast(this._t("toast.opening_no_wall"))}const r=this._openingRebindId?this._curSpaceCfg?.openings?.find(t=>t.id===this._openingRebindId):null;this._openingDialog={...r?{id:r.id,type:r.type,lengthCm:Math.round(r.length*Pg/this._gridPitch*this._cellCm),lengthTouched:!1,contact:r.contact||"",lock:r.lock||"",invert:!!r.invert,flipH:!!r.flip_h,flipV:!!r.flip_v}:{type:o.type,lengthCm:o.lengthCm,contact:"",lock:"",invert:!1,flipH:o.flipH,flipV:o.flipV},...o.host?{host:o.host}:{},x:o.x,y:o.y,angle:o.angle},this._openingRebindId=null,this._openingHoverCandidate=null,this._cursorPt=null}_editOpening(t){this._openingDialog={id:t.id,type:t.type,lengthCm:Math.round(t.rlen/this._gridPitch*this._cellCm),lengthTouched:!1,contact:t.contact||"",lock:t.lock||"",invert:!!t.invert,flipH:!!t.flip_h,flipV:!!t.flip_v,...t.host?{host:{...t.host}}:{},x:t.rx,y:t.ry,angle:t.angle}}_opPointerDown(t,e){if("plan"===this._mode&&this._spaceModel()&&"resize"!==this._tool){t.preventDefault(),t.stopPropagation();try{Ng(t)}catch{}this._opDrag={id:e.id,moved:!1,sx:t.clientX,sy:t.clientY,dirty:!1,before:this._geometrySnapshot()}}}_opPointerMove(t,e){if(!this._opDrag||this._opDrag.id!==e.id)return;if(Math.abs(t.clientX-this._opDrag.sx)+Math.abs(t.clientY-this._opDrag.sy)<=3)return;const i=this._spaceModel();if(!i)return;const s=this._svgPoint(t),n=this._curSpaceCfg,o=n?.openings?.find(t=>t.id===e.id);if(!o)return;if("partition"===o.host?.kind){const t=i.partitions.find(t=>t.id===o.host.id);if(!t)return;const e=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(e,n);if(!(r>1e-9))return;const a=e/r,l=n/r;if(Math.abs((s[0]-t.a[0])*l-(s[1]-t.a[1])*a)>4*this._gridPitch)return;const c=o.length*Pg/2+pd(t,this._cellCm,this._gridPitch);let h=(s[0]-t.a[0])*a+(s[1]-t.a[1])*l;if(h=Math.round(h/this._gridPitch)*this._gridPitch,h=Math.max(c,Math.min(r-c,h)),r<2*c-1e-9)return;const d=h/r,u=(t.a[0]+a*h)/Pg,p=(t.a[1]+l*h)/this._spaceH;let _=180*Math.atan2(n,e)/Math.PI;_>=90?_-=180:_<-90&&(_+=180);const g=o.host.t!==d||o.x!==u||o.y!==p||o.angle!==_;return this._opDrag.moved=!0,g&&(this._opDrag.dirty=!0),o.host={...o.host,t:d},o.x=u,o.y=p,o.angle=_,this._opMeasure=null,g&&this._cfgEpoch++,void this.requestUpdate()}const r=pi(s,i.rooms,4*this._gridPitch);if(!r)return;this._opDrag.moved=!0;const a=this._opRuler(r,o.length*Pg);this._opMeasure=a.measure;const l=a.x/Pg,c=a.y/this._spaceH,h=o.x!==l||o.y!==c||o.angle!==r.angle;h&&(this._opDrag.dirty=!0),o.x=l,o.y=c,o.angle=r.angle,h&&this._cfgEpoch++,this.requestUpdate()}_opRuler(t,e){const i=this._spaceModel()?.rooms||[],s=this._gridPitch/2;let n=t.x,o=t.y,r=_i([n,o],t.angle,e,i,s);if(r&&r.centered&&(n!==r.wallCenter[0]||o!==r.wallCenter[1]))[n,o]=r.wallCenter,r=_i([n,o],t.angle,e,i,s);else if(r){const[a,l]=r.wallA,[c,h]=r.wallB,d=c-a,u=h-l,p=Math.hypot(d,u);if(p>0){const c=this._gridPitch,h=Math.min(e/2,p/2);let _=Math.round(((n-a)*d+(o-l)*u)/p/c)*c;_=Math.max(h,Math.min(p-h,_)),n=a+_/p*d,o=l+_/p*u,r=_i([n,o],t.angle,e,i,s)||r}}if(!r)return{x:n,y:o,angle:t.angle,measure:null};const a="mi"===this.hass?.config?.unit_system?.length,l=(t,e)=>({x:e[0],y:e[1],text:li(t/this._gridPitch*this._cellCm,a)});return{x:n,y:o,angle:t.angle,measure:{labels:[l(r.sideA,r.midA),l(r.sideB,r.midB)],guide:r.centered?{x:r.wallCenter[0],y:r.wallCenter[1],angle:t.angle}:null}}}_opPointerUp(t,e){if(!this._opDrag||this._opDrag.id!==e.id)return;const i=this._opDrag,s=i.moved;this._opMeasure=null,s&&i.dirty&&(this._recordGeometry(this._t("history.move_opening"),i.before),this._saveConfig()),s?window.setTimeout(()=>this._opDrag=null,0):this._opDrag=null}_opClick(t,e){"plan"===this._mode&&"resize"===this._tool||(t.stopPropagation(),this._opDrag?.moved||"plan"===this._mode&&this._editOpening(e))}_saveOpening(){const t=this._openingDialog,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=this._geometrySnapshot(),n=this._spaceH,o=(e.openings||[]).find(e=>e.id===t.id),r={...o||{},id:t.id||"o"+Date.now().toString(36),type:t.type,x:t.x/Pg,y:t.y/n,angle:t.angle,length:o&&!t.lengthTouched?o.length:this._cmToUnits(Math.max(20,t.lengthCm))/Pg,...t.host?{host:{...t.host}}:{}};if(r.host){const t=fd(o,r)?md(r,i.partitions,Pg,this._cellCm,this._gridPitch):gd(r,i.partitions,Pg,this._cellCm,this._gridPitch);if(!t.resolved){const e=i.partitions.find(t=>t.id===r.host.id);if("does-not-fit-jamb"===t.reason&&e){const t=pd(e,this._cellCm,this._gridPitch);this._showToast(this._t("opening.partition_jamb_margin",{distance:li(t/this._gridPitch*this._cellCm,this._imperial)}))}else this._showToast(this._t("opening.partition_orphan"));return}const s=(e.openings||[]).flatMap(t=>{if(!t.host||t.id===r.id)return[];const e=gd(t,i.partitions,Pg,this._cellCm,this._gridPitch).resolved;return e?[e]:[]});if(function(t,e,i=1e-9){const s=t.length/(2*t.axis.length),n=t.t-s,o=t.t+s;return e.some(e=>{if(e.host.id!==t.host.id||e.opening.id===t.opening.id)return!1;const s=e.length/(2*e.axis.length);return Math.max(n,e.t-s)t.id===r.id);a>=0?e.openings[a]=r:e.openings.push(r),this._recordGeometry(this._t(t.id?"history.edit_opening":"history.add_opening"),s),this._saveConfig(),this._openingDialog=null,this.requestUpdate()}_deleteOpening(){const t=this._openingDialog,e=this._curSpaceCfg;if(!t?.id||!e?.openings)return;const i=this._geometrySnapshot();e.openings=e.openings.filter(e=>e.id!==t.id),this._recordGeometry(this._t("history.delete_opening"),i),this._saveConfig(),this._openingDialog=null,this.requestUpdate()}_contactCandidates(){const t=[];for(const e of Object.keys(this.hass.states)){if(!this._openingEntityAvailable(e))continue;const i=e.split(".")[0];if("binary_sensor"!==i&&"cover"!==i)continue;const s=this.hass.states[e],n=["door","window","opening","garage_door","garage"].includes(s?.attributes?.device_class||"");("cover"!==i||n)&&t.push([e,s?.attributes?.friendly_name||e,n?0:1])}return t.sort((t,e)=>t[2]-e[2]||t[1].localeCompare(e[1])).map(([t,e])=>({value:t,label:e}))}_lockCandidates(){return Object.keys(this.hass.states).filter(t=>t.startsWith("lock.")&&this._openingEntityAvailable(t)).map(t=>({value:t,label:this.hass.states[t]?.attributes?.friendly_name||t})).sort((t,e)=>t.label.localeCompare(e.label))}_mergeClick(t){const e=this._spaceModel();if(!e)return;const i=e.rooms,s=[...i].reverse().find(e=>this._pointInRoom(t,e));if(!s?.id)return;const n=s.id;if(!this._mergeSel||this._mergeSel===n)return void(this._mergeSel=this._mergeSel===n?null:n);const o=i.find(t=>t.id===this._mergeSel),r=o?hi(o):null,a=hi(s),l=r&&a?function(t,e){if(!t||!e||t.length<3||e.length<3)return null;const i=si(Ri(t),Ri(e));if(1!==i.length)return null;if(1!==i[0].length)return null;const s=i[0][0].slice(0,-1).map(t=>[t[0],t[1]]);return s.length>=3?s:null}(r,a):null;if(!l)return this._showToast(this._t("toast.merge_not_adjacent")),void(this._mergeSel=null);this._mergeDialog={aId:this._mergeSel,bId:n,poly:l,pick:"a"},this._mergeSel=null}_commitMerge(){const t=this._mergeDialog,e=this._curSpaceCfg;if(!t||!e||!this._spaceModel())return;const i=this._geometrySnapshot(),s=this._spaceH,n="a"===t.pick?t.aId:t.bId,o="a"===t.pick?t.bId:t.aId,r=e.rooms.find(t=>t.id===n);r?(r.poly=t.poly.map(t=>[t[0]/Pg,t[1]/s]),delete r.x,delete r.y,delete r.w,delete r.h,e.rooms=e.rooms.filter(t=>t.id!==o),this._commitOpenSpans(),this._recordGeometry(this._t("history.merge_rooms"),i),this._saveConfig(),this._mergeDialog=null,this._regSignature="",this._maybeRebuildDevices(),this._showToast(this._t("toast.rooms_merged",{name:r.name||""}))):this._mergeDialog=null}_splitClick(t){const e=this._spaceModel();if(!e)return;const i=e.rooms;if(!this._splitSel){const e=[...i].reverse().find(e=>this._pointInRoom(t,e));if(!e?.id)return;return void(this._splitSel={roomId:e.id,pts:[]})}const s=i.find(t=>t.id===this._splitSel.roomId),n=s?hi(s):null;if(!s||!n)return void(this._splitSel=null);const o=.02*this._gridPitch,r=6*this._gridPitch,a=function(t,e){if(!e||e.length<2)return null;let i=null,s=1/0;for(let n=0;n=n)continue;n=_;const g=Math.sqrt(u),m=(i>0?Math.max(0,Math.min(g,Math.round(p*g/i)*i)):p*g)/g;s=[r+m*h,a+m*d]}return s}(a,n,this._gridPitch)||a,c=a&&l&&Math.hypot(a[0]-t[0],a[1]-t[1])<=r?l:null,h=!!c&&bi(c,n,o),d=this._splitSel.pts;if(!d.length)return h?void(this._splitSel={...this._splitSel,pts:[c]}):void this._showToast(this._t("toast.split_pick_wall"));if(!h){const e=this._snap(t);return wi(e,n,o)?void(this._splitSel={...this._splitSel,pts:[...d,e]}):void this._showToast(this._t("toast.split_pick_inside"))}const u=Fi(n,[...d,c],o);if(!u)return void this._showToast(this._t("toast.split_bad_cut"));this._resetRoomDialogFields();const[p,_]=u,g=Pi(p)>=Pi(_)?p:_,m=g===p?_:p;this._pendingSplit={roomId:s.id,mainPoly:g,newPoly:m},this._cursorPt=null,this._nameSel="",this._areaSel="",this._roomDialog=!0}get _contourClosed(){return this._path.length>=4&&this._samePt(this._path[0],this._path[this._path.length-1])&&(null!=this._closingWallCm||!this._activeDraftId)}_markupMove(t){if(!this._markup)return;const e=t.pointerType;if(e&&(this._boundaryPointerType=e),"column"===this._tool)return void(this._cursorPt=this._snap(this._svgPoint(t)));if("opening"===this._tool||"boundary"===this._tool||"wallthick"===this._tool)return void(this._cursorPt=this._svgPoint(t));const i="draw"===this._tool&&!this._contourClosed,s="split"===this._tool&&!!this._splitSel?.pts?.length;if(!i&&!s)return;const n=this._svgPoint(t);if(i){const e=this._resolvePlanDrawPoint(n,t.shiftKey);return this._planSnapHover={contextKey:e.contextKey,candidate:e.candidate,conflicts:e.conflicts},this._syncPlanSnapConflictMarkers(e.conflicts),this._path.length?void(this._cursorPt=e.point):void this._syncPlanSnapActiveMarker(e.candidate)}this._cursorPt=this._snap(n)}get _openingPreview(){const t=this._openingPreset;if("opening"!==this._tool||!t||!this._cursorPt)return null;const e=this._cursorPt,i=this._openingHoverCandidate;if(i&&V_(i,[e[0],e[1]],t.revision,this._cfgEpoch))return i;if(this._openingAt(e))return this._openingHoverCandidate=null,null;const s=this._resolveOpeningPlacement(e);return this._openingHoverCandidate=s,s}get _opMeasureView(){return this._opMeasure||this._openingPreview?.measure||null}_saveRoom(){(this._areaSel||this._nameSel.trim())&&(this._wallFaceBatch?this._decideWallFace(!0):this._commitRoom())}_decideWallFace(t){const e=this._wallFaceBatch;if(!e)return;const i=e.candidates[e.index];if(!i)return;if(!t&&(i.existing||i.repair)&&1===e.candidates.length)return this._wallFaceBatch=null,this._roomDialog=!1,this._nameSel="",this._areaSel="",void this.requestUpdate();const s=t?{candidate:i,create:!0,name:this._nameSel.trim(),area:this._areaSel||null,settings:this._roomSettingsFromDialog()?JSON.parse(JSON.stringify(this._roomSettingsFromDialog())):null}:{candidate:i,create:!1},n=[...e.decisions,s],o=e.index+1;if(o"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null,n=.02*this._gridPitch,o=this._spaceModel();if(!o)return fa;for(const e of this._planSnapGeometrySnapshot().value.segments){if("room"===e.sourceKind||Hs(t,[e.a[0],e.a[1],e.b[0],e.b[1]])>n)continue;if("partition"===e.sourceKind)return s(o.partitions.find(t=>t.id===e.sourceId)?.cm)??fa;const i=e.sourceId.lastIndexOf(":"),r=i>=0?e.sourceId.slice(0,i):e.sourceId,a=i>=0?Number(e.sourceId.slice(i+1)):-1;return s(o.room_drafts.find(t=>t.id===r)?.segments[a]?.cm)??fa}const r=Nd(Math.max(0,e.length-1),i,this._drawWallCm,fa);for(let i=0;i+1[...t]);if(!e?.sourceKey.startsWith("active:"))return i;const s=/:(\d+)$/.exec(e.sourceKey),n=s?Number(s[1])+("b"===e.endpoint?1:0):-1;return n>=0&&ne.key===t.sourceKey),o=s.find(e=>e.key===t.targetSourceKey);if(!n||!o)return!1;const r="a"===t.endpoint?n.a:n.b;return!(Math.hypot(r[0]-t.from[0],r[1]-t.from[1])>i)&&(!(Hs(t.to,[o.a[0],o.a[1],o.b[0],o.b[1]])>i)&&!function(t,e){if(!t.sourceKey.startsWith("static:partition|"))return!1;const i=t.sourceKey.slice(17).split("|")[0];return!!i&&e.some(t=>"partition"===t.host?.kind&&t.host.id===i)}(t,this._curSpaceCfg?.openings||[]))}_applyWallRepair(t,e){const i=this._curSpaceCfg;if(!i||!this._validateWallRepair(t,e.activePath))return!1;const s=e=>{e[0]=t.to[0]/Pg,e[1]=t.to[1]/Pg};if(t.sourceKey.startsWith("active:")){const n=/:(\d+)$/.exec(t.sourceKey),o=n?Number(n[1])+("b"===t.endpoint?1:0):-1;if(o<0||o>=e.activePath.length)return!1;e.activePath[o]=[...t.to];const r=(i.room_drafts||[]).find(t=>t.id===e.activeDraftId);return r?.points?.[o]&&s(r.points[o]),!0}if(!t.sourceKey.startsWith("static:"))return!1;const[n,o]=t.sourceKey.slice(7).split("|");if("partition"===n){const e=(i.partitions||[]).find(t=>t.id===o);if(!e)return!1;const n=[e.a[0]*Pg,e.a[1]*Pg],r=[e.b[0]*Pg,e.b[1]*Pg],a=Math.hypot(n[0]-t.from[0],n[1]-t.from[1])<=2e-4*this._gridPitch?e.a:Math.hypot(r[0]-t.from[0],r[1]-t.from[1])<=2e-4*this._gridPitch?e.b:null;return!!a&&(s(a),!0)}if("draft"===n){const e=o.lastIndexOf(":"),n=e>=0?o.slice(0,e):"",r=e>=0?Number(o.slice(e+1)):-1,a=(i.room_drafts||[]).find(t=>t.id===n);if(!a?.points?.[r]||!a?.points?.[r+1])return!1;const l=[r,r+1].find(e=>Math.hypot(a.points[e][0]*Pg-t.from[0],a.points[e][1]*Pg-t.from[1])<=2e-4*this._gridPitch);return null!=l&&(s(a.points[l]),!0)}return!1}_applyWallFaceBatch(){const t=this._wallFaceBatch,e=this._curSpaceCfg,i=this._spaceModel();if(!t||!e||!i)return;const s=(t,e)=>{this._showToast(this._t(t,e)),this._roomDialogCancel()},n=t.decisions.filter(t=>t.create),o=n.map(t=>t.candidate.ring),r=i.rooms;for(let t=0;ti.id!==e&&!!hi(i)&&Di(o[t],hi(i)));if(i)return void s("toast.room_overlap",{name:i.name||""})}if((e.rooms||[]).length+n.length>400)return void s("toast.physical_limit");if(n.some(t=>t.candidate.split&&!e.rooms.some(e=>e.id===t.candidate.split.roomId)))return void s("toast.contour_cannot_close");const a=n.map(t=>t.candidate.repair).filter(t=>!!t);if(a.length>1||a[0]&&!this._validateWallRepair(a[0],t.activePath))return void s("toast.wall_repair_changed");const l=this._activePathWithRepair(t.activePath,a[0]),c=2e-4*this._gridPitch,h=new Map;for(let e=0;et.candidate.atomKeys)),e=n.some(t=>t.candidate.consumeAllActive);for(const i of ru(this._wallGraphSources(l),c)){const s=i.sourceKeys.find(t=>h.has(t));!s||e||t.has(i.key)||d.push({a:i.a,b:i.b,cm:h.get(s)})}}else d.push(...Hd(l,Nd(l.length-1,t.activeCms,this._drawWallCm,fa)));if((e.partitions||[]).length+d.length>Fg)return void s("toast.physical_limit");const u=this._geometrySnapshot();if(a[0]&&!this._applyWallRepair(a[0],t))return void s("toast.wall_repair_changed");const p=n.some(t=>!!t.candidate.split),_=p?rl(i.rooms,e.walls,this._openCuts(),this._wallKeyPitch,this._cellCm,this._gridPitch,Pg):null,g=p&&Array.isArray(e.walls)?e.walls:null;for(const t of n){const i=t.candidate.split;if(!i)continue;const n=e.rooms.find(t=>t.id===i.roomId);if(!n)return void s("toast.contour_cannot_close");n.poly=i.mainPoly.map(t=>[t[0]/Pg,t[1]/this._spaceH]),delete n.x,delete n.y,delete n.w,delete n.h}const m=Date.now().toString(36),f=[];if(n.forEach((t,i)=>{const s=t.area?this.hass.areas[t.area]?.name:"",n={id:`r${m}-${i}`,name:t.name||s||this._t("room.default_name"),area:t.area||null,poly:t.candidate.ring.map(t=>[t[0]/Pg,t[1]/this._spaceH]),...t.settings?{settings:JSON.parse(JSON.stringify(t.settings))}:{}};e.rooms.push(n),f.push({room:n,decision:t})}),t.activeDraftId&&Array.isArray(e.room_drafts)&&(e.room_drafts=e.room_drafts.filter(e=>e.id!==t.activeDraftId),e.room_drafts.length||delete e.room_drafts),d.length&&(e.partitions||=[],d.forEach((t,i)=>e.partitions.push({id:`partition-${m}-${i}`,a:[t.a[0]/Pg,t.a[1]/Pg],b:[t.b[0]/Pg,t.b[1]/Pg],cm:t.cm}))),p){this._commitOpenSpans();const t=this._normalizeWalls(_,this._openCuts());t.length?e.walls=t:g?.length?e.walls=g:delete e.walls}if(f.length){this._cfgEpoch++;const i=this._openCuts(),s=this._spaceModel();if(!s)return;let n=e.walls;for(const{room:e,decision:o}of f){const r=o.candidate.ring,a=this._wallSourceCmAt(r[0],t.activePath,t.activeCms);n=La(n,s.rooms,e.id,a,this._wallKeyPitch,i,Pg);for(const o of ol(s.rooms,n,i,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)){if(o.roomId!==e.id||"outer"!==o.kind)continue;const i=[(o.a[0]+o.b[0])/2,(o.a[1]+o.b[1])/2];n=Na(n,o.a,o.b,this._wallSourceCmAt(i,t.activePath,t.activeCms),this._wallKeyPitch,Pg)}}const o=this._normalizeWalls(n,i);o.length?e.walls=o:delete e.walls}this._recordGeometry(this._t("history.wall_face_batch"),u),this._saveConfig(),delete this._resumeDraftBySpace[this._space],this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._wallFaceBatch=null,this._roomDialog=!1,this._nameSel="",this._areaSel="",this._regSignature="",this._maybeRebuildDevices();const v=new Set(n.map(t=>t.area).filter(t=>!!t));if(v.size){const t={...this._layout};for(const e of this._devices){if(!v.has(e.area||"")||e.space!==this._space)continue;if(this._layout[e.id])continue;const i=this._defPos[e.id];i&&(t[e.id]={s:this._space,x:i.x/Pg,y:i.y/Pg},this._dirtyPos.add(e.id))}this._layout=t,this._persistLayout()}this._showToast(this._t(n.length?"toast.wall_rooms_saved":"toast.wall_chain_saved",{n:n.length}))}_commitRoom(){const t=this._curSpaceCfg,e=this._spaceModel();if(!t||!e)return;const i=this._geometrySnapshot(),s=this._spaceH,n=!!this._pendingSplit,o=n?rl(e.rooms,t.walls,this._openCuts(),this._wallKeyPitch,this._cellCm,this._gridPitch,Pg):null,r=n&&Array.isArray(t.walls)?t.walls:null;let a;if(this._pendingSplit){const e=t.rooms.find(t=>t.id===this._pendingSplit.roomId);if(!e)return this._pendingSplit=null,this._splitSel=null,void(this._roomDialog=!1);e.poly=this._pendingSplit.mainPoly.map(t=>[t[0]/Pg,t[1]/s]),delete e.x,delete e.y,delete e.w,delete e.h,a=this._pendingSplit.newPoly}else{if(!this._contourClosed)return;a=this._path.slice(0,-1)}const l=this._areaSel?this.hass.areas[this._areaSel]?.name:"",c={id:"r"+Date.now().toString(36),name:this._nameSel||l||this._t("room.default_name"),area:this._areaSel||null,poly:a.map(t=>[t[0]/Pg,t[1]/s]),...this._roomSettingsFromDialog()?{settings:this._roomSettingsFromDialog()}:{}};if(t.rooms.push(c),!n&&this._activeDraftId&&Array.isArray(t.room_drafts)&&(t.room_drafts=t.room_drafts.filter(t=>t.id!==this._activeDraftId),t.room_drafts.length||delete t.room_drafts),n){this._commitOpenSpans();const e=this._normalizeWalls(o,this._openCuts());e.length?t.walls=e:r?.length?t.walls=r:delete t.walls}if(!n){const e=Nd(a.length,[...this._draftSegmentCms,this._closingWallCm??void 0],this._drawWallCm,fa),i=e[0];if(null!=i){this._cfgEpoch++;const s=this._openCuts(),n=this._spaceModel();if(!n)return;let o=La(t.walls,n.rooms,c.id,i,this._wallKeyPitch,s,Pg);for(const t of ol(n.rooms,o,s,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)){if(t.roomId!==c.id||"outer"!==t.kind)continue;const i=[(t.a[0]+t.b[0])/2,(t.a[1]+t.b[1])/2],s=a.findIndex((t,e)=>{const s=a[(e+1)%a.length];return Hs(i,[t[0],t[1],s[0],s[1]])<=.02*this._gridPitch});s>=0&&(o=Na(o,t.a,t.b,e[s],this._wallKeyPitch,Pg))}o=this._normalizeWalls(o,s),o.length?t.walls=o:delete t.walls}}this._recordGeometry(this._t(n?"history.split_room":"history.add_room"),i),this._saveConfig(),this._path=[],delete this._resumeDraftBySpace[this._space],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._pendingSplit=null,this._splitSel=null;const h=this._areaSel;this._areaSel="",this._nameSel="",this._roomDialog=!1,this._regSignature="",this._maybeRebuildDevices();let d=0;if(h){const t=Pg,e={...this._layout};for(const i of this._devices){if(i.area!==h||i.space!==this._space)continue;if(d++,this._layout[i.id])continue;const s=this._defPos[i.id];s&&(e[i.id]={s:this._space,x:s.x/Pg,y:s.y/t},this._dirtyPos.add(i.id))}this._layout=e,this._persistLayout()}const u=this._model.find(t=>t.id===this._space)?.rooms.length||0;this._showToast(h?this._t("toast.room_saved",{n:u,added:d}):this._t("toast.room_saved_no_area",{n:u}))}_cancelPath(){this._wallRepairDiagnostic=null,this._activeDraftId&&(this._resumeDraftBySpace[this._space]=this._activeDraftId),this._path=[],this._activeDraftId=null,this._draftSegmentCms=[],this._closingWallCm=null,this._clearPlanSnapHover(),this._roomDialog=!1,this._pendingSplit=null,this._wallFaceBatch=null,this._splitSel=null,this._mergeSel=null,this._mergeDialog=null,this._openWallAnchor=null,this._boundaryRestoreGuard=null,this._physicalSel=null,this._physicalDrag=null,this._physicalRotate=null,this._clearOpeningPlacement(!0)}_resumeLastDraft(){const t=this._resumeDraftBySpace[this._space];if(!t)return;const e=this._spaceModel()?.room_drafts.find(e=>e.id===t);e?(this._activeDraftId=t,this._path=e.points.map(t=>[...t]),this._draftSegmentCms=this._adoptDraftCms(this._path,e.segments.map(t=>t.cm),e.id),this._clearPlanSnapHover()):delete this._resumeDraftBySpace[this._space]}_roomDialogCancel(){if(this._roomDialog=!1,this._roomEditId)return this._roomEditId=null,this._nameSel="",void(this._areaSel="");if(this._wallFaceBatch){const t=this._wallFaceBatch;return this._wallFaceBatch=null,this._path=t.activePath.map(t=>[...t]),this._draftSegmentCms=[...t.activeCms],this._activeDraftId=t.activeDraftId,this._nameSel="",this._areaSel="",void this.requestUpdate()}if(this._pendingSplit)return this._pendingSplit=null,void(this._splitSel=null);this._undoPoint()}get _freeAreas(){const t=new Set;for(const e of this._serverCfg?.spaces||[])for(const i of e.rooms||[])i.area&&t.add(i.area);for(const e of this._wallFaceBatch?.decisions||[])e.create&&e.area&&t.add(e.area);return Object.values(this.hass?.areas||{}).filter(e=>!t.has(e.area_id)).sort((t,e)=>(t.name||"").localeCompare(e.name||""))}_openMarkerDialog(t){if(this._vacAllCamerasFor=null,this._vacAllCameraCache=null,t&&this._ackNewDevice(t.id),this._norm)if(t){const e=t.marker,i=Object.prototype.hasOwnProperty.call(e||{},"is_light"),s=Object.prototype.hasOwnProperty.call(e||{},"light_entity"),n=Object.prototype.hasOwnProperty.call(e||{},"glow_color"),o=Object.prototype.hasOwnProperty.call(e||{},"value_badge"),r=Object.prototype.hasOwnProperty.call(e||{},"tap_action"),a=Object.prototype.hasOwnProperty.call(e||{},"toggle_entity"),l=ks(e?.glow_color),c=this._devicePresentation(t,!0).valueBadge,h=Wo(this._planHass,t,this._devices),d=jo(this._planHass,t,h);this._markerDialog={devId:t.id,name:t.name,binding:"virtual"===t.bindingKind?"virtual":t.bindingKind+":"+t.bindingRef,bindingMode:"virtual"===t.bindingKind?"virtual":"ha",bindingOpen:!1,showEntities:"entity"===t.bindingKind&&!!this._fullRegistryHass.entities[t.bindingRef||""]?.device_id,bindingFilter:"",icon:t.marker?.icon||"",autoIcon:t.icon||"",display:Bi(t.marker?.display),rippleColor:Rt(t.marker?.ripple_color,""),rippleSize:Number(t.marker?.ripple_size)>0?Number(t.marker.ripple_size):1.5,size:Number(t.marker?.size)>0?Number(t.marker.size):1,angle:Number(t.marker?.angle)||0,tapAction:nd(t.marker?.tap_action,t.primary?.split(".")[0]),tapActionTouched:!1,originalHasTapAction:r,originalTapAction:t.marker?.tap_action,tapHintAnnouncement:"",toggleEntity:e?.toggle_entity||"",toggleEntityTouched:!1,originalHasToggleEntity:a,originalToggleEntity:e?.toggle_entity,tapTarget:t.marker?.tap_target||"",tapConfirm:!0===t.marker?.tap_confirm,runFilter:"",controls:Zn(t.marker?.binding,t.marker?.controls,t.entities),controlsFilter:"",lightRole:!0===e?.is_light?"always":!1===e?.is_light?"never":"auto",lightRoleTouched:!1,originalHasIsLight:i,originalIsLight:e?.is_light,lightEntity:e?.light_entity||"",lightEntityTouched:!1,originalHasLightEntity:s,originalLightEntity:e?.light_entity,glowMode:null!=l?.bri?"fixed":l?"color":"auto",glowColor:l?.c||this._fillColors.glow_light.c,glowBrightness:Math.max(1,Math.round(100*(l?.bri??1))),glowColorDrafted:!!l,glowBrightnessDrafted:null!=l?.bri,glowTouched:!1,originalHasGlowColor:n&&(!!l||null===e?.glow_color),originalGlowColor:l||(null===e?.glow_color?null:void 0),valueBadgeEnabled:o?!0===e?.value_badge?.enabled:!!c,valueBadgeSource:e?.value_badge?.source||c?.source||d,valueBadgePosition:e?.value_badge?.position||c?.position||"right",valueBadgeTouched:!1,originalHasValueBadge:o,originalValueBadge:e?.value_badge,useClimateTemp:!0===t.marker?.use_climate_temp,glowRadius:Number(t.marker?.glow_radius_cm)>0?String(this._imperial?Math.round(Number(t.marker.glow_radius_cm)/30.48*10)/10:Math.round(Number(t.marker.glow_radius_cm))/100):"",model:t.model||"",link:t.link||"",description:t.description||"",pdfs:[...t.pdfs||[]],room:t.marker?.room_id?t.space+"#@"+t.marker.room_id:t.space&&t.area?t.space+"#"+t.area:"",hideFromPlan:!0===t.marker?.hidden,busy:!1}}else this._markerDialog={name:"",binding:"virtual",bindingMode:"virtual",bindingOpen:!1,showEntities:!1,bindingFilter:"",icon:"",autoIcon:"",display:"badge",rippleColor:"",rippleSize:1.5,size:1,angle:0,tapAction:"info",tapActionTouched:!1,originalHasTapAction:!1,originalTapAction:void 0,tapHintAnnouncement:"",toggleEntity:"",toggleEntityTouched:!1,originalHasToggleEntity:!1,originalToggleEntity:void 0,tapTarget:"",tapConfirm:!1,runFilter:"",controls:[],controlsFilter:"",lightRole:"auto",lightRoleTouched:!1,originalHasIsLight:!1,originalIsLight:void 0,lightEntity:"",lightEntityTouched:!1,originalHasLightEntity:!1,originalLightEntity:void 0,glowMode:"auto",glowColor:this._fillColors.glow_light.c,glowBrightness:100,glowColorDrafted:!1,glowBrightnessDrafted:!1,glowTouched:!1,originalHasGlowColor:!1,originalGlowColor:void 0,valueBadgeEnabled:!1,valueBadgeSource:null,valueBadgePosition:"right",valueBadgeTouched:!1,originalHasValueBadge:!1,originalValueBadge:void 0,useClimateTemp:!1,glowRadius:"",model:"",link:"",description:"",pdfs:[],room:"",hideFromPlan:!1,busy:!1,uploadId:"up_"+Date.now().toString(36)+Math.random().toString(36).slice(2,6)};else this._showToast(this._t("toast.marker_needs_server"))}_runCandidates(){const t=[];for(const e of Gi)for(const[i,s]of Object.entries(this.hass.states))i.startsWith(e+".")&&this._planEntityAvailable(i)&&t.push({value:i,label:s?.attributes?.friendly_name||i,sub:this._t("run."+e)});return t.sort((t,e)=>t.sub.localeCompare(e.sub)||t.label.localeCompare(e.label))}_bindingCandidates(){const t=this._planHass,e=wo(this._markers),i=new Set(this._markers.filter(t=>t.removed).map(t=>t.binding)),s=new Set;for(const t of this._devices)t.id!==this._markerDialog?.devId&&("device"===t.bindingKind&&t.bindingRef&&s.add("device:"+t.bindingRef),"entity"===t.bindingKind&&t.bindingRef&&s.add("entity:"+t.bindingRef));const n=new Set;for(const t of this._devices)"device"===t.bindingKind&&t.name&&n.add(t.name.trim()+"|"+(t.area||""));const o=[];for(const e of Object.values(t.devices)){if("service"===e.entry_type)continue;const t="device:"+e.id;if(s.has(t))continue;const r=(e.name_by_user||e.name||e.id).trim();t!==this._markerDialog?.binding&&!i.has(t)&&n.has(r+"|"+(e.area_id||""))||o.push({value:t,label:r,sub:(e.model||this._t("marker.sub_device"))+("Group"===e.model?this._t("marker.sub_z2m_group"):"")})}const r=new Set(["group","template","derivative","min_max","threshold","integration","statistics","trend","utility_meter","tod","switch_as_x","schedule"]);for(const[n,a]of Object.entries(t.entities)){const l="entity:"+n;if(s.has(l))continue;if(ko(t,n,e)&&!i.has(l))continue;const c=r.has(a.platform),h="group"===a.platform;if(!c&&!h)continue;if(a.hidden&&!i.has(l))continue;const d=t.states[n];o.push({value:l,label:a.name||d?.attributes?.friendly_name||n,sub:n.split(".")[0]+" · "+("group"===a.platform?this._t("marker.sub_group"):this._t("marker.sub_helper"))})}if(this._markerDialog?.showEntities){const n=new Set(o.map(t=>t.value));for(const[r,a]of Object.entries(t.entities)){const l="entity:"+r;if(s.has(l)||n.has(l)||a.hidden&&!i.has(l))continue;if(ko(t,r,e)&&!i.has(l))continue;const c=t.states[r],h=a.name||c?.attributes?.friendly_name||r,d=a.device_id?t.devices[a.device_id]:null,u=d&&(d.name_by_user||d.name)||"";o.push({value:l,label:h,sub:r.split(".")[0]+" · "+this._t("marker.sub_entity")+(u?" · "+u:"")})}}const a=(this._markerDialog?.bindingFilter||"").toLowerCase().trim(),l=a?o.filter(t=>(t.label+" "+t.sub+" "+t.value).toLowerCase().includes(a)):o;return l.sort((t,e)=>t.label.localeCompare(e.label)),l.slice(0,200)}_physicalBodiesR(t=this._spaceModel()){if(!t)return[];const e=`${t.id}|${this._cfgEpoch}|${this._cellCm}|${this._gridPitch}`;if(this._physicalBodiesCache?.key===e)return this._physicalBodiesCache.all;const i=Ll(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t));return this._physicalBodiesCache={key:e,...i},i.all}_rawPhysicalBodiesR(t=this._spaceModel()){if(!t)return[];this._physicalBodiesR(t);const e=this._physicalBodiesCache;return e?[...e.drafts,...e.partitions,...e.columns]:[]}_cleanFloor(t,e,i=this._spaceModel()){if(!i)return{floor:e,geom:null,path:"",area:Gl([[[...e,e[0]]]])};const s=t.id||`#${i.rooms.indexOf(t)}`,n=`${i.id}|${this._cfgEpoch}|${s}`;if(!this._rszPreview){const t=fg(this._cleanFloorCache,n);if(t.hit)return t.value}const o=e.map(t=>t[0]),r=e.map(t=>t[1]),a=[Math.min(...o),Math.min(...r),Math.max(...o),Math.max(...r)],l=this._physicalBodiesR(i).filter(t=>{const e=t.map(t=>t[0]),i=t.map(t=>t[1]);return Math.max(...e)>=a[0]&&Math.min(...e)<=a[2]&&Math.max(...i)>=a[1]&&Math.min(...i)<=a[3]}),c=l.length?Ul(e,l):null,h={floor:e,geom:c,path:c?zl(c):"",area:Gl(c||[[[...e,e[0]]]])};return this._rszPreview||vg(this._cleanFloorCache,n,h,600),h}_autoIconForBinding(t){if("virtual"===t)return"mdi:map-marker";const[e,i]=t.split(":");if(!i)return"";const s=this._fullRegistryHass,n=this._bindingStatus(t),o="active"===n.kind?n.enabledEntityIds:n.allEntityIds;if("device"===e){const t=s.devices?.[i];if(!t)return"mdi:help-circle";const e=o;return e.some(t=>t.startsWith("lock."))?"mdi:lock":bo(s,t.name_by_user||t.name||"",t.model,e,this._iconRules)}if("entity"===e){const t=s.entities?.[i],e=this.hass.states?.[i],n=t?.name||e?.attributes?.friendly_name||i;return i.startsWith("lock.")?"mdi:lock":bo(s,n,"",[i],this._iconRules)}return""}_allRoomsFlat(){const t=[];for(const e of this._serverCfg?.spaces||[])for(const i of e.rooms||[])i.area?t.push({value:e.id+"#"+i.area,label:(e.title||e.id)+" · "+i.name}):i.id&&t.push({value:e.id+"#@"+i.id,label:(e.title||e.id)+" · "+i.name+" · "+this._t("marker.subarea")});return t}_errText(t){if(!t)return this._t("err.unknown");if("string"==typeof t)return t;if("invalid_passage_fields"===t.code){const e=String(t.message||t.error||"").match(/space=([^;]*);\s*opening=([^;]*);\s*fields=([^;]*)/);if(e){const t=this._serverCfg?.spaces?.find(t=>String(t.id)===e[1]),i={contact:"opening.contact_label",lock:"opening.lock_label",invert:"opening.invert",flip_h:"opening.flip_h",flip_v:"opening.flip_v"},s=e[3].split(",").filter(Boolean).map(t=>i[t]?this._t(i[t]):t).join(", ");return this._t("opening.invalid_passage_fields",{room:t?.title||e[1],fields:s})}}if("invalid_partition_opening_jamb_margin"===t.code){const e=String(t.message||t.error||"").match(/margin_cm=([^;]*)/),i=e?Number(e[1]):NaN;if(Number.isFinite(i))return this._t("opening.partition_jamb_margin",{distance:li(i,this._imperial)})}if(t.message)return t.message;if(t.error)return t.error;if(null!=t.code)return this._t("err.code",{code:t.code});try{return JSON.stringify(t)}catch{return String(t)}}_backupErrorText(t){const e=t?.code??t?.error;if("string"==typeof e){const t=`backup.error.${e}`,i=this._t(t);if(i!==t)return i}return this._errText(t)}async _pickMarkerFiles(t){const e=t.target,i=e.files?[...e.files]:[];if(e.value="",!i.length||!this._markerDialog)return;const s=this._markerDialog.uploadId||this._markerDialog.devId||"new",n=[];for(const t of i)try{const e=new FormData;e.append("marker_id",s),e.append("file",t,t.name);const i=this.hass?.fetchWithAuth?await this.hass.fetchWithAuth("/api/houseplan/upload",{method:"POST",body:e}):await fetch("/api/houseplan/upload",{method:"POST",body:e,headers:this.hass?.auth?.data?.access_token?{authorization:`Bearer ${this.hass.auth.data.access_token}`}:{}}),o=await i.json().catch(()=>({}));if(!i.ok||o.error){const t={too_large:this._t("err.too_large",{mb:o.max_mb||50}),bad_ext:this._t("err.bad_ext"),unauthorized:this._t("err.unauthorized")};throw new Error(t[o.error]||o.error||"HTTP "+i.status)}n.push({name:o.name||t.name,url:o.url})}catch(e){this._showToast(this._t("toast.file_failed",{name:t.name,err:this._errText(e)}))}n.length&&this._markerDialog&&(this._markerDialog={...this._markerDialog,pdfs:[...this._markerDialog.pdfs,...n]},this._showToast(this._t("toast.files_attached",{n:n.length})))}_removeMarkerPdf(t){this._markerDialog&&(this._markerDialog={...this._markerDialog,pdfs:this._markerDialog.pdfs.filter(e=>e.url!==t)})}_markerLightFields(t){const e={};if(t.lightRoleTouched?"always"===t.lightRole?e.is_light=!0:"never"===t.lightRole&&(e.is_light=!1):t.originalHasIsLight&&(e.is_light=t.originalIsLight??null),t.lightEntityTouched?t.lightEntity&&(e.light_entity=t.lightEntity):t.originalHasLightEntity&&(e.light_entity=t.originalLightEntity??null),t.glowTouched){if("auto"!==t.glowMode){const i={c:Rt(t.glowColor,this._fillColors.glow_light.c)};"fixed"===t.glowMode&&(i.bri=Math.max(.01,Math.min(1,Math.round(t.glowBrightness)/100))),e.glow_color=i}}else t.originalHasGlowColor&&(e.glow_color=t.originalGlowColor??null);return e}_markerTapActionFields(t){return t.tapActionTouched?{tap_action:t.tapAction||null}:t.originalHasTapAction?{tap_action:t.originalTapAction??null}:{}}_markerToggleEntityFields(t){return(e={touched:t.toggleEntityTouched,originalHas:t.originalHasToggleEntity,original:t.originalToggleEntity,value:t.toggleEntity}).touched?e.value?{toggle_entity:e.value}:{}:e.originalHas?{toggle_entity:e.original??null}:{};var e}async _saveMarker(){const t=this._markerDialog;if(!t||t.busy)return;const e=this._effectiveMarkerTapAction(t);if("ha"===t.bindingMode&&(!t.binding||"virtual"===t.binding))return;if("virtual"===t.binding&&!t.name.trim())return void this._showToast(this._t("toast.virtual_name_required"));if("run"===e&&!t.tapTarget)return void this._showToast(this._t("toast.run_target_required"));if(t.valueBadgeTouched&&t.valueBadgeEnabled&&!t.valueBadgeSource)return void this._showToast(this._t("toast.value_badge_source_required"));if("ha"===t.bindingMode){const e=this._bindingStatus(t.binding),i=t.devId?this._markers.find(e=>e.id===t.devId):null,s=!i||i.binding!==t.binding;if("active"!==e.kind&&s)return void this._showToast(this._t("ha_disabled"===e.kind?"toast.ha_disabled_add":"toast.ha_binding_unverified"));if("ha_disabled"===e.kind&&!0===i?.hidden&&!t.hideFromPlan)return this._markerDialog={...t,hideFromPlan:!0},void this._showToast(this._t("entity"===e.reason?"toast.ha_disabled_show_entity":"toast.ha_disabled_show_device"))}const i=this._serverCfg;if(!i)return;const s=i.markers||[],n=qs(t.room);let o=n?.space||null;const r=n?.area||null,a=n?.roomId||null,l=Ei(t.binding,t.devId,()=>"v_"+Date.now().toString(36)),c=t.devId,h=c?this._devices.find(t=>t.id===c):null,d=n?.space||h?.space||null,u=d?this._spaceModelById(d):this._spaceModel();if(!u)return;const p=u.id;"virtual"!==t.binding||o||(o=p),this._markerDialog={...t,busy:!0};try{const n="virtual"===t.binding?[]:s.filter(e=>e.removed&&e.binding===t.binding).map(t=>t.id),d=n.length>0,_=Zn(t.binding,t.controls,this._bindingEntities(t.binding)),g=s.find(t=>t.id===l||t.id===c)?.vacuum||null,m={id:l,vacuum:g,binding:t.binding,name:t.name.trim()||null,icon:t.icon||null,display:"badge"!==t.display?t.display:null,ripple_color:"icon_ripple"===t.display&&t.rippleColor?t.rippleColor:null,ripple_size:"icon_ripple"===t.display&&1.5!==t.rippleSize?t.rippleSize:null,size:1!==t.size?t.size:null,angle:t.angle?t.angle:null,...this._markerTapActionFields(t),...this._markerToggleEntityFields(t),tap_target:"run"===e&&t.tapTarget||null,tap_confirm:!!t.tapConfirm||null,controls:_.length?_:null,...this._markerLightFields(t),...this._markerValueBadgeFields(t),use_climate_temp:!!t.useClimateTemp||null,glow_radius_cm:(()=>{const e=mg(t.glowRadius);return null==e||e<=0?null:Math.round(this._imperial?30.48*e:100*e)})(),model:t.model.trim()||null,link:t.link.trim()||null,description:t.description.trim()||null,pdfs:t.pdfs,hidden:!!t.hideFromPlan};("virtual"===t.binding||t.room)&&(m.space=o,m.area=r,m.room_id=a);const f=h?.marker?.room_id??null,v=!!t.room&&null!=h&&(h.space!==o||h.area!==r||f!==a);let y=!1;const b=t.uploadId||c;if(b&&b!==l&&m.pdfs?.length)try{const t=await this.hass.callWS({type:"houseplan/files/migrate",from_id:b,to_id:l}),e=t?.mapping||{};m.pdfs=function(t,e,i,s){if(!e||!i||e===i)return t;const n="/files/"+e+"/",o="/files/"+i+"/";return t.map(t=>{if(!t.url.includes(n))return t;const e=t.url.split(n)[1]||"",[i,r]=[e.split("?")[0],e.includes("?")?"?"+e.split("?")[1]:""];if(s){const e=s[decodeURIComponent(i)]??s[i];return e?{...t,url:t.url.split(n+i)[0]+o+encodeURIComponent(e)+r}:t}return{...t,url:t.url.split(n).join(o)}})}(m.pdfs,b,l,e),y=Object.keys(e).length>0}catch(t){this._showToast(this._t("toast.files_migrate_failed",{err:this._errText(t)}))}i.markers=s,c&&c!==l&&(i.markers=function(t,e,i){if(!e||!i||e===i)return[...t];const s=`marker:${e}`,n=`marker:${i}`;return t.map(t=>{const e=Array.isArray(t.controls)?t.controls.map(t=>t===s?n:t):t.controls,i="derived_marker_state"===t.value_badge?.source?.kind&&t.value_badge.source.ref===s?{...t.value_badge,source:{...t.value_badge.source,ref:n}}:t.value_badge;return e===t.controls&&i===t.value_badge?t:{...t,controls:e,value_badge:i}})}(i.markers,c,l)),c&&c!==l&&"derived_marker_state"===m.value_badge?.source?.kind&&m.value_badge.source.ref===`marker:${c}`&&(m.value_badge.source={kind:"derived_marker_state",ref:`marker:${l}`}),i.markers=i.markers.filter(t=>t.id!==l&&t.id!==c&&("virtual"===m.binding||t.binding!==m.binding)),i.markers.push(m);let w=null;const k=c?this._layout[c]:null,x=k?{s:k.s||h?.space||this._space,x:k.x,y:k.y}:c&&h&&this._defPos[c]?this._normPos(h.space,this._defPos[c].x,this._defPos[c].y):null;if(!d&&x&&x.s===p)l===c&&this._layout[l]&&!v||(w={s:x.s,x:x.x,y:x.y},this._layout={...this._layout,[l]:w});else if(d||!this._layout[l]||v){let t=u.vb[0]+u.vb[2]/2,e=u.vb[1]+u.vb[3]/2;const i=a?u.rooms.find(t=>t.id===a):r?u.rooms.find(t=>t.area===r):void 0;i&&([t,e]=this._roomCenter(i)),w=this._normPos(p,t,e),this._layout={...this._layout,[l]:w}}await this._saveConfigNow(),w&&this._noteLayoutRev(await this.hass.callWS({type:"houseplan/layout/update",device_id:l,pos:w}));const $=new Set(n);c&&c!==l&&$.add(c),$.delete(l);for(const t of $)delete this._layout[t],await this.hass.callWS({type:"houseplan/layout/delete",device_id:t}).then(t=>this._noteLayoutRev(t)).catch(()=>{});y&&b&&await this.hass.callWS({type:"houseplan/files/cleanup",marker_id:b}).catch(()=>{}),this._markerDialog=null,this._regSignature="",this._maybeRebuildDevices(),this._showToast(this._t("toast.marker_saved"))}catch(t){this._markerDialog&&(this._markerDialog={...this._markerDialog,busy:!1}),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}async _deleteMarker(){const t=this._markerDialog;if(!t||t.busy||!t.devId)return;const e=t.devId?this._devices.find(e=>e.id===t.devId):null;if(!e)return;const i=t.name||this._t("device.fallback");if(!confirm(this._t("confirm.remove_marker",{name:i})))return;const s=this._serverCfg;s.markers=s.markers||[];const n=s.markers,o="virtual"===e.bindingKind?"virtual":e.bindingKind&&e.bindingRef?`${e.bindingKind}:${e.bindingRef}`:"";if(!o)return;const r=function(t,e,i,s){const n=new Set([e]),o=t.filter(t=>{const o=t.id===e||!s&&t.binding===i;return o&&n.add(t.id),!o});return{markers:s?o:[...o,{id:e,binding:i,removed:!0,hidden:!0}],cleanupIds:n}}(s.markers,e.id,o,"virtual"===e.bindingKind);var a,l;s.markers=(a=r.markers,l=r.cleanupIds,a.map(t=>{if(!Array.isArray(t.controls))return t;const e=t.controls.filter(t=>!("string"==typeof t&&t.startsWith("marker:")&&l.has(t.slice(7))));return e.length===t.controls.length?t:{...t,controls:e.length?e:null}}));const c=r.cleanupIds;this._markerDialog={...t,busy:!0};try{await this._saveConfigNow();for(const t of c){delete this._layout[t],delete this._defPos[t],this._dirtyPos.delete(t),this._sentPos.delete(t);const e=this._activityRt.get(t);e&&clearTimeout(e.timer),this._activityRt.delete(t),this._vacRt.delete(t),delete this._vacSrvTrails[t],await this.hass.callWS({type:"houseplan/layout/delete",device_id:t}).then(t=>this._noteLayoutRev(t)).catch(()=>{}),await this.hass.callWS({type:"houseplan/files/cleanup",marker_id:t}).catch(()=>{}),await this.hass.callWS({type:"houseplan/trail/delete",marker_id:t}).catch(()=>{})}this._markerDialog=null,this._infoCard?.id===e.id&&this._closeInfoCard(),this._selId===e.id&&(this._selId=null),this._drag?.id===e.id&&(this._drag=null),this._regSignature="",this._maybeRebuildDevices(),this._showToast(this._t("toast.marker_removed"))}catch(t){this._serverCfg===s&&(s.markers=n),this._markerDialog&&(this._markerDialog={...this._markerDialog,busy:!1}),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}_normPos(t,e,i){return{s:t,x:e/Pg,y:i/Pg}}_openSpaceDialog(t,e){if(this._serverStorage&&this._serverCfg)if("edit"===t){const i=this._serverCfg.spaces.find(t=>t.id===e);if(!i)return;const s=cs(i),n=i.settings?.custom_fill&&"object"==typeof i.settings.custom_fill?as(i.settings.custom_fill):null,o="none"===s.fill?{...n||rs,a:0}:n;this._spaceDialog={mode:t,spaceId:e,title:i.title,planUrl:i.plan_url||null,planFile:null,source:i.plan_url?"file":"draw",showBorders:s.showBorders,showNames:s.showNames,displayTouched:!0,hideDecor:s.hideDecor,hideOpenings:s.hideOpenings,roomColor:s.color,roomOpacity:s.opacity,fillMode:"none"===s.fill?"custom":s.fill,customFill:o,glowEnabled:s.glow,bgColor:s.bgColor,bgMode:"static"===i.settings?.bg_mode||"daynight"===i.settings?.bg_mode?i.settings.bg_mode:null,northDeg:Zr({},i.settings),sunRays:"boolean"==typeof i.settings?.sun_rays?i.settings.sun_rays:null,tempMin:s.tempMin,tempMax:s.tempMax,showLqi:s.showLqi??this._config?.show_signal??!0,cardFontScale:s.cardFontScale,labelTemp:s.labelTemp,labelHum:s.labelHum,labelLqi:s.labelLqi,labelLight:s.labelLight,cellCm:Number(i.cell_cm)>0?Number(i.cell_cm):5,busy:!1}}else this._spaceDialog={mode:t,title:"",planUrl:null,planFile:null,...fh(),hideDecor:!1,hideOpenings:!1,roomColor:ns,roomOpacity:os,fillMode:"custom",customFill:{...rs,a:0},glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:20,tempMax:25,showLqi:this._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:5,busy:!1};else this._showToast(this._t("toast.integration_missing"))}async _pickPlanFile(t){const e=t.target,i=e.files?.[0];if(!i||!this._spaceDialog)return;const s={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/webp":"webp"}[i.type]||(i.name.toLowerCase().endsWith(".svg")?"svg":"");if(!s)return void this._showToast(this._t("toast.plan_formats"));const n=new Uint8Array(await i.arrayBuffer());let o="";for(let t=0;t{const e=new Image;e.onload=()=>t(e.naturalWidth&&e.naturalHeight?e.naturalWidth/e.naturalHeight:1.414),e.onerror=()=>t(1.414),e.src=a});URL.revokeObjectURL(a),this._spaceDialog={...this._spaceDialog,planFile:{ext:s,b64:r,aspect:l,name:i.name}}}_useServerPlan(t){const e=this._spaceDialog;e&&(this._spaceDialog={...e,planUrl:t,planFile:null,pickSaved:!1,savedAspect:void 0},this._aspectJob=this._readPlanAspect(t))}async _readPlanAspect(t){for(let e=0;e<40;e++){const e=this._display(t);if(e){const i=await new Promise(t=>{const i=new Image;i.onload=()=>t(i.naturalWidth&&i.naturalHeight?i.naturalWidth/i.naturalHeight:0),i.onerror=()=>t(0),i.src=e}),s=this._spaceDialog;return s&&s.planUrl===t&&Number.isFinite(i)&&i>0?(this._spaceDialog={...s,savedAspect:i},i):0}if(await new Promise(t=>setTimeout(t,150)),this._spaceDialog?.planUrl!==t)return 0}return 0}async _deleteServerPlan(t){if(confirm(this._t("confirm.delete_plan",{name:t})))try{await this.hass.callWS({type:"houseplan/plans/delete",name:t});const e=this._spaceDialog;e?.saved&&(this._spaceDialog={...e,saved:e.saved.filter(e=>e.name!==t)})}catch(t){this._showToast(this._t("toast.plan_delete_failed",{err:this._errText(t)}))}}_renderServerPlans(t){if(t.savedBusy)return W`${this._t("space.loading")}
`;const e=t.saved||[];if(!e.length)return W`${this._t("space.no_saved")}
`;return W`
${e.map(e=>W`
${e.name}
${(t=>t>=1048576?(t/1048576).toFixed(1)+" MB":Math.round(t/1024)+" KB")(e.size)}${e.used_by.length?" · "+this._t("space.used_by",{list:e.used_by.join(", ")}):""}
this._useServerPlan(e.url)}
?disabled=${e.url===t.planUrl}>${this._t("btn.use")}
0||e.url===t.planUrl}
@click=${()=>this._deleteServerPlan(e.name)}>
`)}
`}async _saveSpaceDialog(){const t=this._spaceDialog;if(!t||t.busy||!t.title.trim())return;if("file"===t.source&&!t.planFile&&!t.planUrl)return void this._showToast(this._t("toast.plan_required"));const e="create"===t.mode&&0===(this._serverCfg?.spaces.length||0);this._spaceDialog={...t,busy:!0};try{const i="create"===t.mode?"s"+Date.now().toString(36):t.spaceId;let s=null;if("file"===t.source&&t.planFile){s={url:(await this.hass.callWS({type:"houseplan/plan/set",space_id:i,ext:t.planFile.ext,data:t.planFile.b64})).url,aspect:t.planFile.aspect}}let n=t.savedAspect||null;!s&&"file"===t.source&&t.planUrl&&!n&&this._aspectJob&&(n=await this._aspectJob||null);const o=this._serverCfg;let r;if("create"===t.mode)r={id:i,title:t.title.trim(),plan_url:null,view_box:[0,0,1,1],rooms:[]},o.spaces.push(r);else{if(r=o.spaces.find(t=>t.id===i),!r)throw new Error("space "+i+" is gone from the config");r.title=t.title.trim()}s?(r.plan_url=s.url,r.plan_aspect=s.aspect):"file"===t.source&&t.planUrl&&t.planUrl!==r.plan_url&&(r.plan_url=t.planUrl,r.plan_aspect=n),"draw"===t.source&&(r.plan_url=null,r.plan_aspect=null,delete r.plan_x,delete r.plan_y,delete r.plan_scale,delete r.plan_scale_x,delete r.plan_scale_y,delete r.plan_angle),r.settings={...r.settings||{},show_borders:t.showBorders,show_names:t.showNames,hide_decor:t.hideDecor||void 0,hide_openings:t.hideOpenings||void 0,room_color:t.roomColor,room_opacity:t.roomOpacity,bg_color:t.bgColor||void 0,bg_mode:t.bgMode||void 0,north_deg:t.northDeg??void 0,sun_rays:t.sunRays??void 0,fill_mode:t.fillMode,custom_fill:t.customFill||void 0,glow_enabled:t.glowEnabled,temp_min:Number.isFinite(t.tempMin)?Math.min(t.tempMin,t.tempMax):20,temp_max:Number.isFinite(t.tempMax)?Math.max(t.tempMin,t.tempMax):25,show_lqi:t.showLqi,card_font_scale:1!==t.cardFontScale?t.cardFontScale:void 0,label_temp:t.labelTemp,label_hum:t.labelHum,label_lqi:t.labelLqi,label_light:t.labelLight},r.cell_cm=Number.isFinite(t.cellCm)&&t.cellCm>0?Math.max(.1,Math.min(_g,t.cellCm)):5,await this._saveConfigNow(),this._spaceDialog=null,"create"===t.mode&&this._commitSpace(r.id),this._regSignature="",this._maybeRebuildDevices(),this._importQueue.length?this._openNextImport():e||this._importTotal>0?(this._importTotal=0,this._commitSpace(this._serverCfg.spaces[0]?.id||this._space),this._setMode("plan"),this._tool="draw",this._path=[],this._cursorPt=null,this._primeDrawWallField(),this._showToast(this._t(e&&!this._importTotal?"toast.space_added_onboard":"import.done"))):(this._showToast("create"===t.mode?this._t("toast.space_added"):this._t("toast.space_saved")),"create"===t.mode&&("plan"!==this._mode?this._setMode("plan"):(this._tool="draw",this._path=[],this._cursorPt=null,this._primeDrawWallField(),this._saveNav())))}catch(t){this._spaceDialog&&(this._spaceDialog={...this._spaceDialog,busy:!1}),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}async _deleteSpace(){const t=this._spaceDialog;if(!t||"edit"!==t.mode)return;const e=this._serverCfg.spaces.find(e=>e.id===t.spaceId);if(confirm(this._t("confirm.delete_space",{title:e.title}))){this._serverCfg.spaces=this._serverCfg.spaces.filter(e=>e.id!==t.spaceId);try{await this._saveConfigNow(),this._spaceDialog=null,this._space===t.spaceId&&this._commitSpace(this._serverCfg.spaces[0]?.id||""),this._regSignature="",this._maybeRebuildDevices(),this._showToast(this._t("toast.space_deleted"))}catch(t){this._showToast(this._t("toast.delete_failed",{err:this._errText(t)}))}}}async _saveConfigNow(){this._cfgEpoch++;try{await this._writeConfig()}catch(t){throw"conflict"===t?.code&&await this._reloadConfigOnly(),t}}_startImport(){const t=this._importDialog;if(!t)return;const e=t.floors.filter(t=>t.checked).map(t=>t.name);this._importDialog=null,e.length?(this._importQueue=e,this._importTotal=e.length,this._openNextImport()):this._openSpaceDialog("create")}_openNextImport(){const t=this._importQueue.shift();void 0!==t&&(this._spaceDialog={mode:"create",title:t,planUrl:null,planFile:null,...fh(),hideDecor:!1,hideOpenings:!1,roomColor:ns,roomOpacity:os,fillMode:"custom",customFill:null,glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:20,tempMax:25,showLqi:this._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:5,busy:!1})}_skipImport(){this._spaceDialog=null,this._importQueue.length?this._openNextImport():this._importTotal>0&&this._model.length&&(this._importTotal=0,this._commitSpace(this._serverCfg.spaces[0]?.id||this._space),this._setMode("plan"),this._showToast(this._t("import.done")))}_renderImportDialog(){const t=this._importDialog,e=t.floors.filter(t=>t.checked).length;return W`this._importDialog=null}>
${this._t("import.hint")}
${t.floors.map((e,i)=>W`
{const n=[...t.floors];n[i]={...e,checked:s.target.checked},this._importDialog={floors:n}}} />
${e.name}
${null!=e.level?W`L${e.level} `:G}
`)}
{this._importDialog=null,this._openSpaceDialog("create")}}>
${this._t("import.manual")}
this._startImport()} ?disabled=${!e}>
${this._t("import.start",{n:e})}
`}_sunGlobal(){const t=this._settingsDialog;return t?{...this._settings,north_deg:t.northDeg??void 0,bg_mode:t.bgMode,sun_rays:t.sunRays}:this._settings}_sunSpace(){const t=this._spaceDialog,e=this._curSpaceCfg?.settings||{};return t&&"edit"===t.mode&&t.spaceId===this._space?{...e,north_deg:t.northDeg??void 0,bg_mode:t.bgMode??void 0,sun_rays:t.sunRays??void 0}:e}_effNorth(){return Zr(this._sunGlobal(),this._sunSpace())}_effBgMode(){return Qr(this._sunGlobal(),this._sunSpace())}_dayCycleState(t=new Date){return(this._modeTransitionVisual?.viewWeight??("view"===this._mode?1:0))<=0||"daynight"!==this._effBgMode()?null:qr(this._renderPlanHass,t)}_syncDayCycleClock(){const t=this._dayCycleState();this._dayCycleClockKey=t?Wr(t):"";const e="clock"===t?.source&&"hidden"!==this.ownerDocument.visibilityState&&this.isConnected;e&&!this._dayCycleTimer?this._dayCycleTimer=window.setInterval(this._dayCycleTick,3e4):!e&&this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_dayCycleVisibility(t){"hidden"!==t.kind?(this._dayCycleTick(),this._syncDayCycleClock()):this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_effSunRays(){return ta(this._sunGlobal(),this._sunSpace())}_sunNow(){return null!==this._effNorth()?ea(this._renderPlanHass):null}_renderSunRays(t){const e=j``,i=this._modeTransitionVisual?.viewWeight??0;if(this._editing&&i<=0||!this._effSunRays())return this._sunFadeReset(),e;const s=this._effNorth(),n=null!==s?ea(this._renderPlanHass):null;if(!n||n.elevation<=0)return this._sunFadeReset(),e;if(o=n.elevation,Number(o)>=3)this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunOut=!1,this._sunShown=!0;else{if(!this._sunShown)return e;this._sunOut||(this._sunOut=!0,this._sunOutTimer=window.setTimeout(()=>{this._sunOutTimer=0,this._sunShown=!1,this._sunOut=!1,this.requestUpdate()},2e3))}var o;const r=`${t.id}|${n.azimuth}|${n.elevation}|${s}|${this._cfgEpoch}`;if(!this._sunRaysCache||this._sunRaysCache.key!==r){const e=t.rooms.map(t=>({id:t.id||"",poly:hi(t)})).filter(t=>!!t.id&&!!t.poly),i=this._openingsR.filter(t=>"window"===t.type&&!t.host).map(t=>({id:t.id,x:t.rx,y:t.ry,angle:t.angle,length:t.rlen})),o=this._spaceWalls,a=this._openPairs().flatMap(t=>t.segs),l=this._openingWallIndexFor(t,a).value,c={},h={};if(o.length){for(const i of e){const e=hl(t.rooms,i.id,o,a,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg);e&&(c[i.id]=e)}for(const t of i){const e=Sl(l,{x:t.x,y:t.y,angle:t.angle,length:t.length});e.cm>0&&(h[t.id]=xa(e.cm,this._cellCm,this._gridPitch))}}let d=Xr(e,i,n.azimuth,n.elevation,s,o.length?c:void 0,o.length?h:void 0);const u=this._physicalBodiesR(t);u.length&&(d=d.map(t=>{const e=function(t,e,i){return i>0?t.map(t=>function(t){const e=[...t].sort((t,e)=>t[0]-e[0]||t[1]-e[1]);if(e.length<=2)return e;const i=(t,e,i)=>(e[0]-t[0])*(i[1]-t[1])-(e[1]-t[1])*(i[0]-t[0]),s=[];for(const t of e){for(;s.length>=2&&i(s[s.length-2],s[s.length-1],t)<=0;)s.pop();s.push(t)}const n=[];for(let t=e.length-1;t>=0;t--){const s=e[t];for(;n.length>=2&&i(n[n.length-2],n[n.length-1],s)<=0;)n.pop();n.push(s)}return s.slice(0,-1).concat(n.slice(0,-1))}([...t,...t.map(t=>[t[0]+e[0]*i,t[1]+e[1]*i])])).filter(t=>t.length>=3):t}(u,t.dir,t.len),i=t.polys.map(t=>Ul(t,e));return{...t,paths:i.map(zl).filter(Boolean),polys:i.flatMap(Vl)}}).filter(t=>t.paths?.length||t.polys.length)),this._sunRaysCache={key:r,rays:d,rims:d.map(t=>function(t,e=1e-4){const[i,s]=t.dir,n=-s,o=i,r=[];for(const a of[t.a,t.b]){const l=[];for(const r of t.polys)for(let t=0;te)continue;if(Math.abs((h[0]-a[0])*n+(h[1]-a[1])*o)>e)continue;const d=(c[0]-a[0])*i+(c[1]-a[1])*s,u=(h[0]-a[0])*i+(h[1]-a[1])*s;Math.abs(u-d)<=e||l.push(dt[0]-e[0]);const c=[];for(const t of l){const i=c[c.length-1];i&&t[0]<=i[1]+e?i[1]=Math.max(i[1],t[1]):c.push([t[0],t[1]])}for(const[t,e]of c)r.push([[a[0]+i*t,a[1]+s*t],[a[0]+i*e,a[1]+s*e]])}return r}(t))}}const a=this._sunRaysCache.rays,l=this._sunRaysCache.rims;if(!a.length)return e;const c=(h=function(t){const e=Math.min(90,Math.max(-90,Number(t)||0));let i=jr[jr.length-1][1];for(let t=1;t
${a.map((t,e)=>{const i=(t.a[0]+t.b[0])/2,s=(t.a[1]+t.b[1])/2,n=i+t.normal[0]*t.depth,o=s+t.normal[1]*t.depth;return j`
${d.map(([t,e])=>j` `)}
${u.map(([t,e])=>j` `)}
`})}
${a.map((t,e)=>t.paths?.length?t.paths.map(t=>j` `):t.polys.map(t=>j` `))}
${a.map((t,e)=>(l[e]||[]).map(t=>j` `))}
`}_sunFadeReset(){this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunShown=!1,this._sunOut=!1}_compassPoint(t){const e=t.currentTarget.getBoundingClientRect(),i=t.clientX-(e.left+e.width/2),s=t.clientY-(e.top+e.height/2);if(Math.hypot(i,s)<5)return;let n=Math.round(180*Math.atan2(i,-s)/Math.PI);t.shiftKey&&(n=15*Math.round(n/15)),n=(n%360+360)%360,this._settingsDialog={...this._settingsDialog,northDeg:n}}_renderCompass(){const t=this._settingsDialog.northDeg;return W`{t.currentTarget.setPointerCapture(t.pointerId),this._compassDrag=!0,this._compassPoint(t)}}
@pointermove=${t=>{this._compassDrag&&this._compassPoint(t)}}
@pointerup=${()=>this._compassDrag=!1}
@pointercancel=${()=>this._compassDrag=!1}>
${[0,45,90,135,180,225,270,315].map(t=>j` `)}
${this._t("gs.north_letter")}
${null===t?"—":t+"°"}
`}_stageBg(t){const e=this._settingsDialog,i=this._spaceDialog,s=e?e.bgColor||"":hs(this._settings,{bgColor:null});return(i&&"edit"===i.mode&&i.spaceId===this._space?i.bgColor||"":t.bgColor||"")||s}_stageBgHex(){const t=this._stageEl;if(t){const e=getComputedStyle(t).backgroundColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e)return"#"+e.slice(1,4).map(t=>(+t).toString(16).padStart(2,"0")).join("")}return"#111111"}async _runAlignToGrid(){const t=this._alignDialog;if(t&&!t.busy&&this._serverCfg){this._clearGeometryGesture(),this._alignDialog={...t,busy:!0};try{this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),await this._writeChain;const e=await this.hass.callWS({type:"houseplan/plan/optimize",config:t.config,layout:t.layout,expected_config_rev:this._cfgRev,expected_layout_rev:this._layoutRev});this._serverCfg=t.config,this._layout=t.layout,this._geometryHistory.clear(),this._cfgRev=e?.config_rev??this._cfgRev+1,this._layoutRev=e?.layout_rev??this._layoutRev+1,this._canOptimizeUndo=!!e?.can_undo,this._undoKind=e?.can_undo?"optimize":null,this._dirtyPos.clear(),this._sentPos.clear(),this._cfgEpoch++,this._modelCache=null,this._frame=null,this._cacheSnapshot(),this._alignDialog=null,this.requestUpdate(),this._showToast(this._t("gs.align_done",{n:String(t.report.moved),m:String(t.report.migrated+t.report.canonicalized+t.report.coordsCanonicalized+t.report.wallsMerged+t.report.spansMerged+t.report.partitionsMerged)}))}catch(t){this._alignDialog&&(this._alignDialog={...this._alignDialog,busy:!1}),"conflict"===t?.code&&await Promise.all([this._reloadConfigOnly(!0),this._reloadLayoutOnly()]),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}}async _undoPlanOptimization(){if(!this._canOptimizeUndo||this._optimizeUndoBusy)return;const t=this._undoKind;this._clearGeometryGesture(),this._optimizeUndoBusy=!0,this.requestUpdate();try{await this.hass.callWS({type:"houseplan/plan/optimize_undo",expected_config_rev:this._cfgRev,expected_layout_rev:this._layoutRev});const[e,i]=await Promise.all([this.hass.callWS({type:"houseplan/config/get"}),this.hass.callWS({type:"houseplan/layout/get"})]);this._serverCfg=e?.config||this._serverCfg,this._cfgRev=e?.rev??this._cfgRev,this._layout=i?.layout||this._layout,this._geometryHistory.clear(),this._layoutRev=i?.rev??this._layoutRev,this._canOptimizeUndo=!1,this._undoKind=null,this._cfgEpoch++,this._modelCache=null,this._frame=null,this._cacheSnapshot(),this.requestUpdate(),this._showToast(this._t("import"===t?"backup.import_undone":"gs.optimize_undone"))}catch(t){this._canOptimizeUndo=!1,this._undoKind=null,this._showToast(this._t("toast.error",{err:this._errText(t)}))}finally{this._optimizeUndoBusy=!1,this.requestUpdate()}}async _runBackupExport(){const t=this._backupExportDialog;if(t&&!t.busy){this._backupExportDialog={...t,busy:!0,error:""};try{const e=await this.hass.callWS({type:"houseplan/export/create",kind:t.kind,space_id:"space"===t.kind?this._space:void 0,..."space"===t.kind&&t.planOnly?{plan_only:!0}:{},card_version:hg}),i=new Blob([JSON.stringify(e.document,null,2)+"\n"],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=e.filename||`houseplan-${t.kind}.json`,n.style.display="none",document.body.append(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(s),0),this._backupExportDialog=null,this._showToast(this._t("backup.export_done"))}catch(t){this._backupExportDialog&&(this._backupExportDialog={...this._backupExportDialog,busy:!1,error:this._backupErrorText(t)})}}}async _pickBackupImport(t){const e=t.target,i=e.files?.[0];if(e.value="",i){this._settingsDialog=null,this._backupImportDialog={filename:i.name,size:i.size,token:"",preview:null,expectedConfigRev:this._cfgRev,expectedLayoutRev:this._layoutRev,duplicatePolicy:"skip",confirmMissing:!1,busy:!0,error:""};try{this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),await this._writeChain,this._persistLayout.pending()&&this._persistLayout.flush();const t="/api/houseplan/import/preview?duplicate_policy=skip",e={method:"POST",body:i,headers:{"content-type":"application/json"}},s=this.hass?.fetchWithAuth?await this.hass.fetchWithAuth(t,e):await fetch(t,{...e,headers:{...e.headers,...this.hass?.auth?.data?.access_token?{authorization:`Bearer ${this.hass.auth.data.access_token}`}:{}}}),n=await s.json().catch(()=>({}));if(!s.ok||n.error)throw Object.assign(new Error(n.message||n.error||`HTTP ${s.status}`),{code:n.error});this._backupImportDialog&&(this._backupImportDialog={...this._backupImportDialog,token:n.token,preview:n.preview,expectedConfigRev:n.expected_config_rev,expectedLayoutRev:n.expected_layout_rev,busy:!1})}catch(t){this._backupImportDialog&&(this._backupImportDialog={...this._backupImportDialog,busy:!1,error:this._backupErrorText(t)})}}}async _setBackupDuplicatePolicy(t){const e=this._backupImportDialog;if(e&&!e.busy&&e.token&&t!==e.duplicatePolicy){this._backupImportDialog={...e,duplicatePolicy:t,busy:!0,error:""};try{const i=await this.hass.callWS({type:"houseplan/import/revalidate",token:e.token,duplicate_policy:t});this._backupImportDialog&&(this._backupImportDialog={...this._backupImportDialog,preview:{...e.preview,...i.preview},expectedConfigRev:i.expected_config_rev,expectedLayoutRev:i.expected_layout_rev,confirmMissing:!1,busy:!1})}catch(t){this._backupImportDialog&&(this._backupImportDialog={...this._backupImportDialog,duplicatePolicy:e.duplicatePolicy,preview:e.preview,confirmMissing:e.confirmMissing,busy:!1,error:this._backupErrorText(t)})}}}async _applyBackupImport(){const t=this._backupImportDialog;if(!t||t.busy||!t.token||!t.preview)return;if(t.preview.confirmation_required&&!t.confirmMissing)return;this._backupImportDialog={...t,busy:!0,error:""};const e=this._space;try{const i=await this.hass.callWS({type:"houseplan/import/apply",token:t.token,expected_config_rev:t.expectedConfigRev,expected_layout_rev:t.expectedLayoutRev,duplicate_policy:t.duplicatePolicy,confirm_missing_content:t.confirmMissing}),[s,n]=await Promise.all([this.hass.callWS({type:"houseplan/config/get"}),this.hass.callWS({type:"houseplan/layout/get"})]);this._adoptStructuralResponses(s,n),this._geometryHistory.clear(),this._dirtyPos.clear(),this._sentPos.clear(),this._defPos={},this._cfgEpoch++,this._modelCache=null,this._frame=null,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotConfigEpoch=-1,this._regSignature="",this._signer.invalidate(this.hass),this._resign(),this._maybeRebuildDevices();const o=this._serverCfg?.spaces||[],r="space"===i.kind&&i.space_id?i.space_id:o.some(t=>t.id===e)?e:o[0]?.id||this._space;this._hasFixedFloor?this._adoptInitialSpace(this._model,!0):this._commitSpace(r),this._backupImportDialog=null,this._cacheSnapshot(),this.requestUpdate();const a="space"===i.kind?t.preview.counts:i.counts;this._showToast(this._t("space"===i.kind?"backup.space_done":"backup.full_done",{spaces:String(a?.spaces||0),rooms:String(a?.rooms||0),markers:String(a?.markers||0)}))}catch(t){if("conflict"===t?.code&&this._backupImportDialog?.token)try{const t=this._backupImportDialog,e=await this.hass.callWS({type:"houseplan/import/revalidate",token:t.token,duplicate_policy:t.duplicatePolicy});return void(this._backupImportDialog={...t,preview:{...t.preview,...e.preview},expectedConfigRev:e.expected_config_rev,expectedLayoutRev:e.expected_layout_rev,confirmMissing:!1,busy:!1,error:this._t("backup.revalidated")})}catch(e){t=e}this._backupImportDialog&&(this._backupImportDialog={...this._backupImportDialog,busy:!1,error:this._backupErrorText(t)})}}_renderBackupExportDialog(){const t=this._backupExportDialog,e=(this._serverCfg?.spaces||[]).find(t=>t.id===this._space);return W`this._backupExportDialog=null}>
this._backupExportDialog=null}>${this._t("btn.cancel")}
${t.busy?"…":this._t("backup.download")}
`}_renderBackupImportDialog(){const t=this._backupImportDialog,e=t.preview,i=e?.counts||{};return W`this._backupImportDialog=null}>
${t.filename} ${(t.size/1024).toFixed(1)} KB
${t.busy&&!e?W`
${this._t("backup.reading")}
`:G}
${t.error?W`
${t.error}
`:G}
${e?W`
${this._t("full"===e.kind?"backup.full":"backup.current_space")}
${e.plan_only?W`${this._t("backup.plan_only_preview")} `:G}
${this._t("same"===e.source?"backup.same_source":"backup.foreign_source")}
${this._t("backup.created",{value:e.created_at||"—"})}
${this._t("backup.versions",{card:e.card_version||"—",integration:e.integration_version||"—",model:String(e.model_version??"—")})}
${this._t("backup.count_spaces",{n:"full"===e.kind?`${e.current_counts?.spaces||0} → ${i.spaces||0}`:String(i.spaces||0)})}
${this._t("backup.count_rooms",{n:"full"===e.kind?`${e.current_counts?.rooms||0} → ${i.rooms||0}`:String(i.rooms||0)})}
${this._t("backup.count_walls",{n:"full"===e.kind?`${e.current_counts?.walls||0} → ${i.walls||0}`:String(i.walls||0)})}
${this._t("backup.count_openings",{n:"full"===e.kind?`${e.current_counts?.openings||0} → ${i.openings||0}`:String(i.openings||0)})}
${this._t("backup.count_decor",{n:"full"===e.kind?`${e.current_counts?.decor||0} → ${i.decor||0}`:String(i.decor||0)})}
${this._t("backup.count_markers",{n:"full"===e.kind?`${e.current_counts?.markers||0} → ${i.markers||0}`:String(i.markers||0)})}
${this._t("backup.count_layout",{n:"full"===e.kind?`${e.current_counts?.layout||0} → ${i.layout||0}`:String(i.layout||0)})}
${e.bindings?W`
${this._t("backup.bindings",{device:String(e.bindings.device||0),entity:String(e.bindings.entity||0),virtual:String(e.bindings.virtual||0),legacy:String(e.legacy_positions||0)})}
${this._t("backup.binding_status",{active:String(e.bindings.active||0),disabled:String(e.bindings.disabled||0),missing:String(e.bindings.missing||0)})}
`:G}
${e.missing_areas?.length?W`
${this._t("backup.missing_areas",{areas:e.missing_areas.join(", ")})}
`:G}
${e.dropped_marker_links?W`
${this._t("backup.dropped_marker_links",{n:String(e.dropped_marker_links)})}
`:G}
${"full"===e.kind?W`
${this._t("backup.replace_warning")}
${"foreign"===e.source?W`
${this._t("backup.foreign_bookkeeping")}
`:G}`:W`
${this._t("backup.final_name")} ${e.space_title}
${this._t("backup.target_settings")}
${e.duplicates?W`
${this._t("backup.duplicates",{n:String(e.duplicates)})}
this._setBackupDuplicatePolicy("skip")} />${this._t("backup.skip")}
this._setBackupDuplicatePolicy("virtual")} />${this._t("backup.virtual_copy")}
`:G}`}
${e.content?.length?W`
${this._t("backup.content")}
${e.content.map(t=>W`${t.url} · ${this._t("available"===t.state?"backup.content_available":"external"===t.state?"backup.content_external":"backup.content_detach_required")} `)}
`:G}
${e.confirmation_required?W`
this._backupImportDialog={...t,confirmMissing:e.target.checked}} />
${this._t("backup.confirm_detach")}
`:G}
`:G}
this._backupImportDialog=null}>${this._t("btn.cancel")}
${e?W`
${t.busy?"…":this._t("full"===e.kind?"backup.replace":"backup.add")}
`:G}
`}_setFillColor(t,e){const i=this._settingsDialog;this._settingsDialog={...i,colors:{...i.colors,[t]:{...i.colors[t],...e}}}}async _saveSettingsDialog(){const t=this._settingsDialog;if(t&&!t.busy){this._settingsDialog={...t,busy:!0};try{const e=this._serverCfg,i=JSON.stringify(t.colors)===JSON.stringify(ds),s={...e.settings};i?delete s.fill_colors:s.fill_colors=t.colors;const n=this._imperial?30.48*t.glowRadius:100*t.glowRadius;Number.isFinite(n)&&n>0&&300!==Math.round(n)?s.glow_radius_cm=Math.round(n):delete s.glow_radius_cm,t.bgColor?s.bg_color=t.bgColor:delete s.bg_color,null!==t.northDeg&&Number.isInteger(t.northDeg)&&t.northDeg>=0&&t.northDeg<=359?s.north_deg=t.northDeg:delete s.north_deg,s.bg_mode=t.bgMode,t.sunRays?s.sun_rays=!0:delete s.sun_rays,delete s.weather_entity,this._serverCfg={...e,settings:s},await this._saveConfigNow(),this._settingsDialog=null,this.requestUpdate(),this._showToast(this._t("gs.saved"))}catch(t){this._settingsDialog&&(this._settingsDialog={...this._settingsDialog,busy:!1}),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}}_boolInput(t,e,i=!1){const s=t=>e(!!t.target.checked);return customElements.get("ha-switch")?W` `:W` `}_rangeInput(t,e,i,s,n,o=!1,r){const a=t=>{const e=Number(t.target.value);Number.isFinite(e)&&n(e)};return customElements.get("ha-slider")?W` `:W` `}_renderColorRow(t,e){const i=this._settingsDialog.colors[t];return W`
{this._setFillColor(t,{c:e.detail.color,a:e.detail.opacity})}}>
`}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._openPairs().flatMap(t=>t.segs),s=[...i],n=Math.max(this._cmToUnits(10),.5*this._gridPitch),o=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),r=Math.cos(i);return o([t.rx+s*n,t.ry+r*n])&&o([t.rx-s*n,t.ry-r*n])}),a=this._roomWallOpeningInputs(r,t);for(const t of a){const e=t.angle*Math.PI/180,i=Math.cos(e)*t.length/2,n=Math.sin(e)*t.length/2;s.push([t.x-i,t.y-n,t.x+i,t.y+n])}const l=new Set(r.filter(t=>t.partitionHost).map(t=>t.id)),c=[t.id,this._cfgEpoch,this._cellCm,this._gridPitch,[...l].sort().join(",")].join("|");this._lightPhysicalBodiesCache?.key!==c&&(this._lightPhysicalBodiesCache={key:c,all:Ll(t,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(t,t=>l.has(t.id))).all});const h=this._lightPhysicalBodiesCache.all;let d=2166136261;const u=t=>{d^=Math.round(64*(Number.isFinite(t)?t:0)),d=Math.imul(d,16777619)>>>0},p=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 s)for(const e of t)u(e);for(const t of h){u(t.length);for(const e of t)u(e[0]),u(e[1])}for(const t of p)u(t.cm),u(t.a?.[0]??0),u(t.a?.[1]??0),u(t.b?.[0]??0),u(t.b?.[1]??0);const _=d.toString(36),g=`${t.id}|${_}`;if(this._lightBarrierCache?.key===g)return this._lightBarrierCache.value;const m=.02*this._gridPitch,f=[],v=p.length||h.length?fl(t.rooms,p,i,a,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg,h):null;if(v)for(const t of function(t){const e=[];for(const i of t||[])for(const t of i||[])t?.length>=4&&e.push(t.slice(0,-1).map(t=>[t[0],t[1]]));return e}(v.geom))f.push(...ku(t));else for(const t of h)f.push(...ku(t));for(const{poly:t}of e)for(const e of s.length?Ts(t,s,m):ku(t))f.push(e);const y={occluders:wu(f),floor:e.map(t=>t.poly),fingerprint:_,masonryGeometry:v?.geom||[],opaqueBodies:h};return this._lightBarrierCache={key:g,value:y},y}_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})=>Es(e.glow,t));if(!o.length)return this._forgetGlowSpace(t.id),j``;const{occluders:r,floor:a,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),u=new Map;for(const t of d){if(!t.device.id)continue;const e=u.get(t.device.id)||[];e.push(t),u.set(t.device.id,e)}const p=[],_=new Set;for(const e of this._renderDevices){if(e.space!==t.id)continue;const o=uo(u.get(e.id)||[]);if(!o)continue;const d=`${t.id}|${e.id}`;_.add(d);const g=$s(o.passive?{state:o.on?"on":"off",attributes:{}}:this._renderPlanHass.states[o.eid],e.marker?.glow_color,i.glow_light.c),m=Number(e.marker?.glow_radius_cm),f=Number.isFinite(m)&&m>0?m/this._cellCm*this._gridPitch:s,v=this._pos(e);if(Yl([v.x,v.y],c,h)){this._forgetGlowSource(d);continue}const y=this._glowTransition(d,!!g);if(!y)continue;g&&this._glowLastAppearance.set(d,{c:g.c,alpha:Ss(g.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=fg(this._glowClipCache,k);if(x.hit)w=x.value;else{const e=Su([v.x,v.y],f,r,96);w={lit:e.length>=3?jl([e],a,{onBoundsFailure:({boundIndex:e,phase:i})=>{const s=n[e]?.r;this._warnGlowGeometryFallback(t.id,l,s?.id||`#${e}`,i)}}):[]},vg(this._glowClipCache,k,w,256)}p.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 g=`${t.id}|`;for(const t of this._glowRenderedSources.keys())t.startsWith(g)&&!_.has(t)&&this._forgetGlowSource(t);if(!p.length)return j``;const m=this._spaceWalls,f=o.length===n.length?[]:this._openPairs().flatMap(t=>t.segs),v=o.length===n.length?null:o.map(({r:e,poly:i})=>{const s=m.length&&e.id&&hl(t.rooms,e.id,m,f,this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)||i,o=this._cleanFloor(e,s,t).path,r=Ti(s,n.filter(t=>t.r!==e).map(t=>t.poly)),a=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z";return[o||a(s),...r.map(a)].join(" ")}),y=this._viewOr(this._baseVb()),b=this._stageEl?.clientWidth&&y.w?this._stageEl.clientWidth/y.w:1,w=1/(b>0?b:1),k=!this._pinchStart&&!this._panStart&&Date.now()>=this._glowFeatherSuspendUntil;(null==this._glowFeatherUnits||k)&&(this._glowFeatherUnits=w);const x=this._glowFeatherUnits??w,$=4*x,S=p.reduce((t,e)=>({x:Math.min(t.x,e.pos.x-e.r-$),y:Math.min(t.y,e.pos.y-e.r-$),maxX:Math.max(t.maxX,e.pos.x+e.r+$),maxY:Math.max(t.maxY,e.pos.y+e.r+$),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});return S.w=S.maxX-S.x,S.h=S.maxY-S.y,j`
${Mt(p,t=>t.key,t=>{const e=t.domId,i=t.geometry;return j`
${""}
${Rg.map(([e,i])=>j`
`)}
${""}
${i?j`
`:G}`})}
${v?j`${v.map(t=>j` `)} `:G}
${""}
${""}
${Mt(p,t=>t.key,t=>{const e=t.domId;return j`
`})}
`}_renderAlignDialog(){const t=this._alignDialog,e=t.report;return W`this._alignDialog=null}>
${t.changed?W`
${e.moved?W`
${this._t("gs.align_count",{n:String(e.moved),total:String(e.total),cm:String(t.cm)})}
`:G}
${t.where?W`
${this._t("gs.align_where",{s:t.where})}
`:G}
${e.rotated?W`
${this._t("gs.align_turned",{n:String(e.rotated)})}
`:G}
${e.removedDrafts?W`
${this._t("gs.align_removed_drafts",{n:String(e.removedDrafts)})}
`:G}
${this._t("gs.optimize_changes",{m:String(e.migrated),c:String(e.canonicalized),p:String(e.coordsCanonicalized),w:String(e.wallsMerged),s:String(e.spansMerged),i:String(e.partitionsMerged)})}
${e.glowSpacesMigrated||e.glowRoomsMigrated?W`
${this._t("gs.optimize_glow_migration",{spaces:String(e.glowSpacesMigrated),rooms:String(e.glowRoomsMigrated)})}
`:G}
${this._t("gs.align_warn")}
`:W`
${this._t("gs.align_none")}
`}
this._alignDialog=null}>${this._t("btn.cancel")}
${t.changed?W`
${t.busy?"…":this._t("gs.align_run")}
`:G}
`}_renderSettingsDialog(){return W`this._settingsDialog=null}>
${this._t("gs.hint")}
${this._t("gs.light_group")}
${this._renderColorRow("light_on","gs.light_on")}
${this._renderColorRow("light_off","gs.light_off")}
${this._renderColorRow("light_none","gs.light_none")}
${this._t("gs.temp_group")}
${this._renderColorRow("temp_cold","gs.temp_cold")}
${this._renderColorRow("temp_ok","gs.temp_ok")}
${this._renderColorRow("temp_hot","gs.temp_hot")}
${this._t("gs.lqi_group")}
${this._renderColorRow("lqi_low","gs.lqi_low")}
${this._renderColorRow("lqi_high","gs.lqi_high")}
${this._t("gs.glow_group")}
${this._renderColorRow("glow_base","gs.glow_base")}
${this._renderColorRow("glow_light","gs.glow_light")}
${this._t("gs.glow_radius")}
{const e=mg(t.target.value);null!=e&&e>0&&(this._settingsDialog={...this._settingsDialog,glowRadius:e})}} />
${this._imperial?this._t("gs.unit_ft"):this._t("gs.unit_m")}
${this._t("gs.wall_group")}
${this._renderColorRow("wall_fill","gs.wall_fill")}
${this._t("gs.bg_group")}
${this._t("gs.bg_mode")}
this._settingsDialog={...this._settingsDialog,bgMode:"daynight"===t.target.value?"daynight":"static"}}>
${this._t("gs.bg_static")}
${this._t("gs.bg_daynight")}
${"static"===this._settingsDialog.bgMode?W`
{this._settingsDialog={...this._settingsDialog,bgColor:t.detail.color}}}>
${this._settingsDialog.bgColor?W`this._settingsDialog={...this._settingsDialog,bgColor:null}}>${this._t("gs.bg_default")} `:W`${this._t("gs.bg_theme")} `}
`:W`
${this._t("gs.bg_daynight_hint")}
`}
${this._t("gs.sun_group")}
${ea(this.hass)?G:W`
${this._t("gs.sun_missing")}
`}
${this._renderCompass()}
${this._t("gs.north")}
{const e=t.target.value.trim(),i=""===e?null:Math.round(Number(e));this._settingsDialog={...this._settingsDialog,northDeg:null!==i&&Number.isFinite(i)?Math.min(359,Math.max(0,i)):null}}} />
${null!==this._settingsDialog.northDeg?W`this._settingsDialog={...this._settingsDialog,northDeg:null}}>${this._t("gs.north_clear")} `:G}
${null===this._settingsDialog.northDeg?W`
${this._t("gs.north_hint")}
`:G}
${this._boolInput(this._settingsDialog.sunRays,t=>this._settingsDialog={...this._settingsDialog,sunRays:t})}
${this._t("gs.sun_rays")}
${this._canEdit?W`
${this._t("gs.backup_group")}
${this._t("gs.backup_hint")}
${this._t("backup.export_open")}
t.currentTarget.nextElementSibling?.click()}>
${this._t("backup.import_open")}
${this._canOptimizeUndo&&"import"===this._undoKind?W`
${this._t("backup.undo_import")}
`:G}
`:G}
${this._t("gs.grid_group")}
${this._t("gs.grid_hint")}
${this._t("gs.align_all")}
${this._canOptimizeUndo&&"import"!==this._undoKind?W`
${this._t("gs.optimize_undo")}
`:G}
${this._t("gs.about_group")}
${this._t("gs.about_version",{v:hg})}
${this._t("gs.about_github")}
${this._t("gs.about_telegram")}
this._settingsDialog={...this._settingsDialog,colors:JSON.parse(JSON.stringify(ds)),glowRadius:this._imperial?9.8:3,bgColor:null,northDeg:null,bgMode:"daynight",sunRays:!1}}>
${this._t("gs.reset")}
this._settingsDialog=null}>${this._t("btn.cancel")}
${this._settingsDialog.busy?"…":this._t("btn.save")}
`}_rulesSet(t){this._rulesDialog={...this._rulesDialog,rules:t}}async _saveRules(){const t=this._rulesDialog;if(!t||t.busy)return;const e=t.rules.filter(t=>t.pattern.trim()&&t.icon.trim());this._rulesDialog={...t,busy:!0};try{const t=this._serverCfg,i=JSON.stringify(e)===JSON.stringify(Xt),s={...t.settings};i?delete s.icon_rules:s.icon_rules=e,this._serverCfg={...t,settings:s},await this._saveConfigNow(),this._rulesDialog=null,this._regSignature="",this._maybeRebuildDevices(),this._showToast(this._t("rules.saved"))}catch(t){this._rulesDialog&&(this._rulesDialog={...this._rulesDialog,busy:!1}),this._showToast(this._t("toast.error",{err:this._errText(t)}))}}_renderRulesDialog(){const t=this._rulesDialog,e=Jt(t.rules),i=t.test.trim()?ee(t.test,"",e):null,s=(e,i)=>{const s=[...t.rules],n=e+i;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],this._rulesSet(s))};return W`this._rulesDialog=null}>
${this._t("rules.hint")}
this._rulesDialog={...t,test:e.target.value}} />
${i?W`${i} `:G}
${t.rules.map((e,i)=>{const n=""!==e.pattern.trim()&&!function(t){try{return new RegExp(t,"i"),!0}catch{return!1}}(e.pattern);return W`
{const n=[...t.rules];n[i]={...e,pattern:s.target.value},this._rulesSet(n)}} />
{const n=[...t.rules];n[i]={...e,icon:s.target.value},this._rulesSet(n)}} />
s(i,-1)}>
s(i,1)}>
this._rulesSet(t.rules.filter((t,e)=>e!==i))}>
`})}
this._rulesSet([...t.rules,{pattern:"",icon:""}])}>
${this._t("rules.add")}
this._rulesSet(Xt.map(t=>({...t})))}>
${this._t("rules.reset")}
this._rulesDialog=null}>${this._t("btn.cancel")}
${t.busy?"…":this._t("btn.save")}
`}_saveKioskScale(t){this._kioskScale={...this._kioskScale,...t};try{localStorage.setItem(Cg,JSON.stringify(this._kioskScale))}catch{}this.requestUpdate()}_renderKioskDialog(){const t=this._kioskScale,e=(e,i)=>W`${i}
${this._rangeInput(50,300,5,Math.round(100*t[e]),t=>this._saveKioskScale({[e]:t/100}))}
${Math.round(100*t[e])}%
`;return W`this._kioskDialog=!1}>
${this._t("kiosk.hint")}
${e("icon",this._t("kiosk.icon_scale"))}
${e("font",this._t("kiosk.font_scale"))}
this._saveKioskScale({icon:1,font:1})}>${this._t("gs.reset")}
this._kioskDialog=!1}>${this._t("btn.close")}
`}_fixedFloorValue(t){if("string"==typeof t)return t||"''";try{const e=JSON.stringify(t);return(void 0===e?String(t):e).slice(0,160)}catch{return String(t).slice(0,160)}}render(){if(!this._config||!this.hass)return G;const t=this._model,e=this.houseplanDiagnostics(),i=this._fixedFloorState(t);if("pending"===i.kind)return W`
${this._config.title||this._t("card.title")}
${this._t("fixed_floor.loading")}
`;if("invalid"===i.kind)return W`
${this._config.title||this._t("card.title")}
${this._t("fixed_floor.invalid_title")}
${this._t("fixed_floor.invalid_body",{value:this._fixedFloorValue(i.value)})}
`;if(!t.length)return W`
${this._config.title||this._t("card.title")}
${this._t("empty.no_spaces")}
${this._serverStorage?W`
${this._t("empty.add_first")}
this._openSpaceDialog("create")}>
${this._t("btn.add_space")}
`:W`
${this._t("empty.install")}
`}
${this._spaceDialog?this._renderSpaceDialog():G}
${this._importDialog?this._renderImportDialog():G}
${this._toast?W`${this._toast}
`:G}
`;const s=this._spaceModel();if(!s)return G;const n="valid"===i.kind?[s]:t,o=s.vb,r=this._effectiveProjection();this._renderProjection=r,this._labs.active.length&&function(t){g_||w_(t);const e=__,i=e.active.join(",");if(!i||i===f_)return;f_=i;const s=new Map(o_.map(t=>[t.id,t])),n=e.active.map(t=>{const e=s.get(t);return`${t} (#${e.issue}, expires ${e.expires})`}).join(", ");console.info(`HOUSEPLAN LABS: ${n}`)}(hg);const a="iso"===r,l="devices"===this._mode&&this._showAll,c=this._renderDevices.filter(t=>t.space===s.id&&(!t.hidden||l)),h=this._renderDeviceSnapshot,d=this._spaceDisplayForRender(),u=a?this._isoDecorationLayers(d):null,p=u?this._isoOpeningPanels(u):[],_=this._resolvedRoomFills(s,d),g=this._resolvedGlowBase(s,d,_),m=d.showLqi??this._config.show_signal??!0,f=this._config.icon_size??2.5,v=f>8?2.5:f,y=Gu(v),b=this._viewOr(this._baseVb()),w=this._floorView(b),k=this._editing?"":this._stageBg(d),x=this._opMeasureView,$=this._decorMeasure,S=this._bdLive,M=this._furnLive,C="view"===this._mode?this._editorChromeMode:this._mode,D=this._roomHoverPaths(s),T=s.bg?this._display(s.bg.href):"",P=this._continuity.overlayVisible||"recovery-error"===this._continuity.state?this._continuity.recoveryReason:null,R=this._modeTransitionVisual,I=this._dayCycleState(),A=R?.viewWeight??("view"===this._mode?1:0),F=this._modeTransition.state?.from.presentedMode,E=!this._markup||!!R&&("view"===R.presentedMode||"devices"===R.presentedMode||"view"===F||"devices"===F),z=R?.stageColor||k,O=R?.sceneBrightness??1;return W`
this._notePointer(t)}
@pointerdown=${this._touchGestureGuard}
@pointermove=${this._touchGestureGuard}
@pointerup=${this._touchGestureGuard}
@pointercancel=${this._touchGestureGuard}
@lostpointercapture=${this._touchGestureGuard}
@click=${this._touchGestureGuard}>
${this._config.title||this._t("card.title")}
${n.map(t=>W`this._tabPointerDown(e,t.id)}
@pointermove=${e=>this._tabPointerMove(e,t.id)}
@pointerup=${t=>this._tabPointerUp(t)}
@pointercancel=${()=>this._endTabDrag()}
@click=${()=>this._tabClick(t.id)}
>
${t.title}${this._norm&&this._canEdit?W`{e.stopPropagation(),this._openSpaceDialog("edit",t.id)}}> `:G}
`)}
${""}
${!this._canEdit||this._kiosk||this._hasFixedFloor?G:W`this._openSpaceDialog("create")}>
`}
${this._canEdit?W`
${[["plan","mdi:floor-plan"],["devices","mdi:tune-variant"],["decor","mdi:draw"]].map(([t,e])=>W`this._setMode(t)}>
${this._t("mode."+t)}
${this._mode===t?W`{t.stopPropagation(),this._setMode("view")}}> `:G}
`)}
`:G}
${this._t("count.devices",{n:c.filter(t=>!t.hidden).length})}
${this._labsIso&&"view"===this._mode&&!this._kiosk?W`
this._setProjection(a?"flat":"iso")}>
`:G}
this._stepZoom(-1)} title=${this._t("title.zoom_out")}>
${""}
this._fitAll()}
title=${this._t("title.zoom_fit")}>
this._stepZoom(1)} title=${this._t("title.zoom_in")}>
${this._norm&&this._canEdit?W`
`:G}
${this._canEdit&&!this._kiosk?W`
${"plan"===C?this._renderMarkupBar():"devices"===C?this._renderDevicesBar():this._renderDecorBar()}
`:G}
this._markupClick(t)}
@wheel=${t=>this._onWheel(t)}
@pointerdown=${t=>{this._notePointer(t),this._stagePointerDown(t)}}
@pointermove=${t=>this._stagePointerMove(t)}
@pointerleave=${t=>this._stagePointerLeave(t)}
@pointerup=${t=>this._stagePointerUp(t)}
@pointercancel=${t=>this._stagePointerCancel(t)}>
${na(I,A)}
${this._renderEditorSecondary()}
${a&&u?.structural?j`
${this._renderIsoUnderlay(u)}
`:G}
${""}
${this._wallHatchDefs(d.color)}${j`${this._paperShapes(s.rooms).map(t=>"path"in t?j` `:"poly"in t?j` `:j` `)} `}
${this._editing?this._renderMarkupDefs(o):G}
${""}
${this._editing&&!this._markup&&this._gridLevels()?j` `:G}
${s.bg&&T?j`this._onBackdropLoaded(s.bg.href,T)}
transform=${s.bg.angle?`rotate(${s.bg.angle} ${s.bg.x+s.bg.w/2} ${s.bg.y+s.bg.h/2})`:G}
@dblclick=${t=>this._openBackdropDialog(t)}
preserveAspectRatio="none" />`:G}
${""}
${d.hideDecor&&"decor"!==this._mode?G:this._renderDecorLayer()}
${(()=>{const t=this._openPairs(),e=new Map,i=t=>(e.has(t)||e.set(t,hi(t)),e.get(t));return s.rooms.filter(t=>t.area||"view"===this._mode||this._markup||d.showBorders).map(e=>{let n="room "+(s.bg?"overlay":"yard")+(this._markup?" outlined":"");!this._markup||e.id!==this._mergeSel&&e.id!==this._splitSel?.roomId||(n+=" picked");let o="";const r=Fs(d.fill,e);if(!this._markup&&(d.showBorders||"none"!==r)){n+=" styled";const t=[];t.push(`--room-stroke:${d.color}`,`--room-stroke-op:${d.showBorders?d.opacity:0}`);const i=_.byRoom.get(e)||null;i?(n+=" filled",t.push(`--room-fill:${i.color}`,`--room-fill-op:${i.opacity}`)):t.push("--room-fill:transparent","--room-fill-op:0"),o=t.join(";")}let a;const l=t=>{"view"===this._mode&&(void 0===a&&(a=this._roomArea(e)),this._showTip(t,e.name||this._t("room.unnamed"),a?this._t("tip.area",{value:a}):"",m?this._roomLqi(e.area):null,this._roomTemp(e),this._roomHum(e)))},c=this._markup&&(e.id===this._mergeSel||e.id===this._splitSel?.roomId),h=e.id&&!c?t.filter(t=>t.a.id===e.id||t.b.id===e.id).flatMap(t=>t.segs):[],u=c?[]:this._thickWallCuts(),p=h.concat(u);p.length&&(n+=" noedge");const g=i(e),f=this._spaceWalls,v=f.length&&e.id&&g&&hl(s.rooms,e.id,f,this._openPairs().flatMap(t=>t.segs),this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)||g,y=v?Ti(v,(b=e,s.rooms.filter(t=>t!==b).map(i).filter(Boolean))):[];var b;const w=t=>"M "+t.map(t=>t[0]+" "+t[1]).join(" L ")+" Z",k=v?this._cleanFloor(e,v,s).path:"",x=e.id||G,$=e.area||G,S=k&&v?j`{this._notePointer(t),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:s.id,room:e})}}
@pointermove=${l}
@pointerleave=${()=>this._clearTransientHover()}> `:y.length&&v?j`{this._notePointer(t),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:s.id,room:e})}}
@pointermove=${l}
@pointerleave=${()=>this._clearTransientHover()}> `:v&&v!==g?j`{this._notePointer(t),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:s.id,room:e})}}
@pointermove=${l}
@pointerleave=${()=>this._clearTransientHover()}> `:e.poly?j`{this._notePointer(t),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:s.id,room:e})}}
@pointermove=${l}
@pointerleave=${()=>this._clearTransientHover()}> `:j`{this._notePointer(t),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:s.id,room:e})}}
@pointermove=${l}
@pointerleave=${()=>this._clearTransientHover()}> `,M=p.length&&g?Ts(g,p,.02*this._gridPitch):null,C=M?j` `:G;return j`${S}${C}`})})()}
${this._renderRoomHoverFill(D)}
${this._renderOpeningTunnelFills(s,_)}
${this._renderGlowBaseRooms(s,g)}
${this._renderOpeningTunnelFills(s,g,"glow-base")}
${E?this._renderGlowLayer(s,d):G}
${this._renderSunRays(s)}
${this._editing?j`${this._renderAlignGuides()} `:G}
${this._markup?j`${this._renderMarkupLayer(o)} `:G}
${""}
${""}
${this._editing?G:this._renderOpenWalls(d)}
${this._renderWallBodies(d)}
${this._markup?j`${this._renderPlanSnapOverlay()} `:G}
${this._markup?j`${this._renderOpeningPlacementPreview()} `:G}
${x?this._renderOpeningDimensionGuides(x):G}
${x?.guide?this._renderOpeningCenterTick(x.guide):G}
${this._renderRoomHoverOutline(D)}
${""}
${this._editing?this._renderOpenWalls(d):G}
${d.hideOpenings&&!this._markup||u&&!u.floorSymbols?G:this._renderOpenings(d)}
${this._renderWallThickUi()}
${this._markup&&"resize"===this._tool?this._renderResizeLayer(b):G}
${""}
${this._renderBackdropFrame(b)}
${this._renderTextFrame(b)}
${a&&u?.structural?j`
${this._renderIsoShadows(u,p)}
${this._renderIsoWalls(u,p)}
`:G}
${""}
${c.map(t=>this._renderDevice(t,b,m))}
${this._renderVacuums(c,b)}
${this._renderVacFit(b)}
${this._renderOpeningLocks(b)}
${d.showNames||this._markup?s.rooms.map(t=>this._renderRoomLabel(t,s,b,d)):G}
${this._markup?s.rooms.map(t=>this._renderRoomGear(t,s,b)):G}
${this._measureAnchor?W`
${this._renderMeasureLabel(b)}
`:G}
${this._rszLive?W`
${this._rszLive.map(t=>W`
${t.text}
`)}
`:G}
${x?W`
${x.labels.map(t=>W`
${t.text}
`)}
`:G}
${this._wallDialog?W`
${this._renderWallThickDialog()}
`:G}
${$?W`
`:G}
${M?W`
${M.map(t=>W`
${t.text}
`)}
`:G}
${S?W`
`:G}
${this._zoom>1?W`
${Math.round(100*this._zoom)}%
`:G}
${this._renderFarHint()}
${this._renderHomeArrow()}
${this._renderRecoveryOverlay()}
${this._booting||this._bootFading?W`
`:G}
${this._roomDialog?this._renderRoomDialog():G}
${this._mergeDialog?this._renderMergeDialog():G}
${this._openingDialog?this._renderOpeningDialog():G}
${this._physicalDialog?this._renderPhysicalDialog():G}
${this._partitionDeleteDialog?this._renderPartitionDeleteDialog():G}
${this._roomDeleteDialog?this._renderRoomDeleteDialog():G}
${this._openingInfo?this._renderOpeningInfoCard():G}
${this._decorTextDialog?this._renderDecorTextDialog():G}
${this._decorShapeDialog?this._renderDecorShapeDialog():G}
${this._backdropDialog?this._renderBackdropDialog():G}
${this._decorEraseConfirm?this._renderDecorEraseConfirm():G}
${this._spaceDialog?this._renderSpaceDialog():G}
${this._markerDialog?this._renderMarkerDialog():G}
${this._vacCalConfirm?W`this._vacCalConfirm=null}>
${this._t("vac.residual_message",{error:this._vacCalConfirm.error})}
this._vacCalConfirm=null}>${this._t("btn.cancel")}
this._vacApplyCalibrationProposal(!0)}>${this._t("vac.fit")}
this._vacApplyCalibrationProposal(!1)}>
${this._t("vac.apply_proposal")}
`:G}
${this._infoCard?this._renderInfoCard():G}
${this._rulesDialog?this._renderRulesDialog():G}
${this._settingsDialog?this._renderSettingsDialog():G}
${this._alignDialog?this._renderAlignDialog():G}
${this._backupExportDialog?this._renderBackupExportDialog():G}
${this._backupImportDialog?this._renderBackupImportDialog():G}
${this._importDialog?this._renderImportDialog():G}
${this._tip?W`
${this._tip.title} ${this._tip.meta?W`${this._tip.meta} `:G}
${null!=this._tip.temp?W`${this._t("tip.temp_avg")} ${this._tip.temp}° `:G}
${null!=this._tip.hum?W`${this._t("tip.hum_avg")} ${this._tip.hum}% `:G}
${null!=this._tip.lqi?W`${this._t("tip.lqi")}
${this._tip.lqi} `:G}
`:G}
${this._kiosk&&!this._hasFixedFloor&&this._kioskDots&&this._model.length>1?W`
${this._model.map(t=>W` `)}
`:G}
${this._kioskDialog?this._renderKioskDialog():G}
${this._vacFit?W`
${this._t("vac.fit_hint")}
this._vacFitTurn({rot:(this._vacFit.p.rot+90)%360})}>${this._t("vac.fit_rotate")}
this._vacFitTurn({mir:!this._vacFit.p.mir})}>${this._t("vac.fit_mirror")}
this._vacFitSave()}>${this._t("btn.save")}
{this._vacFit=null}}>${this._t("btn.cancel")}
`:G}
${this._tapConfirm?W`this._tapConfirm=null}>
${"run"===this._tapConfirm.kind?W`
${this._tapConfirm.text}
`:this._tapConfirm.lines.map((t,e)=>W`
${t}
`)}
this._tapConfirm=null}>${this._t("btn.cancel")}
{const t=this._tapConfirm;this._tapConfirm=null,t.exec()}}>
${this._t("btn.run")}
`:G}
${this._toast?W`${this._toast}
`:G}
`}_vacCandidateStatus(t,e,i=this._planHass){const s=this._bindingStatus("entity:"+t);if("ha_disabled"===s.kind)return"disabled";if("orphaned"===s.kind)return"missing";if("unverified"===s.kind)return"unverified";const n=i?.states?.[t];return"unavailable"===n?.state?"unavailable":e?.hasPosition?"ok":"unsupported"}_vacOpenAllCameras(t){const e=this._haRegistry.entities||{},i=[];for(const[t,s]of Object.entries(this.hass?.states||{})){if(!t.startsWith("camera."))continue;const n=Ph(t,s,e[t]);n&&i.push(n)}this._vacAllCameraCache={devId:t.id,candidates:i},this._vacAllCamerasFor=t.id}_vacSourceResolution(t,e=!1,i=this._planHass){const s=t.marker?.vacuum,n="string"==typeof s?.source&&!!s.source,o=new Set(t.entities||[]),r=new Set(o);n&&r.add(s.source);const a=i?.entities||{},l=[];for(const t of r){const e=i?.states?.[t],o=Ph(t,e,a[t]);o?l.push(o):n&&t===s.source&&l.push({entityId:t,name:String(e?.attributes?.friendly_name||t),platform:a[t]?.platform?String(a[t].platform):null,category:t.startsWith("camera.")?"camera":"partial",hasPosition:!1,hasRooms:!1,hasPath:!1,hasMapId:!1,score:0})}if(e&&this._vacAllCameraCache?.devId===t.id){const t=new Set(l.map(t=>t.entityId));for(const e of this._vacAllCameraCache.candidates)t.has(e.entityId)||l.push(e)}const c={};for(const t of l)c[t.entityId]=this._vacCandidateStatus(t.entityId,t,i);return function(t,e,i,s){const n="string"==typeof t&&t.length>0,o=new Set(e),r=Array.from(i).sort((e,i)=>n&&e.entityId===t?-1:n&&i.entityId===t?1:i.score-e.score||e.entityId.localeCompare(i.entityId));if(n){const e=r.find(e=>e.entityId===t);return{entityId:t,status:s[t]||(e?.hasPosition?"ok":"unverified"),pinned:!0,candidates:r}}const a=r.find(t=>o.has(t.entityId)&&t.hasPosition&&"ok"===s[t.entityId]);return a?{entityId:a.entityId,status:"ok",pinned:!1,candidates:r}:{entityId:null,status:"none",pinned:!1,candidates:r}}(s?.source,o,l,c)}_vacSource(t,e=this._planHass){if(!1===t.marker?.vacuum?.live)return null;const i=this._vacSourceResolution(t,!1,e);return"ok"===i.status||"unsupported"===i.status?i.entityId:null}_vacEntity(t){return t.primary?.startsWith("vacuum.")?t.primary:(t.entities||[]).find(t=>t.startsWith("vacuum."))||null}_isVacDev(t){return!!this._vacEntity(t)}_activitySourceKey(t){return this._activitySnapshot(t).sourceKey}_activitySnapshot(t,e=ho(this._planHass,this._devices,null,this._virtualLights)){const i=zu(this._planHass,t,this._devices,e,this._fullRegistryHass);return{samples:i.samples,sourceKey:Hu(this._planHass,t,i)}}_stampActivity(t,e,i){let s=this._activityRt.get(t);s||(s=cp(i||"",[]),this._activityRt.set(t,s)),null!=i&&(s.sources=i),dp(s,e,Date.now(),window.clearTimeout.bind(window),t=>window.setTimeout(()=>this.requestUpdate(),t))}_syncActivityRuntime(){const t=new Map;if(!this.hass)return t;if(!1===this._config?.live_states){for(const t of this._activityRt.values())clearTimeout(t.timer);return this._activityRt.clear(),t}const e=new Set,i=ho(this._planHass,this._devices,null,this._virtualLights);for(const s of this._devices){if(s.hidden)continue;if("icon_ripple"!==Bi(s.marker?.display))continue;e.add(s.id);const n=this._activitySnapshot(s,i);t.set(s.id,n);const{samples:o,sourceKey:r}=n;let a=this._activityRt.get(s.id);a?a.sources!==r&&hp(a,r,o,window.clearTimeout.bind(window)):(a=cp(r,o),this._activityRt.set(s.id,a))}for(const[t,i]of this._activityRt)e.has(t)||(clearTimeout(i.timer),this._activityRt.delete(t));return t}_activityTick(){if(!this.hass)return;const t=this._syncActivityRuntime();for(const e of this._devices){if(e.hidden)continue;if("icon_ripple"!==Bi(e.marker?.display))continue;const i=t.get(e.id)||this._activitySnapshot(e),{samples:s,sourceKey:n}=i,o=this._activityRt.get(e.id);if(!o||o.sources!==n)continue;const r=up(o,s,window.clearTimeout.bind(window));r&&this._stampActivity(e.id,r,n)}}_vacTick(){if(this.hass)for(const t of this._devices){if(t.hidden||!this._isVacDev(t))continue;if("static_icon"===Bi(t.marker?.display)){this._vacRt.delete(t.id);continue}const e=this._vacSource(t);if(!e)continue;const i=this._vacEntity(t),s=Fh(this.hass.states[i||""]?.state),n=Th(this.hass.states[e]?.attributes);let o=this._vacRt.get(t.id);o||(o={trail:[],lastKey:"",lastTs:0,moving:!1,jump:!1,endedTs:0,lastPos:null},this._vacRt.set(t.id,o)),s&&!o.moving&&(o.trail=[],o.lastPos=null);const r="never"!==Hh(t.marker?.vacuum)&&!n?.path.length;!s&&o.moving&&(o.endedTs=Date.now(),r&&o.lastPos&&(o.trail=Ah(o.trail,o.lastPos,40)),o.lastPos=null),o.moving=s;const a=n?.pos;if(s&&a){const t=a.x+":"+a.y;if(t!==o.lastKey){const e=Date.now();o.jump=o.lastTs>0&&e-o.lastTs>1e4,o.lastKey=t,o.lastTs=e,r&&o.lastPos&&(o.trail=Ah(o.trail,o.lastPos,40)),o.lastPos=[a.x,a.y]}}}}_vacEnsureMarker(t){const e=this._serverCfg;if(!e)return null;e.markers=e.markers||[];const i=e.markers.find(e=>e.id===t.id);if(i)return i;if("device"!==t.bindingKind&&"entity"!==t.bindingKind||!t.bindingRef)return null;const s={id:t.id,binding:t.bindingKind+":"+t.bindingRef,space:t.space||null,area:t.area||null,hidden:!!t.hidden};return e.markers.push(s),s}_renderVacSection(t){const e=this._devices.find(e=>e.id===t.devId);if(!e||!this._isVacDev(e))return G;const i=e.marker?.vacuum||{},s=this._vacAllCamerasFor===e.id,n=this._vacSourceResolution(e,s),o=n.entityId,r=n.candidates.find(t=>t.entityId===o)||null,a=o?Th(this.hass?.states[o]?.attributes):null,l=!1!==i.live&&("ok"===n.status||"unsupported"===n.status),c=this._vacPlanRoomAnchors(e.space),h=a?function(t,e){const i=new Set(e.map(Rh).filter(Boolean)),s=new Set;for(const e of t){const t=Rh(e.name||"");t&&i.has(t)&&s.add(t)}return s.size}(a.rooms,c.map(t=>t.name)):0,d=!!(l&&a&&h>=3),u=Object.keys(i.calibration||{}),p=t=>{const i=this._vacEnsureMarker(e);i&&(i.vacuum={...i.vacuum||{},...t},this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate())},_=new Set(e.entities||[]),g=n.candidates.filter(t=>_.has(t.entityId)||t.entityId===i.source),m=s?n.candidates.filter(t=>t.entityId.startsWith("camera.")&&!g.some(e=>e.entityId===t.entityId)):[],f=t=>[t.hasPosition?this._t("vac.cap_position"):"",t.hasRooms?this._t("vac.cap_rooms_short"):"",t.hasPath?this._t("vac.cap_path"):"",t.hasMapId?this._t("vac.cap_map"):""].filter(Boolean).join(" · ")||this._t("vac.cap_none"),v=t=>W`
p({source:t.entityId})}>
${t.name} ${t.entityId}
${t.platform||this._t("vac.platform_unknown")} · ${f(t)}
`,y=n.candidates.some(t=>_.has(t.entityId)&&"known_xcme_incomplete"===t.category)||!!n.pinned&&!!o?.startsWith("camera.")&&!r?.hasPosition;return W`
${this._t("vac.section")}
${this._t("vac.diag_source")} ${o||this._t("vac.source_none")}
${r?.platform?W`
${this._t("vac.diag_platform")} ${r.platform}
`:G}
${this._t("vac.diag_status")} ${this._t(`vac.source_status_${n.status}`)}
${this._t("vac.diag_position")} ${a?.pos?this._t("common.yes"):this._t("common.no")}
${this._t("vac.diag_rooms")} ${ss(this._t("vac.diag_rooms_value"),{total:String(a?.rooms.length||0),matched:String(h),readiness:this._t(h>=3?"vac.autocal_ready":"vac.autocal_not_ready")})}
${this._t("vac.diag_path")} ${a?.path.length?this._t("common.yes"):this._t("common.no")}
${this._t("vac.diag_map")} ${a?.mapId??"default"}
${"missing"===n.status||"disabled"===n.status||"unverified"===n.status?W`
${this._t(`vac.source_banner_${n.status}`)}
{const t=[...this.renderRoot.querySelectorAll("details.vacpicker")].find(t=>t.dataset.devId===e.id);t&&(t.open=!0,t.querySelector("summary")?.focus())}}>${this._t("vac.choose_source")}
`:G}
${y?W`
${this._t("vac.xcme_hint")}
attributes:
- vacuum_position
- rooms
- path
- map_name
`:G}
${this._t("vac.choose_source")}
p({source:null})}>
${this._t("vac.source_auto")} ${this._t("vac.source_auto_hint")}
${g.map(v)}
{t.currentTarget.open?this._vacOpenAllCameras(e):(this._vacAllCamerasFor=null,this._vacAllCameraCache=null)}}>
${this._t("vac.all_cameras")}
${this._t("vac.all_cameras_warn")}
${s?m.length?m.map(v):W`${this._t("vac.all_cameras_empty")}
`:G}
${a?W`
${this._boolInput(!1!==i.live,t=>p({live:!!t&&null}))}
${this._t("vac.live")}
${this._t("vac.trail")}
p({trail_mode:t.target.value,trail:null})}>
${["never","cleaning","always"].map(t=>W`
${this._t("vac.trail_"+t)} `)}
${u.length?W`
${ss(this._t("vac.cal_maps"),{maps:u.join(", ")})}
`:G}
`:G}
`}_vacMapId(t,e,i=this._planHass){const s=this._vacEntity(t),n=s?i?.states?.[s]?.attributes?.selected_map:null;return o=e.mapId,r=n,"default"!==o?o:null!=r?String(r):"default";var o,r}_vacSaveMatrix(t,e,i,s){const n=this._devices.find(e=>e.id===t),o=n?this._vacEnsureMarker(n):this._serverCfg?.markers?.find(e=>e.id===t);if(!o)return!1;const r={...o.vacuum||{}};return r.source=e,r.calibration={...r.calibration||{},[i]:s.map(t=>Number(t.toFixed(6)))},o.vacuum=r,this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate(),!0}_vacPlanRoomAnchors(t){return(this._spaceModelById(t)?.rooms||[]).map(t=>({room:t,poly:hi(t)})).filter(({room:t,poly:e})=>t.name&&e).map(({room:t,poly:e})=>{const i=$h(e);return i?{name:String(t.name),cx:i[0],cy:i[1]}:null}).filter(Boolean)}_vacAutoCalibrate(t){const e=this._vacSource(t),i=e?Th(this.hass?.states[e]?.attributes):null;if(!e||!i||i.rooms.length<3)return void this._showToast(this._t("vac.autocal_no_rooms"));const s=this._vacPlanRoomAnchors(t.space),n=Ih(i.rooms,s);if(!n)return void this._showToast(this._t("vac.autocal_no_match"));const o=this._serverCfg?.spaces?.find(e=>e.id===t.space),r=Number(o?.cell_cm),a=Number.isFinite(r)&&r>0?r:5,l=function(t,e,i){return![t,e,i].every(Number.isFinite)||t<0||e<=0||i<=0?Number.POSITIVE_INFINITY:t/e*i}(n.residual,this._gridPitch,a),c=this._vacMapId(t,i);l>40?this._vacCalConfirm={markerId:t.id,source:e,mapId:c,matrix:n.matrix,rooms:n.matched.length,error:li(l,"mi"===this.hass?.config?.unit_system?.length)}:this._vacSaveMatrix(t.id,e,c,n.matrix)&&this._showToast(ss(this._t("vac.autocal_done"),{rooms:String(n.matched.length)}))}_vacApplyCalibrationProposal(t){const e=this._vacCalConfirm;if(e){if(this._vacCalConfirm=null,t){const t=this._devices.find(t=>t.id===e.markerId),i=Oh(e.matrix);if(!t||!i)return;if(this._markerDialog=null,t.space!==this._space&&!this._commitSpace(t.space))return;return void(this._vacFit={markerId:e.markerId,source:e.source,mapId:e.mapId,p:i,drag:null})}this._vacSaveMatrix(e.markerId,e.source,e.mapId,e.matrix)&&this._showToast(ss(this._t("vac.autocal_done"),{rooms:String(e.rooms)}))}}_vacStartFit(t){const e=this._vacSource(t),i=e?Th(this.hass?.states[e]?.attributes):null;if(!e||!i)return void this._showToast(this._t("vac.cal_need_pos"));const s=this._vacMapId(t,i),n=t.marker?.vacuum?.calibration?.[s],o=this._spaceModelById(t.space);if(!o)return;const r=o.vb,a=n&&6===n.length&&Oh(n)||function(t,e){const i=[],s=[];for(const e of t)null!=e.x0?(i.push(e.x0,e.x1),s.push(e.y0,e.y1)):(i.push(e.cx),s.push(e.cy));if(!i.length)return{ox:e[0]+e[2]/2,oy:e[1]+e[3]/2,s:e[2]/1e4,rot:0,mir:!0};const n=Math.min(...i),o=Math.max(...i),r=Math.min(...s),a=Math.max(...s),l=Math.max(o-n,a-r)||1,c={ox:0,oy:0,s:.6*Math.min(e[2],e[3])/l,rot:0,mir:!0},h=zh(c),[d,u]=bh(h,(n+o)/2,(r+a)/2);return c.ox=e[0]+e[2]/2-d,c.oy=e[1]+e[3]/2-u,c}(i.rooms,r);this._markerDialog=null,(t.space===this._space||this._commitSpace(t.space))&&(this._vacFit={markerId:t.id,source:e,mapId:s,p:a,drag:null})}_vacFitSave(){const t=this._vacFit;if(!t)return;const e=this._vacSaveMatrix(t.markerId,t.source,t.mapId,zh(t.p));this._vacFit=null,e&&this._showToast(this._t("vac.cal_done"))}_vacFitTurn(t){const e=this._vacFit;if(!e)return;const i=Th(this.hass?.states[e.source]?.attributes),s=this._vacGhostCentre(i?.rooms||[]),n={...e.p,...t};this._vacFit={...e,p:Nh(n,e.p,s[0],s[1])}}_vacGhostCentre(t){const e=[],i=[];for(const s of t)e.push(s.x0??s.cx,s.x1??s.cx),i.push(s.y0??s.cy,s.y1??s.cy);return e.length?[(Math.min(...e)+Math.max(...e))/2,(Math.min(...i)+Math.max(...i))/2]:[0,0]}_vacDelta(t,e,i){const s=this._stageEl,n=s?.clientWidth||1,o=s?.clientHeight||1;return[e/n*t.w,i/o*t.h]}_vacFitPointer(t,e){const i=this._vacFit;if(!i)return;if(t.stopPropagation(),"pointerdown"===t.type){const e=t.target,s=e.getAttribute?.("data-corner");try{t.currentTarget.setPointerCapture?.(t.pointerId)}catch{}return void(this._vacFit={...i,drag:s?{kind:"scale",sx:t.clientX,sy:t.clientY,p0:{...i.p},fx:Number(s.split(",")[0]),fy:Number(s.split(",")[1])}:{kind:"move",sx:t.clientX,sy:t.clientY,p0:{...i.p},fx:0,fy:0}})}const s=i.drag;if(s){if("pointermove"===t.type){const[n,o]=this._vacDelta(e,t.clientX-s.sx,t.clientY-s.sy);if("move"===s.kind)this._vacFit={...i,p:{...s.p0,ox:s.p0.ox+n,oy:s.p0.oy+o}};else{const t=Th(this.hass?.states[i.source]?.attributes),e=this._vacGhostCentre(t?.rooms||[]),r=zh(s.p0),[a,l]=bh(r,e[0],e[1]),[c,h]=bh(r,s.fx,s.fy),d=Math.hypot(a-c,l-h)||1,[u,p]=[2*a-c,2*l-h],_=Math.hypot(u+2*n-c,p+2*o-h)/2,g=Math.max(.05,_/d),m={...s.p0,s:s.p0.s*g};this._vacFit={...i,p:Nh(m,s.p0,s.fx,s.fy)}}return}"pointerup"!==t.type&&"pointercancel"!==t.type||(this._vacFit={...i,drag:null})}}_renderVacFit(t){const e=this._vacFit;if(!e)return G;const i=Th(this._renderPlanHass?.states?.[e.source]?.attributes);if(!i)return G;const s=zh(e.p),n=[],o=[],r=[];for(const t of i.rooms){if(null==t.x0)continue;const e=[[t.x0,t.y0],[t.x1,t.y0],[t.x1,t.y1],[t.x0,t.y1]].map(([t,e])=>bh(s,t,e));e.forEach(([t,e])=>{o.push(t),r.push(e)});const[i,a]=bh(s,t.cx,t.cy);n.push(j`
${t.name} `)}let a=G;if(i.pos){const[e,n]=bh(s,i.pos.x,i.pos.y);a=j` `}const l=[];if(o.length){const e=(()=>{const t=s[0]*s[4]-s[1]*s[3];return(e,i)=>[(s[4]*(e-s[2])-s[1]*(i-s[5]))/t,(-s[3]*(e-s[2])+s[0]*(i-s[5]))/t]})(),i=Math.min(...o),n=Math.max(...o),a=Math.min(...r),c=Math.max(...r),h=.022*t.w,d=h/4;for(const[t,s,o,r]of[[i,a,n,c],[n,a,i,c],[n,c,i,a],[i,c,n,a]]){const i=e(o,r);l.push(j`
`)}}return W`this._vacFitPointer(e,t)}
@pointermove=${e=>this._vacFitPointer(e,t)}
@pointerup=${e=>this._vacFitPointer(e,t)}
@pointercancel=${e=>this._vacFitPointer(e,t)}>${n}${a}${l} `}_vacRafLoop(){this._vacRaf=requestAnimationFrame(()=>{const t=this.renderRoot,e=this._stageEl,i=this._vacLastView,s=t?.querySelectorAll?.(".vacpuck")||[];if(!e||!i||!s.length)return void(this._vacRaf=0);const n=e.getBoundingClientRect();for(const e of s){const s=e.getAttribute("data-mid"),o=e.getBoundingClientRect(),r=i.x+(o.left+o.width/2-n.left)/n.width*i.w,a=i.y+(o.top+o.height/2-n.top)/n.height*i.h;for(const e of t.querySelectorAll(`line.tip[data-mid="${s}"]`))e.setAttribute("x2",r.toFixed(1)),e.setAttribute("y2",a.toFixed(1))}this._vacRafLoop()})}_renderVacuums(t,e){if(this._markup||"decor"===this._mode)return G;const i=this._space+"|"+e.x+"|"+e.y+"|"+e.w+"|"+e.h,s=this._vacJumpOnce||i!==this._vacViewKey;this._vacViewKey=i,this._vacJumpOnce=!1;const n=[],o=[];for(const i of t){if(i.hidden||!this._isVacDev(i))continue;if("static_icon"===Bi(i.marker?.display))continue;const t=this._renderDeviceSnapshot?.facts.get(`vacuum:${i.id}`),r=t?.source??this._vacSource(i,this._renderPlanHass);if(!r)continue;const a=t?.telemetry??Th(this._renderPlanHass?.states[r]?.attributes);if(!a)continue;const l=String(t?.mapId??this._vacMapId(i,a,this._renderPlanHass)),c=i.marker?.vacuum?.calibration?.[l];if(!c||6!==c.length)continue;const h=t?.runtime??this._vacRt.get(i.id),d=h?.moving??!1,u=Hh(i.marker?.vacuum),p="always"===u||"cleaning"===u&&d,_=t?.server??this._vacSrvTrails[i.id],g=_?.current?.map_id===l&&Array.isArray(_.current.points)?_.current:null,m=_?.previous?.map_id===l&&Array.isArray(_.previous.points)?_.previous:null;if("always"===u&&m&&m.points.length>1){const t=m.points.map(([t,e])=>{const[i,s]=bh(c,t,e),n=this._scenePoint([i,s]);return n[0].toFixed(1)+","+n[1].toFixed(1)}).join(" ");o.push(j` `)}if(p){const t=Ch(a,g,h?.trail||[]),e=!d||"integration"!==t.source&&"server"!==t.source?t.path:Dh(t.path);if(e.length){const t=e.map(t=>t.map(([t,e],i)=>{const[s,n]=bh(c,t,e),o=this._scenePoint([s,n]);return`${i?"L":"M"} ${o[0].toFixed(1)} ${o[1].toFixed(1)}`}).join(" ")).join(" ");o.push(j` `);const s=e[e.length-1];if(d&&s?.length>=2){const t=s[s.length-1],[e,n]=bh(c,t[0],t[1]),r=this._scenePoint([e,n]),a=r[0].toFixed(1),l=r[1].toFixed(1);o.push(j` `)}}}if(!d||!a.pos)continue;const[f,v]=bh(c,a.pos.x,a.pos.y),y=this._scenePoint([f,v]),b=(y[0]-e.x)/e.w*100,w=(y[1]-e.y)/e.h*100,k=h&&h.lastTs>0&&Date.now()-h.lastTs>6e4,x=i.marker?.icon||i.icon||"mdi:robot-vacuum";n.push(W`{t.stopPropagation();const e=this._vacEntity(i);e&&this._openMoreInfo(e)}}>
`)}return this._vacLastView=e,n.length&&!this._vacRaf&&this._vacRafLoop(),n.length||o.length?W`
${o.length?j`${o} `:G}
${n}`:G}_renderDevice(t,e,i=!0){const s=this._pos(t),n=this._scenePoint([s.x,s.y]),o=(n[0]-e.x)/e.w*100,r=(n[1]-e.y)/e.h*100,a=this._devicePresentation(t,i),l=[`left:${o}%`,`top:${r}%`,...Go(a)],c=a.disabledReason,h=a.haDisabled?this._t(`marker.ha_disabled_${c}`):t.userHidden?this._t("marker.hidden_ghost"):t.name,d=Ru(a),u="view"===this._mode||"devices"===this._mode,p=[h,a.haDisabled?"":this._t(`marker.state_a11y_${d}`),"none"!==a.pulse.kind?this._t(`marker.pulse_a11y_${a.pulse.reason}`):"",a.valueFullText||a.valueText||"",Ro(a.valueBadge),null!=a.lqiText&&a.lqiBand?this._t(`marker.lqi_a11y_${a.lqiBand}`,{value:a.lqiText}):""].filter(Boolean).join(", "),_=[t.model,a.valueBadge?.fullText||"",null!=a.lqiText?"LQI "+a.lqiText:""].filter(Boolean).join(" · ");return W`this._clickDevice(e,t)}
@keydown=${e=>this._keyDevice(e,t)}
@contextmenu=${e=>this._ctxDevice(e,t)}
@pointerover=${e=>this._showTip(e,t.name,a.haDisabled?h:_)}
@pointerleave=${()=>this._clearTransientHover()}
@pointerdown=${e=>this._pointerDown(e,t)}
@pointermove=${e=>{this._pointerMove(e,t),this._showTip(e,t.name,a.haDisabled?h:_)}}
@pointerup=${e=>this._pointerUp(e,t)}
@pointercancel=${e=>this._pointerUp(e,t)}
>
${Ko(a,{newDevice:this._newIds.has(t.id),newDeviceTitle:this._t("device.new"),disabledTitle:a.haDisabled?h:""})}
`}_roomArea(t){const e=hi(t);if(!e)return null;const i=this._spaceModel();if(!i)return null;const s=this._spaceWalls,n=s.length&&t.id&&hl(i.rooms,t.id,s,this._openPairs().flatMap(t=>t.segs),this._wallKeyPitch,this._cellCm,this._gridPitch,Pg)||e,o=this._cleanFloor(t,n),r=this._cellCm/this._gridPitch;return Ir(o.area*r*r/1e4,"mi"===this._renderPlanHass?.config?.unit_system?.length)}_roomTemp(t){const e=t.settings?.temp_source;return e?Mo(this._renderPlanHass,e,"temp",this._markers):t.area?this._climate().get(t.area)?.temp??null:null}_roomHum(t){const e=t.settings?.hum_source;return e?Mo(this._renderPlanHass,e,"hum",this._markers):t.area?this._climate().get(t.area)?.hum??null:null}_climate(){const t=this._serverCfg?.markers,e=this._renderPlanHass,i=this._climateCache;if(i&&i.h===e&&i.r===this._iconRules&&i.mk===t)return i.m;const s=function(t,e,i){const s=new Map;if(!t?.entities)return s;const n=wo(i),o=new Set;for(const t of i||[]){if(t?.removed||!0!==t?.use_climate_temp)continue;const e=(t.binding||"").indexOf(":");e>0&&o.add(t.binding.slice(e+1))}const r=new Map;for(const[e,i]of Object.entries(t.entities)){if(i.device_id&&n.devices.has(i.device_id)||!i.device_id&&n.entities.has(e))continue;const s=i.device_id?t.devices?.[i.device_id]:null,a=i.area_id||s?.area_id||null;if(!a)continue;if(i.entity_category)continue;if(!(o.size>0&&e.startsWith("climate.")&&(o.has(e)||i.device_id&&o.has(i.device_id)))){if(Yt.has(i.platform))continue;if(Co.test(e))continue}let l=r.get(a);l||(l=new Map,r.set(a,l));const c=i.device_id||e;let h=l.get(c);if(!h){const n=t.states?.[e];h={name:(s?s.name_by_user||s.name:i.name||n?.attributes?.friendly_name||e)||e,model:s?.model,ents:[]},l.set(c,h)}h.ents.push(e)}for(const[i,n]of r){const r=[],a=[];for(const[i,s]of n){const n=bo(t,s.name,s.model,s.ents,e),l="mdi:thermometer"===n||"mdi:air-filter"===n;if(l){const e=go(t,s.ents);null!=e&&r.push(e)}if(o.size>0&&(o.has(i)||s.ents.some(t=>o.has(t)))){const e=mo(t,s.ents);null!=e&&r.push(e)}if(l||"mdi:water-percent"===n){const e=vo(t,s.ents);null!=e&&a.push(e)}}(r.length||a.length)&&s.set(i,{temp:r.length?Math.round(r.reduce((t,e)=>t+e,0)/r.length*10)/10:null,hum:a.length?Math.round(a.reduce((t,e)=>t+e,0)/a.length):null})}return s}(e,this._iconRules,t);return this._climateCache={h:e,r:this._iconRules,mk:t,m:s},s}_resetRoomDialogFields(){this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1}_openRoomEdit(t){if(!t.id)return;this._roomEditId=t.id,this._nameSel=t.name||"",this._areaSel=t.area||"",this._roomFill="glow"===t.settings?.fill_mode?"":t.settings?.fill_mode||"";const e=t.settings?.custom_fill;this._roomCustomFill=e&&"object"==typeof e?as(e,cs(this._curSpaceCfg).customFill):null,this._roomTempSrc=t.settings?.temp_source||"",this._roomHumSrc=t.settings?.hum_source||"",this._roomNameScale=zs(t.settings?.name_scale),this._roomLabelScale=zs(t.settings?.label_scale),this._roomSrcOpen=null,this._roomSrcFilter="",this._roomDialog=!0}_roomSettingsFromDialog(){const t={};return this._roomFill&&(t.fill_mode=this._roomFill),this._roomCustomFill&&(t.custom_fill=this._roomCustomFill),this._roomTempSrc&&(t.temp_source=this._roomTempSrc),this._roomHumSrc&&(t.hum_source=this._roomHumSrc),1!==this._roomNameScale&&(t.name_scale=this._roomNameScale),1!==this._roomLabelScale&&(t.label_scale=this._roomLabelScale),Object.keys(t).length?t:null}_saveRoomEdit(){const t=this._curSpaceCfg,e=t?.rooms.find(t=>t.id===this._roomEditId);if(!e)return this._roomDialog=!1,void(this._roomEditId=null);e.name=this._nameSel.trim()||e.name,e.area=this._areaSel||null;const i=e.settings||{},s={...i};this._roomFill?s.fill_mode=this._roomFill:delete s.fill_mode,this._roomCustomFill?s.custom_fill=this._roomCustomFill:delete s.custom_fill,"glow"===i.fill_mode&&"boolean"!=typeof i.glow&&(s.glow=!0),this._roomTempSrc?s.temp_source=this._roomTempSrc:delete s.temp_source,this._roomHumSrc?s.hum_source=this._roomHumSrc:delete s.hum_source,1!==this._roomNameScale?s.name_scale=this._roomNameScale:delete s.name_scale,1!==this._roomLabelScale?s.label_scale=this._roomLabelScale:delete s.label_scale,Object.keys(s).length?e.settings=s:delete e.settings,this._saveConfig(),this._roomDialog=!1,this._roomEditId=null,this._nameSel="",this._areaSel="",this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate(),this._showToast(this._t("toast.room_updated"))}_roomSrcCandidates(){const t=this._planHass,e=wo(this._markers),i=this._roomSrcFilter.trim().toLowerCase(),s=[];for(const n of Object.values(t.devices)){if("service"===n.entry_type)continue;if(e.devices.has(n.id))continue;const t=(n.name_by_user||n.name||n.id).trim();i&&!t.toLowerCase().includes(i)||s.push({value:"device:"+n.id,label:t,sub:n.model||this._t("marker.sub_device")})}for(const[n,o]of Object.entries(t.entities)){if(!n.startsWith("sensor.")||o.hidden)continue;if(ko(t,n,e))continue;const r=o.name||t.states[n]?.attributes?.friendly_name||n;i&&!(r+" "+n).toLowerCase().includes(i)||s.push({value:"entity:"+n,label:r,sub:n})}return s.sort((t,e)=>t.label.localeCompare(e.label)),s.slice(0,200)}_roomSrcLabel(t){const e=t.indexOf(":"),i=t.slice(0,e),s=t.slice(e+1);return"device"===i?this._fullRegistryHass.devices[s]?.name_by_user||this._fullRegistryHass.devices[s]?.name||s:this._fullRegistryHass.entities[s]?.name||this.hass.states[s]?.attributes?.friendly_name||s}_labelPos(t,e){const i=this._layout["rl_"+(t.id||"")];if(i&&i.s===e)return{x:i.x*Pg,y:i.y*Pg};const s=this._snap(this._roomCenter(t));return{x:s[0],y:s[1]}}_labelDown(t,e,i){if("plan"!==this._mode)return;t.preventDefault(),t.stopPropagation();const s=this._labelPos(e,i);this._drag={id:"rl_"+(e.id||""),sx:t.clientX,sy:t.clientY,ox:s.x,oy:s.y,moved:!1},Ng(t),this._tip=null}_labelMove(t,e,i){const s="rl_"+(e.id||"");if(!this._drag||this._drag.id!==s)return;const n=this._stageEl;if(!n)return;const o=this._spaceModelById(i);if(!o)return;const r=o.vb,a=n.getBoundingClientRect(),l=this._viewOr(r),c=(t.clientX-this._drag.sx)/a.width*l.w,h=(t.clientY-this._drag.sy)/a.height*l.h;Math.abs(t.clientX-this._drag.sx)+Math.abs(t.clientY-this._drag.sy)>3&&(this._drag.moved=!0);const d=dc(this._drag.ox+c),u=dc(this._drag.oy+h);this._savePos({id:s,space:i},d,u)}_labelUp(t){const e="rl_"+(t.id||"");if(!this._drag||this._drag.id!==e)return;const i=this._drag.moved;this._drag=i?this._drag:null,i&&window.setTimeout(()=>this._drag=null,0)}_labelScale(t){const e=this._layout["rl_"+(t.id||"")]?.k;return"number"==typeof e&&Number.isFinite(e)?Math.min(3,Math.max(.5,e)):1}_rlResizeDown(t,e,i){if("plan"!==this._mode)return;t.preventDefault(),t.stopPropagation();const s=t.target.closest(".roomlabel");if(!s)return;const n=s.getBoundingClientRect(),o=n.left+n.width/2,r=n.top+n.height/2,a=Math.max(8,Math.hypot(t.clientX-o,t.clientY-r));this._rlResize={id:"rl_"+(e.id||""),space:i,k0:this._labelScale(e),cx:o,cy:r,d0:a},Ng(t)}_rlResizeMove(t){const e=this._rlResize;if(!e)return;t.stopPropagation();const i=Math.max(8,Math.hypot(t.clientX-e.cx,t.clientY-e.cy)),s=Math.min(3,Math.max(.5,e.k0*(i/e.d0))),n=this._layout[e.id];if(n)this._layout={...this._layout,[e.id]:{...n,k:s}};else{const t=e.id.slice(3),i=this._spaceModelById(e.space);if(!i)return;const n=i.rooms.find(e=>e.id===t);if(!n)return;const o=this._labelPos(n,e.space);this._layout={...this._layout,[e.id]:{s:e.space,x:o.x/Pg,y:o.y/Pg,k:s}}}this._dirtyPos.add(e.id)}_rlResizeUp(){this._rlResize&&(this._rlResize=null,this._persistLayout())}_renderRoomGear(t,e,i){if(!t.id)return G;let s=null;if(t.poly?(s=this._gearPtCache.get(t.poly)||null,s||(s=$i(t.poly),this._gearPtCache.set(t.poly,s))):null!=t.x&&null!=t.y&&(s=[t.x+(t.w||0)/2,t.y+(t.h||0)/2]),!s)return G;const n=(s[0]-i.x)/i.w*100,o=(s[1]-i.y)/i.h*100;return W`t.stopPropagation()}
@click=${e=>{e.stopPropagation(),this._openRoomEdit(t)}}>
${this._t("room.settings_short")}
`}_renderRoomLabel(t,e,i,s){if(!t.name&&!this._markup)return G;const n=this._labelPos(t,e.id),o=this._scenePoint([n.x,n.y]),r=(o[0]-i.x)/i.w*100,a=(o[1]-i.y)/i.h*100,l=Math.min(1,s.opacity+.25),c=this._labelScale(t),h=[];if(t.area||t.settings?.temp_source||t.settings?.hum_source||s.labelLight){if(s.labelTemp){const e=this._roomTemp(t);null!=e&&h.push(W` ${e}° `)}if(s.labelHum){const e=this._roomHum(t);null!=e&&h.push(W` ${e}% `)}if(s.labelLqi&&t.area){const e=this._roomLqi(t.area);null!=e&&h.push(W` ${e} `)}if(s.labelLight){const e=(d=ho(this._renderPlanHass,this._renderDevices,t,this._virtualLights)).length?{on:d.filter(t=>t.on).length,total:d.length}:null;if(e){const t=0===e.on?this._t("roomcard.light_off"):e.on===e.total?this._t("roomcard.light_on"):this._t("roomcard.light_partial",{on:e.on,total:e.total});h.push(W` ${t} `)}}}var d;const u=!!t.area,p=!this._markup;return W`this._labelDown(i,t,e.id)}
@pointermove=${i=>this._labelMove(i,t,e.id)}
@pointerup=${()=>this._labelUp(t)}
@pointercancel=${()=>this._labelUp(t)}
>${t.name||(this._markup?this._t("room.unnamed"):"")}${u?W`{e.stopPropagation(),this._clickRoom(t)}:G}
@pointerdown=${p?t=>t.stopPropagation():G}> `:G}
${h.length?W`${h} `:G}
${"plan"===this._mode?["tl","tr","bl","br"].map(i=>W`this._rlResizeDown(i,t,e.id)}
@pointermove=${t=>this._rlResizeMove(t)}
@pointerup=${()=>this._rlResizeUp()}
@pointercancel=${()=>this._rlResizeUp()}> `):G}
`}get _measureAnchor(){return this._markup&&this._cursorPt?"draw"===this._tool&&this._path.length&&!this._contourClosed?this._path[this._path.length-1]:"split"===this._tool&&this._splitSel?.pts?.length?this._splitSel.pts[this._splitSel.pts.length-1]:null:null}_renderMeasureLabel(t){const e=this._measureAnchor,i=this._cursorPt,s=(i[0]-t.x)/t.w*100,n=(i[1]-t.y)/t.h*100,o=Os(e,i),r=Math.round(10*o)/10,a=function(t,e,i=.001){if(t.length<2||e.length<2)return!1;const s=Math.abs(e[0]-t[0]),n=Math.abs(e[1]-t[1]);if(!Number.isFinite(s)||!Number.isFinite(n)||Math.hypot(s,n)<=i)return!1;const o=Math.max(s,n,1);return s<=i*o||n<=i*o||Math.abs(s-n)<=i*o}(e,i,2e-4*this._gridPitch);return W`
${this._fmtLen(e,i)} · ${r}°
`}get _decorMeasure(){const t=this._decorDraft;if(!t||"decor"!==this._mode)return null;const[e,i]=t.a,[s,n]=t.b;if(Math.abs(e-s)<1e-6&&Math.abs(i-n)<1e-6)return null;const o=(e+s)/2,r=(i+n)/2;if("line"===t.kind){const e=Os(t.a,t.b);return{x:o,y:r,on45:Ns(e),text:`${this._fmtLen(t.a,t.b)} · ${Math.round(10*e)/10}°`}}const a=this._fmtLen([e,i],[s,i]),l=this._fmtLen([s,i],[s,n]);if("ellipse"===t.kind){const t=this._fmtLen([0,0],[Math.abs(s-e)/2,0]),a=this._fmtLen([0,0],[0,Math.abs(n-i)/2]);return{x:o,y:r,on45:!1,text:Math.abs(Math.abs(s-e)-Math.abs(n-i))<1e-6?`R ${t}`:`Rx ${t} × Ry ${a}`}}return{x:o,y:r,on45:!1,text:`${a} × ${l} · ${Ir(ha(Math.abs(s-e),this._cellCm,this._gridPitch)*ha(Math.abs(n-i),this._cellCm,this._gridPitch)/1e4,this._imperial)}`}}get _alignPoint(){if(this._markup){if("draw"===this._tool&&this._path.length&&!this._contourClosed&&this._cursorPt)return this._cursorPt;if("split"===this._tool&&this._splitSel?.pts?.length&&this._cursorPt)return this._cursorPt;if(this._drag?.id.startsWith("rl_")&&this._drag.moved){const t=this._drag.id.slice(3),e=this._spaceModel()?.rooms.find(e=>e.id===t);return e?(()=>{const t=this._labelPos(e,this._space);return[t.x,t.y]})():null}return null}if("devices"===this._mode&&this._drag?.moved){const t=this._devices.find(t=>t.id===this._drag.id);return t?(()=>{const e=this._pos(t);return[e.x,e.y]})():null}if("decor"===this._mode){if(this._decorDraft)return this._decorDraft.b;if(this._decorMove){const t=this._decorList.find(t=>t.id===this._decorMove.id);if(!t)return null;const e=Pg,i=this._decorH;return"line"===t.kind?[t.x1*e,t.y1*i]:[t.x*e,t.y*i]}return null}return null}_alignCandidates(){const t=[],e=this._spaceModel();if(this._markup){if(!e)return t;if(this._drag?.id.startsWith("rl_")){const i=this._drag.id.slice(3);for(const s of e.rooms){if(!s.name||s.id===i)continue;const e=this._labelPos(s,this._space);t.push([e.x,e.y])}return t}for(const i of e.rooms){const e=hi(i);if(e)for(const i of e)t.push(i)}if("draw"===this._tool)for(const e of this._path)t.push(e);if("split"===this._tool&&this._splitSel?.pts)for(const e of this._splitSel.pts)t.push(e);return t}if("devices"===this._mode){for(const e of this._devices){if(e.space!==this._space||e.id===this._drag?.id||"ha_disabled"===e.bindingStatus?.kind)continue;const i=this._pos(e);t.push([i.x,i.y])}return t}if("decor"===this._mode){const e=this._decorMove?.id;return t.push(...this._decorSnapGeometry(e).points),this._decorDraft&&t.push(this._decorDraft.a),t}return t}_renderAlignGuides(){const t=this._alignPoint;if(!t)return j``;const e=this._drag?.id.startsWith("rl_")?.5*this._gridPitch:.05*this._gridPitch,i=function(t,e,i){let s=null,n=null;for(const o of e)if(!(Math.abs(o[0]-t[0])<1e-6&&Math.abs(o[1]-t[1])<1e-6)){if(Math.abs(o[0]-t[0])<=i){const e=Math.abs(o[1]-t[1]);e>1e-6&&(!s||e1e-6&&(!n||e
${i.map(e=>{const[i,o,r,a]="x"===e.axis?[e.at,e.from[1],e.at,t[1]+Math.sign(t[1]-e.from[1])*n]:[e.from[0],e.at,t[0]+Math.sign(t[0]-e.from[0])*n,e.at];return j`
`})}
`}_renderOpeningCenterTick(t){const e=(t.angle+90)*Math.PI/180;return j` `}_renderOpeningDimensionGuides(t){const e=t.labels.flatMap(t=>t.dimension?[t.dimension]:[]);if(!e.length)return j``;const i=this._cssPxToRender(4);return j`
${e.map(t=>{const e=-t.axis[1],s=t.axis[0],n=(t,n)=>j` `;return j`
${n(t.from,"from")}${n(t.to,"to")}
`})}
`}_roomCenter(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)]}_openingAmt(t){const e=t.contact&&this._renderOpeningEntityAvailable(t.contact)?this._renderPlanHass.states[t.contact]?.state:null;return gi(t.type,e,!!t.invert)}_planEntityAvailable(t){return!!t&&(!ko(this._fullRegistryHass,t,wo(this._markers))&&"active"===this._bindingStatus("entity:"+t).kind)}_renderEntityAvailable(t){return!!t&&(!ko(this._renderPlanHass,t,wo(this._markers))&&(!!this._renderPlanHass.entities?.[t]&&!!this._renderPlanHass.states?.[t]))}_openingEntityAvailable(t){return function(t,e,i=An(t)){return!!e&&"active"===Bn(t,`entity:${e}`,i).kind}(this.hass,t,this._haRegistry)}_renderOpeningEntityAvailable(t){return e=this._renderPlanHass,!!(i=t)&&!!e?.states?.[i];var e,i}_renderOpeningPlacementPreview(){const t=this._openingPreview;if(!t)return j``;const e={type:t.type,length:t.renderedLength,angle:t.angle,amount:gi(t.type,null),flipH:t.flipH,flipV:t.flipV,base:"var(--hp-open)",tone:"var(--hp-open)",cellCm:this._cellCm,gridPitch:this._gridPitch,face:t.face},i="passage"===t.type?function(t,e){const i=Math.max(0,t.renderedLength)/2,s=Math.max(0,t.target.physicalHalfWidth),n=s+.18*Math.max(0,e),o=t=>({x1:t,y1:-n,x2:t,y2:n});return{rect:{x:-i,y:s?-s:0,width:2*i,height:2*s},boundaries:[o(-i),o(i)]}}(t,this._gridPitch):null;return j`
${i?j`
${i.boundaries.map(t=>j`
`)}
`:Du(e)}
`}_renderOpenings(t){const e=this._openingsR;if(!e.length)return j``;const i=this._spaceModel();if(!i)return j``;const s=t.color,n=this._spaceWalls,o=this._openPairs().flatMap(t=>t.segs),r=this._openingWallIndexFor(i,o).value;return j`${e.map(t=>{if(t.orphanReason)return j`{e.stopPropagation(),this._editOpening(t)}}>
!
`;const e=this._openingAmt(t),i=e>0&&!!t.contact&&this._renderOpeningEntityAvailable(t.contact)?"var(--hp-open)":s,o="gate"===t.type?!t.flip_v:t.flip_v,a=t.partitionHost||n.length||"gate"===t.type?this._openingFace(t,r,!!o):{ox:0,oy:0,cm:0,side:-1},l={type:t.type,length:t.rlen,angle:t.angle,amount:e,flipH:!!t.flip_h,flipV:!!t.flip_v,base:s,tone:i,cellCm:this._cellCm,gridPitch:this._gridPitch,face:a},{half:c,outlineHalf:h,hitHalf:d}=Cu(l);return j`
${Du(l)}
this._opClick(e,t)}
@pointerdown=${e=>this._opPointerDown(e,t)}
@pointermove=${e=>this._opPointerMove(e,t)}
@pointerup=${e=>this._opPointerUp(e,t)}
@pointercancel=${e=>this._opPointerUp(e,t)}>
`})}`}_renderOpeningLocks(t){const e=this._openingsR.filter(t=>!t.orphanReason&&("door"===t.type||"gate"===t.type)&&t.lock&&this._renderOpeningEntityAvailable(t.lock));if(!e.length)return W``;const i=this._spaceModel();if(!i)return W``;const s=this._openPairs().flatMap(t=>t.segs),n=this._openingWallIndexFor(i,s).value;return W`${e.map(e=>{const i=this._renderPlanHass.states[e.lock]?.state,s="locked"===i,o=s||["unlocked","open","opening","unlocking","locking"].includes(String(i)),r=(e.angle+90)*Math.PI/180,a="gate"===e.type?this._openingFace(e,n,!e.flip_v):null,l=a?-16*a.side:16*(e.flip_v?-1:1),c=e.rx+Math.cos(r)*l,h=e.ry+Math.sin(r)*l,d=this._scenePoint([c,h]),u=(d[0]-t.x)/t.w*100,p=(d[1]-t.y)/t.h*100;return W`{t.stopPropagation(),"view"===this._mode&&(this._openingInfo=e)}}>
`})}`}_lockAction(t,e){if(this._openingEntityAvailable(t)){if("unlock"===e){const e=this.hass?.states?.[t]?.attributes?.friendly_name||t;if(!confirm(this._t("confirm.unlock",{name:e})))return}this.hass?.callService?.("lock",e,{entity_id:t})}}_renderOpeningInfoCard(){const t=this._openingInfo,e="passage"!==t.type&&t.contact&&this._openingEntityAvailable(t.contact)?t.contact:null,i=("door"===t.type||"gate"===t.type)&&t.lock&&this._openingEntityAvailable(t.lock)?t.lock:null,s=e?this.hass.states[e]?.state:null,n=this._openingAmt(t),o=i?this.hass.states[i]?.state:null,r="door"===t.type?"opening.door":"gate"===t.type?"opening.gate":"passage"===t.type?"opening.passage":"opening.window",a="door"===t.type?"mdi:door":"gate"===t.type?"mdi:gate":"passage"===t.type?"mdi:arch":"mdi:window-closed-variant",l="gate"===t.type?n>0?"mdi:gate-open":"mdi:gate":n>0?"mdi:door-open":"mdi:door-closed",c=(t,e,i,s="")=>W`${e} ${i}
`;return W`this._openingInfo=null}>
${e?c(l,this._t("opening.contact_label"),"unavailable"===s||null==s?this._t("opening.state_unknown"):this._t(n>0?"opening.open":"opening.closed"),n>0?"warn":"ok"):G}
${i?c("locked"===o?"mdi:lock":"mdi:lock-open-variant",this._t("opening.lock_label"),"locked"===o?this._t("opening.locked"):["unlocked","open"].includes(String(o))?this._t("opening.unlocked"):this._t("opening.state_unknown"),"locked"===o?"ok":"warn"):G}
${i&&("locked"===o||["unlocked","open"].includes(String(o)))?W`
this._lockAction(i,"locked"===o?"unlock":"lock")}>
${this._t("locked"===o?"opening.unlock_action":"opening.lock_action")}
`:i&&["locking","unlocking"].includes(String(o))?W`
${this._t("opening.lock_pending")}
`:G}
${e||i?G:W`
${this._t("opening.no_entities")}
`}
this._openingInfo=null}>${this._t("btn.close")}
`}_renderOpeningDialog(){const t=this._openingDialog,e=this._spaceModel()?.partitions||[],i=t.id?this._curSpaceCfg?.openings?.find(e=>e.id===t.id):null,s={id:t.id||"preview",type:t.type,x:t.x/Pg,y:t.y/this._spaceH,angle:t.angle,length:i&&!t.lengthTouched?i.length:this._cmToUnits(Math.max(20,t.lengthCm))/Pg,...t.host?{host:t.host}:{}},n=fd(i,s),o=t.host?n?md(s,e,Pg,this._cellCm,this._gridPitch):gd(s,e,Pg,this._cellCm,this._gridPitch):null,r="does-not-fit-jamb"===o?.reason,a=t.host?e.find(e=>e.id===t.host.id):null,l=a?li(a.cm/2,this._imperial):"",c=!!t.host&&!o?.resolved&&!r,h="gate"===t.type?"mdi:gate":"window"===t.type?"mdi:window-closed-variant":"passage"===t.type?"mdi:arch":"mdi:door",d=(t,e,i)=>W`i(t.target.value)}>
${this._t("opening.none")}
${t.map(t=>W`${t.label} `)}
`;return W`this._openingDialog=null}>
${t.host?W`
${this._t("opening.host_partition")}
${c||r?W` `:G}
${c?this._t("opening.partition_orphan"):r?this._t("opening.partition_jamb_margin",{distance:l}):this._t("opening.host_partition")}
`:G}
${this._t("opening.type_label")}
this._openingDialog={...t,type:"window",lengthCm:t.id?t.lengthCm:q_("window")}} />
${this._t("opening.window")}
this._openingDialog={...t,type:"door",lengthCm:t.id?t.lengthCm:q_("door")}} />
${this._t("opening.door")}
this._openingDialog={...t,type:"passage",lengthCm:t.id?t.lengthCm:q_("passage")}} />
${this._t("opening.passage")}
this._openingDialog={...t,type:"gate",lengthCm:t.id?t.lengthCm:q_("gate"),flipH:!1}} />
${this._t("opening.gate")}
${this._t("opening.length_label")}
{const i=mg(e.target.value);null!=i&&(this._openingDialog={...t,lengthCm:i,lengthTouched:!0})}} />
${"passage"===t.type&&(t.contact||t.lock)?W`
${this._t("opening.passage_binding_warning")}
`:G}
${"passage"!==t.type?W`
${this._t("opening.contact_label")}
${d(this._contactCandidates(),t.contact,e=>this._openingDialog={...t,contact:e})}
${t.contact?W`
${this._boolInput(t.invert,e=>this._openingDialog={...t,invert:e})}
${this._t("opening.invert")} `:G}`:G}
${"door"===t.type||"gate"===t.type?W`
${this._t("opening.lock_label")}
${d(this._lockCandidates(),t.lock,e=>this._openingDialog={...t,lock:e})}`:G}
${"gate"!==t.type&&"passage"!==t.type?W`
${this._boolInput(t.flipH,e=>this._openingDialog={...t,flipH:e})}
${this._t("opening.flip_h")} `:G}
${"passage"!==t.type?W`
${this._boolInput(t.flipV,e=>this._openingDialog={...t,flipV:e})}
${this._t("opening.flip_v")} `:G}
`}_gridLevels(){const t=this._stageEl,e=this._viewOr(this._baseVb()),i=t&&t.clientWidth&&e.w?t.clientWidth/e.w:1;return function(t,e,i=7){if(!(t>0&&e>0&&Number.isFinite(e)))return null;const s=Mc.find(s=>t*s*e>=i);if(void 0===s)return null;const n=Mc.find(t=>t>=5*s)??5*s;return{fine:s,coarse:n}}(this._gridPitch,i)}_renderMarkupDefs(t){const e=this._gridLevels();if(!e)return j` `;const i=this._gridPitch*e.fine,s=this._gridPitch*e.coarse,n=this._gridPitch*e.fine*.14;return j`
`}_renderPhysicalEditorLayer(){const t=this._spaceModel();if(!t)return j``;const e=this._gridPitch,i=this._viewOr(this._baseVb()),s=this._stageEl,n=s?.clientWidth?i.w/s.clientWidth:e/8,o=Math.max(.22*e,8*n),r=Math.max(o,12*n),a=t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`,l=(t,e)=>this._physicalSel?.kind===t&&this._physicalSel.id===e||"column"===t&&this._duplicateColumnId===e,c=(t.room_drafts||[]).flatMap(t=>t.points.slice(0,-1).map((e,i)=>{const s=t.points[i+1],o=xa(t.segments[i]?.cm||15,this._cellCm,this._gridPitch);return j`{this._physicalSel={kind:"draft",id:t.id,segment:i},this._registerPhysicalTap("draft",t.id,i)}}> `})),h=(t.partitions||[]).map(t=>{const e=Ol(t.a,t.b,t.cm,this._cellCm,this._gridPitch);return e?j`this._physicalDown(e,"partition",t.id)}
@pointermove=${t=>this._physicalMove(t)}
@pointerup=${t=>this._physicalUp(t)}> `:G}),d=(t.wall_columns||[]).map(t=>{const e=Nl(this._physicalRotate?.id===t.id?{...t,angle:this._physicalRotate.angle}:t,this._cellCm,this._gridPitch);return j`this._physicalDown(e,"column",t.id)}
@pointermove=${t=>this._physicalMove(t)}
@pointerup=${t=>this._physicalUp(t)}> `}),u=this._physicalDrag,p=(()=>{if(!u?.moved)return G;const t="partition"===u.kind?Ol(u.base.a,u.base.b,u.base.cm,this._cellCm,this._gridPitch):Nl(u.base,this._cellCm,this._gridPitch);return t?j` `:G})(),_=(()=>{const i=this._physicalSel;if(!i)return G;if("draft"===i.kind){const e=t.room_drafts.find(t=>t.id===i.id);return e?j`
t.join(",")).join(" ")}>
${e.points.map(t=>j` `)}
`:G}if("partition"===i.kind){const e=t.partitions.find(t=>t.id===i.id);if(!e)return G;const s=Ol(e.a,e.b,e.cm,this._cellCm,this._gridPitch);if(!s)return G;const n=(e.a[0]+e.b[0])/2,r=(e.a[1]+e.b[1])/2;return j`
`}const s=t.wall_columns.find(t=>t.id===i.id);if(!s)return G;const l=this._physicalRotate?.id===s.id?{...s,angle:this._physicalRotate.angle}:s,c=Nl(l,this._cellCm,this._gridPitch);if("square"!==l.shape)return j`
`;const h=xa(l.cm,this._cellCm,this._gridPitch),d=Il(l.angle)*Math.PI/180,u=Math.sin(d),p=-Math.cos(d),_=[l.center[0]+u*h/2,l.center[1]+p*h/2],g=[_[0]+u*Math.max(e,24*n),_[1]+p*Math.max(e,24*n)];return j`
this._physicalRotateDown(t,s)}
@pointermove=${t=>this._physicalRotateMove(t)}
@pointerup=${t=>this._physicalRotateUp(t)}>
`})();return j`${c}${h}${d}${p}${_} `}_renderPlanSnapOverlay(){if(!this._markup||"draw"!==this._tool)return j``;const t=this._planSnapGeometrySnapshot().value,e=this._activePlanSnapCandidate,i=new Set(this._activePlanSnapConflicts.map(t=>t.key)),s=xa(5,this._cellCm,this._gridPitch),n=xa(10,this._cellCm,this._gridPitch);return j`
${mt([t,s,[...i].sort().join("|")],()=>j`
${t.segments.map(t=>j` `)}
${t.endpoints.map(t=>j` `)}
`)}
`}_syncPlanSnapActiveMarker(t){const e=this.renderRoot?.querySelector('[data-hp="plan-snap-active-marker"]');if(e){if(e.setAttribute("class",`plan-snap-node${t?" active":""}${"line"===t?.kind?" dynamic":""}`),e.setAttribute("data-active",t?"true":"false"),e.setAttribute("visibility",t?"visible":"hidden"),!t)return e.removeAttribute("data-kind"),void e.removeAttribute("data-key");e.setAttribute("data-kind",t.kind),e.setAttribute("data-key",t.key),e.setAttribute("cx",String(t.point[0])),e.setAttribute("cy",String(t.point[1])),e.setAttribute("r",String(xa(10,this._cellCm,this._gridPitch)))}}_syncPlanSnapConflictMarkers(t){const e=new Set(t.map(t=>t.key));for(const t of this.renderRoot?.querySelectorAll('.plan-snap-node[data-kind="endpoint"]')||[])t.setAttribute("class","plan-snap-node"+(e.has(t.dataset.key||"")?" conflict":""))}_planSnapPhysicalSegment(t){let e=0;const i=this._spaceModel();if(!i)return null;if("partition"===t.sourceKind)e=Number(i.partitions.find(e=>e.id===t.sourceId)?.cm)||0;else if("draft"===t.sourceKind){const s=/^(.*):(\d+)$/.exec(t.sourceId),n=s?i.room_drafts.find(t=>t.id===s[1]):null;e=n&&s&&Number(n.segments[Number(s[2])]?.cm)||0}else e=ll(i.rooms,this._spaceWalls,this._openCuts(),[t.a[0],t.a[1],t.b[0],t.b[1]],this._wallKeyPitch,this._cellCm,this._gridPitch,Pg);return e>0?{a:[...t.a],b:[...t.b],halfDepth:xa(e,this._cellCm,this._gridPitch)/2}:null}_drawPreviewJoinPatchD(t,e){if(t.length<2)return"";const i=[];for(let s=0;s+10&&i.push({a:t[s],b:t[s+1],halfDepth:e[s]});if(!i.length)return"";const s=2e-4*this._gridPitch,n=this._planSnapGeometrySnapshot().value.segments.filter(e=>t.some(t=>Hs(t,[e.a[0],e.a[1],e.b[0],e.b[1]])<=s)).map(t=>this._planSnapPhysicalSegment(t)).filter(t=>!!t);return Ua([...i,...n],s).map(t=>`M ${t.map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`).join(" ")}_renderMarkupLayer(t){const e=this._openPairs().flatMap(t=>t.segs),i=this._thickWallCuts(),s=e.concat(i),n=s.length?Ds(this._segments,s,.02*this._gridPitch):this._segments,o=this._path,r=this._gridPitch,a=this._viewOr(this._baseVb()),l="draw"===this._tool?this._drawWallCm:null,c=(()=>"draw"===this._tool&&o.length&&null!=l&&l>0?this._contourClosed?o:this._cursorPt?[...o,this._cursorPt]:o.length>=2?o:null:null)(),h=c?Nd(c.length-1,this._contourClosed?[...this._draftSegmentCms,this._closingWallCm??void 0]:this._draftSegmentCms,l,fa).map(t=>xa(t,this._cellCm,this._gridPitch)/2):[],d=c?Ga(c,xa(l,this._cellCm,this._gridPitch)/2,this._contourClosed,h):"",u=c?this._drawPreviewJoinPatchD(c,h):"",p=this._wallFaceBatch?.candidates[this._wallFaceBatch.index]?.repair||this._wallRepairDiagnostic;return j`
${this._gridLevels()?j` `:G}
${n.map(t=>j` `)}
${this._renderPhysicalEditorLayer()}
${"column"===this._tool&&this._cursorPt&&this._drawWallCm?j``M ${Nl({shape:"square",center:this._cursorPt,cm:this._drawWallCm},this._cellCm,this._gridPitch).map(t=>`${t[0]} ${t[1]}`).join(" L ")} Z`)()}> `:G}
${d?j`
`:G}
${u?j`
`:G}
${p?j` `:G}
${o.length>1?j` `:G}
${o.length&&this._cursorPt&&"draw"===this._tool&&!this._contourClosed?j`
${this._activePlanSnapCandidate||this._activePlanSnapConflicts.length?G:j` `}`:G}
${o.map((t,e)=>j` `)}
${"split"===this._tool&&this._splitSel?.pts?.length?j`${this._splitSel.pts.length>1?j` `:G}
${this._splitSel.pts.map((t,e)=>j` `)}
${this._cursorPt?j` `:G}`:G}
`}_renderPartitionDeleteDialog(){const t=this._partitionDeleteDialog,e="mi"===this.hass?.config?.unit_system?.length;return W`this._partitionDeleteDialog=null}>
${this._t("confirm.delete_partition_openings_body",{count:t.openings.length})}
${t.openings.map(t=>W`${this._t("confirm.delete_partition_openings_item",{type:this._t(`opening.${t.type}`),length:li(t.length*Pg/this._gridPitch*this._cellCm,e)})} `)}
this._partitionDeleteDialog=null}>
${this._t("btn.cancel")}
${this._t("btn.delete")}
`}_renderRoomDeleteDialog(){const t=this._roomDeleteDialog;return W`this._roomDeleteDialog=null}>
${this._t("confirm.delete_room_body")}
this._roomDeleteDialog=null}>
${this._t("btn.cancel")}
this._confirmRoomDelete(!0)}>
${this._t("btn.delete_room_keep_walls")}
this._confirmRoomDelete(!1)}>
${this._t("btn.delete_room_with_walls")}
`}_renderPhysicalDialog(){const t=this._physicalDialog,e="column"===t.kind;return W`this._physicalDialog=null}>
${e?W`
${this._t("physical.shape")}
{const i=e.target.value;this._physicalDialog={...t,shape:i}}}>
${this._t("physical.square")}
${this._t("physical.circle")}
`:G}
${this._t(e?"circle"===t.shape?"physical.diameter":"physical.side":"wallthick.field")}
this._physicalDialog={...t,cm:e.target.value}} />
${this._t(this._imperial?"wallthick.unit_in":"wallthick.unit_cm")}
${e&&"square"===t.shape?W`
${this._t("physical.rotation")}
this._physicalDialog={...t,angle:e.target.value}} />`:G}
${t.length?W`
${this._t("physical.length")}: ${t.length}
`:G}
`}_renderMarkupBar(){const t=this._geometryHistory.undoName,e=this._geometryHistory.redoName,i="boundary"===this._tool&&!!this._openWallAnchor,s=i?this._t("markup.boundary_cancel"):t?this._t("history.undo_named",{name:t}):this._t("history.undo_empty"),n=i?this._t("markup.boundary_cancel"):e?this._t("history.redo_named",{name:e}):this._t("history.redo_empty");return W`
this._activateMarkupTool("select")}
title=${this._t("title.markup_select")}>
${this._t("markup.select")}
this._activateMarkupTool("draw")}
title=${this._t("title.markup_add")}>
${this._t("markup.add")}
this._activateMarkupTool("column")}
title=${this._t("title.markup_column")}>
${this._t("markup.column")}
this._activateMarkupTool("merge")}
title=${this._t("title.markup_merge")}>
${this._t("markup.merge")}
this._activateMarkupTool("split")}
title=${this._t("title.markup_split")}>
${this._t("markup.split")}
this._activateMarkupTool("resize")}
title=${this._t("title.markup_resize")}>
${this._t("markup.resize")}
${this._editorToolbarGroups.map(t=>this._renderEditorGroupLauncher(t))}
this._activateMarkupTool("boundary")}
aria-pressed=${"boundary"===this._tool?"true":"false"}
title=${this._t("title.markup_boundary")}>
${this._t("markup.boundary")}
this._activateMarkupTool("wallthick")}
title=${this._t("title.markup_wallthick")}>
${this._t("markup.wallthick")}
this._activateMarkupTool("delroom")}
title=${this._t("title.markup_delroom")}>
${this._t("markup.delete_room")}
this._setMode("view")}>
`}_renderDevicesBar(){return W`
this._openMarkerDialog()} title=${this._t("title.add_device")}>
${this._t("devbar.add")}
${this._t("devbar.show_all")}
${this._t("devbar.rules")}
${this._editorToolbarGroups.map(t=>this._renderEditorGroupLauncher(t))}
this._setMode("view")}>
`}_cardEntities(t){const e=this._planHass,i=[],s=new Set,n=t=>{if(!t||s.has(t)||!e.states[t])return;const n=e.entities[t];if("config"===n?.entity_category||"diagnostic"===n?.entity_category)return;s.add(t);const o=t.split(".")[0];["light","switch","fan","humidifier","siren","input_boolean"].includes(o)?i.push({eid:t,kind:"toggle"}):["cover","valve","lock","climate","media_player","vacuum","water_heater"].includes(o)?i.push({eid:t,kind:"open"}):["sensor","binary_sensor","number","select"].includes(o)&&i.push({eid:t,kind:"value"})};for(const i of ho(e,this._devices,null,this._virtualLights))if(i.device.id===t.id)for(const t of[...i.serviceEids,...i.stateEids])n(t);t.primary&&n(t.primary);for(const e of t.entities)n(e);return i.slice(0,12)}_cardToggle(t){const e=t.split(".")[0];"lock"!==e&&"alarm_control_panel"!==e&&this._planEntityAvailable(t)&&this.hass.callService("homeassistant","toggle",{entity_id:t}).catch(t=>this._showToast(this._t("toast.error",{err:this._errText(t)})))}_renderInfoCard(){const t=this._infoCard,e=t.primary?this.hass.states[t.primary]:void 0,i=e?Ji(this.hass,t.primary)?.text??e.state:null,s=(t.controls??t.marker?.controls??[]).filter(Ms).filter(t=>this._planEntityAvailable(t));return W`
${(()=>{const e=this._cardEntities(t);return e.length?W`
${e.map(({eid:t,kind:e})=>{const i=this.hass.states[t],s=this.hass.entities[t]?.name||i?.attributes?.friendly_name||t,n=i?Ji(this.hass,t)?.text??i.state:"",o="on"===i?.state||["open","unlocked","playing","cleaning"].includes(i?.state);return W`
${s}
${"toggle"===e?W`this._cardToggle(t)}>${n} `:"open"===e?W`{this._closeInfoCard(),this._openMoreInfo(t)}}>${n} `:W`${n} `}
`})}
`:G})()}
${t.model?W`
${this._t("info.model")} ${t.model}
`:G}
${i&&!this._cardEntities(t).length?W`
${this._t("info.state")} ${i}
`:G}
${Hi(t.link)?W`
`:G}
${t.description?W`
${t.description}
`:G}
${t.pdfs&&t.pdfs.length?W`
${this._t("info.manuals")}
${t.pdfs.map(t=>W`
${t.name} `)} `:G}
${s.length?W`
${this._t("info.controls")}
${s.map(t=>{const e=this.hass.states[t],i="on"===e?.state;return W`
${e?.attributes?.friendly_name||t} `})}
`:G}
${t.model||i||t.link||t.description||t.pdfs&&t.pdfs.length||s.length?G:W`
${this._t("info.none")}
`}
`}_markerValueBadgeFields(t){return(e={touched:t.valueBadgeTouched,originalHas:t.originalHasValueBadge,original:t.originalValueBadge,enabled:t.valueBadgeEnabled,source:t.valueBadgeSource,position:t.valueBadgePosition}).touched?{value_badge:{enabled:e.enabled,source:e.source,position:e.position}}:e.originalHas?{value_badge:e.original}:{};var e}_markerDraft(t){if("ha"===t.bindingMode&&(!t.binding||"virtual"===t.binding))return null;const e=qs(t.room),i=Ei(t.binding,t.devId,()=>"__hp_device_preview__"),s=this._markers.find(e=>e.id===i||e.id===t.devId),n=Zn(t.binding,t.controls,this._bindingEntities(t.binding)),o=this._effectiveStoredTapAction(t),r={id:i,binding:t.binding,name:t.name.trim()||null,icon:t.icon||null,display:"badge"!==t.display?t.display:null,ripple_color:"icon_ripple"===t.display&&t.rippleColor?t.rippleColor:null,ripple_size:"icon_ripple"===t.display&&1.5!==t.rippleSize?t.rippleSize:null,size:1!==t.size?t.size:null,angle:t.angle||null,...this._markerTapActionFields(t),...this._markerToggleEntityFields(t),tap_target:"run"===o&&t.tapTarget||null,tap_confirm:!!t.tapConfirm||null,controls:n.length?n:null,...this._markerLightFields(t),...this._markerValueBadgeFields(t),use_climate_temp:!!t.useClimateTemp||null,glow_radius_cm:(()=>{const e=mg(t.glowRadius);return null==e||e<=0?null:Math.round(this._imperial?30.48*e:100*e)})(),model:t.model.trim()||null,link:t.link.trim()||null,description:t.description.trim()||null,pdfs:t.pdfs,hidden:t.hideFromPlan,vacuum:s?.vacuum||null};return("virtual"===t.binding||t.room)&&(r.space=e?.space||("virtual"===t.binding?this._space:null),r.area=e?.area||null,r.room_id=e?.roomId||null),r}_markerPreviewDevice(t){const e=this._markerDraft(t);if(!e)return null;const i=`${this._haRegistry.revision}\n${JSON.stringify(e)}`;if(this._markerPreviewMemo?.key===i)return this._markerPreviewMemo.device;const s=function(t){const{marker:e,...i}=t;return So({...i,markers:[e]}).find(t=>t.id===e.id)||null}({hass:this.hass,registry:this._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this._areaToSpace).map(([t,e])=>[t,e.space])),marker:e,settings:this._settings,excluded:this._excluded,showAll:this._showAll,firstSpaceId:this._model[0]?.id||this._space,loc:t=>this._t(t),iconRules:this._iconRules});return this._markerPreviewMemo={key:i,device:s},s}_markerPreviewDevices(t){const e=this._markerPreviewDevicesMemo;if(e?.base===this._devices&&e.preview===t)return e.devices;const i=[...this._devices.filter(e=>e.id!==t.id),t];return this._markerPreviewDevicesMemo={base:this._devices,preview:t,devices:i},i}_toggleIntent(t,e=this._devices){return ld({hass:this._planHass,registryHass:this._fullRegistryHass,devices:e,device:t,virtualLights:this._virtualLights})}_toggleIntentForDialog(t){const e=this._markerPreviewDevice(t);if(!e)return null;const i=this._markerPreviewDevices(e);return this._toggleIntent(e,i)}_toggleStateText(t,e){const i=this._planHass?.states?.[t]||this.hass?.states?.[t];try{return i&&"function"==typeof this.hass?.formatEntityState?this.hass.formatEntityState(i):e}catch{return e}}_toggleConfirmationStateText(t){const e=String(t.state||"unknown"),i=t.entityId?this._toggleStateText(t.entityId,e):e;if(i.trim().toLocaleLowerCase()!==e.trim().toLocaleLowerCase())return i;const s={on:"confirm.state_on",off:"confirm.state_off",open:"confirm.state_open",closed:"confirm.state_closed",opening:"confirm.state_opening",closing:"confirm.state_closing",unknown:"confirm.state_unknown"}[e];return s?this._t(s):e.replaceAll("_"," ").replaceAll("-"," ")}_toggleConfirmationLines(t){const e={"turn-on":"confirm.state_on","turn-off":"confirm.state_off",open:"confirm.state_open",close:"confirm.state_closed",stop:"confirm.state_stopped"};return function(t,e){if(!hd(t)||!t.nextEffect||!t.targets.length)return[];const i="group"===t.kind,s=i?t.targets.filter(t=>"on"===t.state).length:0,n=i?0===s?e.groupAllOff():e.groupCurrent(s,t.targets.length):e.state(t.targets[0]);let o;return o="toggle"===t.nextEffect?e.expectedByHa():i&&"turn-on"===t.nextEffect?e.groupAllOn():i&&"turn-off"===t.nextEffect?e.groupAllOff():e.effect(t.nextEffect),[e.current(n),e.expected(o),...t.skippedTargets.length?[e.unavailable(t.skippedTargets.length)]:[]]}(t,{state:t=>this._toggleConfirmationStateText(t),current:t=>this._t("confirm.current_state",{state:t}),expected:t=>this._t("confirm.expected_state",{state:t}),groupCurrent:(t,e)=>this._t("confirm.group_current",{on:t,total:e}),groupAllOn:()=>this._t("confirm.group_all_on"),groupAllOff:()=>this._t("confirm.group_all_off"),unavailable:t=>this._t("confirm.unavailable_targets",{count:t}),effect:t=>this._t(e[t]),expectedByHa:()=>this._t("confirm.expected_by_ha")})}_toggleHintLines(t){if(!t)return[];const e=t=>this._t(`marker.toggle_effect_${t.replace("-","_")}`),i=t=>this._t(`marker.toggle_skip_${t.replace("-","_")}`);return function(t,e){const i=t.targets[0]||t.skippedTargets[0],s=[];return"group"===t.kind?t.targets.length&&s.push(e.group(t.targets)):i&&s.push(e.single(i)),t.nextEffect&&t.targets.length&&s.push("group"===t.kind?e.groupCurrentNext(t.targets,t.nextEffect):e.currentNext(t.targets[0],t.nextEffect)),t.skippedTargets.length&&s.push(e.skipped(t.skippedTargets)),!t.command&&t.noneReason&&s.push(e.none(t.noneReason)),s}(t,{single:t=>{if("via"in t&&"virtual-light"===t.via)return this._t("marker.virtual_light_target",{name:t.name});const e=t.entityId||("ref"in t?t.ref:""),i=t.name||e;return this._t("marker.toggle_hint_single",{name:i,id:e})},group:t=>this._t("marker.toggle_hint_group",{count:t.length,names:t.map(t=>`${t.name} (${t.entityId})`).join(", ")}),currentNext:(t,i)=>"virtual-light"===t.via?this._t("marker.virtual_light_current",{state:this._t("on"===t.state?"marker.virtual_light_state_on":"marker.virtual_light_state_off"),effect:e(i)}):this._t("marker.toggle_hint_current",{state:this._toggleStateText(t.entityId,t.state),effect:e(i)}),groupCurrentNext:(t,i)=>this._t("marker.toggle_hint_group_current",{on:t.filter(t=>"on"===t.state).length,count:t.length,effect:e(i)}),skipped:t=>this._t("marker.toggle_hint_skipped",{count:t.length,targets:t.map(t=>{const e=t.entityId||t.ref;return`${t.name||e} (${e}: ${i(t.reason)})`}).join(", ")}),none:t=>this._t(`marker.toggle_none_${t.replaceAll("-","_")}`)})}_effectiveStoredTapAction(t,e){return t.tapActionTouched?t.tapAction:nd(t.originalHasTapAction?t.originalTapAction:null,e)}_effectiveMarkerTapAction(t,e=this._markerPreviewDevice(t)){return this._effectiveStoredTapAction(t,e?.primary?.split(".")[0])}_announceToggleDraft(t){const e=this._markerPreviewDevice(t),i=t.tapActionTouched?t:{...t,tapAction:this._effectiveMarkerTapAction(t,e)},s="toggle"===i.tapAction?this._toggleHintLines(this._toggleIntentForDialog(i)).join(" "):"";return{...i,tapHintAnnouncement:s}}_valueBadgeForBinding(t,e){const i={...t,binding:e,valueBadgeEnabled:!1,valueBadgeSource:null,valueBadgeTouched:!0},s=this._markerPreviewDevice(i);if(!s)return{valueBadgeEnabled:!1,valueBadgeSource:null,valueBadgeTouched:!0};const n=[...this._devices.filter(t=>t.id!==s.id),s],o=Wo(this._planHass,s,n),r=jo(this._planHass,s,o);return{valueBadgeEnabled:t.valueBadgeEnabled&&!!r,valueBadgeSource:r,valueBadgeTouched:!0}}_markerSpatialSource(t){const e=this._markerPreviewDevice(t);if(!e)return null;const i={...e,hidden:!1};return uo(ho(this._planHass,[...this._devices.filter(t=>t.id!==i.id),i],null,this._virtualLights).filter(t=>t.device.id===i.id))}_markerAutoHasSpatialSource(t){const e={...t,lightRole:"auto",lightRoleTouched:!0},i=this._markerPreviewDevice(e);return!!i&&lo(this._planHass,{...i})}_setMarkerLightRole(t){const e=this._markerDialog;e&&(this._markerDialog={...e,lightRole:t,lightRoleTouched:!0})}_controlRefInfo(t){if(!t.startsWith("marker:"))return{label:this.hass.states[t]?.attributes?.friendly_name||t,sub:t,icon:t.startsWith("light.")?"mdi:lightbulb":"mdi:toggle-switch",warning:!this._planEntityAvailable(t)};const e=t.slice(7),i=this._markers.find(t=>t.id===e),s=this._devices.find(t=>t.id===e);if(!i||i.removed||!0!==i.is_light)return{label:this._t("marker.control_missing_label"),sub:`${this._t("marker.control_broken")} (${t})`,icon:"mdi:alert-outline",warning:!0};const n=this._serverCfg?.spaces.find(t=>t.id===(s?.space||i.space)),o=!!s&&to(s).length>0;return{label:i.name||s?.name||e,sub:[n?.title||s?.space||i.space,i.room_id||s?.area,o?"":this._t("marker.control_passive")].filter(Boolean).join(" · "),icon:i.icon||s?.icon||"mdi:lightbulb-outline",warning:!0===i.hidden||!0===s?.hidden}}_valueBadgeCandidateLabel(t){const e=t.source;if("derived_lqi"===e.kind)return this._t("marker.value_badge_lqi");if("derived_marker_state"===e.kind)return this._t("marker.value_badge_marker_state",{name:t.label});if("entity_state"===e.kind)return this._t("marker.value_badge_state",{name:t.label});const i=this.hass.states[e.entity_id]?.attributes?.friendly_name||this._fullRegistryHass.entities[e.entity_id]?.name||e.entity_id;return this._t(`marker.value_badge_attr_${e.attribute}`,{name:i})}_controlCandidates(t){const e=this._markerDraft(t)?.id||t.devId||"",i=[],s=new Set;for(const t of this._markers){if(t.id===e||t.removed||t.hidden||!0!==t.is_light)continue;if("virtual"!==t.binding&&"active"!==this._bindingStatus(t.binding).kind)continue;const n=this._devices.find(e=>e.id===t.id);if(!n||n.hidden)continue;const o=this._controlRefInfo(`marker:${t.id}`);for(const t of to(n))s.add(t);i.push({value:`marker:${t.id}`,label:o.label,sub:o.sub,icon:o.icon,search:`${o.label} ${o.sub} ${t.id} ${to(n).join(" ")}`.toLowerCase()})}const n=Object.keys(this.hass.states||{}).filter(e=>Ms(e)&&!s.has(e)&&Jn(t.binding,[e],this._bindingEntities(t.binding)).length>0&&this._planEntityAvailable(e)).map(t=>{const e=this._controlRefInfo(t);return{value:t,label:e.label,sub:t,icon:e.icon,search:`${e.label} ${t}`.toLowerCase()}}),o=t.controlsFilter.trim().toLowerCase();return[...i,...n].filter(e=>!t.controls.includes(e.value)&&(!o||e.search.includes(o))).slice(0,12).map(({search:t,...e})=>e)}_addControlRef(t,e){if(e.startsWith("marker:")){const i=this._markerDraft(t)?.id||t.devId||"";if(!i)return void this._showToast(this._t("toast.marker_binding_required"));const s=e.slice(7),n=this._markerDraft(t);if(function(t,e,i){if(!e||e===i)return!0;const s=new Map;for(const e of t)s.set(e.id,(e.controls||[]).filter(t=>"string"==typeof t&&t.startsWith("marker:")).map(t=>t.slice(7)));const n=new Set,o=[i];for(;o.length;){const t=o.pop();if(t===e)return!0;n.has(t)||(n.add(t),o.push(...s.get(t)||[]))}return!1}(n?[...this._markers.filter(t=>t.id!==i),n]:this._markers,i,s))return void this._showToast(this._t("toast.marker_control_cycle"))}this._markerDialog=this._announceToggleDraft({...t,controls:[...t.controls,e],controlsFilter:""})}_setMarkerGlowMode(t){const e=this._markerDialog;if(!e)return;if("auto"===t)return void(this._markerDialog={...e,glowMode:t,glowTouched:!0});const i=this._markerSpatialSource(e),s=xs(i?this._planHass.states[i.eid]:void 0,null,this._fillColors.glow_light.c),n=!e.glowColorDrafted,o="fixed"===t&&!e.glowBrightnessDrafted;this._markerDialog={...e,glowMode:t,glowColor:n?s.c:e.glowColor,glowBrightness:o?Math.max(1,Math.round(100*s.bri)):e.glowBrightness,glowColorDrafted:!0,glowBrightnessDrafted:e.glowBrightnessDrafted||"fixed"===t,glowTouched:!0}}_renderMarkerDialog(){const t=this._markerDialog,e="virtual"===t.bindingMode,i=this._bindingCandidates();this._bindingEntities(t.binding);const s=e?null:this._bindingStatus(t.binding),n=!e&&this._bindingHasHaPage(t.binding),o=this._markerPreviewDevice(t),r=this._effectiveMarkerTapAction(t,o),a=o?cs(this._serverCfg?.spaces.find(t=>t.id===o.space)):null,l=o?this._markerPreviewDevices(o):this._devices,c="toggle"===r&&o?this._toggleIntent(o,l):null,h=this._toggleHintLines(c),d=o?Bu(this._planHass,o,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:a?.showLqi??!1!==this._config?.show_signal,designPreview:!0,activityRuntime:this._activityRt.get(o.id),lightDevices:l,registryHass:this._fullRegistryHass,reducedMotion:this._reducedMotion}):null,u=o?Wo(this._planHass,o,l):[],p=o?jo(this._planHass,o,u):null,_=t.valueBadgeTouched?t.valueBadgeEnabled:!!d?.valueBadge,g=t.valueBadgeTouched?t.valueBadgeSource:d?.valueBadge?.source||t.valueBadgeSource,m=t.valueBadgeTouched?t.valueBadgePosition:d?.valueBadge?.position||t.valueBadgePosition,f=Ao(g),v=!!g&&!u.some(t=>t.key===f),y=u.find(t=>t.key===f),b=d?.valueSource?d.valueSource.attribute?`attr:${d.valueSource.eid}:${d.valueSource.attribute}`:`state:${d.valueSource.eid}`:"",w=this._markerAutoHasSpatialSource(t),k=!!o&&function(t,e){return io(t,e).some(t=>!!t.eid)}(this._planHass,{...o}),x=function(t,e,i,s){const n="always"===t||"auto"===t&&e,o=n&&!i;return{sourceExists:n,fromSourceEnabled:n&&i,manualEnabled:n,radiusEnabled:n,passive:o,effectiveMode:o&&"auto"===s?"fixed":s}}(t.lightRole,w,k,t.glowMode),$=!x.sourceExists,S=!x.fromSourceEnabled,M=x.passive,C=x.effectiveMode,D="never"===t.lightRole?this._t("marker.glow_disabled_never"):"auto"!==t.lightRole||w?M?this._t("marker.glow_passive_hint"):this._t("marker.glow_disabled_no_entity"):this._t("marker.glow_disabled_auto"),T=o?to(o):[],P=o&&eo(o)||"",R=!!t.lightEntity&&!T.includes(t.lightEntity),I=o?Qh(o):[],A=!!t.toggleEntity&&!I.includes(t.toggleEntity),F="toggle"===r?this._toggleIntentForDialog({...t,toggleEntity:"",toggleEntityTouched:!0}):null,E=F?[...F.targets,...F.skippedTargets].map(t=>t.entityId||("ref"in t?t.ref:"")).filter(Boolean).join(", "):"",z=(()=>{if(e)return null;const s=i.find(e=>e.value===t.binding);if(s)return s.label;const[n,o]=t.binding.split(":");return"device"===n?this._fullRegistryHass.devices[o]?.name_by_user||this._fullRegistryHass.devices[o]?.name||o:this._fullRegistryHass.entities[o]?.name||this.hass.states[o]?.attributes?.friendly_name||o})();return W`this._markerDialog=null}>
${"ha_disabled"===s?.kind?W`
${this._t(`marker.ha_disabled_${s.reason}`)}
${n?W`this._openBindingInHa(t.binding)}>
${this._t("btn.open_in_ha")}
`:G}
`:"unverified"===s?.kind&&t.binding?W`
${this._t("marker.ha_registry_limited")}
`:G}
${this._t("marker.name_label")}
this._markerDialog={...t,name:e.target.value}} />
${this._t("marker.binding_label")}
{const e={...t,bindingMode:"virtual",binding:"virtual",bindingOpen:!1,controls:Zn("virtual",t.controls),autoIcon:this._autoIconForBinding("virtual")};this._markerDialog=this._announceToggleDraft({...e,...this._valueBadgeForBinding(e,"virtual")})}} />
${this._t("marker.virtual_option")}
this._markerDialog=this._announceToggleDraft({...t,bindingMode:"ha",binding:"virtual"===t.binding?"":t.binding,bindingOpen:"virtual"===t.binding||!t.binding})} />
${this._t("marker.from_ha_option")}
${this._boolInput(t.showEntities,e=>this._markerDialog={...t,showEntities:e},"ha"!==t.bindingMode)}
${this._t("marker.show_entities")}
${"ha"===t.bindingMode?W`
this._markerDialog={...t,bindingOpen:!t.bindingOpen}}>
${z?W`${z} ${t.binding}${"ha_disabled"===s?.kind?` · ${this._t("marker.binding_disabled")}`:""} `:W`${this._t("marker.pick_ph")} `}
${t.bindingOpen?W`
this._markerDialog={...t,bindingFilter:e.target.value}} />
${i.map(e=>W`
{const i={...t,binding:e.value,bindingOpen:!1,controls:Zn(e.value,t.controls,this._bindingEntities(e.value)),autoIcon:this._autoIconForBinding(e.value)};this._markerDialog=this._announceToggleDraft({...i,...this._valueBadgeForBinding(i,e.value)})}}>
${e.label} ${e.sub}
`)}
${i.length?G:W`
${this._t("marker.nothing_found")}
`}
`:G}`:G}
${this._t("marker.room_label")}${e?"":this._t("marker.room_override")}
this._markerDialog={...t,room:e.target.value}}>
${e?this._t("marker.room_choose"):this._t("marker.room_auto")}
${this._allRoomsFlat().map(e=>W`${e.label} `)}
${this._renderVacSection(t)}
${this._t("marker.tap_label")}
{const i={...t,tapAction:e.target.value,tapActionTouched:!0};this._markerDialog=this._announceToggleDraft(i)}}>
${qi.map(t=>[t,"tap."+t.replace("-","_")]).map(([t,e])=>W`
${this._t(e)}
`)}
${"toggle"===r&&(I.length>1||A)?W`
${this._t("marker.toggle_entity_label")}
${this._help("marker.toggle_entity.help")}
{const i={...t,toggleEntity:e.target.value,toggleEntityTouched:!0};this._markerDialog=this._announceToggleDraft(i)}}>
${this._t("marker.toggle_entity_auto",{entity:E||this._t("marker.toggle_entity_none")})}
${I.map(e=>W`
${this.hass.states[e]?.attributes?.friendly_name||this._fullRegistryHass.entities[e]?.name||e} · ${e}
`)}
${A?W`
${this._t("marker.toggle_entity_missing",{entity:t.toggleEntity,fallback:E||this._t("marker.toggle_entity_none")})}
`:G}
`:G}
${"toggle"===r?W`
${t.tapHintAnnouncement}
`:G}
${"run"===r?(()=>{const e=t.runFilter.trim().toLowerCase(),i=this._runCandidates().filter(t=>!e||t.label.toLowerCase().includes(e)||t.value.includes(e)),s=t.tapTarget?this._runCandidates().find(e=>e.value===t.tapTarget):null;return W`
${this._t("marker.run_target_label")}
${t.tapTarget&&!s?W`
${this._t("marker.run_target_gone",{id:t.tapTarget})}
`:G}
{t.target.select()}}
@input=${e=>this._markerDialog={...t,runFilter:e.target.value,tapTarget:""}} />
${s?G:W`
${i.slice(0,40).map(e=>W`
this._markerDialog={...t,tapTarget:e.value,runFilter:""}}>
${e.label} ${e.sub}
`)}
${i.length?G:W`
${this._t("marker.nothing_found")}
`}
`}`})():G}
${"run"===r||"toggle"===r?W`
${this._boolInput(t.tapConfirm,e=>this._markerDialog={...t,tapConfirm:e})}
${this._t("marker.tap_confirm")}
`:G}
${this._t("marker.controls_label")}
${this._t("marker.controls_hint")}
${t.controls.length?W`
${t.controls.map(e=>{const i=this._controlRefInfo(e);return W`
${i.label}
this._markerDialog=this._announceToggleDraft({...t,controls:t.controls.filter(t=>t!==e)})}>
`})}
`:G}
this._markerDialog={...t,controlsFilter:e.target.value}} />
${t.controlsFilter.trim()?W`
${this._controlCandidates(t).map(e=>W`this._addControlRef(t,e.value)}>
${e.label}
${e.sub}
`)}
`:G}
${this._bindingHasClimate(t.binding)?W`
${this._boolInput(t.useClimateTemp,e=>this._markerDialog={...t,useClimateTemp:e})}
${this._t("marker.use_climate_temp")}
`:G}
${this._t("marker.light_role_label")} ${this._help("marker.light_role.help")}
this._setMarkerLightRole("auto")} />
${this._t(w?"marker.light_role_auto_yes":"marker.light_role_auto_no")}
this._setMarkerLightRole("always")} />
${this._t("marker.light_role_always")}
this._setMarkerLightRole("never")} />
${this._t("marker.light_role_never")}
${"always"===t.lightRole&&(T.length>1||R)?W`
${this._t("marker.light_entity_label")}
${this._help("marker.light_entity.help")}
this._markerDialog={...t,lightEntity:e.target.value,lightEntityTouched:!0}}>
${this._t("marker.light_entity_auto",{entity:P||this._t("marker.light_entity_none")})}
${T.map(e=>W`
${this.hass.states[e]?.attributes?.friendly_name||this._fullRegistryHass.entities[e]?.name||e} · ${e}
`)}
${R?W`
${this._t("marker.light_entity_missing",{entity:t.lightEntity,fallback:P||"—"})}
`:G}
`:G}
${this._t("marker.glow_color_label")} ${this._help("marker.glow_mode.help")}
this._setMarkerGlowMode("auto")} />
${this._t("marker.glow_mode_auto")}
this._setMarkerGlowMode("color")} />
${this._t("marker.glow_mode_color")}
this._setMarkerGlowMode("fixed")} />
${this._t("marker.glow_mode_fixed")}
${"auto"!==C?W`
{this._markerDialog={...t,glowMode:C,glowColor:e.detail.color,glowColorDrafted:!0,glowTouched:!0}}}>
${"fixed"===C?W`
${this._t("marker.glow_brightness")}
${this._rangeInput(1,100,1,t.glowBrightness,e=>{this._markerDialog={...t,glowMode:C,glowBrightness:e,glowBrightnessDrafted:!0,glowTouched:!0}},$,this._t("marker.glow_brightness"))}
${Math.round(t.glowBrightness)}% `:G}
`:G}
${$||M?W`
${D}
`:G}
${this._t("marker.icon_label")}
${customElements.get("ha-icon-picker")?W`
{const i=e.detail.value||"";(t.icon||i!==t.autoIcon)&&(this._markerDialog={...t,icon:i})}}> `:W`
this._markerDialog={...t,icon:e.target.value}} />`}
${!t.icon&&t.autoIcon?W`
${this._t("marker.icon_auto",{icon:t.autoIcon})}
this._markerDialog={...t,icon:t.autoIcon}}>
${this._t("marker.icon_pin_auto")}
`:G}
${this._t("marker.display_label")}
this._markerDialog={...t,display:Bi(e.target.value)}}>
${Li.map(e=>W`
${this._t(dg[e])}
`)}
${this._t(ug[t.display])}
${"static_icon"===t.display&&this._bindingHasAlarm(t.binding)?W`
${this._t("marker.static_alarm_warning")}
`:G}
${this._t("marker.value_badge_title")} ${this._help("marker.value_badge.help")}
${this._boolInput(_,e=>{const i=g||p;this._markerDialog={...t,valueBadgeEnabled:e&&!!i,valueBadgeSource:i,valueBadgeTouched:!0}},"static_icon"===t.display||!u.length&&!t.valueBadgeSource)}
${this._t("marker.value_badge_enabled")}
${"static_icon"===t.display?W`
${this._t("marker.value_badge_static")}
`:u.length||t.valueBadgeSource?G:W`
${this._t("marker.value_badge_empty")}
`}
${_?W`
${this._t("marker.value_badge_source")}
${this._help("marker.value_badge_source.help")}
this._markerDialog={...t,valueBadgeSource:Fo(e.target.value),valueBadgeEnabled:!0,valueBadgeTouched:!0}}>
${v?W`
${this._t("marker.value_badge_missing")}
`:G}
${u.map(t=>W`
${this._valueBadgeCandidateLabel(t)} · ${t.value}
`)}
${y?W`${y.technical}
`:G}
${v?W`
${this._t("marker.value_badge_missing_hint")}
`:G}
${"value"===t.display&&f===b?W`
${this._t("marker.value_badge_duplicate")}
`:G}
${this._t("marker.value_badge_position")}
${this._help("marker.value_badge_position.help")}
this._markerDialog={...t,valueBadgeEnabled:_,valueBadgeSource:g,valueBadgePosition:e.target.value,valueBadgeTouched:!0}}>
${["right","bottom","left","top"].map(t=>W`
${this._t(`marker.value_badge_${t}`)}
`)}
`:G}
${d?W`
`:W`
${this._t("marker.preview.select_source")}
`}
${"icon_ripple"===t.display?W`
{this._markerDialog={...t,rippleColor:e.detail.color}}}>
${this._t("marker.ripple_size")}
${this._rangeInput(1,8,.5,t.rippleSize,e=>this._markerDialog={...t,rippleSize:e})}
×${t.rippleSize}
${this._t("marker.activity_alarm_note")}
`:G}
${this._t("marker.size_label")}
${this._rangeInput(.5,3,.1,t.size,e=>this._markerDialog={...t,size:e})}
×${t.size.toFixed(1)}
${this._t("marker.angle_label")}
${""}
${this._rangeInput(0,355,5,t.angle,e=>this._markerDialog={...t,angle:e})}
${t.angle}°
${this._t("marker.model_label")}
this._markerDialog={...t,model:e.target.value}} />
${this._t("marker.link_label")}
this._markerDialog={...t,link:e.target.value}} />
${this._t("marker.desc_label")}
${this._t("marker.manuals_label")}
`}_renderSpaceDialog(){const t=this._spaceDialog,e=this._importTotal>0&&"create"===t.mode?this._t("import.progress",{i:this._importTotal-this._importQueue.length,n:this._importTotal}):"",i=()=>{this._spaceDialog=null,this._importQueue=[],this._importTotal=0};return W`
${this._t("space.title_label")}
this._spaceDialog={...t,title:e.target.value}} />
${this._t("space.plan_label")}
this._spaceDialog=vh(t,"file")} />
${this._t("space.source_file")}
${"file"===t.source?W`
${t.planFile?W`
${t.planFile.name} `:t.planUrl?W`
`:W`
${this._t("space.no_plan")} `}
t.currentTarget.nextElementSibling?.click()}>
${t.planUrl||t.planFile?this._t("btn.replace"):this._t("btn.upload")}
this._pickPlanFile(t)} />
${this._t("space.pick_saved")}
${t.pickSaved?this._renderServerPlans(t):G}`:G}
this._spaceDialog=vh(t,"draw")} />
${this._t("space.source_draw")}
${this._t("space.scale_label")}
{const i=mg(e.target.value);this._spaceDialog={...t,cellCm:null!=i&&i>0?Math.max(.1,Math.min(_g,i)):t.cellCm}}} />
${this._t("space.scale_unit")}
${this._t("space.display_section")}
${this._boolInput(t.showBorders,e=>this._spaceDialog=yh(t,"showBorders",e))}
${this._t("space.show_borders")}
${this._boolInput(t.showNames,e=>this._spaceDialog=yh(t,"showNames",e))}
${this._t("space.show_names")}
${this._boolInput(t.showLqi,e=>this._spaceDialog={...t,showLqi:e})}
${this._t("space.show_lqi")}
${""}
${this._boolInput(t.hideDecor,e=>this._spaceDialog={...t,hideDecor:e})}
${this._t("space.hide_decor")}
${this._t("space.hide_decor_tip")}
${this._boolInput(t.hideOpenings,e=>this._spaceDialog={...t,hideOpenings:e})}
${this._t("space.hide_openings")}
${this._t("space.hide_openings_tip")}
${this._t("space.roomcard_section")}
${[["labelTemp","space.label_temp"],["labelHum","space.label_hum"],["labelLqi","space.label_lqi"],["labelLight","space.label_light"]].map(([e,i])=>W`
${this._boolInput(t[e],i=>this._spaceDialog={...t,[e]:i})}
${this._t(i)}
`)}
${this._t("space.card_font")}
${this._rangeInput(50,300,5,Math.round(100*t.cardFontScale),e=>this._spaceDialog={...t,cardFontScale:e/100})}
${Math.round(100*t.cardFontScale)}%
${this._renderCardPreview(t.cardFontScale,1,1)}
{this._spaceDialog={...t,roomColor:e.detail.color,roomOpacity:e.detail.opacity}}}>
${this._t("space.bg_mode")}
{const i=e.target.value;this._spaceDialog={...t,bgMode:"static"===i||"daynight"===i?i:null}}}>
${this._t("space.sun_inherit")}
${this._t("gs.bg_static")}
${this._t("gs.bg_daynight")}
${"static"===(t.bgMode??Qr(this._settings,{}))?W`
{this._spaceDialog={...t,bgColor:e.detail.color}}}>
${t.bgColor?W`this._spaceDialog={...t,bgColor:null}}>
${this._t("space.bg_inherit")} `:W`${this._t("space.bg_inherited")} `}
`:G}
${this._t("space.north")}
{const i=e.target.value.trim(),s=""===i?null:Math.round(Number(i));this._spaceDialog={...t,northDeg:null!==s&&Number.isFinite(s)?Math.min(359,Math.max(0,s)):null}}} />
${null===t.northDeg?this._t("space.north_inherited",{v:null===Zr(this._settings,{})?"—":String(Zr(this._settings,{}))+"°"}):"°"}
${this._t("space.sun_rays")}
{const i=e.target.value;this._spaceDialog={...t,sunRays:""===i?null:"1"===i}}}>
${this._t("space.sun_inherit")}
${this._t("space.sun_on")}
${this._t("space.sun_off")}
${this._t("space.fill_label")}
${Wi.map(t=>[t,"fill."+t]).map(([e,i])=>W`
this._spaceDialog={...t,fillMode:e}} />
${this._t(i)}
${"temp"===e&&"temp"===t.fillMode?W`
{const i=mg(e.target.value);null!=i&&(this._spaceDialog={...t,tempMin:i})}} />
–
{const i=mg(e.target.value);null!=i&&(this._spaceDialog={...t,tempMax:i})}} />
°C
`:G}
${"custom"===e&&"custom"===t.fillMode?W`
${this._t("space.custom_fill")}
{this._spaceDialog={...t,customFill:{c:e.detail.color,a:e.detail.opacity}}}}>
${t.customFill?W`this._spaceDialog={...t,customFill:null}}>
${this._t("btn.reset")} `:G}
`:G}`)}
${this._boolInput(t.glowEnabled,e=>{this._spaceDialog={...t,glowEnabled:e}})}
${this._t("space.glow_enabled")}
`}_renderMergeDialog(){const t=this._mergeDialog,e=this._spaceModel()?.rooms||[],i=(i,s)=>{const n=e.find(t=>t.id===i),o=n?.area?this.hass.areas[n.area]?.name:null;return W`
this._mergeDialog={...t,pick:s}} />
${n?.name||""} · ${o||this._t("merge.no_area")}
`};return W`this._mergeDialog=null}>
${this._t("merge.hint")}
${this._t("merge.keep")}
${i(t.aId,"a")}
${i(t.bId,"b")}
this._mergeDialog=null}>${this._t("btn.cancel")}
${this._t("btn.save")}
`}_renderCardPreview(t,e,i){const s=18*t;return W`
${this._t("preview.room_name")}
22.4° ·
45% ·
${this._t("roomcard.light_partial",{on:1,total:3})}
`}_renderRoomSource(t){const e="temp"===t?this._roomTempSrc:this._roomHumSrc,i=e=>{"temp"===t?this._roomTempSrc=e:this._roomHumSrc=e,this.requestUpdate()},s=this._roomSrcOpen===t;return W`
${this._t("temp"===t?"room.temp_src_label":"room.hum_src_label")}
{i(""),this._roomSrcOpen=null}} />
${this._t("room.src_average")}
{this._roomSrcOpen=t,this._roomSrcFilter="",this.requestUpdate()}} />
${this._t("room.src_pick")}
${e||s?W`{this._roomSrcOpen=s?null:t,this._roomSrcFilter=""}}>
${e?W`${this._roomSrcLabel(e)} ${e} `:W`${this._t("room.src_ph")} `}
${s?W`
{this._roomSrcFilter=t.target.value,this.requestUpdate()}} />
${this._roomSrcCandidates().map(t=>W`
{i(t.value),this._roomSrcOpen=null}}>
${t.label} ${t.sub}
`)}
`:G}`:G}`}_renderRoomDialog(){const t=!!this._roomEditId,e=t?null:this._wallFaceBatch,i=e&&e.candidates.length>1?this._t("room.queue_progress",{current:e.index+1,total:e.candidates.length}):"",s=!!this._areaSel||!!this._nameSel.trim(),n=cs(this._curSpaceCfg),o=this._roomFill||n.fill,r=this._roomCustomFill||n.customFill,a=[...this._freeAreas];if(t&&this._areaSel&&!a.some(t=>t.area_id===this._areaSel)){const t=this.hass.areas[this._areaSel];t&&a.unshift(t)}return W`
${i?W`
${i}
`:G}
${this._t("room.name_label")}
this._nameSel=t.target.value} />
${this._t("room.area_label")}
{this._areaSel=t.target.value,!this._nameSel&&this._areaSel&&(this._nameSel=this.hass.areas[this._areaSel]?.name||""),this.requestUpdate()}}>
${this._t("room.no_area_option")}
${a.map(t=>W`${t.name} `)}
${this._t("room.settings_section")}
${this._t("room.fill_label")}
${[["","fill.inherit"],...ji.map(t=>[t,"fill."+t])].map(([t,e])=>W`
{this._roomFill=t,this.requestUpdate()}} />
${this._t(e)}
`)}
${"custom"===o?W`
${this._roomCustomFill?this._t("room.custom_fill_own"):this._t("room.custom_fill_space")}
{this._roomCustomFill={c:t.detail.color,a:t.detail.opacity}}}>
${this._roomCustomFill?W`{this._roomCustomFill=null}}>${this._t("btn.reset")} `:G}
`:G}
${this._renderRoomSource("temp")}
${this._renderRoomSource("hum")}
${this._t("room.sizes_section")}
${this._t("room.name_scale")}
${this._rangeInput(50,300,5,Math.round(100*this._roomNameScale),t=>{this._roomNameScale=t/100,this.requestUpdate()})}
${Math.round(100*this._roomNameScale)}%
${this._t("room.label_scale")}
${this._rangeInput(50,300,5,Math.round(100*this._roomLabelScale),t=>{this._roomLabelScale=t/100,this.requestUpdate()})}
${Math.round(100*this._roomLabelScale)}%
${this._renderCardPreview(cs(this._curSpaceCfg).cardFontScale,this._roomNameScale,this._roomLabelScale)}
`}}Hg.properties={_tabDrag:{state:!0},_hdrH:{state:!0},_booting:{state:!0},_bootFading:{state:!0},_bootSoft:{state:!0},_continuityEpoch:{state:!0},_tapConfirm:{state:!0},hass:{attribute:!1},_config:{state:!0},_space:{state:!0},_layout:{state:!0},_devices:{state:!0},_tip:{state:!0},_hoverRoom:{state:!0},_selId:{state:!0},_toast:{state:!0},_serverCfg:{state:!0},_mode:{state:!0},_tool:{state:!0},_wallDialog:{state:!0},_drawWallField:{state:!0},_activeDraftId:{state:!0},_physicalSel:{state:!0},_physicalDialog:{state:!0},_partitionDeleteDialog:{state:!0},_roomDeleteDialog:{state:!0},_physicalDrag:{state:!0},_physicalRotate:{state:!0},_duplicateColumnId:{state:!0},_rszSel:{state:!0},_rszLive:{state:!0},_opMeasure:{state:!0},_path:{state:!0},_cursorPt:{state:!0},_mergeSel:{state:!0},_openingPreset:{state:!0},_openingDialog:{state:!0},_openingInfo:{state:!0},_mergeDialog:{state:!0},_openWallAnchor:{state:!0},_splitSel:{state:!0},_decorTool:{state:!0},_decorStyle:{state:!0},_decorDraft:{state:!0},_decorSel:{state:!0},_decorEraseConfirm:{state:!0},_decorTextDialog:{state:!0},_decorShapeDialog:{state:!0},_backdropDialog:{state:!0},_furnPalette:{state:!0},_bdDrag:{state:!0},_dtBox:{state:!0},_dtDrag:{state:!0},_kioskDialog:{state:!0},_vacFit:{state:!0},_vacAllCamerasFor:{state:!0},_vacCalConfirm:{state:!0},_kioskDots:{state:!0},_areaSel:{state:!0},_nameSel:{state:!0},_roomDialog:{state:!0},_roomEditId:{state:!0},_roomFill:{state:!0},_roomCustomFill:{state:!0},_roomTempSrc:{state:!0},_roomHumSrc:{state:!0},_roomSrcOpen:{state:!0},_roomSrcFilter:{state:!0},_roomNameScale:{state:!0},_roomLabelScale:{state:!0},_spaceDialog:{state:!0},_infoCard:{state:!0},_rulesDialog:{state:!0},_settingsDialog:{state:!0},_alignDialog:{state:!0},_backupExportDialog:{state:!0},_backupImportDialog:{state:!0},_importDialog:{state:!0},_markerDialog:{state:!0},_zoom:{state:!0},_view:{state:!0}},Hg.ZOOM_MAX=8,Hg.ZOOM_MIN=1/3,Hg.styles=[Kt,fp],customElements.get("houseplan-card")||customElements.define("houseplan-card",Hg),window.customCards=window.customCards||[],window.customCards.find(t=>"houseplan-card"===t.type)||window.customCards.push({type:"houseplan-card",name:"House Plan Card",description:"Interactive house plan: spaces, rooms and devices with live states and drag layout."}),console.info(`%c HOUSEPLAN-CARD %c v${hg} `,"background:#3ea6ff;color:#04121f;font-weight:700","");