/*! maintenance_supporter frontend 2.99.0 */ import{a as it,b as nt,c as at,d as ot,e as lt,f as dt,g as ct,h as pt,i as ht,j as ut}from"./chunk-SZ5OZQBM.js";import"./chunk-QZSR3CS5.js";import{a as Ce,b as le,c as kt,d as V,e as wt}from"./chunk-GVWULYYT.js";import{c as $t,d as xt,e as ge,f as ve,g as fe,h as Ue,i as Y,j as oe,k as te}from"./chunk-47YHJMQQ.js";import{A as bt,B as A,a as w,b as l,c as ne,d as h,e as T,f as v,g as p,h as me,j as P,k as _t,l as mt,m as E,n as z,o as ae,p as De,q as U,r as Ie,s as Te,t as gt,u as Se,v as ze,w as vt,x as ft,y as yt,z as Ae}from"./chunk-KWXSFMBP.js";import{a as d,b as Xe,d as ke,g as s,h as et,i as tt,k as Fe,l as we,n as Ee,o as st,p as ee,q as rt}from"./chunk-P2ZDMNV3.js";var C=class extends T{constructor(){super(...arguments);this.label="";this.value="";this.placeholder="";this.type="text";this.required=!1;this.disabled=!1;this.multiline=!1;this.rows=3}_onInput(e){let i=e.target.value;this.value=i,this.dispatchEvent(new CustomEvent("input",{bubbles:!0,composed:!0,detail:{value:i}}))}render(){return l` `}};C.styles=w` :host { display: block; } .field { display: flex; flex-direction: column; gap: 4px; } .label { font-size: 12px; color: var(--secondary-text-color, #888); font-weight: 500; } .req { color: var(--error-color, #f44336); margin-left: 2px; } input { padding: 8px 10px; font-size: 14px; background: var(--secondary-background-color, rgba(0,0,0,0.06)); color: var(--primary-text-color); border: 1px solid var(--divider-color, rgba(255,255,255,0.12)); border-radius: 6px; font-family: inherit; width: 100%; box-sizing: border-box; outline: none; } input:focus { border-color: var(--primary-color); } input:disabled { opacity: 0.5; cursor: not-allowed; } textarea { padding: 8px 10px; font-size: 14px; background: var(--secondary-background-color, rgba(0,0,0,0.06)); color: var(--primary-text-color); border: 1px solid var(--divider-color, rgba(255,255,255,0.12)); border-radius: 6px; font-family: inherit; width: 100%; box-sizing: border-box; outline: none; resize: vertical; } textarea:focus { border-color: var(--primary-color); } textarea:disabled { opacity: 0.5; cursor: not-allowed; } .helper { font-size: 11px; color: var(--secondary-text-color); font-style: italic; } `,d([v()],C.prototype,"label",2),d([v()],C.prototype,"value",2),d([v()],C.prototype,"placeholder",2),d([v()],C.prototype,"type",2),d([v({type:Boolean})],C.prototype,"required",2),d([v({type:Boolean})],C.prototype,"disabled",2),d([v()],C.prototype,"step",2),d([v()],C.prototype,"min",2),d([v()],C.prototype,"max",2),d([v()],C.prototype,"pattern",2),d([v()],C.prototype,"helper",2),d([v({type:Boolean})],C.prototype,"multiline",2),d([v({type:Number})],C.prototype,"rows",2);customElements.get("ms-textfield")||customElements.define("ms-textfield",C);var k=class extends T{constructor(){super(...arguments);this.objects=[];this.placesEnabled=!1;this._open=!1;this._loading=!1;this._error="";this._name="";this._manufacturer="";this._model="";this._serialNumber="";this._areaId="";this._installationDate="";this._warrantyExpiry="";this._documentationUrl="";this._notes="";this._haDeviceId="";this._parentEntryId="";this._place="";this._remindOnSite=!1;this._entryId=null;this._replacing=!1;this._oldDeviceId="";this._replaceDevice="keep"}get _lang(){return P(this.hass)}openCreate(){this._entryId=null,this._name="",this._manufacturer="",this._model="",this._serialNumber="",this._areaId="",this._installationDate="",this._warrantyExpiry="",this._documentationUrl="",this._notes="",this._haDeviceId="",this._parentEntryId="",this._place="",this._remindOnSite=!1,this._replacing=!1,this._error="",this._open=!0}openReplace(e,i){this._entryId=e,this._replacing=!0,this._name=i.name||"",this._oldDeviceId=i.ha_device_id||"",this._haDeviceId="",this._replaceDevice="keep",this._error="",this._open=!0}openEdit(e,i){this._entryId=e,this._name=i.name||"",this._manufacturer=i.manufacturer||"",this._model=i.model||"",this._serialNumber=i.serial_number||"",this._areaId=i.area_id||"",this._installationDate=i.installation_date||"",this._warrantyExpiry=i.warranty_expiry||"",this._documentationUrl=i.documentation_url||"",this._notes=i.notes||"",this._haDeviceId=i.ha_device_id||"",this._parentEntryId=i.parent_entry_id||"",this._place=i.place||"",this._remindOnSite=!!i.remind_on_site,this._replacing=!1,this._error="",this._open=!0}async _replace(){if(this._loading||!this._entryId)return;let e={type:"maintenance_supporter/object/replace",entry_id:this._entryId,name:this._name.trim()||null};this._oldDeviceId?(this._replaceDevice==="other"&&(e.ha_device_id=this._haDeviceId),this._replaceDevice==="none"&&(e.ha_device_id=null)):this._haDeviceId&&(e.ha_device_id=this._haDeviceId);let i=await A(this,e,{busy:t=>{this._loading=t},fallbackKey:"save_error",onError:t=>{this._error=t}});i!==void 0&&(this._open=!1,this.dispatchEvent(new CustomEvent("object-replaced",{detail:{entry_id:i?.entry_id,device_swap:i?.device_swap}})))}_deviceName(e){let t=this.hass?.devices?.[e];return t?.name_by_user||t?.name||e}_deviceSelector(e){return l`e} @value-changed=${i=>this._haDeviceId=i.detail.value?.device||""} >`}_renderReplace(){let e=this._lang,i=(n,o)=>l``,t=this._replaceDevice==="other"&&!this._haDeviceId;return l`
${s("replace_object",e)}
${this._error?l`
${this._error}
`:h}
${s("replace_object_prompt",e)}
this._name=n.target.value} > ${this._oldDeviceId?l`
${s("replace_device_heading",e)}
${i("keep",s("replace_device_keep",e).replace("{device}",this._deviceName(this._oldDeviceId)))} ${this._replaceDevice==="keep"?l`
${s("replace_device_keep_hint",e)}
`:h} ${i("other",s("replace_device_other",e))} ${this._replaceDevice==="other"?l`${this._deviceSelector(s("replace_device_pick",e))}
${s("replace_device_other_hint",e)}
`:h} ${i("none",s("replace_device_none",e))}
`:this._deviceSelector(s("link_device_optional",e))}
${s("cancel",e)} ${this._loading?s("saving",e):s("replace_object",e)}
`}_renderPlace(e){let i=!!this._place&&!this.hass?.states?.[this._place];return l` s("place_optional",e)} @value-changed=${t=>{this._place=t.detail.value?.place||"",this._place||(this._remindOnSite=!1)}} > ${i?l`
${s("place_missing",e)}
`:h} ${this._place?l`
${s("remind_on_site_hint",e)}
`:h} `}async _save(){if(this._loading||!this._name.trim())return;this._error="";let e={name:this._name,manufacturer:this._manufacturer||null,model:this._model||null,serial_number:this._serialNumber||null,area_id:this._areaId||null,installation_date:this._installationDate||null,warranty_expiry:this._warrantyExpiry||null,documentation_url:this._documentationUrl.trim()||null,notes:this._notes.trim()||null,ha_device_id:this._haDeviceId||null,parent_entry_id:this._parentEntryId||null,...this.placesEnabled?{place:this._place||null,remind_on_site:!!this._place&&this._remindOnSite}:{}},i=await A(this,this._entryId?{type:"maintenance_supporter/object/update",entry_id:this._entryId,...e}:{type:"maintenance_supporter/object/create",...e},{busy:t=>{this._loading=t},fallbackKey:"save_error",onError:t=>{this._error=t}});i!==void 0&&(this._open=!1,this.dispatchEvent(new CustomEvent("object-saved",{detail:{device_swap:i?.device_swap}})))}_parentChoices(){return(this.objects||[]).filter(e=>e.entry_id!==this._entryId)}_close(){this._open=!1}render(){if(!this._open)return l``;if(this._replacing)return this._renderReplace();let e=this._lang,i=this._entryId?s("edit_object",e):s("new_object",e);return l`
${i}
${this._error?l`
${this._error}
`:h} this._name=t.target.value} > this._manufacturer=t.target.value} > this._model=t.target.value} > this._serialNumber=t.target.value} > this._documentationUrl=t.target.value} > this._areaId=t.detail.value||""} > ${this.placesEnabled?this._renderPlace(e):h} this._installationDate=t.detail.value} > this._warrantyExpiry=t.detail.value} > s("link_device_optional",e)} @value-changed=${t=>this._haDeviceId=t.detail.value?.device||""} > ${this._parentChoices().length?l``:h}
${s("cancel",this._lang)} ${this._loading?s("saving",this._lang):s("save",this._lang)}
`}};k.styles=w` .place-on-site { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--primary-text-color); } .place-on-site.disabled { color: var(--disabled-text-color, var(--secondary-text-color)); } .place-hint, .place-missing { font-size: 12px; color: var(--secondary-text-color); margin-top: -4px; } .place-missing { color: var(--warning-color, #c77700); } .dialog-title { font-size: 18px; font-weight: 500; padding-bottom: 12px; } .content { display: flex; flex-direction: column; gap: 16px; min-width: 300px; } .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; } ms-textfield { display: block; } .textarea-field { display: flex; flex-direction: column; gap: 4px; } .textarea-label { font-size: 12px; color: var(--secondary-text-color, #888); font-weight: 500; } .textarea-field textarea { padding: 8px 10px; font-size: 14px; font-family: inherit; background: var(--secondary-background-color, rgba(0,0,0,0.06)); color: var(--primary-text-color); border: 1px solid var(--divider-color); border-radius: 6px; resize: vertical; } .textarea-field textarea:focus { outline: none; border-color: var(--primary-color); } .md-hint { font-size: 11px; color: var(--secondary-text-color); font-style: italic; } .parent-select { padding: 8px 10px; font-size: 14px; font-family: inherit; background: var(--secondary-background-color, rgba(0,0,0,0.06)); color: var(--primary-text-color); border: 1px solid var(--divider-color); border-radius: 6px; } .error { color: var(--error-color, #f44336); font-size: 13px; } .hint { font-size: 13px; color: var(--secondary-text-color); line-height: 1.4; } .radio-group { display: flex; flex-direction: column; gap: 8px; } .radio-row { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; } .radio-row input { margin: 0; } `,d([v({attribute:!1})],k.prototype,"hass",2),d([v({attribute:!1})],k.prototype,"objects",2),d([v({type:Boolean})],k.prototype,"placesEnabled",2),d([p()],k.prototype,"_open",2),d([p()],k.prototype,"_loading",2),d([p()],k.prototype,"_error",2),d([p()],k.prototype,"_name",2),d([p()],k.prototype,"_manufacturer",2),d([p()],k.prototype,"_model",2),d([p()],k.prototype,"_serialNumber",2),d([p()],k.prototype,"_areaId",2),d([p()],k.prototype,"_installationDate",2),d([p()],k.prototype,"_warrantyExpiry",2),d([p()],k.prototype,"_documentationUrl",2),d([p()],k.prototype,"_notes",2),d([p()],k.prototype,"_haDeviceId",2),d([p()],k.prototype,"_parentEntryId",2),d([p()],k.prototype,"_place",2),d([p()],k.prototype,"_remindOnSite",2),d([p()],k.prototype,"_entryId",2),d([p()],k.prototype,"_replacing",2),d([p()],k.prototype,"_oldDeviceId",2),d([p()],k.prototype,"_replaceDevice",2);customElements.get("maintenance-object-dialog")||customElements.define("maintenance-object-dialog",k);var Et=["#c62828","#ad1457","#6a1b9a","#4527a0","#283593","#1565c0","#00838f","#2e7d32","#558b2f","#ef6c00","#6d4c41","#546e7a"];function Ei(r){let a=(r||"").split(/\s+/).filter(Boolean);return a.length===0?"?":a.length===1?a[0][0].toUpperCase():(a[0][0]+a[a.length-1][0]).toUpperCase()}function Ii(r){let a=0;for(let e of r)a=a*31+e.charCodeAt(0)>>>0;return Et[a%Et.length]}function It(r){return r?{id:r.id,name:r.name,initials:r.initials||Ei(r.name),color:r.color||Ii(r.id)}:null}var Pe=class{constructor(a){this.usersCache=null;this.cacheTimestamp=0;this.CACHE_TTL_MS=6e4;this.hass=a}updateHass(a){this.hass=a}async getUsers(a=!1){let e=Date.now();if(!a&&this.usersCache&&e-this.cacheTimestampi.id===a)?.name||null}getPerson(a){return It(this.getUser(a))}getUser(a){return!a||!this.usersCache?null:this.usersCache.find(e=>e.id===a)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(a){return a?a===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}};function j(r){return`${r.entry_id??""}\0${r.part_id}`}function Tt(r,a,e,i){let t=!!r.entry_id&&r.entry_id!==a,n=t?r.entry_id:a,o=e.find(g=>g.entry_id===n),c=(o?.parts||[]).find(g=>g.id===r.part_id)||null,u=t&&o?.object?.name||"",m=c?.name||s("shared_part_unknown",i);return{part:c,foreign:t,ownerName:u,label:u?`${m} (${u})`:m}}function St(r,a,e,i){let{part:t,label:n}=Tt(r,a,e,i),o=t&&t.stock!==null&&t.stock!==void 0?` (${ae(t.stock,t.unit,i)})`:"",c=t?.storage_location?` \u2014 ${t.storage_location}`:"";return`${E(r.quantity,i)}\xD7 ${n}${o}${c}`}function At(r,a,e,i){let n=(e.find(c=>c.entry_id===a)?.parts||[]).map(c=>({...c})),o=new Set(n.map(c=>j({part_id:c.id})));for(let c of r?.consumes_parts||[]){if(!c.entry_id||c.entry_id===a)continue;let u=j(c);if(o.has(u))continue;o.add(u);let{part:m,ownerName:g}=Tt(c,a,e,i);n.push({id:c.part_id,name:m?.name||s("shared_part_unknown",i),unit:m?.unit,stock:m?.stock??null,storage_location:m?.storage_location,entry_id:c.entry_id,owner_name:g})}return n}var je=["sensor","binary_sensor","number","input_number","input_boolean","switch","climate","vacuum","cover","fan","light","water_heater","humidifier","media_player","weather","air_quality","valve","lawn_mower","lock"],Ct=["sensor"],Pt=["temperature","humidity","pressure"];function de(r){let a=(r??"").trim();if(a==="")return null;let e=Number(a.replace(",","."));return!Number.isFinite(e)||e<0?null:Math.round(e)}var Be=["notes","cost","duration","photo","user"],ye={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"};var Ti={cleaning:"mdi:broom",inspection:"mdi:magnify",replacement:"mdi:swap-horizontal",calibration:"mdi:tune",service:"mdi:wrench",reading:"mdi:counter",custom:"mdi:wrench-clock"},Si="mdi:wrench-clock",Ve=r=>r&&Ti[r]||Si;function Re(r){return r?Array.isArray(r.entity_ids)&&r.entity_ids.length>0?[...r.entity_ids]:r.entity_id?[r.entity_id]:[]:[]}function Rt(r){if(!(!r||r.type==="compound"))return Re(r)[0]}var J=class extends T{constructor(){super(...arguments);this.value="";this.lang="en";this._credit=!1;this._amount=""}willUpdate(e){if(!e.has("value"))return;let i=(this.value??"").trim();if(i===this._signed())return;let t=parseFloat(i);if(i===""||Number.isNaN(t)){this._amount="",this._credit=!1;return}this._credit=t<0,this._amount=String(Math.abs(t))}_signed(){let e=this._amount.trim();return e===""?"":this._credit?`-${e}`:e}_emit(){this.value=this._signed(),this.dispatchEvent(new CustomEvent("value-changed",{detail:{value:this.value},bubbles:!0,composed:!0}))}_setCredit(e){this._credit!==e&&(this._credit=e,this._emit())}_onInput(e){let i=e.target.value;i.startsWith("-")&&(this._credit=!0),this._amount=i.replace(/^-+/,""),this._emit()}render(){let e=this.lang;return l`
${this._credit?l`
${s("cost_credit_hint",e)}
`:h} `}};J.styles=[Ae,w` :host { display: block; } .wrap { display: flex; gap: 8px; align-items: stretch; } .sign { display: inline-flex; flex: none; border: 1px solid var(--divider-color); border-radius: 6px; overflow: hidden; } .kind { font: inherit; font-size: 13px; padding: 0 10px; border: none; background: transparent; color: var(--secondary-text-color); cursor: pointer; } .kind.on { background: var(--primary-color); color: var(--text-primary-color, #fff); } .kind.credit.on { background: var(--success-color, #43a047); } .amount { flex: 1; min-width: 0; } .hint { margin-top: 4px; font-size: 12px; color: var(--secondary-text-color); } `],d([v()],J.prototype,"value",2),d([v()],J.prototype,"lang",2),d([p()],J.prototype,"_credit",2),d([p()],J.prototype,"_amount",2);customElements.get("ms-cost-input")||customElements.define("ms-cost-input",J);var Ai=["cleaning","inspection","replacement","calibration","service","reading","custom"],Ci=["low","normal","high"],Pi=["time_based","weekdays","nth_weekday","day_of_month","calendar","sensor_based","one_time","manual"],Le=["weekdays","nth_weekday","day_of_month","calendar"],Lt=["time_based","one_time",...Le],Nt=["threshold","counter","state_change","runtime","due_date"],qt=(r,a)=>s(r==="due_date"?"trigger_type_due_date":r,a),Ri=[...Nt,"compound"],W={alpha:"0.3",min:"7",max:"365"},ie=Y;function Ht(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",equals:"",notEquals:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",daysBefore:"0",carry:{}}}var Li=new Set(["entity_id","entity_ids","type","attribute","trigger_above","trigger_below","trigger_equals","trigger_not_equals","trigger_for_minutes","trigger_target_value","trigger_delta_mode","trigger_from_state","trigger_to_state","trigger_target_changes","trigger_runtime_hours","trigger_on_states","trigger_days_before"]);function Ot(r){return{type:r.type||"threshold",attribute:r.attribute||"",above:r.trigger_above?.toString()??"",below:r.trigger_below?.toString()??"",equals:r.trigger_equals?.toString()??"",notEquals:r.trigger_not_equals?.toString()??"",forMinutes:r.trigger_for_minutes?.toString()??"0",targetValue:r.trigger_target_value?.toString()??"",deltaMode:r.trigger_delta_mode||!1,fromState:r.trigger_from_state||"",toState:r.trigger_to_state||"",targetChanges:r.trigger_target_changes?.toString()??"",runtimeHours:r.trigger_runtime_hours?.toString()??"",onStates:(r.trigger_on_states||[]).join(", "),daysBefore:r.trigger_days_before?.toString()??"0"}}function Mt(r,a){a.attribute&&(r.attribute=a.attribute);let e=parseInt(a.forMinutes,10);if(a.type==="threshold"){let i=parseFloat(a.above);isNaN(i)||(r.trigger_above=i);let t=parseFloat(a.below);isNaN(t)||(r.trigger_below=t);let n=parseFloat(a.equals);isNaN(n)||(r.trigger_equals=n);let o=parseFloat(a.notEquals);isNaN(o)||(r.trigger_not_equals=o),isNaN(e)||(r.trigger_for_minutes=e)}else if(a.type==="counter"){let i=parseFloat(a.targetValue);isNaN(i)||(r.trigger_target_value=i),r.trigger_delta_mode=a.deltaMode}else if(a.type==="state_change"){a.fromState&&(r.trigger_from_state=a.fromState),a.toState&&(r.trigger_to_state=a.toState);let i=parseInt(a.targetChanges,10);isNaN(i)||(r.trigger_target_changes=i),isNaN(e)||(r.trigger_for_minutes=e)}else if(a.type==="runtime"){let i=parseFloat(a.runtimeHours);isNaN(i)||(r.trigger_runtime_hours=i);let t=(a.onStates||"").split(",").map(n=>n.trim()).filter(Boolean);t.length>0&&(r.trigger_on_states=t)}else if(a.type==="due_date"){let i=parseInt(a.daysBefore,10);r.trigger_days_before=isNaN(i)?0:i}}function qi(r){return{entityIds:Re(r).join(", "),...Ot(r),carry:Object.fromEntries(Object.entries(r).filter(([e])=>!Li.has(e)&&!e.startsWith("_")))}}function Hi(r){let a=r.entityIds.split(",").map(i=>i.trim()).filter(Boolean);if(a.length===0)return null;let e={...r.carry||{},entity_id:a[0],entity_ids:a,type:r.type};return Mt(e,r),e}function Ni(r){return Array.from({length:7},(a,e)=>ze(e,r,"short"))}function Oi(r){return Array.from({length:12},(a,e)=>vt(e,r,"short"))}var _=class _ extends T{constructor(){super(...arguments);this.checklistsEnabled=!1;this.scheduleTimeEnabled=!1;this.completionActionsEnabled=!1;this.adaptiveFeature=!1;this.seasonalFeature=!1;this.environmentalFeature=!1;this.defaultWarningDays=7;this.parts=[];this._foreignOwners=[];this._open=!1;this._entityPickerFallback=!1;this._pickerProbeStrikes=0;this._loading=!1;this._error="";this._warning="";this._entryId="";this._taskId=null;this._isFleetTask=!1;this._objectChoices=[];this._name="";this._type="custom";this._scheduleType="time_based";this._intervalDays="30";this._intervalUnit="days";this._dueDate="";this._warningDays="7";this._earliestCompletionDays="";this._intervalAnchor="completion";this._weekdays=[];this._nth="1";this._nthWeekday="5";this._domDay="1";this._domLastDay=!1;this._domBusiness=!1;this._calOffset="0";this._calendarEntity="";this._seasonMonths=[];this._endsMode="never";this._endsCount="";this._endsUntil="";this._schedulePreview=[];this._schedulePreviewEnded=!1;this._previewSeq=0;this._notes="";this._documentationUrl="";this._customIcon="";this._notifyIcon="";this._priority="normal";this._labels="";this._mirrorTodoEntities=[];this._enabled=!0;this._triggerEntityId="";this._triggerEntityIds=[];this._triggerEntityLogic="any";this._triggerAttribute="";this._triggerType="threshold";this._triggerAbove="";this._triggerBelow="";this._triggerEquals="";this._triggerNotEquals="";this._triggerForMinutes="0";this._triggerCombinator="any";this._triggerTargetValue="";this._triggerDeltaMode=!1;this._triggerBaselineValue="";this._liveBaselineValue=null;this._autoCompleteOnRecovery=!1;this._triggerFromState="";this._triggerToState="";this._triggerTargetChanges="";this._triggerRuntimeHours="";this._triggerDaysBefore="0";this._triggerRuntimeMaxSession="";this._triggerOnStates="";this._compoundLogic="AND";this._compoundConditions=[];this._suggestedAttributes=[];this._availableAttributes=[];this._entityDomain="";this._lastPerformed="";this._nfcTagId="";this._requireTagScan=!1;this._allowSkip=!0;this._notifyEnabled=!0;this._readingUnit="";this._readings=[];this._consumesParts={};this._consumesQtyText={};this._partsLoadFailed=!1;this._availableTags=[];this._responsibleUserId=null;this._loadedLastPerformed="";this._loadedResponsibleUserId=null;this._assigneePool=[];this._rotationStrategy="";this._availableUsers=[];this._checklistText="";this._phaseDefs=[];this._phaseSeq=[];this._requiredCompletion=[];this._scheduleTime="";this._scheduleTimeOn=!1;this._actionService="";this._actionTargetEntity="";this._actionTargetStored=null;this._actionTargetInitial="";this._actionSkipAuto=!1;this._actionPresent=!1;this._actionData={};this._actionDataJsonFallback="";this._actionTesting=!1;this._actionTestResult="";this._actionTestError="";this._qcNotes="";this._qcCost="";this._qcDuration="";this._qcFeedback="";this._environmentalEntity="";this._environmentalAttribute="";this._environmentalInitial="";this._environmentalAttributeInitial="";this._adaptiveEnabled=!1;this._adaptiveAlpha=W.alpha;this._adaptiveMin=W.min;this._adaptiveMax=W.max;this._adaptiveSeasonal=!0;this._adaptivePrediction=!0;this._adaptiveInitial="";this._adaptiveWasEnabled=!1;this._userService=null;this._conditionAttrOptions={};this._conditionAttrPending=new Set}_adaptiveSnapshot(){return JSON.stringify([this._adaptiveEnabled,this._adaptiveAlpha,this._adaptiveMin,this._adaptiveMax,this._adaptiveSeasonal,this._adaptivePrediction])}get _lang(){return P(this.hass)}async openCreate(e,i){this._entryId=e,this._taskId=null,this._isFleetTask=!1,this._error="",this._warning="",!e&&i&&i.length>0?(this._objectChoices=i.map(t=>({entry_id:t.entry_id,name:t.object.name})).sort((t,n)=>t.name.localeCompare(n.name)),this._entryId=this._objectChoices[0].entry_id):this._objectChoices=[],this._resetFields(),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}async openEdit(e,i){this._entryId=e,this._taskId=i.id,this._error="",this._warning="",this._objectChoices=[],this._isFleetTask=i.battery_fleet_task===!0,this._name=i.name,this._type=i.type,this._scheduleType=i.schedule_type,this._intervalDays=i.interval_days!=null?String(i.interval_days):"",this._intervalUnit=i.interval_unit||"days",this._dueDate=i.due_date||"";let t=i.schedule;this._weekdays=t?.kind==="weekdays"?[...t.weekdays??[]]:[],this._nth=t?.kind==="nth_weekday"?String(t.nth??1):"1",this._nthWeekday=t?.kind==="nth_weekday"?String(t.weekday??5):"5",this._domDay=t?.kind==="day_of_month"&&(t.day??1)>=1?String(t.day??1):"1",this._domLastDay=t?.kind==="day_of_month"&&t.day===-1,this._domBusiness=t?.kind==="day_of_month"&&t.business===!0,this._calendarEntity=t?.kind==="calendar"&&t.entity_id||"",this._calOffset=t?.offset?String(t.offset):"0",this._seasonMonths=Array.isArray(t?.season_months)?[...t.season_months]:[];let n=t?.ends;n&&typeof n.count=="number"?(this._endsMode="count",this._endsCount=String(n.count),this._endsUntil=""):n&&typeof n.until=="string"?(this._endsMode="until",this._endsUntil=n.until,this._endsCount=""):(this._endsMode="never",this._endsCount="",this._endsUntil=""),this._warningDays=i.warning_days.toString(),this._earliestCompletionDays=i.earliest_completion_days!=null?String(i.earliest_completion_days):"",this._intervalAnchor=i.interval_anchor||"completion",this._notes=i.notes||"",this._documentationUrl=i.documentation_url||"",this._customIcon=i.custom_icon||"",this._notifyIcon=i.notify_icon||"",this._priority=i.priority||"normal",this._labels=(i.labels||[]).join(", "),this._mirrorTodoEntities=[...i.mirror_todo_entities||[]],this._enabled=i.enabled!==!1,this._lastPerformed=i.last_performed||"",this._loadedLastPerformed=this._lastPerformed,this._nfcTagId=i.nfc_tag_id||"",this._requireTagScan=!!i.require_tag_scan,this._allowSkip=i.allow_skip!==!1,this._notifyEnabled=i.notify_enabled!==!1,this._readingUnit=i.reading_unit||"",this._readings=(i.readings||[]).map(m=>({...m})),this._consumesParts=Object.fromEntries((i.consumes_parts||[]).map(m=>[j(m),{...m}])),this._consumesQtyText={},this._responsibleUserId=i.responsible_user_id||null,this._loadedResponsibleUserId=this._responsibleUserId,this._assigneePool=[...i.assignee_pool||[]],this._rotationStrategy=i.rotation_strategy||"",this._checklistText=(i.checklist||[]).join(` `),this._phaseDefs=Object.entries(i.phases||{}).map(([m,g])=>{let{name:f,checklist:x,consumes_parts:b,required_completion_fields:S,...N}=g,K=g.consumes_parts||[],X=K.findIndex(B=>!B.entry_id),F=X>=0?K[X]:void 0;return{id:m,name:g.name||m,checklistText:(g.checklist||[]).join(` `),partId:F?.part_id||"",partQty:F?.quantity!=null?String(F.quantity):"",reqOverride:g.required_completion_fields!==void 0,reqFields:[...g.required_completion_fields||[]],extraParts:K.filter((B,re)=>re!==X).map(B=>({...B})),carry:N}}),this._phaseSeq=[...i.phase_sequence||[]],this._requiredCompletion=[...i.required_completion_fields||[]],this._scheduleTime=i.schedule_time||"",this._scheduleTimeOn=!!i.schedule_time;let o=i.on_complete_action;if(o&&o.service){this._actionService=o.service;let m=o.target?.entity_id;this._actionTargetEntity=Array.isArray(m)?m[0]||"":m||"",this._actionTargetStored=o.target&&typeof o.target=="object"?JSON.parse(JSON.stringify(o.target)):null,this._actionTargetInitial=this._actionTargetEntity,this._actionData=o.data&&typeof o.data=="object"?{...o.data}:{},this._actionDataJsonFallback="",this._actionSkipAuto=o.skip_auto===!0,this._actionPresent=!0}else this._actionService="",this._actionTargetEntity="",this._actionTargetStored=null,this._actionTargetInitial="",this._actionData={},this._actionDataJsonFallback="",this._actionSkipAuto=!1,this._actionPresent=!1;let c=i.quick_complete_defaults;this._qcNotes=c?.notes||"",this._qcCost=c?.cost!=null?String(c.cost):"",this._qcDuration=c?.duration!=null?String(c.duration):"",this._qcFeedback=c?.feedback||"";let u=i.adaptive_config||{};if(this._environmentalEntity=u.environmental_entity||"",this._environmentalAttribute=u.environmental_attribute||"",this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute,this._adaptiveEnabled=!!u.enabled,this._adaptiveAlpha=u.ewa_alpha?.toString()??W.alpha,this._adaptiveMin=u.min_interval_days?.toString()??W.min,this._adaptiveMax=u.max_interval_days?.toString()??W.max,this._adaptiveSeasonal=u.seasonal_enabled!==!1,this._adaptivePrediction=u.sensor_prediction_enabled!==!1,this._adaptiveInitial=this._adaptiveSnapshot(),this._adaptiveWasEnabled=this._adaptiveEnabled,i.trigger_config){let m=i.trigger_config;this._triggerEntityId=Rt(m)||"",this._triggerEntityIds=Re(m),this._triggerEntityLogic=m.entity_logic||"any",this._setTypeFields(Ot(m)),this._triggerCombinator=m.trigger_combinator==="all"?"all":"any",this._triggerBaselineValue=m.trigger_baseline_value?.toString()||"",this._liveBaselineValue=i.trigger_baseline_value??null,this._autoCompleteOnRecovery=m.auto_complete_on_recovery||!1,this._triggerRuntimeMaxSession=m.trigger_runtime_max_session_seconds?.toString()||"",m.type==="compound"?(this._compoundLogic=m.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(m.conditions||[]).map(qi)):(this._compoundLogic="AND",this._compoundConditions=[])}else this._resetTriggerFields();this._triggerEntityId&&this._fetchEntityAttributes(this._triggerEntityId),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}_resetFields(){this._name="",this._type="custom",this._scheduleType="time_based",this._intervalDays="30",this._intervalUnit="days",this._dueDate="",this._warningDays=String(this.defaultWarningDays),this._earliestCompletionDays="",this._intervalAnchor="completion",this._weekdays=[],this._nth="1",this._nthWeekday="5",this._domDay="1",this._domLastDay=!1,this._domBusiness=!1,this._calOffset="0",this._seasonMonths=[],this._endsMode="never",this._endsCount="",this._endsUntil="",this._notes="",this._documentationUrl="",this._customIcon="",this._notifyIcon="",this._priority="normal",this._labels="",this._mirrorTodoEntities=[],this._enabled=!0,this._lastPerformed="",this._nfcTagId="",this._requireTagScan=!1,this._allowSkip=!0,this._readingUnit="",this._readings=[],this._consumesParts={},this._consumesQtyText={},this._responsibleUserId=null,this._assigneePool=[],this._rotationStrategy="",this._checklistText="",this._phaseDefs=[],this._phaseSeq=[],this._requiredCompletion=[],this._scheduleTime="",this._scheduleTimeOn=!1,this._environmentalEntity="",this._environmentalAttribute="",this._environmentalInitial="",this._environmentalAttributeInitial="",this._adaptiveEnabled=!1,this._adaptiveAlpha=W.alpha,this._adaptiveMin=W.min,this._adaptiveMax=W.max,this._adaptiveSeasonal=!0,this._adaptivePrediction=!0,this._adaptiveInitial=this._adaptiveSnapshot(),this._adaptiveWasEnabled=!1,this._actionService="",this._actionTargetEntity="",this._actionTargetStored=null,this._actionTargetInitial="",this._actionData={},this._actionDataJsonFallback="",this._actionSkipAuto=!1,this._actionPresent=!1,this._actionTesting=!1,this._actionTestResult="",this._qcNotes="",this._qcCost="",this._qcDuration="",this._qcFeedback="",this._resetTriggerFields()}_typeFields(){return{type:this._triggerType,attribute:this._triggerAttribute,above:this._triggerAbove,below:this._triggerBelow,equals:this._triggerEquals,notEquals:this._triggerNotEquals,forMinutes:this._triggerForMinutes,targetValue:this._triggerTargetValue,deltaMode:this._triggerDeltaMode,fromState:this._triggerFromState,toState:this._triggerToState,targetChanges:this._triggerTargetChanges,runtimeHours:this._triggerRuntimeHours,onStates:this._triggerOnStates,daysBefore:this._triggerDaysBefore}}_setTypeFields(e){this._triggerType=e.type,this._triggerAttribute=e.attribute,this._triggerAbove=e.above,this._triggerBelow=e.below,this._triggerEquals=e.equals,this._triggerNotEquals=e.notEquals,this._triggerForMinutes=e.forMinutes,this._triggerTargetValue=e.targetValue,this._triggerDeltaMode=e.deltaMode,this._triggerFromState=e.fromState,this._triggerToState=e.toState,this._triggerTargetChanges=e.targetChanges,this._triggerRuntimeHours=e.runtimeHours,this._triggerOnStates=e.onStates,this._triggerDaysBefore=e.daysBefore}_resetTriggerFields(){this._triggerEntityId="",this._triggerEntityIds=[],this._triggerEntityLogic="any",this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="",this._setTypeFields(Ht()),this._triggerCombinator="any",this._triggerBaselineValue="",this._liveBaselineValue=null,this._autoCompleteOnRecovery=!1,this._triggerRuntimeMaxSession="",this._compoundLogic="AND",this._compoundConditions=[]}async _loadUsers(){this._userService||(this._userService=new Pe(this.hass));try{this._availableUsers=await this._userService.getUsers()}catch(e){console.error("Failed to load users:",e),this._availableUsers=[]}}_toggleAssignee(e){this._assigneePool=this._assigneePool.includes(e)?this._assigneePool.filter(i=>i!==e):[...this._assigneePool,e]}async _testAction(){let e=this._actionService.trim();if(!e||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(e)){this._actionTestResult="error",this._actionTestError=s("action_test_bad_format",this._lang),setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[i,t]=e.split(".");if(!this.hass?.services?.[i]?.[t]){this._actionTestResult="error",this._actionTestError=s("action_test_unknown_service",this._lang).replace("{service}",e),setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}let n=this._actionTargetEntity.trim();if(n){let o=n.split(".")[0];if(o!==i&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(i)){this._actionTestResult="error",this._actionTestError=s("action_test_domain_mismatch",this._lang).replace("{service}",e).replace("{domain}",i).replace("{entity}",n).replace("{entity_domain}",o).replace("{suggestion}",`${o}.${t}`),setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}if(!this.hass.states?.[n]){this._actionTestResult="error",this._actionTestError=s("action_test_entity_missing",this._lang).replace("{entity}",n),setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}}this._actionTestResult="ok",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3)}_buildActionData(){if(this._actionDataJsonFallback.trim())try{let e=JSON.parse(this._actionDataJsonFallback);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{...this._actionData}}_serviceSchema(){let e=this._actionService.trim();if(!e||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(e))return null;let[i,t]=e.split("."),n=this.hass?.services?.[i]?.[t]?.fields;return!n||Object.keys(n).length===0?null:Object.entries(n).map(([o,c])=>({name:o,required:!!c.required,selector:c.selector||{text:{}}}))}_actionTargetExtended(){let e=this._actionTargetStored;return e?Object.entries(e).some(([i,t])=>i==="entity_id"?Array.isArray(t)&&t.length>1:Array.isArray(t)?t.length>0:!!t):!1}_actionTargetSummary(){let e=this._actionTargetStored||{},i=n=>(Array.isArray(n)?n:[n]).filter(o=>typeof o=="string"&&!!o),t=this.hass;return[...i(e.entity_id).map(n=>t.states?.[n]?.attributes?.friendly_name||n),...i(e.device_id).map(n=>t.devices?.[n]?.name_by_user||t.devices?.[n]?.name||n),...i(e.area_id).map(n=>t.areas?.[n]?.name||n),...i(e.floor_id).map(n=>t.floors?.[n]?.name||n),...i(e.label_id)].join(", ")}_renderCompletionActionsSection(e){if(!this.completionActionsEnabled&&!this._actionPresent)return h;let i=this._serviceSchema();return l`
${s("on_complete_action_title",e)}

${s("on_complete_action_desc",e)}

{this._actionService=t.detail.value||"";let n=this._serviceSchema();if(n){let o=new Set(n.map(c=>c.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([c])=>o.has(c)))}}} > s("on_complete_action_target",e)} @value-changed=${t=>{let n=t.detail.value;this._actionTargetEntity=n.target_entity||""}} > ${this._actionTargetExtended()&&this._actionTargetEntity.trim()===this._actionTargetInitial?l`

${s("on_complete_action_target_more",e).replace("{targets}",this._actionTargetSummary())}

`:h}

${s("on_complete_action_target_hint",e)}

${i?l` {this._actionData={...t.detail.value}}} > `:l` {this._actionDataJsonFallback=t.target.value}} > `}
${this._actionTestResult==="ok"?l`${s("on_complete_action_test_success",e)}`:h} ${this._actionTestResult==="error"?l`
${s("on_complete_action_test_failed",e)} ${this._actionTestError?l`
${this._actionTestError}
`:h}
`:h}
${this.completionActionsEnabled?l`
${s("quick_complete_defaults_title",e)}

${s("quick_complete_defaults_desc",e)}

{this._qcNotes=t.target.value}} >
${s("quick_complete_defaults_cost",e)} {this._qcCost=t.detail.value}}>
{this._qcDuration=t.target.value}} >
`:h} `}async _loadParts(){if(this.parts=[],!!this._entryId)try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object",entry_id:this._entryId});this.parts=e.parts||[],this._partsLoadFailed=!1}catch{this.parts=[],this._partsLoadFailed=!0}}async _loadForeignPools(){if(this._foreignOwners=[],!!this._entryId)try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/objects"});this._foreignOwners=(e.objects||[]).filter(i=>i.entry_id!==this._entryId&&(i.parts||[]).length>0).map(i=>({entry_id:i.entry_id,name:i.object?.name||i.entry_id,parts:i.parts||[]})).sort((i,t)=>i.name.localeCompare(t.name))}catch{this._foreignOwners=[]}}async _loadTags(){try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/tags/list"});this._availableTags=e.tags||[]}catch{this._availableTags=[]}}_fetchConditionAttributes(e){!e||!this.hass||this._conditionAttrOptions[e]||this._conditionAttrPending.has(e)||(this._conditionAttrPending.add(e),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e}).then(i=>{let t=i;this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:t.suggested_attributes||[],available:t.available_attributes||[]}}}).catch(()=>{this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:[],available:[]}}}))}async _fetchEntityAttributes(e){if(!e||!this.hass){this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="";return}try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e});this._entityDomain=i.domain||"",this._suggestedAttributes=i.suggested_attributes||[],this._availableAttributes=i.available_attributes||[]}catch{this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain=""}}get _hasForeignPick(){return Object.values(this._consumesParts).some(e=>!!e.entry_id)}_renderConsumesRow(e,i){let t=j({part_id:e.id,entry_id:i}),n=this._consumesParts[t],o=i?{part_id:e.id,quantity:1,entry_id:i}:{part_id:e.id,quantity:1};return l`
${n!==void 0?l`{let u=c.target.value;this._consumesQtyText={...this._consumesQtyText,[t]:u};let m=parseFloat(u.replace(",","."));Number.isFinite(m)&&m>=ie[0]&&(this._consumesParts={...this._consumesParts,[t]:{...o,quantity:m}})}} />`:h}
`}_applyConsumesQtyText(){let e={...this._consumesParts};for(let i of Object.keys(e)){let t=this._consumesQtyText[i];if(t===void 0)continue;let n=parseFloat(t.replace(",","."));if(!Number.isFinite(n)||nie[1]){let o=c=>E(c,this._lang,{maximumFractionDigits:2});return this._error=s("settings_value_out_of_range",this._lang).replace("{min}",o(ie[0])).replace("{max}",o(ie[1])),!1}e[i]={...e[i],quantity:n}}return this._consumesParts=e,!0}_toggleRequired(e,i){let t=new Set(this._requiredCompletion);i?t.add(e):t.delete(e),this._requiredCompletion=[...t]}_patchReading(e,i){this._readings=this._readings.map(t=>t.id===e?{...t,...i}:t)}_renderReadingsEditor(e){let i=pt(this._readings);return l`
${s("readings_section",e)}
${s("readings_hint",e)}
${this._readings.map(t=>l` ${i.has(t.id)?l`
${s("reading_duplicate_name",e)}
`:h}
this._patchReading(t.id,{name:n.target.value})} > this._patchReading(t.id,{unit:n.target.value})} > this._readings=this._readings.filter(n=>n.id!==t.id)}>
`)} ${this._readings.lengththis._readings=[...this._readings,{id:at(),name:"",unit:this._readings.length?this._readings[this._readings.length-1].unit:this._readingUnit}]}> ${s("reading_add",e)} `:h}
`}_phaseSlug(e){let i=e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"phase",t=i,n=2;for(;this._phaseDefs.some(o=>o.id===t);)t=`${i}-${n++}`;return t}_addPhaseDef(){let e=this._phaseSlug(`phase-${this._phaseDefs.length+1}`);this._phaseDefs=[...this._phaseDefs,{id:e,name:"",checklistText:"",partId:"",partQty:"",reqOverride:!1,reqFields:[],extraParts:[],carry:{}}]}_removePhaseDef(e){this._phaseDefs=this._phaseDefs.filter(i=>i.id!==e),this._phaseSeq=this._phaseSeq.filter(i=>i!==e)}_patchPhaseDef(e,i){this._phaseDefs=this._phaseDefs.map(t=>t.id===e?{...t,...i}:t)}_renderPhasesEditor(e){let i=t=>this._phaseDefs.find(n=>n.id===t)?.name||t;return l`

${s("phases_section",e)}

${s("phases_hint",e)}
${this._phaseDefs.map(t=>l`
this._patchPhaseDef(t.id,{name:n.target.value})} > ${this.parts.length?l` ${t.partId?l` this._patchPhaseDef(t.id,{partQty:n.target.value})} /> `:h} `:h} this._removePhaseDef(t.id)}>
${this.checklistsEnabled?l` `:h} ${t.reqOverride?l`
${Be.map(n=>l` `)}
`:h}
`)} ${s("phase_add",e)} ${this._phaseDefs.some(t=>t.name.trim())?l`
${s("phase_sequence_label",e)}
${this._phaseSeq.map((t,n)=>l` ${n+1}. ${i(t)} `)}
`:h} `}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),i=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(i)&&e>i){this._error=`${s("adaptive_min_interval",this._lang)} > ${s("adaptive_max_interval",this._lang)}`;return}}if(this._triggerType==="threshold"&&this._thresholdLimitsOverlap()){this._error=s("trigger_hint_overlap",this._lang);return}if(this._scheduleType==="calendar"&&!this._calendarEntity.trim().startsWith("calendar.")){this._error=s("calendar_entity_required",this._lang);return}if(this._applyConsumesQtyText()){this._loading=!0,this._error="";try{let e=await A(this,()=>this.hass.connection.sendMessagePromise(this._savePayload()),{fallbackKey:"save_error",onError:o=>{this._error=o}});if(e===void 0)return;let i=this._taskId||e?.task_id,t=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;this._warning="";let n=o=>{this._warning=s("subsave_warning",this._lang).replace("{detail}",o)};if(i&&this._scheduleType==="sensor_based"&&t&&await A(this,{type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:i,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null},{onError:n})!==void 0&&(this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute),i&&this._adaptiveSnapshot()!==this._adaptiveInitial){let o=parseFloat(this._adaptiveAlpha),c=parseInt(this._adaptiveMin,10),u=parseInt(this._adaptiveMax,10);await A(this,{type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:i,enabled:this._adaptiveEnabled,...o>=fe[0]&&o<=fe[1]?{ewa_alpha:o}:{},...!isNaN(c)&&c>=1?{min_interval_days:c}:{},...!isNaN(u)&&u>=1?{max_interval_days:u}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction},{onError:n})!==void 0&&(this._adaptiveInitial=this._adaptiveSnapshot())}this._warning?i&&(this._taskId=i):this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}finally{this._loading=!1}}}}_savePayload(){let e={type:this._taskId?"maintenance_supporter/task/update":"maintenance_supporter/task/create",entry_id:this._entryId,name:this._name,task_type:this._type,schedule_type:this._scheduleType,warning_days:Number.isNaN(parseInt(this._warningDays,10))?this.defaultWarningDays:Math.max(0,parseInt(this._warningDays,10))},i=this._earliestCompletionDays.trim();e.earliest_completion_days=i===""?null:Math.max(0,parseInt(i,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):Le.includes(this._scheduleType)?(e.schedule={...this._buildSchedule(),...this._recurrenceExtras()},e.interval_days=null,this._taskId&&(e.due_date=null)):(this._taskId&&(e.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(e.interval_days=parseInt(this._intervalDays,10),e.interval_unit=this._intervalUnit,e.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(e.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(e.interval_days=null,e.interval_anchor="completion")),e.notes=this._notes||null,e.documentation_url=this._documentationUrl||null,e.custom_icon=this._customIcon||null,e.notify_icon=this._notifyIcon.trim()||null,e.priority=this._priority,e.labels=this._labels.split(",").map(t=>t.trim()).filter(Boolean),e.mirror_todo_entities=this._mirrorTodoEntities.filter(Boolean),e.enabled=this._enabled,(!this._taskId||this._lastPerformed!==this._loadedLastPerformed)&&(e.last_performed=this._lastPerformed||null),e.nfc_tag_id=this._nfcTagId||null,e.require_tag_scan=this._requireTagScan,e.allow_skip=this._allowSkip,e.notify_enabled=this._notifyEnabled,e.reading_unit=this._readingUnit.trim()||null,e.readings=ht(this._readings);{let t={};for(let o of this._phaseDefs){if(!o.name.trim())continue;let c={...o.carry,name:o.name.trim()},u=o.checklistText.split(` `).map(g=>g.trim()).filter(Boolean);u.length&&(c.checklist=u);let m=[];if(o.partId){let g=parseFloat(o.partQty);m.push({part_id:o.partId,quantity:Number.isFinite(g)&&g>0?g:1})}for(let g of o.extraParts)m.push(g.entry_id?{part_id:g.part_id,quantity:g.quantity,entry_id:g.entry_id}:{part_id:g.part_id,quantity:g.quantity});m.length&&(c.consumes_parts=m),o.reqOverride&&(c.required_completion_fields=[...o.reqFields]),t[o.id]=c}let n=this._phaseSeq.filter(o=>o in t);e.phases=Object.keys(t).length&&n.length?t:null,e.phase_sequence=e.phases?n:null}if((this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(t=>t.entry_id?{part_id:t.part_id,quantity:t.quantity,entry_id:t.entry_id}:{part_id:t.part_id,quantity:t.quantity})),(!this._taskId||this._responsibleUserId!==this._loadedResponsibleUserId)&&(e.responsible_user_id=this._responsibleUserId),e.assignee_pool=this._assigneePool,e.required_completion_fields=this._requiredCompletion,e.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let t=this._compoundConditions.map(Hi).filter(n=>n!==null);if(t.length>0){let n={type:"compound",compound_logic:this._compoundLogic,conditions:t};this._autoCompleteOnRecovery&&(n.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(n.trigger_combinator="all"),e.trigger_config=n}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let t=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],n={entity_id:t[0],entity_ids:t,type:this._triggerType};if(Mt(n,this._typeFields()),this._autoCompleteOnRecovery&&(n.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(n.trigger_combinator="all"),t.length>1&&(n.entity_logic=this._triggerEntityLogic),this._triggerType==="counter"&&this._triggerDeltaMode&&this._triggerBaselineValue){let o=parseFloat(this._triggerBaselineValue);!isNaN(o)&&o>=0&&(n.trigger_baseline_value=o)}else if(this._triggerType==="runtime"&&this._triggerRuntimeMaxSession){let o=parseInt(this._triggerRuntimeMaxSession,10);!isNaN(o)&&o>0&&(n.trigger_runtime_max_session_seconds=o)}e.trigger_config=n}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&Lt.includes(this._scheduleType)){let t=this._scheduleTimeOn?this._scheduleTime.trim():"";e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(t)?t:null}if(this.checklistsEnabled){let t=this._checklistText.split(` `).map(n=>n.trim()).filter(Boolean).slice(0,100);e.checklist=t.length?t:null}if(this.completionActionsEnabled||this._actionPresent){let t=this._actionService.trim();if(t&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(t)){let n={service:t},o=this._actionTargetEntity.trim();this._actionTargetStored&&o===this._actionTargetInitial?n.target=JSON.parse(JSON.stringify(this._actionTargetStored)):o&&(n.target={entity_id:o});let c=this._buildActionData();Object.keys(c).length>0&&(n.data=c),this._actionSkipAuto&&(n.skip_auto=!0),e.on_complete_action=n}else e.on_complete_action=null}if(this.completionActionsEnabled){let t={};this._qcNotes.trim()&&(t.notes=this._qcNotes.trim());let n=parseFloat(this._qcCost);isNaN(n)||(t.cost=n);let o=de(this._qcDuration);o!==null&&(t.duration=o),this._qcFeedback&&(t.feedback=this._qcFeedback),e.quick_complete_defaults=Object.keys(t).length?t:null}return e}_close(){this._open=!1,this._warning="",this._pickerProbeTimer!==void 0&&(clearTimeout(this._pickerProbeTimer),this._pickerProbeTimer=void 0),this._pickerProbeStrikes=0}_renderTriggerFields(){if(this._scheduleType!=="sensor_based")return h;let e=this._lang,i=this._triggerType==="compound";return l`

${s("trigger_configuration",e)}

${i?this._renderCompoundEditor():l` ${this._entityPickerFallback?l` 0?this._triggerEntityIds.join(", "):this._triggerEntityId} @input=${t=>{let o=t.target.value.split(",").map(c=>c.trim()).filter(Boolean);this._triggerEntityId=o[0]||"",this._triggerEntityIds=o,o[0]&&this._fetchEntityAttributes(o[0])}} > `:l` 0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}} .computeLabel=${()=>s("entity_id",e)} @value-changed=${t=>{let n=(t.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=n[0]||"",this._triggerEntityIds=n,n[0]?this._fetchEntityAttributes(n[0]):this._fetchEntityAttributes("")}} >`} ${this._triggerEntityIds.length>1?l`
`:h} ${this._renderAttributeSelect({label:s("attribute_optional",e),value:this._triggerAttribute,suggested:this._suggestedAttributes,available:this._availableAttributes,onSelect:t=>this._triggerAttribute=t})} ${this._renderTriggerTypeFields()} ${this._renderTriggerLiveHint()} `}
${s("auto_complete_on_recovery_help",e)}
this._intervalDays=t.target.value} > ${this._intervalDays?this._renderUnitSelect():h} ${this._intervalDays?l`
`:h} `}_patchCondition(e,i){this._compoundConditions=this._compoundConditions.map((t,n)=>n===e?{...t,...i}:t)}_addCondition(){this._compoundConditions=[...this._compoundConditions,Ht()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((i,t)=>t!==e)}_renderCompoundEditor(){let e=this._lang;return l`
${s("compound_help",e)}
${this._compoundConditions.length===0?l`
${s("compound_no_conditions",e)}
`:this._compoundConditions.map((i,t)=>this._renderCondition(i,t))} `}_renderCondition(e,i){let t=this._lang,n=i+1;return l`
${s("compound_condition",t)} ${n}
${this._entityPickerFallback?l` this._patchCondition(i,{entityIds:o.target.value})} > `:l` o.trim()).filter(Boolean)}} .computeLabel=${()=>s("entity_id",t)} @value-changed=${o=>{let c=(o.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(i,{entityIds:c.join(", ")})}} >`} ${this._renderConditionAttribute(e,i)}
${this._renderConditionTypeFields(e,i)}
`}_renderStateField(e){return this._entityPickerFallback||!e.entityId?l` e.onInput(i.target.value)} > `:l` e.label} @value-changed=${i=>e.onInput((i.detail.value.s||"").trim())} > `}_renderOnStatesField(e){let i=this._lang;return this._entityPickerFallback||!e.entityId?l` e.onInput(t.target.value)} > `:l` t.trim()).filter(Boolean)}} .computeLabel=${()=>s("runtime_on_states",i)} @value-changed=${t=>e.onInput((t.detail.value.s||[]).join(", "))} > `}_renderAdaptiveSection(e){return this._scheduleType==="one_time"||this._scheduleType==="manual"?h:!this.adaptiveFeature&&!this._adaptiveWasEnabled?h:l`
${s("adaptive_section_title",e)} ${this._adaptiveEnabled?l` this._adaptiveMin=i.target.value} > this._adaptiveMax=i.target.value} > this._adaptiveAlpha=i.target.value} > ${this.seasonalFeature?l``:h} `:h}
`}_renderAttributeSelect(e){let i=this._lang;return e.available.length>0?l`
`:l` e.onSelect(t.target.value.trim())} > `}_renderEnvironmentalAttribute(e){this._fetchConditionAttributes(this._environmentalEntity);let i=this._conditionAttrOptions[this._environmentalEntity];return this._renderAttributeSelect({label:s("environmental_attribute_optional",e),value:this._environmentalAttribute,suggested:i?.suggested??[],available:i?.available??[],onSelect:t=>this._environmentalAttribute=t})}_renderConditionAttribute(e,i){let t=e.entityIds.split(",")[0]?.trim()||"";t&&this._fetchConditionAttributes(t);let n=t?this._conditionAttrOptions[t]:void 0;return this._renderAttributeSelect({label:s("attribute_optional",this._lang),value:e.attribute,suggested:n?.suggested??[],available:n?.available??[],onSelect:o=>this._patchCondition(i,{attribute:o})})}_renderConditionTypeFields(e,i){let t=this._lang;if(e.type==="threshold")return l` this._patchCondition(i,{above:n.target.value})}> this._patchCondition(i,{below:n.target.value})}> this._patchCondition(i,{equals:n.target.value})}> this._patchCondition(i,{notEquals:n.target.value})}> this._patchCondition(i,{forMinutes:n.target.value})}> `;if(e.type==="counter")return l` this._patchCondition(i,{targetValue:n.target.value})}> `;if(e.type==="state_change"){let n=e.entityIds.split(",")[0]?.trim()||"";return l` ${this._renderStateField({label:s("from_state_optional",t),value:e.fromState,entityId:n,onInput:o=>this._patchCondition(i,{fromState:o})})} ${this._renderStateField({label:s("to_state_optional",t),value:e.toState,entityId:n,onInput:o=>this._patchCondition(i,{toState:o})})} this._patchCondition(i,{targetChanges:o.target.value})}> this._patchCondition(i,{forMinutes:o.target.value})}> `}if(e.type==="runtime"){let n=e.entityIds.split(",")[0]?.trim()||"";return l` this._patchCondition(i,{runtimeHours:o.target.value})}> ${this._renderOnStatesField({value:e.onStates,entityId:n,onInput:o=>this._patchCondition(i,{onStates:o})})} `}return e.type==="due_date"?l` this._patchCondition(i,{daysBefore:n.target.value})}> `:h}_renderUnitSelect(){let e=this._lang;return l`
`}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(i=>i!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(this._scheduleType==="calendar"&&!this._calendarEntity.trim())return null;if(Le.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let e=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!e||e<=0?null:{kind:"interval",every:e,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(e){super.updated?.(e),this._scheduleEntityPickerProbe();for(let i of e.keys())if(_._PREVIEW_RELEVANT.has(String(i))){this._schedulePreviewRefresh();return}}_scheduleEntityPickerProbe(){this._entityPickerFallback||this._pickerProbeTimer!==void 0||!this._open||this._scheduleType!=="sensor_based"||(this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),1500))}_probeEntityPickers(){if(this._pickerProbeTimer=void 0,this._entityPickerFallback||!this._open)return;let e=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),i=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!i){this._pickerProbeStrikes=0;return}let t=(u,m,g=0)=>{if(!(!u||g>10)){(u.tagName?.toLowerCase()??"")==="ha-entity-picker"&&m.push(u);for(let f of[u.shadowRoot,u])if(f)for(let x of Array.from(f.children??[]))t(x,m,g+1)}},n=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],o=[];for(let u of n)t(u,o);let c=o.length===0||o.some(u=>u.offsetHeight===0);if(e.offsetHeight===0||c){if(this._pickerProbeStrikes+=1,this._pickerProbeStrikes>=2){this._entityPickerFallback=!0;return}this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),700)}else this._pickerProbeStrikes=0}_schedulePreviewRefresh(){this._previewTimer&&clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._fetchSchedulePreview()},300)}async _fetchSchedulePreview(){let e=this._open?this._previewScheduleDict():null;if(!e){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let i=++this._previewSeq;try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(i!==this._previewSeq)return;this._schedulePreview=t.occurrences||[],this._schedulePreviewEnded=!!t.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return h;let e=this._lang,i=this.scheduleTimeEnabled&&this._scheduleTimeOn&&this._scheduleTime?` ${this._scheduleTime}`:"",t=this._schedulePreview.map((o,c)=>{let u=new Date(`${o}T12:00:00`).getDay();return`${ze(u===0?6:u-1,e,"short")} ${U(o,e)}${c===0?i:""}`}).join(" \xB7 "),n=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?l`
${s("schedule_preview_ontime",e)}
`:h;return l`
${s("schedule_preview_title",e)}: ${t}${this._schedulePreviewEnded?l` ${s("schedule_preview_ends",e)}`:h} ${n}
`}_buildSchedule(){let e=t=>{let n=parseInt(this._calOffset,10)||0;return n&&(t.offset=Math.max(-ve,Math.min(n,ve))),t};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((t,n)=>t-n)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});if(this._scheduleType==="calendar")return e({kind:"calendar",entity_id:this._calendarEntity.trim()});let i={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(i.business=!0),e(i)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((i,t)=>i-t)),this._endsMode==="count"){let i=parseInt(this._endsCount,10);i>=1&&(e.ends={count:i})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(i=>i!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||Le.includes(this._scheduleType)))return h;let t=Oi(e);return l`
${s("season_window_hint",e)}
${t.map((n,o)=>l` `)}
${this._endsMode==="count"?l` this._endsCount=n.target.value} >`:h} ${this._endsMode==="until"?l` this._endsUntil=n.detail.value} >`:h} `}_renderCalendarFields(){let e=this._lang,i=Ni(e);if(this._scheduleType==="weekdays")return l`
${i.map((t,n)=>l` `)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let t=[["1",s("ord_1",e)],["2",s("ord_2",e)],["3",s("ord_3",e)],["4",s("ord_4",e)],["5",s("ord_5",e)],["-1",s("ord_last",e)]];return l`
${this._renderCalOffsetField()}`}return this._scheduleType==="calendar"?l` ${this._entityPickerFallback?l` this._calendarEntity=t.target.value.trim()} > `:l` s("calendar_entity_label",e)} .computeHelper=${()=>s("calendar_entity_hint",e)} @value-changed=${t=>{this._calendarEntity=(t.detail.value.calendar_entity||"").trim()}} >`} ${this._renderCalOffsetField()}`:this._scheduleType==="day_of_month"?l` ${this._domLastDay?h:l` this._domDay=t.target.value} >`} ${this._renderCalOffsetField()}`:h}_renderCalOffsetField(){let e=this._lang;return l` this._calOffset=i.target.value} >`}_thresholdLimitsOverlap(){let e=parseFloat(this._triggerAbove),i=parseFloat(this._triggerBelow);return!isNaN(e)&&!isNaN(i)&&i>e}_renderTriggerLiveHint(){if(this._triggerType==="compound")return h;let e=this._triggerType==="threshold"&&this._thresholdLimitsOverlap()?l`
${s("trigger_hint_overlap",this._lang)}
`:h,i=this._triggerEntityId||this._triggerEntityIds[0];if(!i||!this.hass?.states)return e;let t=this.hass.states[i];if(!t)return e;let n=this._lang,o=t.attributes?.unit_of_measurement,c=typeof o=="string"&&o?` ${o}`:"",u=this._triggerAttribute?t.attributes?.[this._triggerAttribute]:t.state,m=typeof u=="number"?u:parseFloat(String(u)),g=u!=="unknown"&&u!=="unavailable"&&u!=null&&!isNaN(m),f=b=>E(b,n,{maximumFractionDigits:1}),x=[];if(this._triggerType==="threshold"){let b=parseFloat(this._triggerAbove),S=parseFloat(this._triggerBelow);if(isNaN(b)&&isNaN(S))return h;g&&x.push(s("trigger_hint_now",n).replace("{value}",f(m)+c)),isNaN(b)||x.push(s("trigger_hint_above",n).replace("{target}",f(b)+c)),isNaN(S)||x.push(s("trigger_hint_below",n).replace("{target}",f(S)+c))}else if(this._triggerType==="counter"){let b=parseFloat(this._triggerTargetValue);if(isNaN(b))return h;this._triggerDeltaMode?this._taskId?x.push(s("trigger_hint_counter_delta_edit",n).replace("{target}",f(b)+c)):g?x.push(s("trigger_hint_counter_delta",n).replace("{value}",f(m)+c).replace("{due}",f(m+b)+c).replace("{target}",f(b)+c)):x.push(s("trigger_hint_counter_delta_edit",n).replace("{target}",f(b)+c)):(g&&x.push(s("trigger_hint_now",n).replace("{value}",f(m)+c)),x.push(s("trigger_hint_counter_abs",n).replace("{target}",f(b)+c)))}else if(this._triggerType==="runtime"){let b=parseFloat(this._triggerRuntimeHours);if(isNaN(b))return h;x.push(s("trigger_hint_runtime",n).replace("{hours}",f(b))),x.push(s("trigger_hint_state_now",n).replace("{value}",String(t.state)))}else if(this._triggerType==="state_change"){let b=parseInt(this._triggerTargetChanges,10)||1,S=this._triggerToState.trim();x.push((S?s("trigger_hint_state_change_to",n).replace("{state}",S):s("trigger_hint_state_change",n)).replace("{count}",String(b))),x.push(s("trigger_hint_state_now",n).replace("{value}",String(t.state)))}else if(this._triggerType==="due_date"){let b=parseInt(this._triggerDaysBefore,10)||0;x.push(b===0?s("trigger_hint_due_date_same_day",n):b===1?s("trigger_hint_due_date_one",n):s("trigger_hint_due_date",n).replace("{days}",String(b)));let S=u==null?"":String(u);S&&!isNaN(Date.parse(S))&&x.push(s("trigger_hint_due_date_now",n).replace("{date}",U(S,n)))}return x.length?l`
${x.join(" ")}
${e}`:e}_renderTriggerTypeFields(){let e=this._lang;return this._triggerType==="threshold"?l` this._triggerAbove=i.target.value} > this._triggerBelow=i.target.value} > this._triggerEquals=i.target.value} > this._triggerNotEquals=i.target.value} > this._triggerForMinutes=i.target.value} > `:this._triggerType==="counter"?l` this._triggerTargetValue=i.target.value} > ${this._triggerDeltaMode?l` this._triggerBaselineValue=i.target.value} >
${this._taskId?s("baseline_start_help_edit",e):s("baseline_start_help",e)} ${this._taskId&&this._liveBaselineValue!=null?l`
${s("baseline_current_effective",e).replace("{value}",String(this._liveBaselineValue))}
`:h}
`:h} `:this._triggerType==="state_change"?l` ${this._renderStateField({label:s("from_state_optional",e),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:i=>this._triggerFromState=i})}
${s("state_value_help",e)}
${this._renderStateField({label:s("to_state_optional",e),value:this._triggerToState,entityId:this._triggerEntityId,onInput:i=>this._triggerToState=i})} this._triggerTargetChanges=i.target.value} >
${s("target_changes_help",e)}
${(this._triggerTargetChanges||"1")==="1"&&(this._triggerFromState||this._triggerToState)?l`
${s("state_latch_help",e)}
`:h} this._triggerForMinutes=i.target.value} >
${s("for_minutes_state_help",e)}
`:this._triggerType==="runtime"?l` this._triggerRuntimeHours=i.target.value} > this._triggerRuntimeMaxSession=i.target.value} >
${s("runtime_max_session_help",e)}
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:i=>this._triggerOnStates=i})}
${s("runtime_on_states_help",e)}
`:this._triggerType==="due_date"?l` this._triggerDaysBefore=i.target.value} >
${s("days_before_help",e)}
`:h}render(){if(!this._open)return l``;let e=this._lang,i=this._taskId?s("edit_task",e):s("new_task",e);return l`
${i}
${this._error?l`
${this._error}
`:h} ${this._warning?l`
${this._warning}
`:h} ${this._taskId===null&&this._objectChoices.length>0?l`
`:h} this._name=t.target.value} >
${this._type==="reading"?l` this._readingUnit=t.target.value} >
${s("reading_unit_help",e)}
${this._renderReadingsEditor(e)} `:h} ${this._partsLoadFailed?l`
${s("parts_load_failed",e)}
`:h} ${this._isFleetTask?l`
${s("task_parts_fleet_hint",e)}
`:this.parts.length||this._foreignOwners.length?l`
${this.parts.map(t=>this._renderConsumesRow(t))} ${this._foreignOwners.length?l`
${s("shared_parts_other_objects",e)}
${s("shared_parts_help",e)}
${this._foreignOwners.map(t=>l`
${t.name}
${t.parts.map(n=>this._renderConsumesRow(n,t.entry_id))} `)}
`:h}
`:h}
this._labels=t.target.value} />
${s("labels_help",e)}
${this._entityPickerFallback?l` {this._mirrorTodoEntities=t.target.value.split(",").map(n=>n.trim()).filter(Boolean)}} > `:l` s("task_mirror_todo",e)} @value-changed=${t=>{let n=(t.detail.value.mirror_todo_entities||[]).filter(Boolean);this._mirrorTodoEntities=n}} >`}
${s("task_mirror_todo_hint",e)}
${this._scheduleType==="time_based"?l` this._intervalDays=t.target.value} > ${this._renderUnitSelect()}
`:h} ${this._renderCalendarFields()} ${this._scheduleType==="one_time"?l` this._dueDate=t.detail.value} > `:h} ${this.scheduleTimeEnabled&&Lt.includes(this._scheduleType)?l` ${this._scheduleTimeOn?l` this._scheduleTime=t.detail.value} > `:h} `:h} ${this._renderRecurrenceExtras()} ${this._renderSchedulePreview()} this._warningDays=t.target.value} > this._earliestCompletionDays=t.target.value} > ${this.checklistsEnabled?l`

${s("checklist_steps_optional",e)}

${s("checklist_help",e)}
`:h} ${this._renderPhasesEditor(e)}

${s("require_on_completion",e)}

${Be.map(t=>l` `)}
this._lastPerformed=t.detail.value} >
${this._availableUsers.length>=2?l`
${s("shared_with_help",e)}
${this._availableUsers.map(t=>l` `)}
${this._assigneePool.length>=2?l`
`:h} `:h} ${this._renderTriggerFields()} ${this._scheduleType==="sensor_based"&&(this.environmentalFeature||this._environmentalInitial)?l` ${this._entityPickerFallback?l` this._environmentalEntity=t.target.value.trim()} > `:l` s("environmental_entity_optional",e)} .computeHelper=${()=>s("environmental_entity_helper",e)} @value-changed=${t=>{this._environmentalEntity=(t.detail.value.environmental_entity||"").trim()}} >`} ${this._environmentalEntity?this._renderEnvironmentalAttribute(e):h} `:h} ${this._renderAdaptiveSection(e)} this._notes=t.target.value} > this._documentationUrl=t.target.value} > this._customIcon=t.detail.value||""} > this._notifyIcon=t.detail.value||""} >
${s("notify_icon_hint",e).replace("{default}",Ve(this._type))}
${this._availableTags.length>0?l`
`:l` this._nfcTagId=t.target.value} >
${s("nfc_tags_empty_help",e)} ${s("nfc_tags_open_settings",e)} ·
`} ${this._requireTagScan?l`
${s("require_tag_scan_help",e)}
`:h} ${this._allowSkip?h:l`
${s("disallow_skip_help",e)}
`} ${this._notifyEnabled?h:l`
${s("no_notifications_help",e)}
`} ${this._renderCompletionActionsSection(e)}
${s("cancel",e)} ${this._loading?s("saving",e):s("save",e)}
`}};_._PREVIEW_RELEVANT=new Set(["_open","_scheduleType","_intervalDays","_intervalUnit","_intervalAnchor","_dueDate","_weekdays","_nth","_nthWeekday","_domDay","_domLastDay","_domBusiness","_calOffset","_calendarEntity","_seasonMonths","_endsMode","_endsCount","_endsUntil","_lastPerformed"]),_.styles=w` .dialog-title { font-size: 18px; font-weight: 500; padding-bottom: 12px; } /* #129: entity/state pickers in the trigger form (ha-form + selector) */ .entity-picker-form, .state-picker-form { display: block; margin: 8px 0; } /* v1.3.0: completion-action sections (.adaptive-section shares the shell but keeps its own class — tests count .ca-section elements) */ .ca-section, .adaptive-section { border: 1px solid var(--divider-color); border-radius: 6px; padding: 8px 12px; margin-top: 8px; } .ca-section > summary, .adaptive-section > summary { cursor: pointer; font-weight: 500; } .adaptive-section ms-textfield { width: 100%; margin-top: 8px; display: block; } .adaptive-section label { display: block; margin-top: 8px; } .ca-section ms-textfield, .ca-section ha-entity-picker, .ca-section ha-service-picker, .ca-section ha-form, .ca-section .qc-feedback { width: 100%; margin-top: 8px; display: block; } .ca-section .qc-feedback { padding: 8px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color, #fff); color: var(--primary-text-color); } .ca-test-row { display: flex; align-items: center; gap: 12px; margin-top: 8px; } .ca-test-ok { color: var(--success-color, #4caf50); font-size: 13px; } .ca-test-error { color: var(--error-color, #f44336); font-size: 13px; font-weight: 500; } .ca-test-error-block { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; } .ca-test-error-detail { font-size: 12px; color: var(--secondary-text-color); background: rgba(244, 67, 54, 0.08); padding: 6px 8px; border-radius: 4px; line-height: 1.4; word-break: break-word; } .content { display: flex; flex-direction: column; gap: 12px; min-width: 350px; max-height: 70vh; overflow-y: auto; } @media (max-width: 600px) { .content { min-width: 0; max-height: none; } } .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; } ms-textfield { display: block; } .field-label { font-size: 12px; color: var(--secondary-text-color); } .checklist-textarea { width: 100%; min-height: 88px; padding: 8px; font-family: inherit; font-size: 14px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color); color: var(--primary-text-color); resize: vertical; box-sizing: border-box; } .consumes-row { display: flex; align-items: center; gap: 8px; padding: 2px 0; } .phase-def { border: 1px solid var(--divider-color); border-radius: 6px; padding: 8px; margin: 6px 0; } .phase-def-head { display: flex; align-items: center; gap: 8px; } .phase-def-head ms-textfield { flex: 1; min-width: 0; } .phase-part { max-width: 160px; padding: 6px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color); color: var(--primary-text-color); } .phase-qty { width: 64px; padding: 6px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color); color: var(--primary-text-color); } .phase-checklist { min-height: 56px; margin-top: 6px; } .phase-req-toggle { margin-top: 6px; font-size: 13px; color: var(--secondary-text-color); } .phase-req-fields { margin: 2px 0 0 22px; font-size: 13px; } .phase-remove { display: inline-flex; --ha-icon-button-size: 36px; --mdc-icon-button-size: 36px; color: var(--secondary-text-color); } /* #161 phase 2: reading slots — name wide, unit narrow, trash. */ .readings-editor { margin-top: 14px; } .reading-row { display: flex; align-items: center; gap: 8px; margin: 4px 0; } .reading-row .reading-name { flex: 2; min-width: 0; } .reading-row .reading-unit { flex: 1; min-width: 0; max-width: 140px; } .reading-dup { color: var(--warning-color, #ff9800); margin-top: 6px; } .phase-seq-label { font-size: 12px; color: var(--secondary-text-color); margin-top: 8px; } .phase-seq { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 4px 0; } .phase-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 12px; background: var(--secondary-background-color); font-size: 13px; } .phase-chip-x { border: none; background: none; color: var(--secondary-text-color); cursor: pointer; padding: 0 2px; font-size: 12px; } .phase-seq-add { padding: 4px 8px; border: 1px dashed var(--divider-color); border-radius: 12px; background: transparent; color: var(--secondary-text-color); font-size: 13px; } .consumes-check { display: flex; align-items: center; gap: 6px; flex: 1; } .consumes-qty { width: 64px; padding: 4px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color); color: var(--primary-text-color); } /* #111: other objects' pools sit behind a disclosure so the object's OWN parts stay the primary list; each group is headed by the owning object's name, so which pool a checkbox means is never a guess. */ .shared-pools { margin-top: 6px; } .shared-pools > summary { cursor: pointer; padding: 2px 0; font-size: 13px; color: var(--secondary-text-color); } .shared-pool-owner { margin-top: 6px; font-size: 12px; font-weight: 500; color: var(--secondary-text-color); } .qc-cost { display: flex; flex-direction: column; gap: 4px; margin: 8px 0; } .qc-cost-label { font-size: 12px; color: var(--secondary-text-color); } .field-help { font-size: 12px; color: var(--secondary-text-color); } .baseline-effective { margin-top: 2px; font-weight: 500; color: var(--primary-text-color); } /* Live computed trigger hint — reads the bound sensor and explains what happens next. Info-accented so it reads as guidance, not an error. */ .trigger-live-hint { font-size: 12px; color: var(--secondary-text-color); border-left: 3px solid var(--info-color, #2196f3); background: rgba(33, 150, 243, 0.08); border-radius: 0 6px 6px 0; padding: 6px 10px; margin: 4px 0; } .trigger-live-hint.warn { color: var(--primary-text-color); border-left-color: var(--warning-color, #ff9800); background: rgba(255, 152, 0, 0.1); } .field-help a, .link-button { background: none; border: 0; padding: 0; color: var(--primary-color); cursor: pointer; font: inherit; text-decoration: underline; } .field-help a:hover, .link-button:hover { text-decoration: none; } /* Smaller refresh icon-button when shown next to the dropdown. */ .select-row .link-button { margin-left: 8px; text-decoration: none; font-size: 16px; } .select-row .link-button:hover { color: var(--primary-color); opacity: 0.7; } h3 { margin: 8px 0 0; font-size: 14px; color: var(--primary-color); } .select-row { display: flex; flex-direction: column; gap: 4px; } .assignee-pool { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 4px; } .checkbox-row { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; cursor: pointer; margin: 2px 0; } .checkbox-row input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; } .schedule-time-toggle { display: flex; margin: 8px 0 4px; } .pool-item { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; } .pool-item input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; } .select-row label { font-size: 12px; color: var(--secondary-text-color); } .select-row select { padding: 8px; border: 1px solid var(--divider-color); border-radius: 4px; background: var(--card-background-color, #fff); color: var(--primary-text-color); font-size: 14px; } .field-label { font-size: 12px; color: var(--secondary-text-color); } .weekday-chips { display: flex; flex-wrap: wrap; gap: 6px; } .weekday-chip { padding: 6px 12px; border: 1px solid var(--divider-color); border-radius: 16px; background: var(--card-background-color, #fff); color: var(--primary-text-color); font-size: 13px; cursor: pointer; } .weekday-chip.selected { background: var(--primary-color, #03a9f4); color: var(--text-primary-color, #fff); border-color: var(--primary-color, #03a9f4); } .season-chip { padding: 6px 10px; border: 1px solid var(--divider-color); border-radius: 16px; background: var(--card-background-color, #fff); color: var(--primary-text-color); font-size: 13px; cursor: pointer; } .season-chip.selected { background: var(--primary-color, #03a9f4); color: var(--text-primary-color, #fff); border-color: var(--primary-color, #03a9f4); } .error.warning { color: var(--warning-color, #ff9800); } .error { color: var(--error-color, #f44336); font-size: 13px; } .toggle-row { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; } `,d([v({attribute:!1})],_.prototype,"hass",2),d([v({type:Boolean,attribute:"checklists-enabled"})],_.prototype,"checklistsEnabled",2),d([v({type:Boolean,attribute:"schedule-time-enabled"})],_.prototype,"scheduleTimeEnabled",2),d([v({type:Boolean,attribute:"completion-actions-enabled"})],_.prototype,"completionActionsEnabled",2),d([v({type:Boolean,attribute:"adaptive-feature"})],_.prototype,"adaptiveFeature",2),d([v({type:Boolean,attribute:"seasonal-feature"})],_.prototype,"seasonalFeature",2),d([v({type:Boolean,attribute:"environmental-feature"})],_.prototype,"environmentalFeature",2),d([v({type:Number,attribute:"default-warning-days"})],_.prototype,"defaultWarningDays",2),d([p()],_.prototype,"parts",2),d([p()],_.prototype,"_foreignOwners",2),d([p()],_.prototype,"_open",2),d([p()],_.prototype,"_entityPickerFallback",2),d([p()],_.prototype,"_loading",2),d([p()],_.prototype,"_error",2),d([p()],_.prototype,"_warning",2),d([p()],_.prototype,"_entryId",2),d([p()],_.prototype,"_taskId",2),d([p()],_.prototype,"_isFleetTask",2),d([p()],_.prototype,"_objectChoices",2),d([p()],_.prototype,"_name",2),d([p()],_.prototype,"_type",2),d([p()],_.prototype,"_scheduleType",2),d([p()],_.prototype,"_intervalDays",2),d([p()],_.prototype,"_intervalUnit",2),d([p()],_.prototype,"_dueDate",2),d([p()],_.prototype,"_warningDays",2),d([p()],_.prototype,"_earliestCompletionDays",2),d([p()],_.prototype,"_intervalAnchor",2),d([p()],_.prototype,"_weekdays",2),d([p()],_.prototype,"_nth",2),d([p()],_.prototype,"_nthWeekday",2),d([p()],_.prototype,"_domDay",2),d([p()],_.prototype,"_domLastDay",2),d([p()],_.prototype,"_domBusiness",2),d([p()],_.prototype,"_calOffset",2),d([p()],_.prototype,"_calendarEntity",2),d([p()],_.prototype,"_seasonMonths",2),d([p()],_.prototype,"_endsMode",2),d([p()],_.prototype,"_endsCount",2),d([p()],_.prototype,"_endsUntil",2),d([p()],_.prototype,"_schedulePreview",2),d([p()],_.prototype,"_schedulePreviewEnded",2),d([p()],_.prototype,"_notes",2),d([p()],_.prototype,"_documentationUrl",2),d([p()],_.prototype,"_customIcon",2),d([p()],_.prototype,"_notifyIcon",2),d([p()],_.prototype,"_priority",2),d([p()],_.prototype,"_labels",2),d([p()],_.prototype,"_mirrorTodoEntities",2),d([p()],_.prototype,"_enabled",2),d([p()],_.prototype,"_triggerEntityId",2),d([p()],_.prototype,"_triggerEntityIds",2),d([p()],_.prototype,"_triggerEntityLogic",2),d([p()],_.prototype,"_triggerAttribute",2),d([p()],_.prototype,"_triggerType",2),d([p()],_.prototype,"_triggerAbove",2),d([p()],_.prototype,"_triggerBelow",2),d([p()],_.prototype,"_triggerEquals",2),d([p()],_.prototype,"_triggerNotEquals",2),d([p()],_.prototype,"_triggerForMinutes",2),d([p()],_.prototype,"_triggerCombinator",2),d([p()],_.prototype,"_triggerTargetValue",2),d([p()],_.prototype,"_triggerDeltaMode",2),d([p()],_.prototype,"_triggerBaselineValue",2),d([p()],_.prototype,"_liveBaselineValue",2),d([p()],_.prototype,"_autoCompleteOnRecovery",2),d([p()],_.prototype,"_triggerFromState",2),d([p()],_.prototype,"_triggerToState",2),d([p()],_.prototype,"_triggerTargetChanges",2),d([p()],_.prototype,"_triggerRuntimeHours",2),d([p()],_.prototype,"_triggerDaysBefore",2),d([p()],_.prototype,"_triggerRuntimeMaxSession",2),d([p()],_.prototype,"_triggerOnStates",2),d([p()],_.prototype,"_compoundLogic",2),d([p()],_.prototype,"_compoundConditions",2),d([p()],_.prototype,"_suggestedAttributes",2),d([p()],_.prototype,"_availableAttributes",2),d([p()],_.prototype,"_entityDomain",2),d([p()],_.prototype,"_lastPerformed",2),d([p()],_.prototype,"_nfcTagId",2),d([p()],_.prototype,"_requireTagScan",2),d([p()],_.prototype,"_allowSkip",2),d([p()],_.prototype,"_notifyEnabled",2),d([p()],_.prototype,"_readingUnit",2),d([p()],_.prototype,"_readings",2),d([p()],_.prototype,"_consumesParts",2),d([p()],_.prototype,"_consumesQtyText",2),d([p()],_.prototype,"_partsLoadFailed",2),d([p()],_.prototype,"_availableTags",2),d([p()],_.prototype,"_responsibleUserId",2),d([p()],_.prototype,"_assigneePool",2),d([p()],_.prototype,"_rotationStrategy",2),d([p()],_.prototype,"_availableUsers",2),d([p()],_.prototype,"_checklistText",2),d([p()],_.prototype,"_phaseDefs",2),d([p()],_.prototype,"_phaseSeq",2),d([p()],_.prototype,"_requiredCompletion",2),d([p()],_.prototype,"_scheduleTime",2),d([p()],_.prototype,"_scheduleTimeOn",2),d([p()],_.prototype,"_actionService",2),d([p()],_.prototype,"_actionTargetEntity",2),d([p()],_.prototype,"_actionSkipAuto",2),d([p()],_.prototype,"_actionPresent",2),d([p()],_.prototype,"_actionData",2),d([p()],_.prototype,"_actionDataJsonFallback",2),d([p()],_.prototype,"_actionTesting",2),d([p()],_.prototype,"_actionTestResult",2),d([p()],_.prototype,"_actionTestError",2),d([p()],_.prototype,"_qcNotes",2),d([p()],_.prototype,"_qcCost",2),d([p()],_.prototype,"_qcDuration",2),d([p()],_.prototype,"_qcFeedback",2),d([p()],_.prototype,"_environmentalEntity",2),d([p()],_.prototype,"_environmentalAttribute",2),d([p()],_.prototype,"_adaptiveEnabled",2),d([p()],_.prototype,"_adaptiveAlpha",2),d([p()],_.prototype,"_adaptiveMin",2),d([p()],_.prototype,"_adaptiveMax",2),d([p()],_.prototype,"_adaptiveSeasonal",2),d([p()],_.prototype,"_adaptivePrediction",2),d([p()],_.prototype,"_conditionAttrOptions",2);var We=_;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",We);async function Mi(r,a,e){let i=r.auth;if(i?.expired&&i.refreshAccessToken)try{await i.refreshAccessToken()}catch{}return fetch(a,{...e,headers:{...e.headers??{},Authorization:`Bearer ${i?.data?.access_token??""}`}})}var cr=500*1024*1024;async function Fi(r,a,e,i="doc_too_large",t=[]){let n=await Mi(r,a,{method:"POST",body:e});if(n.status===413)throw new Error(i);if(!n.ok){let o=await n.json().catch(()=>null);throw typeof o?.code=="string"&&t.includes(o.code)?new Error(o.code):new Error("doc_upload_failed")}return await n.json()}async function Di(r,a,e,i){let t=new FormData;t.append("entry_id",a);for(let o of i)t.append("tags",o);t.append("file",e,e.name);let n=await Fi(r,"/api/maintenance_supporter/document/upload",t);if(!n.id)throw new Error("doc_upload_failed");return{id:n.id,deduped:!!n.deduped,duplicate_in_object:n.duplicate_in_object??null}}async function Dt(r,a,e){return(await Di(r,a,e,["photo"])).id}async function Ge(r,a,e){await Promise.all(e.map(i=>r.connection.sendMessagePromise({type:"maintenance_supporter/documents/discard_upload",entry_id:a,doc_id:i}).catch(()=>{})))}var ce=class{constructor(a,e){this.host=a;this.opts=e;this.photos=[];this.uploadedIds=[];this.uploading=!1;this.errorKey="";this._session=0;this._uploadEntry=new Map;this.max=e.max??10,a.addController(this)}hostConnected(){}get ids(){return this.photos.map(a=>a.id)}get remaining(){return Math.max(this.max-this.photos.length,0)}get full(){return this.remaining===0}errorText(a){return this.errorKey?s(this.errorKey,a).replace("{max}",String(this.max)):""}clearError(){this.errorKey=""}reset(a=[]){this._endSession(),this._revokeAll(),this.photos=a.map(e=>({id:e,preview:""})),this.uploadedIds=[],this._uploadEntry.clear(),this.errorKey="",this.host.requestUpdate()}async addFiles(a){if(a.length===0)return;let e=this._session,i=this.opts.hass(),t=this.opts.entryId(),n=a.slice(0,this.remaining);this.uploading=!0,this.errorKey="",this.host.requestUpdate();try{for(let o of n){let c=await Dt(i,t,o);if(e!==this._session){Ge(i,t,[c]);return}this.uploadedIds=[...this.uploadedIds,c],this._uploadEntry.set(c,t),this.photos=[...this.photos,{id:c,preview:URL.createObjectURL(o)}],this.host.requestUpdate()}a.length>n.length&&(this.errorKey="photos_limit")}catch(o){if(e!==this._session)return;this.errorKey=o instanceof Error&&o.message==="doc_too_large"?"doc_too_large":"doc_upload_failed"}finally{e===this._session&&(this.uploading=!1,this.host.requestUpdate())}}remove(a){let e=this.photos.find(i=>i.id===a);e?.preview&&URL.revokeObjectURL(e.preview),this.photos=this.photos.filter(i=>i.id!==a),this.uploadedIds.includes(a)&&(this.uploadedIds=this.uploadedIds.filter(i=>i!==a),this._discard([a])),this.host.requestUpdate()}discardOrphans(){if(this._endSession(),this.uploadedIds.length===0)return;let a=this.uploadedIds;this.uploadedIds=[],this._discard(a)}markAttached(){this._endSession(),this.uploadedIds=[],this._uploadEntry.clear()}_endSession(){this._session++,this.uploading=!1}_discard(a){let e=new Map;for(let t of a){let n=this._uploadEntry.get(t)??this.opts.entryId();this._uploadEntry.delete(t),e.set(n,[...e.get(n)??[],t])}let i=this.opts.hass();for(let[t,n]of e)Ge(i,t,n)}_revokeAll(){for(let a of this.photos)a.preview&&URL.revokeObjectURL(a.preview)}};function qe(){if(window.externalApp!==void 0)return!0;let a=typeof navigator<"u"&&navigator.userAgent||"";return/Home Assistant\//.test(a)&&/Android/.test(a)}var Qe={objectSections:"msp-object-sections",printOptions:"msp-print-options",batteryRosterOpen:"msp-bf-roster-open",docSort:"msp-doc-sort",cameraLabel:"msp-camera-label",overviewTab:"msp-overview-tab",collapsedSections:"msp-collapsed-sections",chartRange:"msp-chart-range",chartHideOutliers:"msp-chart-hide-outliers",taskSort:"maintenance_supporter_sort",objectSort:"maintenance_supporter_object_sort",groupBy:"maintenance_supporter_groupby",objectView:"maintenance_supporter_object_view",objectsCache:"msp-objects-cache",gettingStartedDismissed:"msp-gs-dismissed",batteryRosterSort:"ms_bf_roster_sort",areaSort:"msp-area-sort"};function zt(r){try{return localStorage.getItem(r)}catch{return null}}function Ut(r,a){try{localStorage.setItem(r,a)}catch{}}function Qt(){if(!qe())return!1;let r=typeof navigator<"u"?navigator.mediaDevices:void 0;return!!r&&typeof r.getUserMedia=="function"}var zi=1920,Ui=.88,ji={retryMs:500,windowMs:5e3},Bi=new Set(["NotReadableError","AbortError","TrackStartError"]),jt=80,Kt=/back|rear|environment|rück|hinten/i,Bt=/front|user|selfie|vorne/i;function Vt(r){let a=/camera2?\s*(\d+)/i.exec(r);return a?Number(a[1]):Number.MAX_SAFE_INTEGER}function Wt(r,a){if(a){let i=r.find(t=>t.label===a);if(i)return i}return r.filter(i=>i.label&&Kt.test(i.label)).sort((i,t)=>Vt(i.label)-Vt(t.label))[0]??null}var Gt=r=>r?.name||"Error",Vi=r=>r?.message||"",q=class extends T{constructor(){super(...arguments);this.lang="en";this._open=!1;this._busy=!1;this._switching=!1;this._devices=[];this._deviceIndex=-1;this._switchFailed=!1;this._copied=!1;this.timing={...ji};this._facing="environment";this._stream=null;this._opening=!1;this._gen=0;this._refused=new Set;this._log=[];this._t0=0;this._lastError=""}async open(){if(this._open||this._opening)return;this._opening=!0;let e=++this._gen;try{await this._acquireAndShow(e)}finally{this._opening=!1}}_live(e){return e===this._gen&&this.isConnected}async _acquireAndShow(e){let i=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!i||typeof i.getUserMedia!="function"){this._unavailable("no_media_devices");return}this._log=[],this._t0=Date.now(),this._lastError="",this._refused.clear(),this._switchFailed=!1,this._copied=!1,this._note(navigator.userAgent);let t=zt(Qe.cameraLabel),n=await this._enumerate(i);if(!this._live(e))return;let o=Wt(n,t),c="refused";if(o&&(c=await this._openPatiently(i,e,this._byDevice(o))),c==="cancelled")return;if(c!=="ok"){if(c=await this._openPatiently(i,e,{video:{facingMode:{ideal:"environment"}},what:"facing environment"}),c==="cancelled")return;if(c!=="ok"){this._unavailable(this._lastError||"camera_unavailable");return}if(n=await this._enumerate(i),!this._live(e)){this._stopStream();return}}if(this._devices=n,this._deviceIndex=this._indexOfCurrent(),this._facing=this._currentFacing(),this._open=!0,await this.updateComplete,!this._live(e)){this._stopStream(),this._open=!1;return}await this._attach();let u=o?null:Wt(n,t),m=this._deviceIndex>=0?n[this._deviceIndex]:void 0;if(!u||u.deviceId===m?.deviceId)return;let g=await this._replace(i,e,[this._byDevice(u)],this._restoreCandidates(m));if(g!=="cancelled"){if(g==="lost"){this._unavailable("camera_lost");return}this._settle(g)}}async _openPatiently(e,i,t){let n=Date.now();for(;;){let o;try{o=await e.getUserMedia({video:t.video,audio:!1})}catch(c){let u=Gt(c),m=Vi(c);if(this._lastError=u,this._note(`${t.what} \u2192 ${u}${m&&m!==u?`: ${m}`:""}`),!this._live(i))return"cancelled";if(!Bi.has(u))return"refused";if(Date.now()-n+this.timing.retryMs>this.timing.windowMs)return"busy";if(await new Promise(g=>setTimeout(g,this.timing.retryMs)),!this._live(i))return"cancelled";continue}if(!this._live(i)){for(let c of o.getTracks())c.stop();return"cancelled"}return this._stream=o,this._note(`${t.what} \u2192 ok (${this._describeTrack()})`),"ok"}}async _replace(e,i,t,n){this._switching=!0,this._stopStream();try{for(let o of t){let c=await this._openPatiently(e,i,o);if(c==="ok")return o;if(c==="cancelled")return c;if(c==="busy"){o.deviceId&&this._refused.add(o.deviceId);break}}for(let o of n){let c=await this._openPatiently(e,i,o);if(c==="ok")return"restored";if(c==="cancelled")return c}return"lost"}finally{this._switching=!1}}_settle(e){if(e==="restored"){this._switchFailed=!0;let t=this._indexOfCurrent();return t>=0&&(this._deviceIndex=t),this._attach(),!1}this._switchFailed=!1;let i=e.deviceId?this._devices.findIndex(t=>t.deviceId===e.deviceId):-1;return this._deviceIndex=i>=0?i:this._indexOfCurrent(),this._facing=this._currentFacing(),this._attach(),!0}_byDevice(e){return{video:{deviceId:{exact:e.deviceId}},what:e.label||"camera (no label)",deviceId:e.deviceId}}_restoreCandidates(e,i){let t=[],n=e?.deviceId||i;return n&&t.push({video:{deviceId:{exact:n}},what:`${e?.label||"previous camera"} (back again)`,deviceId:n}),t.push({video:{facingMode:{ideal:this._facing}},what:`facing ${this._facing} (back again)`}),t}async _attach(){let e=this._video;if(!(!e||!this._stream)){e.srcObject=this._stream;try{await e.play()}catch{}}}async _enumerate(e){if(typeof e.enumerateDevices!="function")return[];try{let i=(await e.enumerateDevices()).filter(t=>t.kind==="videoinput"&&!!t.deviceId);return this._note(`cameras: ${i.map(t=>t.label||"(no label)").join(" | ")||"none listed"}`),i}catch(i){return this._note(`enumerateDevices \u2192 ${Gt(i)}`),[]}}_indexOfCurrent(){let e=this._stream?.getVideoTracks()[0];if(!e)return-1;let i=e.getSettings().deviceId,t=i?this._devices.findIndex(n=>n.deviceId===i):-1;return t>=0?t:e.label?this._devices.findIndex(n=>n.label===e.label):-1}_currentFacing(){let e=this._stream?.getVideoTracks()[0],i=e?.getSettings().facingMode;if(i==="user"||i==="environment")return i;let t=(this._deviceIndex>=0?this._devices[this._deviceIndex]?.label:"")||e?.label||"";return Bt.test(t)?"user":Kt.test(t)?"environment":this._facing}_describeTrack(){let e=this._stream?.getVideoTracks()[0];if(!e)return"no track";let i=e.getSettings(),t=i.width&&i.height?`${i.width}\xD7${i.height}`:"size ?";return[e.label||"no label",t,i.facingMode].filter(Boolean).join(", ")}_note(e){this._log.push(`+${Date.now()-this._t0} ms ${e}`),this._log.length>jt&&this._log.splice(1,this._log.length-jt)}async _switchCamera(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e||this._devices.length<2||this._busy||this._switching)return;let i=this._gen,t=this._deviceIndex,n=t>=0?this._devices[t]:void 0,o=this._stream?.getVideoTracks()[0]?.getSettings().deviceId||n?.deviceId,c=this._facing==="user"?"environment":"user",u=this._nextCameras(t,o);!u.length&&this._refused.size&&(this._refused.clear(),u=this._nextCameras(t,o)),this._note(`switch from ${n?.label||"unknown camera"}`);let m=[...u.map(g=>this._byDevice(this._devices[g])),{video:{facingMode:{exact:c}},what:`facing ${c} (exact)`},{video:{facingMode:{ideal:c}},what:`facing ${c}`}];this._busy=!0,this._switchFailed=!1,this._copied=!1;try{let g=await this._replace(e,i,m,this._restoreCandidates(n,o));if(g==="cancelled")return;if(g==="lost"){this._unavailable("camera_lost");return}if(g!=="restored"&&!g.deviceId){if(this._isCamera(o,this._facing)){this._switchFailed=!0,await this._attach();return}this._facing=c}if(this._settle(g)&&g!=="restored"&&g.deviceId){let f=this._devices[this._deviceIndex]?.label??"";f&&Ut(Qe.cameraLabel,Bt.test(f)?"":f)}}finally{this._busy=!1}}_nextCameras(e,i){let t=this._devices.length,n=[];for(let o=1;o<=(e<0?t:t-1);o++){let c=(e+o)%t,u=this._devices[c].deviceId;u===i||this._refused.has(u)||n.push(c)}return n}_isCamera(e,i){let t=this._stream?.getVideoTracks()[0]?.getSettings();return e&&t?.deviceId?t.deviceId===e:!!t?.facingMode&&t.facingMode===i}close(){this._gen++,this._stopStream(),this._open=!1,this._busy=!1,this._switching=!1}disconnectedCallback(){super.disconnectedCallback(),this._gen++,this._stopStream()}get _video(){return this.shadowRoot?.querySelector("video")??null}_stopStream(){for(let i of this._stream?.getTracks()??[])i.stop();this._stream=null;let e=this._video;e&&(e.srcObject=null)}_unavailable(e){this._stopStream(),this._open=!1,this.dispatchEvent(new CustomEvent("capture-unavailable",{detail:{reason:e},bubbles:!0,composed:!0}))}async _copyLog(){let e=this._log.join(` `),i=!1;try{navigator.clipboard?.writeText&&(await navigator.clipboard.writeText(e),i=!0)}catch{}if(!i){let t=this.shadowRoot?.querySelector(".details textarea");if(t){t.focus(),t.select();try{i=document.execCommand("copy")}catch{i=!1}}}this._copied=i}async _shoot(){let e=this._video;if(!(!e||this._busy||this._switching)){this._busy=!0;try{let i=e.videoWidth||640,t=e.videoHeight||480,n=Math.min(1,zi/Math.max(i,t)),o=document.createElement("canvas");o.width=Math.round(i*n),o.height=Math.round(t*n);let c=o.getContext("2d");if(!c)throw new Error("no_canvas");c.drawImage(e,0,0,o.width,o.height);let u=await new Promise(f=>o.toBlob(f,"image/jpeg",Ui));if(!u)throw new Error("no_blob");let m=new Date().toISOString().replace(/[-:]/g,"").slice(0,15),g=new File([u],`photo-${m}.jpg`,{type:"image/jpeg"});this.close(),this.dispatchEvent(new CustomEvent("photo-captured",{detail:{file:g},bubbles:!0,composed:!0}))}catch(i){this._unavailable(i instanceof Error?i.message:String(i))}finally{this._busy=!1}}}render(){if(!this._open)return h;let e=this.lang,i=this._busy||this._switching;return l` `}};q.styles=w` :host { display: contents; } .overlay { position: fixed; inset: 0; z-index: 10000; background: #000; color: #fff; display: flex; flex-direction: column; } video { flex: 1; min-height: 0; width: 100%; object-fit: contain; background: #000; } .bar { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px)); background: rgba(0, 0, 0, 0.8); } button { font: inherit; border-radius: 24px; padding: 10px 18px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; } .cancel { background: transparent; color: #fff; border: 1px solid rgba(255, 255, 255, 0.6); } .switch { background: transparent; color: #fff; border: 1px solid rgba(255, 255, 255, 0.6); padding: 10px 12px; } .switch[disabled] { opacity: 0.5; cursor: default; } .switch ha-icon { --mdc-icon-size: 22px; } .switch-pos { font-size: 12px; opacity: 0.85; } .switching { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); padding: 8px 16px; border-radius: 16px; background: rgba(0, 0, 0, 0.6); font-size: 14px; } .switch-note { position: absolute; left: 12px; right: 12px; bottom: 84px; max-height: 60%; overflow: auto; text-align: center; color: #fff; font-size: 13px; text-shadow: 0 1px 2px #000; } .details { margin-top: 6px; text-align: start; text-shadow: none; } .details summary { cursor: pointer; text-align: center; opacity: 0.85; } .details textarea { display: block; box-sizing: border-box; width: 100%; margin: 6px 0; font: 11px/1.35 monospace; color: #fff; background: rgba(255, 255, 255, 0.12); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 6px; padding: 6px; resize: vertical; } .copy { background: transparent; color: #fff; border: 1px solid rgba(255, 255, 255, 0.6); padding: 6px 14px; font-size: 13px; } .shoot { background: var(--primary-color, #03a9f4); color: #fff; border: none; font-weight: 600; } .shoot[disabled] { opacity: 0.6; cursor: default; } .shoot ha-icon { --mdc-icon-size: 22px; } `,d([v({type:String})],q.prototype,"lang",2),d([p()],q.prototype,"_open",2),d([p()],q.prototype,"_busy",2),d([p()],q.prototype,"_switching",2),d([p()],q.prototype,"_devices",2),d([p()],q.prototype,"_deviceIndex",2),d([p()],q.prototype,"_switchFailed",2),d([p()],q.prototype,"_copied",2);customElements.get("ms-camera-capture")||customElements.define("ms-camera-capture",q);var He=w` ms-photo-picker { display: contents; } .photo-pickers { display: flex; flex-wrap: wrap; gap: 8px; } .photo-pick { display: inline-flex; flex-direction: row; align-items: center; gap: 8px; padding: 8px 12px; border: 1px dashed var(--divider-color); border-radius: 8px; cursor: pointer; font-size: 13px; color: var(--secondary-text-color); width: fit-content; } .photo-pick:hover { border-color: var(--primary-color); } .photo-pick:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; } .photo-pick.disabled { opacity: 0.6; cursor: default; } .photo-pick input[type="file"] { display: none; } .photo-android-hint { font-size: 12px; color: var(--secondary-text-color); margin-top: 4px; } `,H=class extends T{constructor(){super(...arguments);this.lang="en";this.disabled=!1;this.busy=!1;this.accept="image/*";this.showCamera=!0;this.showGallery=!0;this.compact=!1;this.remaining=1/0;this._singlePick=qe();this._inAppCamera=Qt()}createRenderRoot(){return this}get _locked(){return this.disabled||this.busy}_emit(e){e.length!==0&&this.dispatchEvent(new CustomEvent("files-picked",{detail:{files:e},bubbles:!0,composed:!0}))}_onInput(e){let i=e.target,t=Array.from(i.files??[]);i.value="",this._emit(t)}_onCameraClick(e){!this._inAppCamera||this._locked||(e.preventDefault(),this.querySelector("ms-camera-capture")?.open())}_onCameraUnavailable(){this._inAppCamera=!1,this.querySelector(".photo-pick-camera input")?.click()}_onKeydown(e){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),!this._locked&&e.currentTarget.click())}render(){if(this.remaining<=0||!this.showCamera&&!this.showGallery)return h;let e=this.lang,i=this._locked?"disabled":"",t=this.busy?s("uploading",e):s("doc_camera",e),n=s(this._singlePick?"choose_photo":"choose_photos",e);return l`
${this.showCamera?l``:h} ${this.showGallery?l``:h}
${this.showGallery&&this._singlePick?l`
${s("photos_android_hint",e)}
`:h} ${this.showCamera&&this._inAppCamera?l`this._emit([o.detail.file])} @capture-unavailable=${this._onCameraUnavailable}>`:h} `}};d([v({type:String})],H.prototype,"lang",2),d([v({type:Boolean})],H.prototype,"disabled",2),d([v({type:Boolean})],H.prototype,"busy",2),d([v({type:String})],H.prototype,"accept",2),d([v({type:Boolean})],H.prototype,"showCamera",2),d([v({type:Boolean})],H.prototype,"showGallery",2),d([v({type:Boolean})],H.prototype,"compact",2),d([v({type:Number})],H.prototype,"remaining",2),d([p()],H.prototype,"_inAppCamera",2);customElements.get("ms-photo-picker")||customElements.define("ms-photo-picker",H);var pe=Y,y=class extends T{constructor(){super(...arguments);this.entryId="";this.taskId="";this.taskName="";this.lang="en";this.checklist=[];this.adaptiveEnabled=!1;this.taskType="";this.readingUnit="";this.readings=[];this.readingHistory=[];this.restockDefault=null;this.restockUnitCost=null;this.restockPackage="";this.currencySymbol="";this.partsCostMode="purchase";this.parts=[];this.consumesParts=[];this.consumesInfo=[];this.requiredFields=[];this.phaseLabel="";this.requireTagScan=!1;this.viaTagScan=!1;this._open=!1;this._notes="";this._cost="";this._duration="";this._loading=!1;this._error="";this._checklistState={};this._feedback="needed";this._photos=new ce(this,{entryId:()=>this.entryId,hass:()=>this.hass});this._readingValue="";this._readingValues={};this._restockQty="";this._completedAt="";this._usedParts={};this._usedQtyText={};this.checklistPrefill={}}open(e={}){this._open||(this._open=!0,this.viaTagScan=!!e.viaTagScan,this._notes="",this._cost="",this._duration="",this._error="",this._checklistState=Object.fromEntries(this.checklist.map((i,t)=>[String(t),!!this.checklistPrefill[i]]).filter(([,i])=>i)),this._feedback="needed",this._photos.reset(),this._readingValue="",this._readingValues={},this._restockQty=this.restockDefault!==null?String(this.restockDefault):"",this._completedAt="",this._usedParts=Object.fromEntries(this.consumesParts.map(i=>[j(i),{...i}])),this._usedQtyText={})}_rangeError(e,i){let t=this.lang;return s("settings_value_out_of_range",t).replace("{min}",E(e,t,{maximumFractionDigits:2})).replace("{max}",E(i,t,{maximumFractionDigits:2}))}_toggleCheck(e){let i=String(e);this._checklistState={...this._checklistState,[i]:!this._checklistState[i]}}_setFeedback(e){this._feedback=e}async _complete(){if(this._loading||this._photos.uploading)return;this._error="",this._photos.clearError();let e={type:"maintenance_supporter/task/complete",entry_id:this.entryId,task_id:this.taskId},i=this._notes.trim();if(i&&(e.notes=i),this._cost){let c=parseFloat(this._cost);isNaN(c)||(e.cost=c)}let t=de(this._duration);if(t!==null&&(e.duration=t),this.checklist.length>0&&(e.checklist_state=this._checklistState),this.adaptiveEnabled&&(e.feedback=this._feedback),this._photos.photos.length>0&&(e.photo_doc_ids=this._photos.ids),this.viaTagScan&&(e.via_tag_scan=!0),this._completedAt){if(ee(this._completedAt)>Date.now()){this._error=s("completed_at_future_error",this.lang);return}e.completed_at=this._completedAt.length===16?`${this._completedAt}:00`:this._completedAt}if(this.readings.length>0){let c={};for(let u of this.readings){let m=(this._readingValues[u.id]??"").trim();if(m==="")continue;let g=parseFloat(m.replace(",","."));isNaN(g)||(c[u.id]=g)}Object.keys(c).length>0&&(e.reading_values=c)}else if(this._readingValue!==""){let c=parseFloat(this._readingValue);isNaN(c)||(e.reading_value=c)}if(this.restockDefault!==null&&this._restockQty.trim()!==""){let c=parseFloat(this._restockQty.replace(",","."));if(!Number.isFinite(c)||coe[1]){this._error=this._rangeError(...oe);return}e.restock_quantity=c}if(this.parts.length>0){let c=[];for(let[u,m]of Object.entries(this._usedParts)){let g=this._usedQtyText[u],f=g===void 0?m.quantity:parseFloat(g.replace(",","."));if(!Number.isFinite(f)||fpe[1]){this._error=this._rangeError(...pe);return}c.push({...m,quantity:f})}e.used_parts=c.map(u=>u.entry_id?{part_id:u.part_id,quantity:u.quantity,entry_id:u.entry_id}:{part_id:u.part_id,quantity:u.quantity})}let n=await A(this,e,{busy:c=>{this._loading=c},lang:this.lang,fallbackKey:"save_error",onError:c=>{this._error=c}});if(n===void 0)return;this._photos.markAttached(),this._open=!1;let o={entryId:this.entryId,taskId:this.taskId,taskName:this.taskName,undo:n?.undo===!0};this.dispatchEvent(new CustomEvent("task-completed",{detail:o}))}_renderReadingField(e,i){let t=this._completedAt?ee(this._completedAt):NaN,n=dt(this.readingHistory,e.id,isNaN(t)?void 0:t),o=e.unit||this.readingUnit,c=(this._readingValues[e.id]??"").trim(),u=c===""?NaN:parseFloat(c.replace(",",".")),m=n!==void 0&&!isNaN(u)&&u ${e.name}${o?` (${o})`:""} {this._readingValues={...this._readingValues,[e.id]:f.target.value}}} /> ${m?l`${s("reading_below_last",i).replace("{value}",g)}`:h} `}get _missingRequired(){let e={notes:this._notes.trim()!=="",cost:this._cost.trim()!=="",duration:this._duration.trim()!=="",photo:this._photos.photos.length>0,user:!!this.hass?.user};return this.requiredFields.filter(i=>!e[i])}_demands(e){return this.requiredFields.includes(e)}_req(e){return this._demands(e)?l``:h}_purchaseSuggestion(){if(this.restockDefault===null)return null;let e=parseFloat(this._restockQty);return this.restockUnitCost==null||!Number.isFinite(e)||e<=0?null:Math.round(this.restockUnitCost*e*100)/100}_partsValue(){if(this.restockDefault!==null||!this.parts.length)return null;let e=0,i=!1;for(let t of Object.values(this._usedParts)){let n=this.parts.find(c=>j({part_id:c.id,entry_id:c.entry_id})===j(t)),o=kt(n);o!==null&&(e+=o*(t.quantity||1),i=!0)}return i?Math.round(e*100)/100:null}_renderCostSuggestion(e){let i=this._purchaseSuggestion();if(this.restockDefault!==null){let c=this.partsCostMode==="use"?l`
${s("cost_purchase_use_hint",e)}
`:h;if(this._cost.trim()!==""||i==null||i<=0)return c;let u=z(i,this.currencySymbol,e);return l`${c}`}let t=this._partsValue();if(t==null||t<=0)return h;let n=z(t,this.currencySymbol,e),o=this.partsCostMode==="use"?"cost_parts_booked":"cost_parts_info";return l`
${s(o,e).replace("{amount}",n)}
`}_close(){this._open=!1,this._photos.discardOrphans()}_pickCompletedAt(){this._completedAt=`${st()}:00`}render(){if(!this._open)return l``;let e=this.lang||this.hass?.language||"en",i=this._error||this._photos.errorText(e);return l`
${s("complete_title",e)}${this.taskName}
${this.phaseLabel?l`
${s("phase_current",e)}: ${this.phaseLabel}
`:h} ${this.requireTagScan&&!this.viaTagScan?l`
${s("require_tag_scan_hint",e)}
`:h}
${i?l`
${i}
`:h} ${this.checklist.length>0?l`
${this.checklist.map((t,n)=>l` `)}
`:h} ${this.readings.length>0?l`
${s("readings_section",e)} ${this.readings.map(t=>this._renderReadingField(t,e))}
`:this.taskType==="reading"?l` `:h} ${this.parts.length?l`
${s("complete_parts_used",e)} ${this.parts.map(t=>{let n=j({part_id:t.id,entry_id:t.entry_id}),o=this._usedParts[n],c=o!==void 0,u=t.entry_id?{part_id:t.id,quantity:1,entry_id:t.entry_id}:{part_id:t.id,quantity:1};return l`
${c?l`{let g=m.target.value;this._usedQtyText={...this._usedQtyText,[n]:g};let f=parseFloat(g.replace(",","."));Number.isFinite(f)&&f>=pe[0]&&(this._usedParts={...this._usedParts,[n]:{...u,quantity:f}})}} />`:h}
`})}
`:this.consumesInfo.length?l`
${this.consumesInfo.map(t=>l`
${t}
`)}
`:h} ${this.restockDefault!==null?l` `:h}
${this._demands("cost")?s("cost",e):s("cost_optional",e)}${this._req("cost")} this._cost=t.detail.value}> ${this._renderCostSuggestion(e)}
${s("completed_at_optional",e)} ${this._completedAt?l`this._completedAt=t.detail.value} >`:l``}
${this._demands("photo")?s("completion_photos",e):s("completion_photos_optional",e)}${this._req("photo")} ${this._photos.photos.length>0?l`
${this._photos.photos.map(t=>l`
`)}
`:h} ${this._photos.full?l`
${s("photos_limit",e).replace("{max}",String(this._photos.max))}
`:l`this._photos.addFiles(t.detail.files)} >`}
${this.adaptiveEnabled?l` `:h}
${s("cancel",e)} 0} title=${this._photos.uploading?s("uploading",e):this._missingRequired.length?this._missingRequired.map(t=>s("err_required",e).replace("{field}",s(ye[t]??t,e))).join(" \xB7 "):""} > ${this._loading?s("completing",e):s("complete",e)}
`}};y.styles=[Ae,He,w` .req-mark { color: var(--error-color, #f44336); margin-left: 2px; font-weight: 600; } .notes-input { resize: vertical; line-height: 1.4; } /* #104: one-click cost suggestion from parts — quiet link-style chip. */ .cost-note { font-size: 12px; color: var(--secondary-text-color); margin-top: 4px; line-height: 1.4; } .cost-suggestion { align-self: flex-start; margin-top: 4px; padding: 0; border: none; background: none; color: var(--primary-color); font-size: 12.5px; cursor: pointer; text-decoration: underline dotted; text-underline-offset: 2px; } .dialog-title { font-size: 18px; font-weight: 500; padding-bottom: 12px; } .scan-required-note { margin: -4px 0 12px; padding: 8px 10px; border-radius: 6px; background: rgba(255, 152, 0, 0.12); color: var(--primary-text-color); font-size: 13px; } .phase-line { margin-top: -8px; padding-bottom: 12px; font-size: 13px; color: var(--secondary-text-color); } .content { display: flex; flex-direction: column; gap: 16px; min-width: 300px; } .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; } .consumes-hint { font-size: 13px; color: var(--secondary-text-color); border-left: 3px solid var(--primary-color); padding: 4px 8px; margin: 4px 0 8px; } /* #99: editable per-completion parts selection */ .used-parts { margin: 4px 0 8px; display: flex; flex-direction: column; gap: 4px; } .used-part-row { display: flex; align-items: center; gap: 8px; } .used-part-check { display: flex; align-items: center; gap: 6px; flex: 1; font-size: 13px; cursor: pointer; } .used-part-check input { cursor: pointer; } /* #111: whose stock this row draws on. Muted but never omitted — an unlabelled foreign pool is indistinguishable from an own part. */ .used-part-owner { color: var(--secondary-text-color); } .used-part-qty { width: 76px; padding: 4px 6px; border-radius: 4px; font: inherit; font-size: 13px; border: 1px solid var(--divider-color); background: var(--card-background-color); color: var(--primary-text-color); } .error { color: var(--error-color, #f44336); font-size: 13px; } /* .field/.field-label/.field-input come from nativeFieldStyles */ /* #161 phase 2: the per-slot reading fields */ .readings-block { display: flex; flex-direction: column; gap: 8px; } .readings-block > .field-label { margin-bottom: -4px; } .reading-warn { font-size: 12px; color: var(--warning-color, #ff9800); } /* .photo-pick / .photo-pickers / .photo-android-hint come from photoPickerStyles */ /* #163: the backdate moment starts EMPTY (= now); the button seeds the HA date+time picker with the current minute instead of the picker's own 00:00 default, so a backdated completion never lands at midnight by accident. */ .backdate-pick { display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; border: 1px dashed var(--divider-color); border-radius: 8px; background: transparent; cursor: pointer; font: inherit; font-size: 13px; color: var(--secondary-text-color); width: fit-content; --mdc-icon-size: 18px; } .backdate-pick:hover { border-color: var(--primary-color); } /* #161: several photos per completion — tiles wrap into a strip, the two pickers (camera / gallery) sit underneath while there is room left under the cap. */ .photo-strip { display: flex; flex-wrap: wrap; gap: 12px; margin: 8px 0; /* room for the remove badges above the tiles */ } .photo-limit { font-size: 12px; color: var(--secondary-text-color); } .photo-preview { position: relative; width: fit-content; } /* Uniform tiles: a tiny or portrait shot must not collapse the strip. */ .photo-preview img { width: 96px; height: 96px; object-fit: cover; border-radius: 8px; display: block; background: var(--secondary-background-color, rgba(0,0,0,0.06)); } .photo-remove { position: absolute; top: -8px; right: -8px; width: 24px; height: 24px; border-radius: 50%; border: none; background: var(--error-color, #db4437); color: #fff; cursor: pointer; font-size: 12px; line-height: 1; } .checklist-section { display: flex; flex-direction: column; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--divider-color); margin-bottom: 4px; } .checklist-label { font-weight: 500; font-size: 13px; color: var(--secondary-text-color); } .checklist-item { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 4px 0; font-size: 14px; } .checklist-item input[type="checkbox"] { width: 18px; height: 18px; cursor: pointer; } .feedback-section { display: flex; flex-direction: column; gap: 8px; padding: 8px 0; border-top: 1px solid var(--divider-color); } .feedback-label { font-weight: 500; font-size: 13px; color: var(--secondary-text-color); } .feedback-buttons { display: flex; gap: 8px; } .feedback-btn { flex: 1; padding: 8px 12px; border: 1px solid var(--divider-color); border-radius: 8px; background: var(--card-background-color, #fff); color: var(--primary-text-color); font-size: 13px; cursor: pointer; text-align: center; transition: all 0.2s; } .feedback-btn:hover { background: var(--secondary-background-color, #f5f5f5); } .feedback-btn.selected { background: var(--primary-color); color: var(--text-primary-color, #fff); border-color: var(--primary-color); } `],d([v({attribute:!1})],y.prototype,"hass",2),d([v()],y.prototype,"entryId",2),d([v()],y.prototype,"taskId",2),d([v()],y.prototype,"taskName",2),d([v()],y.prototype,"lang",2),d([v({type:Array})],y.prototype,"checklist",2),d([v({type:Boolean})],y.prototype,"adaptiveEnabled",2),d([v()],y.prototype,"taskType",2),d([v()],y.prototype,"readingUnit",2),d([v({attribute:!1})],y.prototype,"readings",2),d([v({attribute:!1})],y.prototype,"readingHistory",2),d([v({attribute:!1})],y.prototype,"restockDefault",2),d([v({attribute:!1})],y.prototype,"restockUnitCost",2),d([v({attribute:!1})],y.prototype,"restockPackage",2),d([v()],y.prototype,"currencySymbol",2),d([v({attribute:!1})],y.prototype,"partsCostMode",2),d([v({attribute:!1})],y.prototype,"parts",2),d([v({attribute:!1})],y.prototype,"consumesParts",2),d([v({type:Array})],y.prototype,"consumesInfo",2),d([v({type:Array})],y.prototype,"requiredFields",2),d([v()],y.prototype,"phaseLabel",2),d([v({type:Boolean})],y.prototype,"requireTagScan",2),d([v({type:Boolean})],y.prototype,"viaTagScan",2),d([p()],y.prototype,"_open",2),d([p()],y.prototype,"_notes",2),d([p()],y.prototype,"_cost",2),d([p()],y.prototype,"_duration",2),d([p()],y.prototype,"_loading",2),d([p()],y.prototype,"_error",2),d([p()],y.prototype,"_checklistState",2),d([p()],y.prototype,"_feedback",2),d([p()],y.prototype,"_readingValue",2),d([p()],y.prototype,"_readingValues",2),d([p()],y.prototype,"_restockQty",2),d([p()],y.prototype,"_completedAt",2),d([p()],y.prototype,"_usedParts",2),d([p()],y.prototype,"_usedQtyText",2),d([v({attribute:!1})],y.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",y);var he=w` .backdrop { position: fixed; inset: 0; z-index: 100; background: rgba(0,0,0,0.5); } .dialog { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 95vw; max-width: var(--ms-modal-max-width, 480px); max-height: var(--ms-modal-max-height, 92vh); overflow: auto; background: var(--card-background-color, var(--ha-card-background, #1c1c1c)); color: var(--primary-text-color); border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.4); padding: 20px; display: flex; flex-direction: column; gap: var(--ms-modal-gap, 14px); z-index: 101; } /* Focused programmatically on open (so Escape works at once) — no ring. */ .dialog:focus { outline: none; } `;function Wi(r,a){r.key!=="Escape"||r.defaultPrevented||r.composedPath().some(e=>e instanceof Element&&e.localName==="ms-camera-capture")||(r.preventDefault(),r.stopPropagation(),a())}function ue(r,a){return l`
`}function _e(r){r?.querySelector(".dialog")?.focus({preventScroll:!0})}function Yt(r,a,e){let i=new Blob([r],{type:e}),t=URL.createObjectURL(i),n=document.createElement("a");n.href=t,n.download=a,n.target="_blank",n.rel="noopener",n.style.display="none",document.body.appendChild(n),n.dispatchEvent(new MouseEvent("click")),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),6e4)}async function Gi(r,a,e=300){return(await r.connection.sendMessagePromise({type:"auth/sign_path",path:a,expires:e})).path}async function Jt(r,a,e=300){return Gi(r,`/api/maintenance_supporter/document/${a}`,e)}var Z=class extends T{constructor(){super(...arguments);this.docId="";this._url="";this._failed=!1;this._signedFor=""}updated(){this.hass&&this.docId&&this._signedFor!==this.docId&&(this._signedFor=this.docId,this._url="",this._failed=!1,this._sign())}async _sign(){try{this._url=await Jt(this.hass,this.docId)}catch{this._failed=!0}}render(){return this._failed||!this.docId?h:this._url?l` this._failed=!0} /> `:l`
`}};Z.styles=w` .wrap { display: inline-block; margin-top: 4px; } /* #161: uniform 96px tiles — several photos sit in a strip, so a tiny or portrait shot must not collapse its slot. */ img { width: 96px; height: 96px; object-fit: cover; border-radius: 6px; display: block; border: 1px solid var(--divider-color); box-sizing: border-box; } .ph { width: 96px; height: 96px; border-radius: 6px; background: var(--secondary-background-color, rgba(0,0,0,0.06)); margin-top: 4px; } `,d([v({attribute:!1})],Z.prototype,"hass",2),d([v()],Z.prototype,"docId",2),d([p()],Z.prototype,"_url",2),d([p()],Z.prototype,"_failed",2);customElements.get("maintenance-history-photo")||customElements.define("maintenance-history-photo",Z);var R=class extends T{constructor(){super(...arguments);this._open=!1;this._saving=!1;this._error="";this._draft=null;this._originalSnapshot=null;this._partOptions=null;this._partQty={};this._partQtyOriginal="";this._openGen=0;this._photos=new ce(this,{entryId:()=>this._draft?.entry_id??"",hass:()=>this.hass});this._photosOriginal="";this._readingRows=[];this._readingText={};this._readingsOriginal=""}get _lang(){return P(this.hass)}openEdit(e){this._openGen++,this._draft={...e},this._originalSnapshot={...e},this._error="",this._open=!0,this._partOptions=null,this._partQty={},this._partQtyOriginal="",this._photos.reset(e.photo_doc_ids??[]),this._photosOriginal=JSON.stringify(this._photos.ids),this._seedReadings(e),this._loadPartOptions()}_seedReadings(e){let i=[],t=new Set;for(let o of e.readings??[])t.has(o.id)||(t.add(o.id),i.push({id:o.id,name:o.name,unit:o.unit??null}));for(let o of e.reading_values??[])t.has(o.id)||(t.add(o.id),i.push({id:o.id,name:o.name,unit:o.unit??null}));this._readingRows=i;let n={};for(let o of e.reading_values??[])n[o.id]=String(o.value);this._readingText=n,this._readingsOriginal=JSON.stringify(this._readingNumbers())}_readingNumbers(){let e={};for(let i of this._readingRows){let t=(this._readingText[i.id]??"").trim();if(t==="")continue;let n=parseFloat(t.replace(",","."));isNaN(n)||(e[i.id]=n)}return e}async _loadPartOptions(){let e=this._draft;if(!e)return;let i=this._openGen;try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/parts/overview"});if(i!==this._openGen)return;let n=[];for(let c of t.parts||[]){let u=c.entry_id===e.entry_id,m=c.consumers.some(g=>g.entry_id===e.entry_id&&g.task_id===e.task_id);!u&&!m||n.push({part_id:c.part_id,name:c.name,entry_id:c.entry_id,foreign:!u,object_name:c.object_name})}for(let c of e.used_parts||[]){let u=c.entry_id||e.entry_id;n.some(m=>m.part_id===c.part_id&&m.entry_id===u)||n.push({part_id:c.part_id,name:c.name||c.part_id,entry_id:u,foreign:u!==e.entry_id,object_name:null})}let o={};for(let c of e.used_parts||[])o[`${c.entry_id||e.entry_id}:${c.part_id}`]=c.quantity??1;this._partOptions=n,this._partQty=o,this._partQtyOriginal=this._partSelectionKey()}catch{if(i!==this._openGen)return;this._partOptions=[]}}_partSelectionKey(){return JSON.stringify(Object.entries(this._partQty).filter(([,e])=>e>0).sort(([e],[i])=>e.localeCompare(i)))}close(){this._openGen++,this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null,this._photos.discardOrphans()}_set(e,i){this._draft&&(this._draft={...this._draft,[e]:i})}async _delete(){if(!this._draft||!this._originalSnapshot)return;let e=this._lang,t=(this._originalSnapshot.used_parts||[]).filter(u=>u.quantity>0).map(u=>`${E(u.quantity,e)}\xD7 ${u.name||u.part_id}`).join(", ");if(!await te(this.hass,{title:s("history_delete_entry",e),message:t?`${s("history_delete_confirm_entry",e)} ${s("history_delete_returns_parts",e).replace("{parts}",t)}`:s("history_delete_confirm_entry",e),confirmText:s("delete",e),danger:!0})||!this._draft||!this._originalSnapshot)return;let o=this._draft;this._error="",await this._runWs({type:"maintenance_supporter/task/history/delete",entry_id:o.entry_id,task_id:o.task_id,timestamp:this._originalSnapshot.original_timestamp})!==void 0&&(this.dispatchEvent(new CustomEvent("history-entry-saved",{detail:{entry_id:o.entry_id,task_id:o.task_id,deleted:!0},bubbles:!0,composed:!0})),this.close())}_runWs(e){return A(this,e,{busy:i=>{this._saving=i},onError:i=>{this._error=i}})}async _save(){if(!this._draft||!this._originalSnapshot||this._saving||this._photos.uploading)return;this._error="",this._photos.clearError();let e=this._draft,i=this._originalSnapshot,t={type:"maintenance_supporter/task/history/update",entry_id:e.entry_id,task_id:e.task_id,original_timestamp:i.original_timestamp};if(e.timestamp!==i.timestamp&&(t.timestamp=e.timestamp),e.notes!==i.notes&&(t.notes=e.notes),e.cost!==i.cost&&(t.cost=e.cost),e.duration!==i.duration&&(t.duration=e.duration),e.completed_by!==i.completed_by&&(t.completed_by=e.completed_by),this._partOptions!==null&&this._partSelectionKey()!==this._partQtyOriginal&&(t.used_parts=(this._partOptions||[]).filter(o=>(this._partQty[`${o.entry_id}:${o.part_id}`]||0)>0).map(o=>({part_id:o.part_id,quantity:this._partQty[`${o.entry_id}:${o.part_id}`],...o.foreign?{entry_id:o.entry_id}:{}}))),e.reading_value!==i.reading_value&&(t.reading_value=e.reading_value??null),this._readingRows.length>0&&JSON.stringify(this._readingNumbers())!==this._readingsOriginal){let o=this._readingNumbers(),c={};for(let u of this._readingRows)c[u.id]=o[u.id]??null;t.reading_values=c}if(JSON.stringify(this._photos.ids)!==this._photosOriginal&&(t.photo_doc_ids=this._photos.ids),Object.keys(t).filter(o=>!["type","entry_id","task_id","original_timestamp"].includes(o)).length===0){this.close();return}await this._runWs(t)!==void 0&&(this._photos.markAttached(),this.dispatchEvent(new CustomEvent("history-entry-saved",{detail:{entry_id:e.entry_id,task_id:e.task_id,new_timestamp:e.timestamp},bubbles:!0,composed:!0})),this.close())}render(){if(!this._open||!this._draft)return h;let e=this._lang,i=this._draft,t=this._error||this._photos.errorText(e);return ue(()=>this.close(),l`

${s("history_edit_title",e)}

${s(i.type,e)||i.type}
{let o=n.detail.value;o&&this._set("timestamp",o)}} >
${s("cost",e)} {let o=n.detail.value;this._set("cost",o?Number(o):null)}}>
${this._renderReadings(i,e)} ${this._partOptions&&this._partOptions.length>0?l`
${s("complete_parts_used",e)} ${this._partOptions.map(n=>{let o=`${n.entry_id}:${n.part_id}`,c=this._partQty[o]||0;return l` `})}
`:h}
${s("completion_photos",e)} ${this._photos.photos.length>0?l`
${this._photos.photos.map(n=>l`
`)}
`:h} ${this._photos.full?l`${s("photos_limit",e).replace("{max}",String(this._photos.max))}`:l`this._photos.addFiles(n.detail.files)} >`} ${s("history_edit_photos_hint",e)}
${t?l`
${t}
`:h}
`)}updated(e){e.has("_open")&&this._open&&_e(this.shadowRoot)}_renderReadings(e,i){return this._readingRows.length>0?l`
${s("readings_section",i)} ${this._readingRows.map(t=>l` `)}
`:e.reading_value==null&&e.task_type!=="reading"?h:l` `}};R.styles=[He,he,w` :host { display: contents; --ms-modal-max-height: 90vh; --ms-modal-gap: 12px; } h2 { margin: 0; font-size: 18px; } .entry-type { display: flex; align-items: center; gap: 6px; color: var(--secondary-text-color); font-size: 13px; } label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } label span { color: var(--secondary-text-color); } .cost-field { display: flex; flex-direction: column; gap: 4px; font-size: 13px; min-width: 0; } .cost-field > span { color: var(--secondary-text-color); } .row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } input, textarea { padding: 8px; font-size: 14px; background: var(--secondary-background-color, #2c2c2c); color: var(--primary-text-color); border: 1px solid var(--divider-color, #444); border-radius: 6px; width: 100%; box-sizing: border-box; font-family: inherit; } .delete-entry { margin-right: auto; color: var(--error-color, #d32f2f); background: transparent; border: 1px solid var(--error-color, #d32f2f); border-radius: 6px; padding: 6px 10px; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; } .delete-entry ha-icon { --mdc-icon-size: 18px; } .actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; } button { padding: 8px 16px; font-size: 14px; border-radius: 6px; cursor: pointer; border: none; font-weight: 500; } button.cancel { background: transparent; color: var(--primary-text-color); border: 1px solid var(--divider-color); } button.save { background: var(--primary-color); color: var(--text-primary-color, white); } button[disabled] { opacity: 0.5; cursor: wait; } .error { color: var(--error-color, #d32f2f); font-size: 13px; padding: 8px; background: rgba(211,47,47,0.1); border-radius: 6px; } /* #130: parts on the entry */ .parts-block { display: flex; flex-direction: column; gap: 6px; border: 1px solid var(--divider-color, #444); border-radius: 6px; padding: 8px; } .parts-title { color: var(--secondary-text-color); font-size: 13px; } .part-row-edit { display: flex; flex-direction: row; align-items: center; gap: 8px; font-size: 14px; } .part-row-edit input[type="checkbox"] { width: auto; } .part-label { flex: 1; color: var(--primary-text-color); } .part-qty { width: 76px; } /* #161 phase 2: readings on the entry */ .readings-block { display: flex; flex-direction: column; gap: 6px; border: 1px solid var(--divider-color, #444); border-radius: 6px; padding: 8px; } .reading-row-edit { display: flex; flex-direction: row; align-items: center; gap: 8px; font-size: 14px; } .reading-row-name { flex: 1; color: var(--primary-text-color); min-width: 0; } .reading-row-input { width: 140px; font-variant-numeric: tabular-nums; } /* #161: photos on the entry */ .photos-block { display: flex; flex-direction: column; gap: 6px; border: 1px solid var(--divider-color, #444); border-radius: 6px; padding: 8px; } .photo-strip { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 6px; } .photo-tile { position: relative; width: fit-content; } .photo-remove { position: absolute; top: -4px; right: -8px; width: 22px; height: 22px; border-radius: 50%; border: none; background: var(--error-color, #db4437); color: #fff; cursor: pointer; font-size: 11px; line-height: 1; padding: 0; } /* the camera / gallery pickers come from photoPickerStyles (ms-photo-picker) */ .photos-hint { font-size: 12px; color: var(--secondary-text-color); } `],d([v({attribute:!1})],R.prototype,"hass",2),d([p()],R.prototype,"_open",2),d([p()],R.prototype,"_saving",2),d([p()],R.prototype,"_error",2),d([p()],R.prototype,"_draft",2),d([p()],R.prototype,"_partOptions",2),d([p()],R.prototype,"_partQty",2),d([p()],R.prototype,"_readingRows",2),d([p()],R.prototype,"_readingText",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",R);function se(r){return r.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function Ke(r){return!r.startsWith("data:image/svg+xml,")&&!r.startsWith("data:image/png;base64,")?"":se(r)}function Qi(r){return r.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var L=class extends T{constructor(){super(...arguments);this.lang="";this._open=!1;this._loading=!1;this._error="";this._viewResult=null;this._completeResult=null;this._quickResult=null;this._urlMode="companion";this._entryId="";this._taskId=null;this._objectName="";this._taskName="";this._generateSeq=0}get _dialogLang(){return this.lang||P(this.hass)}openForObject(e,i){this._entryId=e,this._taskId=null,this._objectName=i,this._taskName="",this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._quickResult=null,this._open=!0,this._generate()}openForTask(e,i,t,n){this._entryId=e,this._taskId=i,this._objectName=t,this._taskName=n,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._quickResult=null,this._open=!0,this._generate()}async _generate(){let e=++this._generateSeq;this._loading=!0,this._error="",this._viewResult=null,this._completeResult=null,this._quickResult=null;try{let i={type:"maintenance_supporter/qr/generate",entry_id:this._entryId,url_mode:this._urlMode};this._taskId&&(i.task_id=this._taskId);let t=[this.hass.connection.sendMessagePromise({...i,action:"view"})];this._taskId&&(t.push(this.hass.connection.sendMessagePromise({...i,action:"complete"})),await this._hasQuickCompleteDefaults()&&t.push(this.hass.connection.sendMessagePromise({...i,action:"quick_complete"})));let n=await Promise.all(t);if(e!==this._generateSeq)return;this._viewResult=n[0],n.length>1&&(this._completeResult=n[1]),n.length>2&&(this._quickResult=n[2])}catch(i){if(e!==this._generateSeq)return;let t=i?.code,n=i?.message;this._error=t==="no_url"||typeof n=="string"&&n.includes("No Home Assistant URL")?s("qr_error_no_url",this._dialogLang):s("qr_error",this._dialogLang)}finally{e===this._generateSeq&&(this._loading=!1)}}async _hasQuickCompleteDefaults(){try{let i=((await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object",entry_id:this._entryId})).tasks||[]).find(t=>t.id===this._taskId);return!!i?.quick_complete_defaults&&Object.keys(i.quick_complete_defaults).length>0}catch{return!1}}_setUrlMode(e){this._urlMode!==e&&(this._urlMode=e,this._generate())}_print(){if(!this._viewResult)return;let e=this._viewResult,i=e.label.task_name?`${e.label.object_name} \u2014 ${e.label.task_name}`:e.label.object_name,t=[e.label.manufacturer,e.label.model].filter(Boolean).join(" "),n=window.open("","_blank","width=600,height=500");if(!n)return;let o=this._dialogLang,c=se(i),u=se(t),m=!!this._completeResult,g=!!this._quickResult,f=se(s("qr_action_view",o)),x=se(s("qr_action_complete",o)),b=se(s("qr_action_quick_complete",o));n.document.write(` ${c}

${c}

${u?`
${u}
`:""}
QR Info
${f}
${m?`
QR Complete
${x}
`:""} ${g?`
QR Quick-complete
${b}
`:""}
${se(this._viewResult.url)}