t.id===s)?.name||null}getUser(s){return!s||!this.usersCache?null:this.usersCache.find(e=>e.id===s)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(s){return s?s===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}}});function F(a){return`${a.entry_id??""}\0${a.part_id}`}function cs(a,s,e,t){let i=!!a.entry_id&&a.entry_id!==s,n=i?a.entry_id:s,d=e.find(v=>v.entry_id===n),c=(d?.parts||[]).find(v=>v.id===a.part_id)||null,h=i&&d?.object?.name||"",_=c?.name||r("shared_part_unknown",t);return{part:c,foreign:i,ownerName:h,label:h?`${_} (${h})`:_}}function ii(a,s,e,t){let n=(e.find(c=>c.entry_id===s)?.parts||[]).map(c=>({...c})),d=new Set(n.map(c=>F({part_id:c.id})));for(let c of a?.consumes_parts||[]){if(!c.entry_id||c.entry_id===s)continue;let h=F(c);if(d.has(h))continue;d.add(h);let{part:_,ownerName:v}=cs(c,s,e,t);n.push({id:c.part_id,name:_?.name||r("shared_part_unknown",t),unit:_?.unit,stock:_?.stock??null,storage_location:_?.storage_location,entry_id:c.entry_id,owner_name:v})}return n}var Oe=$(()=>{"use strict";C()});function us(a,s){let e=hs[a];if(!e)return a;let t=r(e,s);return t&&t!==e?t:a}function _s(a){let e=a.match(/data\['([^']+)'\]/)?.[1],t;return(t=a.match(/length of value must be at most (\d+)/))?{field:e,rule:"too_long",param:t[1]}:(t=a.match(/length of value must be at least (\d+)/))?{field:e,rule:"too_short",param:t[1]}:(t=a.match(/value must be at most (\S+)/))?{field:e,rule:"value_too_high",param:t[1]}:(t=a.match(/value must be at least (\S+)/))?{field:e,rule:"value_too_low",param:t[1]}:/required key not provided/.test(a)?{field:e,rule:"required"}:(t=a.match(/expected (\w+)/))?{field:e,rule:"wrong_type",param:t[1]}:/value must be one of/.test(a)?{field:e,rule:"invalid_choice"}:/not a valid value/.test(a)?{field:e,rule:"invalid_value"}:{field:e,rule:"unknown"}}function P(a,s,e){if(e=e??r("action_error",s),typeof a=="string")return a;if(typeof a!="object"||a===null)return e;let t=a,i=t.message||t.error?.message||"";if(!i)return e;let n=_s(i),d=n.field?us(n.field,s):"",c=h=>r(h,s).replace("{field}",d).replace("{n}",n.param??"");switch(n.rule){case"too_long":return c("err_too_long");case"too_short":return c("err_too_short");case"value_too_high":return c("err_value_too_high");case"value_too_low":return c("err_value_too_low");case"required":return c("err_required");case"wrong_type":return c("err_wrong_type").replace("{type}",n.param??"");case"invalid_choice":return c("err_invalid_choice");case"invalid_value":return c("err_invalid_value");default:return i||e}}var hs,re=$(()=>{"use strict";C();hs={name:"name",task_type:"maintenance_type",schedule_type:"schedule_type",interval_days:"interval_days",interval_anchor:"interval_anchor",warning_days:"warning_days",last_performed:"last_performed_optional",notes:"notes_optional",documentation_url:"documentation_url_optional",custom_icon:"custom_icon_optional",nfc_tag_id:"nfc_tag_id_optional",responsible_user_id:"responsible_user",entity_slug:"entity_slug",entity_id:"entity_id",area_id:"area_id_optional",manufacturer:"manufacturer_optional",model:"model_optional",serial_number:"serial_number_optional",installation_date:"installation_date_optional",warranty_expiry:"warranty_expiry_optional",checklist:"checklist_steps_optional",reason:"reason",feedback:"feedback",cost:"cost",duration:"duration",description:"description_optional",group_name:"name",group_description:"description_optional",environmental_entity:"environmental_entity_optional",environmental_attribute:"environmental_attribute_optional",trigger_above:"trigger_above",trigger_below:"trigger_below",trigger_for_minutes:"trigger_for_minutes"}});var si,ze,ot=$(()=>{"use strict";si=["notes","cost","duration","photo","user"],ze={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"}});var w,lt=$(()=>{"use strict";L();O();C();re();Oe();ot();w=class extends k{constructor(){super(...arguments);this.entryId="";this.taskId="";this.taskName="";this.lang="en";this.checklist=[];this.adaptiveEnabled=!1;this.taskType="";this.readingUnit="";this.restockDefault=null;this.restockUnitCost=null;this.currencySymbol="";this.parts=[];this.consumesParts=[];this.consumesInfo=[];this.requiredFields=[];this._open=!1;this._notes="";this._cost="";this._duration="";this._loading=!1;this._error="";this._checklistState={};this._feedback="needed";this._photoDocId="";this._photoPreview="";this._photoUploading=!1;this._readingValue="";this._restockQty="";this._usedParts={};this.checklistPrefill={}}open(){this._open||(this._open=!0,this._notes="",this._cost="",this._duration="",this._error="",this._checklistState=Object.fromEntries(this.checklist.map((e,t)=>[String(t),!!this.checklistPrefill[e]]).filter(([,e])=>e)),this._feedback="needed",this._photoDocId="",this._photoPreview="",this._photoUploading=!1,this._readingValue="",this._restockQty=this.restockDefault!==null?String(this.restockDefault):"",this._usedParts=Object.fromEntries(this.consumesParts.map(e=>[F(e),{...e}])))}_toggleCheck(e){let t=String(e);this._checklistState={...this._checklistState,[t]:!this._checklistState[t]}}_setFeedback(e){this._feedback=e}async _onPhotoInput(e){let t=e.target,i=t.files?.[0];if(t.value="",!!i){this._photoUploading=!0,this._error="";try{let n=new FormData;n.append("entry_id",this.entryId),n.append("tags","photo"),n.append("file",i,i.name);let d=await fetch("/api/maintenance_supporter/document/upload",{method:"POST",headers:{Authorization:`Bearer ${this.hass.auth?.data?.access_token??""}`},body:n});if(!d.ok){this._error=d.status===413?r("doc_too_large",this.lang):r("doc_upload_failed",this.lang);return}let c=await d.json();c.id&&(this._photoDocId=c.id,this._photoPreview=URL.createObjectURL(i))}catch{this._error=r("doc_upload_failed",this.lang)}finally{this._photoUploading=!1}}}_removePhoto(){this._photoPreview&&URL.revokeObjectURL(this._photoPreview),this._photoDocId="",this._photoPreview=""}async _complete(){this._loading=!0,this._error="";try{let e={type:"maintenance_supporter/task/complete",entry_id:this.entryId,task_id:this.taskId};if(this._notes&&(e.notes=this._notes),this._cost){let t=parseFloat(this._cost);!isNaN(t)&&t>=0&&(e.cost=t)}if(this._duration){let t=parseInt(this._duration,10);!isNaN(t)&&t>=0&&(e.duration=t)}if(this.checklist.length>0&&(e.checklist_state=this._checklistState),this.adaptiveEnabled&&(e.feedback=this._feedback),this._photoDocId&&(e.photo_doc_id=this._photoDocId),this._readingValue!==""){let t=parseFloat(this._readingValue);isNaN(t)||(e.reading_value=t)}if(this.restockDefault!==null&&this._restockQty!==""){let t=parseFloat(this._restockQty);!isNaN(t)&&t>=1&&(e.restock_quantity=t)}this.parts.length>0&&(e.used_parts=Object.values(this._usedParts).filter(t=>Number.isFinite(t.quantity)&&t.quantity>0).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})),await this.hass.connection.sendMessagePromise(e),this._open=!1,this.dispatchEvent(new CustomEvent("task-completed"))}catch(e){this._error=P(e,this.lang,r("save_error",this.lang))}finally{this._loading=!1}}get _missingRequired(){let e={notes:this._notes.trim()!=="",cost:this._cost.trim()!=="",duration:this._duration.trim()!=="",photo:this._photoDocId!=="",user:!!this.hass?.user};return this.requiredFields.filter(t=>!e[t])}_req(e){return this.requiredFields.includes(e)?o`* `:u}_partsCostSuggestion(){if(this.restockDefault!==null){let i=parseFloat(this._restockQty);return this.restockUnitCost==null||!Number.isFinite(i)||i<=0?null:Math.round(this.restockUnitCost*i*100)/100}if(!this.parts.length)return null;let e=0,t=!1;for(let i of Object.values(this._usedParts)){let n=this.parts.find(d=>F({part_id:d.id,entry_id:d.entry_id})===F(i));n?.cost!=null&&(e+=n.cost*(i.quantity||1),t=!0)}return t?Math.round(e*100)/100:null}_renderCostSuggestion(e){if(this._cost.trim()!=="")return u;let t=this._partsCostSuggestion();if(t==null||t<=0)return u;let i=`${t.toFixed(2)}${this.currencySymbol?` ${this.currencySymbol}`:""}`;return o`this._cost=t.toFixed(2)}
>${r("cost_from_parts",e).replace("{amount}",i)} `}_close(){this._open=!1}render(){if(!this._open)return o``;let e=this.lang||this.hass?.language||"en";return o`
${r("complete_title",e)}${this.taskName}
${this._error?o`
${this._error}
`:u}
${this.checklist.length>0?o`
${r("checklist",e)}
${this.checklist.map((t,i)=>o`
this._toggleCheck(i)}>
${t}
`)}
`:u}
${this.taskType==="reading"?o`
${r("reading_value_label",e)}${this.readingUnit?` (${this.readingUnit})`:""}
this._readingValue=t.target.value} />
`:u}
${this.parts.length?o`
${r("complete_parts_used",e)}
${this.parts.map(t=>{let i=F({part_id:t.id,entry_id:t.entry_id}),n=this._usedParts[i],d=n!==void 0,c=t.entry_id?{part_id:t.id,quantity:1,entry_id:t.entry_id}:{part_id:t.id,quantity:1};return o`
{let _={...this._usedParts};h.target.checked?_[i]=_[i]||c:delete _[i],this._usedParts=_}} />
${t.name}${t.owner_name?o` (${t.owner_name}) `:u}${t.stock!==null&&t.stock!==void 0?` (${t.stock}${t.unit?" "+t.unit:""})`:""}
${d?o` {let _=parseFloat(h.target.value);this._usedParts={...this._usedParts,[i]:{...c,quantity:Number.isFinite(_)&&_>=.01?_:1}}}} />`:u}
`})}
`:this.consumesInfo.length?o`
${this.consumesInfo.map(t=>o`
${t}
`)}
`:u}
${this.restockDefault!==null?o`
${r("restock_quantity_label",e)}
this._restockQty=t.target.value} />
`:u}
${r("notes_optional",e)}${this._req("notes")}
this._notes=t.target.value} />
${r("cost_optional",e)}${this._req("cost")}
this._cost=t.target.value} />
${this._renderCostSuggestion(e)}
${r("duration_minutes",e)}${this._req("duration")}
this._duration=t.target.value} />
${r("completion_photo_optional",e)}${this._req("photo")}
${this._photoPreview?o`
✕
`:o`
${this._photoUploading?r("uploading",e):r("add_photo",e)}
`}
${this.adaptiveEnabled?o`
${r("was_maintenance_needed",e)}
this._setFeedback("needed")}
>${r("feedback_needed",e)}
this._setFeedback("not_needed")}
>${r("feedback_not_needed",e)}
this._setFeedback("not_sure")}
>${r("feedback_not_sure",e)}
`:u}
${r("cancel",e)}
0}
title=${this._missingRequired.length?this._missingRequired.map(t=>r("err_required",e).replace("{field}",r(ze[t]??t,e))).join(" \xB7 "):""}
>
${this._loading?r("completing",e):r("complete",e)}
`}};w.styles=[ti,E`
.req-mark {
color: var(--error-color, #f44336);
margin-left: 2px;
font-weight: 600;
}
/* #104: one-click cost suggestion from parts — quiet link-style chip. */
.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;
}
.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 */
.photo-pick {
display: inline-flex;
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 input[type="file"] { display: none; }
.photo-preview {
position: relative;
width: fit-content;
}
.photo-preview img {
max-width: 160px;
max-height: 160px;
border-radius: 8px;
display: block;
}
.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);
}
`],l([b({attribute:!1})],w.prototype,"hass",2),l([b()],w.prototype,"entryId",2),l([b()],w.prototype,"taskId",2),l([b()],w.prototype,"taskName",2),l([b()],w.prototype,"lang",2),l([b({type:Array})],w.prototype,"checklist",2),l([b({type:Boolean})],w.prototype,"adaptiveEnabled",2),l([b()],w.prototype,"taskType",2),l([b()],w.prototype,"readingUnit",2),l([b({attribute:!1})],w.prototype,"restockDefault",2),l([b({attribute:!1})],w.prototype,"restockUnitCost",2),l([b()],w.prototype,"currencySymbol",2),l([b({attribute:!1})],w.prototype,"parts",2),l([b({attribute:!1})],w.prototype,"consumesParts",2),l([b({type:Array})],w.prototype,"consumesInfo",2),l([b({type:Array})],w.prototype,"requiredFields",2),l([p()],w.prototype,"_open",2),l([p()],w.prototype,"_notes",2),l([p()],w.prototype,"_cost",2),l([p()],w.prototype,"_duration",2),l([p()],w.prototype,"_loading",2),l([p()],w.prototype,"_error",2),l([p()],w.prototype,"_checklistState",2),l([p()],w.prototype,"_feedback",2),l([p()],w.prototype,"_photoDocId",2),l([p()],w.prototype,"_photoPreview",2),l([p()],w.prototype,"_photoUploading",2),l([p()],w.prototype,"_readingValue",2),l([p()],w.prototype,"_restockQty",2),l([p()],w.prototype,"_usedParts",2),l([b({attribute:!1})],w.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",w)});var R,dt=$(()=>{"use strict";L();O();R=class extends k{constructor(){super(...arguments);this.label="";this.value="";this.placeholder="";this.type="text";this.required=!1;this.disabled=!1}_onInput(e){let t=e.target.value;this.value=t,this.dispatchEvent(new CustomEvent("input",{bubbles:!0,composed:!0,detail:{value:t}}))}render(){return o`
${this.label?o`${this.label}${this.required?o`* `:u} `:u}
${this.helper?o`${this.helper} `:u}
`}};R.styles=E`
: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; }
.helper {
font-size: 11px;
color: var(--secondary-text-color);
font-style: italic;
}
`,l([b()],R.prototype,"label",2),l([b()],R.prototype,"value",2),l([b()],R.prototype,"placeholder",2),l([b()],R.prototype,"type",2),l([b({type:Boolean})],R.prototype,"required",2),l([b({type:Boolean})],R.prototype,"disabled",2),l([b()],R.prototype,"step",2),l([b()],R.prototype,"min",2),l([b()],R.prototype,"max",2),l([b()],R.prototype,"pattern",2),l([b()],R.prototype,"helper",2);customElements.get("ms-textfield")||customElements.define("ms-textfield",R)});var A,ri=$(()=>{"use strict";L();O();C();re();dt();A=class extends k{constructor(){super(...arguments);this.objects=[];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._entryId=null}get _lang(){return this.hass?.language??navigator.language.split("-")[0]??"en"}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._error="",this._open=!0}openEdit(e,t){this._entryId=e,this._name=t.name||"",this._manufacturer=t.manufacturer||"",this._model=t.model||"",this._serialNumber=t.serial_number||"",this._areaId=t.area_id||"",this._installationDate=t.installation_date||"",this._warrantyExpiry=t.warranty_expiry||"",this._documentationUrl=t.documentation_url||"",this._notes=t.notes||"",this._haDeviceId=t.ha_device_id||"",this._parentEntryId=t.parent_entry_id||"",this._error="",this._open=!0}async _save(){if(!this._loading&&this._name.trim()){this._loading=!0,this._error="";try{this._entryId?await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object/update",entry_id:this._entryId,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}):await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object/create",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._open=!1,this.dispatchEvent(new CustomEvent("object-saved"))}catch(e){this._error=P(e,this._lang,r("save_error",this._lang))}finally{this._loading=!1}}}_parentChoices(){return(this.objects||[]).filter(e=>e.entry_id!==this._entryId)}_close(){this._open=!1}render(){if(!this._open)return o``;let e=this._lang,t=this._entryId?r("edit_object",e):r("new_object",e);return o`
${t}
${this._error?o`
${this._error}
`:u}
this._name=i.target.value}
>
this._manufacturer=i.target.value}
>
this._model=i.target.value}
>
this._serialNumber=i.target.value}
>
this._documentationUrl=i.target.value}
>
this._areaId=i.detail.value||""}
>
this._installationDate=i.target.value}
>
this._warrantyExpiry=i.target.value}
>
r("link_device_optional",e)}
@value-changed=${i=>this._haDeviceId=i.detail.value?.device||""}
>
${this._parentChoices().length?o`
${r("parent_object_optional",e)}
this._parentEntryId=i.target.value}
>
${r("parent_none",e)}
${this._parentChoices().map(i=>o`${i.object.name} `)}
`:u}
${r("object_notes_optional",e)}
${r("cancel",this._lang)}
${this._loading?r("saving",this._lang):r("save",this._lang)}
`}};A.styles=E`
.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);
}
.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;
}
`,l([b({attribute:!1})],A.prototype,"hass",2),l([b({attribute:!1})],A.prototype,"objects",2),l([p()],A.prototype,"_open",2),l([p()],A.prototype,"_loading",2),l([p()],A.prototype,"_error",2),l([p()],A.prototype,"_name",2),l([p()],A.prototype,"_manufacturer",2),l([p()],A.prototype,"_model",2),l([p()],A.prototype,"_serialNumber",2),l([p()],A.prototype,"_areaId",2),l([p()],A.prototype,"_installationDate",2),l([p()],A.prototype,"_warrantyExpiry",2),l([p()],A.prototype,"_documentationUrl",2),l([p()],A.prototype,"_notes",2),l([p()],A.prototype,"_haDeviceId",2),l([p()],A.prototype,"_parentEntryId",2),l([p()],A.prototype,"_entryId",2);customElements.get("maintenance-object-dialog")||customElements.define("maintenance-object-dialog",A)});var ct,ai,ni,oi=$(()=>{"use strict";ct=["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"],ai=["sensor"],ni=["temperature","humidity","pressure"]});function bs(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",carry:{}}}function xs(a){return{entityIds:(a.entity_ids||(a.entity_id?[a.entity_id]:[])).join(", "),type:a.type||"threshold",attribute:a.attribute||"",above:a.trigger_above?.toString()??"",below:a.trigger_below?.toString()??"",forMinutes:a.trigger_for_minutes?.toString()??"0",targetValue:a.trigger_target_value?.toString()??"",deltaMode:a.trigger_delta_mode||!1,fromState:a.trigger_from_state||"",toState:a.trigger_to_state||"",targetChanges:a.trigger_target_changes?.toString()??"",runtimeHours:a.trigger_runtime_hours?.toString()??"",onStates:(a.trigger_on_states||[]).join(", "),carry:Object.fromEntries(Object.entries(a).filter(([e])=>!ys.has(e)&&!e.startsWith("_")))}}function $s(a){let s=a.entityIds.split(",").map(t=>t.trim()).filter(Boolean);if(s.length===0)return null;let e={...a.carry||{},entity_id:s[0],entity_ids:s,type:a.type};if(a.attribute&&(e.attribute=a.attribute),a.type==="threshold"){let t=parseFloat(a.above);isNaN(t)||(e.trigger_above=t);let i=parseFloat(a.below);isNaN(i)||(e.trigger_below=i);let n=parseInt(a.forMinutes,10);isNaN(n)||(e.trigger_for_minutes=n)}else if(a.type==="counter"){let t=parseFloat(a.targetValue);isNaN(t)||(e.trigger_target_value=t),e.trigger_delta_mode=a.deltaMode}else if(a.type==="state_change"){a.fromState&&(e.trigger_from_state=a.fromState),a.toState&&(e.trigger_to_state=a.toState);let t=parseInt(a.targetChanges,10);isNaN(t)||(e.trigger_target_changes=t)}else if(a.type==="runtime"){let t=parseFloat(a.runtimeHours);isNaN(t)||(e.trigger_runtime_hours=t);let i=(a.onStates||"").split(",").map(n=>n.trim()).filter(Boolean);i.length>0&&(e.trigger_on_states=i)}return e}function ws(a){return Array.from({length:7},(s,e)=>we(e,a,"short"))}function ks(a){let s=new Intl.DateTimeFormat(a||"en",{month:"short"});return Array.from({length:12},(e,t)=>s.format(new Date(2021,t,1)))}var gs,ms,fs,pt,li,vs,ys,m,ht,di=$(()=>{"use strict";L();O();C();nt();Oe();oi();re();ot();dt();gs=["cleaning","inspection","replacement","calibration","service","reading","custom"],ms=["low","normal","high"],fs=["time_based","weekdays","nth_weekday","day_of_month","sensor_based","one_time","manual"],pt=["weekdays","nth_weekday","day_of_month"],li=["threshold","counter","state_change","runtime"],vs=[...li,"compound"];ys=new Set(["entity_id","entity_ids","type","attribute","trigger_above","trigger_below","trigger_for_minutes","trigger_target_value","trigger_delta_mode","trigger_from_state","trigger_to_state","trigger_target_changes","trigger_runtime_hours","trigger_on_states"]);m=class m extends k{constructor(){super(...arguments);this.checklistsEnabled=!1;this.scheduleTimeEnabled=!1;this.completionActionsEnabled=!1;this.defaultWarningDays=7;this.parts=[];this._foreignOwners=[];this._open=!1;this._entityPickerFallback=!1;this._pickerProbeStrikes=0;this._loading=!1;this._error="";this._entryId="";this._taskId=null;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._seasonMonths=[];this._endsMode="never";this._endsCount="";this._endsUntil="";this._schedulePreview=[];this._schedulePreviewEnded=!1;this._previewSeq=0;this._notes="";this._documentationUrl="";this._customIcon="";this._priority="normal";this._labels="";this._enabled=!0;this._triggerEntityId="";this._triggerEntityIds=[];this._triggerEntityLogic="any";this._triggerAttribute="";this._triggerType="threshold";this._triggerAbove="";this._triggerBelow="";this._triggerForMinutes="0";this._triggerTargetValue="";this._triggerDeltaMode=!1;this._triggerBaselineValue="";this._liveBaselineValue=null;this._autoCompleteOnRecovery=!1;this._triggerFromState="";this._triggerToState="";this._triggerTargetChanges="";this._triggerRuntimeHours="";this._triggerOnStates="";this._compoundLogic="AND";this._compoundConditions=[];this._suggestedAttributes=[];this._availableAttributes=[];this._entityDomain="";this._lastPerformed="";this._nfcTagId="";this._readingUnit="";this._consumesParts={};this._partsLoadFailed=!1;this._availableTags=[];this._responsibleUserId=null;this._assigneePool=[];this._rotationStrategy="";this._availableUsers=[];this._checklistText="";this._requiredCompletion=[];this._scheduleTime="";this._actionService="";this._actionTargetEntity="";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="0.3";this._adaptiveMin="7";this._adaptiveMax="365";this._adaptiveSeasonal=!0;this._adaptivePrediction=!0;this._adaptiveInitial="";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 this.hass?.language??navigator.language.split("-")[0]??"en"}async openCreate(e,t){this._entryId=e,this._taskId=null,this._error="",!e&&t&&t.length>0?(this._objectChoices=t.map(i=>({entry_id:i.entry_id,name:i.object.name})).sort((i,n)=>i.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,t){this._entryId=e,this._taskId=t.id,this._error="",this._name=t.name,this._type=t.type,this._scheduleType=t.schedule_type,this._intervalDays=t.interval_days!=null?String(t.interval_days):"",this._intervalUnit=t.interval_unit||"days",this._dueDate=t.due_date||"";let i=t.schedule;this._weekdays=i?.kind==="weekdays"?[...i.weekdays??[]]:[],this._nth=i?.kind==="nth_weekday"?String(i.nth??1):"1",this._nthWeekday=i?.kind==="nth_weekday"?String(i.weekday??5):"5",this._domDay=i?.kind==="day_of_month"&&(i.day??1)>=1?String(i.day??1):"1",this._domLastDay=i?.kind==="day_of_month"&&i.day===-1,this._domBusiness=i?.kind==="day_of_month"&&i.business===!0,this._calOffset=i?.offset?String(i.offset):"0",this._seasonMonths=Array.isArray(i?.season_months)?[...i.season_months]:[];let n=i?.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=t.warning_days.toString(),this._earliestCompletionDays=t.earliest_completion_days!=null?String(t.earliest_completion_days):"",this._intervalAnchor=t.interval_anchor||"completion",this._notes=t.notes||"",this._documentationUrl=t.documentation_url||"",this._customIcon=t.custom_icon||"",this._priority=t.priority||"normal",this._labels=(t.labels||[]).join(", "),this._enabled=t.enabled!==!1,this._lastPerformed=t.last_performed||"",this._nfcTagId=t.nfc_tag_id||"",this._readingUnit=t.reading_unit||"",this._consumesParts=Object.fromEntries((t.consumes_parts||[]).map(_=>[F(_),{..._}])),this._responsibleUserId=t.responsible_user_id||null,this._assigneePool=[...t.assignee_pool||[]],this._rotationStrategy=t.rotation_strategy||"",this._checklistText=(t.checklist||[]).join(`
`),this._requiredCompletion=[...t.required_completion_fields||[]],this._scheduleTime=t.schedule_time||"";let d=t.on_complete_action;if(d&&d.service){this._actionService=d.service;let _=d.target?.entity_id;this._actionTargetEntity=Array.isArray(_)?_[0]||"":_||"",this._actionData=d.data&&typeof d.data=="object"?{...d.data}:{},this._actionDataJsonFallback=""}else this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="";let c=t.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 h=t.adaptive_config||{};if(this._environmentalEntity=h.environmental_entity||"",this._environmentalAttribute=h.environmental_attribute||"",this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute,this._adaptiveEnabled=!!h.enabled,this._adaptiveAlpha=(h.ewa_alpha??.3).toString(),this._adaptiveMin=(h.min_interval_days??7).toString(),this._adaptiveMax=(h.max_interval_days??365).toString(),this._adaptiveSeasonal=h.seasonal_enabled!==!1,this._adaptivePrediction=h.sensor_prediction_enabled!==!1,this._adaptiveInitial=this._adaptiveSnapshot(),t.trigger_config){let _=t.trigger_config;this._triggerEntityId=_.entity_id||_.entity_ids&&_.entity_ids[0]||"",this._triggerEntityIds=_.entity_ids||(_.entity_id?[_.entity_id]:[]),this._triggerEntityLogic=_.entity_logic||"any",this._triggerAttribute=_.attribute||"",this._triggerType=_.type||"threshold",this._triggerAbove=_.trigger_above?.toString()||"",this._triggerBelow=_.trigger_below?.toString()||"",this._triggerForMinutes=_.trigger_for_minutes?.toString()||"0",this._triggerTargetValue=_.trigger_target_value?.toString()||"",this._triggerDeltaMode=_.trigger_delta_mode||!1,this._triggerBaselineValue=_.trigger_baseline_value?.toString()||"",this._liveBaselineValue=t.trigger_baseline_value??null,this._autoCompleteOnRecovery=_.auto_complete_on_recovery||!1,this._triggerFromState=_.trigger_from_state||"",this._triggerToState=_.trigger_to_state||"",this._triggerTargetChanges=_.trigger_target_changes?.toString()||"",this._triggerRuntimeHours=_.trigger_runtime_hours?.toString()||"",this._triggerOnStates=(_.trigger_on_states||[]).join(", "),_.type==="compound"?(this._compoundLogic=_.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(_.conditions||[]).map(xs)):(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._priority="normal",this._labels="",this._enabled=!0,this._lastPerformed="",this._nfcTagId="",this._readingUnit="",this._consumesParts={},this._responsibleUserId=null,this._assigneePool=[],this._rotationStrategy="",this._checklistText="",this._requiredCompletion=[],this._scheduleTime="",this._environmentalEntity="",this._environmentalAttribute="",this._environmentalInitial="",this._environmentalAttributeInitial="",this._adaptiveEnabled=!1,this._adaptiveAlpha="0.3",this._adaptiveMin="7",this._adaptiveMax="365",this._adaptiveSeasonal=!0,this._adaptivePrediction=!0,this._adaptiveInitial=this._adaptiveSnapshot(),this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="",this._actionTesting=!1,this._actionTestResult="",this._qcNotes="",this._qcCost="",this._qcDuration="",this._qcFeedback="",this._resetTriggerFields()}_resetTriggerFields(){this._triggerEntityId="",this._triggerEntityIds=[],this._triggerEntityLogic="any",this._triggerAttribute="",this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="",this._triggerType="threshold",this._triggerAbove="",this._triggerBelow="",this._triggerForMinutes="0",this._triggerTargetValue="",this._triggerDeltaMode=!1,this._triggerBaselineValue="",this._liveBaselineValue=null,this._autoCompleteOnRecovery=!1,this._triggerFromState="",this._triggerToState="",this._triggerTargetChanges="",this._triggerRuntimeHours="",this._triggerOnStates="",this._compoundLogic="AND",this._compoundConditions=[]}async _loadUsers(){this._userService||(this._userService=new de(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(t=>t!==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="Invalid service format (expected 'domain.service')",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[t,i]=e.split(".");if(!this.hass?.services?.[t]?.[i]){this._actionTestResult="error",this._actionTestError=`Service "${e}" is not registered in Home Assistant. Check spelling and that the integration providing it is loaded.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}let n=this._actionTargetEntity.trim();if(n){let d=n.split(".")[0];if(d!==t&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(t)){this._actionTestResult="error",this._actionTestError=`Service "${e}" only works on ${t}.* entities; entity "${n}" is in ${d}.* \u2014 pick a service that matches the entity domain (e.g. ${d}.${i})`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}if(!this.hass.states?.[n]){this._actionTestResult="error",this._actionTestError=`Target entity "${n}" not found in Home Assistant \u2014 the entity may have been renamed or its integration removed.`,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[t,i]=e.split("."),n=this.hass?.services?.[t]?.[i]?.fields;return!n||Object.keys(n).length===0?null:Object.entries(n).map(([d,c])=>({name:d,required:!!c.required,selector:c.selector||{text:{}}}))}_renderCompletionActionsSection(e){if(!this.completionActionsEnabled)return u;let t=this._serviceSchema();return o`
${r("on_complete_action_title",e)}
${r("on_complete_action_desc",e)}
{this._actionService=i.detail.value||"";let n=this._serviceSchema();if(n){let d=new Set(n.map(c=>c.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([c])=>d.has(c)))}}}
>
r("on_complete_action_target",e)}
@value-changed=${i=>{let n=i.detail.value;this._actionTargetEntity=n.target_entity||""}}
>
${r("on_complete_action_target_hint",e)}
${t?o`
{this._actionData={...i.detail.value}}}
>
`:o`
{this._actionDataJsonFallback=i.target.value}}
>
`}
${this._actionTesting?"\u2026":r("on_complete_action_test",e)}
${this._actionTestResult==="ok"?o`
${r("on_complete_action_test_success",e)} `:u}
${this._actionTestResult==="error"?o`
${r("on_complete_action_test_failed",e)}
${this._actionTestError?o`
${this._actionTestError}
`:u}
`:u}
${r("quick_complete_defaults_title",e)}
${r("quick_complete_defaults_desc",e)}
{this._qcNotes=i.target.value}}
>
{this._qcCost=i.target.value}}
>
{this._qcDuration=i.target.value}}
>
{this._qcFeedback=i.target.value}}>
${r("quick_complete_defaults_feedback_none",e)}
${r("quick_complete_defaults_feedback_needed",e)}
${r("quick_complete_defaults_feedback_not_needed",e)}
`}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(t=>t.entry_id!==this._entryId&&(t.parts||[]).length>0).map(t=>({entry_id:t.entry_id,name:t.object?.name||t.entry_id,parts:t.parts||[]})).sort((t,i)=>t.name.localeCompare(i.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(t=>{let i=t;this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:i.suggested_attributes||[],available:i.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 t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e});this._entityDomain=t.domain||"",this._suggestedAttributes=t.suggested_attributes||[],this._availableAttributes=t.available_attributes||[]}catch{this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain=""}}get _hasForeignPick(){return Object.values(this._consumesParts).some(e=>!!e.entry_id)}_renderConsumesRow(e,t){let i=F({part_id:e.id,entry_id:t}),n=this._consumesParts[i],d=t?{part_id:e.id,quantity:1,entry_id:t}:{part_id:e.id,quantity:1};return o`
{let h={...this._consumesParts};c.target.checked?h[i]=h[i]||d:delete h[i],this._consumesParts=h}}
/>
${e.name}${e.unit?` (${e.unit})`:""}
${n!==void 0?o` {let h=parseFloat(c.target.value);this._consumesParts={...this._consumesParts,[i]:{...d,quantity:Number.isFinite(h)&&h>=.01?h:1}}}}
/>`:u}
`}_toggleRequired(e,t){let i=new Set(this._requiredCompletion);t?i.add(e):i.delete(e),this._requiredCompletion=[...i]}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),t=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(t)&&e>t){this._error=`${r("adaptive_min_interval",this._lang)} > ${r("adaptive_max_interval",this._lang)}`;return}}this._loading=!0,this._error="";try{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))},t=this._earliestCompletionDays.trim();if(e.earliest_completion_days=t===""?null:Math.max(0,parseInt(t,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):pt.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.priority=this._priority,e.labels=this._labels.split(",").map(c=>c.trim()).filter(Boolean),e.enabled=this._enabled,e.last_performed=this._lastPerformed||null,e.nfc_tag_id=this._nfcTagId||null,e.reading_unit=this._readingUnit.trim()||null,(this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(c=>c.entry_id?{part_id:c.part_id,quantity:c.quantity,entry_id:c.entry_id}:{part_id:c.part_id,quantity:c.quantity})),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 c=this._compoundConditions.map($s).filter(h=>h!==null);if(c.length>0){let h={type:"compound",compound_logic:this._compoundLogic,conditions:c};this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),e.trigger_config=h}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let c=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],h={entity_id:c[0],entity_ids:c,type:this._triggerType};if(this._triggerAttribute&&(h.attribute=this._triggerAttribute),this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),c.length>1&&(h.entity_logic=this._triggerEntityLogic),this._triggerType==="threshold"){if(this._triggerAbove){let _=parseFloat(this._triggerAbove);isNaN(_)||(h.trigger_above=_)}if(this._triggerBelow){let _=parseFloat(this._triggerBelow);isNaN(_)||(h.trigger_below=_)}if(this._triggerForMinutes){let _=parseInt(this._triggerForMinutes,10);isNaN(_)||(h.trigger_for_minutes=_)}}else if(this._triggerType==="counter"){if(this._triggerTargetValue){let _=parseFloat(this._triggerTargetValue);isNaN(_)||(h.trigger_target_value=_)}if(h.trigger_delta_mode=this._triggerDeltaMode,this._triggerDeltaMode&&this._triggerBaselineValue){let _=parseFloat(this._triggerBaselineValue);!isNaN(_)&&_>=0&&(h.trigger_baseline_value=_)}}else if(this._triggerType==="state_change"){if(this._triggerFromState&&(h.trigger_from_state=this._triggerFromState),this._triggerToState&&(h.trigger_to_state=this._triggerToState),this._triggerTargetChanges){let _=parseInt(this._triggerTargetChanges,10);isNaN(_)||(h.trigger_target_changes=_)}}else if(this._triggerType==="runtime"){if(this._triggerRuntimeHours){let v=parseFloat(this._triggerRuntimeHours);isNaN(v)||(h.trigger_runtime_hours=v)}let _=this._triggerOnStates.split(",").map(v=>v.trim()).filter(Boolean);_.length>0&&(h.trigger_on_states=_)}e.trigger_config=h}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&this._scheduleType==="time_based"){let c=this._scheduleTime.trim();e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(c)?c:null}if(this.checklistsEnabled){let c=this._checklistText.split(`
`).map(h=>h.trim()).filter(Boolean).slice(0,100);e.checklist=c.length?c:null}if(this.completionActionsEnabled){let c=this._actionService.trim();if(c&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(c)){let f={service:c},y=this._actionTargetEntity.trim();y&&(f.target={entity_id:y});let g=this._buildActionData();Object.keys(g).length>0&&(f.data=g),e.on_complete_action=f}else e.on_complete_action=null;let h={};this._qcNotes.trim()&&(h.notes=this._qcNotes.trim());let _=parseFloat(this._qcCost);!isNaN(_)&&_>=0&&(h.cost=_);let v=parseInt(this._qcDuration,10);!isNaN(v)&&v>=0&&(h.duration=v),this._qcFeedback&&(h.feedback=this._qcFeedback),e.quick_complete_defaults=Object.keys(h).length?h:null}let i=await this.hass.connection.sendMessagePromise(e),n=this._taskId||i?.task_id,d=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;if(n&&this._scheduleType==="sensor_based"&&d)try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:n,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null}),this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute}catch{}if(n&&this._adaptiveSnapshot()!==this._adaptiveInitial){let c=parseFloat(this._adaptiveAlpha),h=parseInt(this._adaptiveMin,10),_=parseInt(this._adaptiveMax,10);try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:n,enabled:this._adaptiveEnabled,...c>=.1&&c<=.9?{ewa_alpha:c}:{},...!isNaN(h)&&h>=1?{min_interval_days:h}:{},...!isNaN(_)&&_>=1?{max_interval_days:_}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction}),this._adaptiveInitial=this._adaptiveSnapshot()}catch{}}this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}catch(e){this._error=P(e,this._lang,r("save_error",this._lang))}finally{this._loading=!1}}}_close(){this._open=!1,this._pickerProbeTimer!==void 0&&(clearTimeout(this._pickerProbeTimer),this._pickerProbeTimer=void 0),this._pickerProbeStrikes=0}_renderTriggerFields(){if(this._scheduleType!=="sensor_based")return u;let e=this._lang,t=this._triggerType==="compound";return o`
${r("trigger_configuration",e)}
${r("trigger_type",e)}
this._triggerType=i.target.value}
>
${vs.map(i=>o`${r(i,e)} `)}
${t?this._renderCompoundEditor():o`
${this._entityPickerFallback?o`
0?this._triggerEntityIds.join(", "):this._triggerEntityId}
@input=${i=>{let d=i.target.value.split(",").map(c=>c.trim()).filter(Boolean);this._triggerEntityId=d[0]||"",this._triggerEntityIds=d,d[0]&&this._fetchEntityAttributes(d[0])}}
>
`:o`
0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}}
.computeLabel=${()=>r("entity_id",e)}
@value-changed=${i=>{let n=(i.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?o`
${r("entity_logic",e)}
this._triggerEntityLogic=i.target.value}
>
${r("entity_logic_any",e)}
${r("entity_logic_all",e)}
`:u}
${this._availableAttributes.length>0?o`
${r("attribute_optional",e)}
this._triggerAttribute=i.target.value}
>
${r("use_entity_state",e)}
${this._suggestedAttributes.map(i=>o`${i} ★ `)}
${this._availableAttributes.filter(i=>!this._suggestedAttributes.includes(i.name)).map(i=>o`${i.name}${i.numeric?"":" (non-numeric)"} `)}
`:o`
this._triggerAttribute=i.target.value}
>
`}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
this._autoCompleteOnRecovery=i.target.checked}
/>
${r("auto_complete_on_recovery",e)}
${r("auto_complete_on_recovery_help",e)}
this._intervalDays=i.target.value}
>
${this._intervalDays?this._renderUnitSelect():u}
`}_patchCondition(e,t){this._compoundConditions=this._compoundConditions.map((i,n)=>n===e?{...i,...t}:i)}_addCondition(){this._compoundConditions=[...this._compoundConditions,bs()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((t,i)=>i!==e)}_renderCompoundEditor(){let e=this._lang;return o`
${r("compound_logic",e)}
this._compoundLogic=t.target.value}
>
${r("compound_logic_and",e)}
${r("compound_logic_or",e)}
${r("compound_help",e)}
${this._compoundConditions.length===0?o`${r("compound_no_conditions",e)}
`:this._compoundConditions.map((t,i)=>this._renderCondition(t,i))}
this._addCondition()}>
+ ${r("compound_add_condition",e)}
`}_renderCondition(e,t){let i=this._lang,n=t+1;return o`
${r("compound_condition",i)} ${n}
this._removeCondition(t)}
>✕
${this._entityPickerFallback?o`
this._patchCondition(t,{entityIds:d.target.value})}
>
`:o`
d.trim()).filter(Boolean)}}
.computeLabel=${()=>r("entity_id",i)}
@value-changed=${d=>{let c=(d.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(t,{entityIds:c.join(", ")})}}
> `}
${this._renderConditionAttribute(e,t)}
${r("trigger_type",i)}
this._patchCondition(t,{type:d.target.value})}
>
${li.map(d=>o`${r(d,i)} `)}
${this._renderConditionTypeFields(e,t)}
`}_renderStateField(e){return this._entityPickerFallback||!e.entityId?o`
e.onInput(t.target.value)}
>
`:o`
e.label}
@value-changed=${t=>e.onInput((t.detail.value.s||"").trim())}
>
`}_renderOnStatesField(e){let t=this._lang;return this._entityPickerFallback||!e.entityId?o`
e.onInput(i.target.value)}
>
`:o`
i.trim()).filter(Boolean)}}
.computeLabel=${()=>r("runtime_on_states",t)}
@value-changed=${i=>e.onInput((i.detail.value.s||[]).join(", "))}
>
`}_renderAdaptiveSection(e){return this._scheduleType==="one_time"||this._scheduleType==="manual"?u:o`
${r("adaptive_section_title",e)}
this._adaptiveEnabled=t.target.checked}
/>
${r("adaptive_enabled",e)}
${this._adaptiveEnabled?o`
this._adaptiveMin=t.target.value}
>
this._adaptiveMax=t.target.value}
>
this._adaptiveAlpha=t.target.value}
>
this._adaptiveSeasonal=t.target.checked}
/>
${r("adaptive_seasonal_enabled",e)}
this._adaptivePrediction=t.target.checked}
/>
${r("adaptive_prediction_enabled",e)}
`:u}
`}_renderEnvironmentalAttribute(e){this._fetchConditionAttributes(this._environmentalEntity);let t=this._conditionAttrOptions[this._environmentalEntity];return t&&t.available.length>0?o`
${r("environmental_attribute_optional",e)}
this._environmentalAttribute=i.target.value}
>
${r("use_entity_state",e)}
${t.suggested.map(i=>o`${i} ★ `)}
${t.available.filter(i=>!t.suggested.includes(i.name)).map(i=>o`${i.name}${i.numeric?"":" (non-numeric)"} `)}
`:o`
this._environmentalAttribute=i.target.value.trim()}
>
`}_renderConditionAttribute(e,t){let i=this._lang,n=e.entityIds.split(",")[0]?.trim()||"";n&&this._fetchConditionAttributes(n);let d=n?this._conditionAttrOptions[n]:void 0;return d&&d.available.length>0?o`
${r("attribute_optional",i)}
this._patchCondition(t,{attribute:c.target.value})}
>
${r("use_entity_state",i)}
${d.suggested.map(c=>o`${c} ★ `)}
${d.available.filter(c=>!d.suggested.includes(c.name)).map(c=>o`${c.name}${c.numeric?"":" (non-numeric)"} `)}
`:o`
this._patchCondition(t,{attribute:c.target.value.trim()})}
>
`}_renderConditionTypeFields(e,t){let i=this._lang;if(e.type==="threshold")return o`
this._patchCondition(t,{above:n.target.value})}>
this._patchCondition(t,{below:n.target.value})}>
this._patchCondition(t,{forMinutes:n.target.value})}>
`;if(e.type==="counter")return o`
this._patchCondition(t,{targetValue:n.target.value})}>
this._patchCondition(t,{deltaMode:n.target.checked})} />
${r("delta_mode",i)}
`;if(e.type==="state_change"){let n=e.entityIds.split(",")[0]?.trim()||"";return o`
${this._renderStateField({label:r("from_state_optional",i),value:e.fromState,entityId:n,onInput:d=>this._patchCondition(t,{fromState:d})})}
${this._renderStateField({label:r("to_state_optional",i),value:e.toState,entityId:n,onInput:d=>this._patchCondition(t,{toState:d})})}
this._patchCondition(t,{targetChanges:d.target.value})}>
`}if(e.type==="runtime"){let n=e.entityIds.split(",")[0]?.trim()||"";return o`
this._patchCondition(t,{runtimeHours:d.target.value})}>
${this._renderOnStatesField({value:e.onStates,entityId:n,onInput:d=>this._patchCondition(t,{onStates:d})})}
`}return u}_renderUnitSelect(){let e=this._lang;return o`
${r("interval_unit",e)}
this._intervalUnit=t.target.value}
>
${["days","weeks","months","years"].map(t=>o`${r("unit_"+t,e)} `)}
`}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(t=>t!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(pt.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 t of e.keys())if(m._PREVIEW_RELEVANT.has(String(t))){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"),t=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!t){this._pickerProbeStrikes=0;return}let i=(h,_,v=0)=>{if(!(!h||v>10)){(h.tagName?.toLowerCase()??"")==="ha-entity-picker"&&_.push(h);for(let f of[h.shadowRoot,h])if(f)for(let y of Array.from(f.children??[]))i(y,_,v+1)}},n=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],d=[];for(let h of n)i(h,d);let c=d.length===0||d.some(h=>h.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 t=++this._previewSeq;try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(t!==this._previewSeq)return;this._schedulePreview=i.occurrences||[],this._schedulePreviewEnded=!!i.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return u;let e=this._lang,t=this.scheduleTimeEnabled&&this._scheduleTime?` ${this._scheduleTime}`:"",i=this._schedulePreview.map((d,c)=>{let h=new Date(`${d}T12:00:00`).getDay();return`${we(h===0?6:h-1,e,"short")} ${W(d,e)}${c===0?t:""}`}).join(" \xB7 "),n=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?o`${r("schedule_preview_ontime",e)}
`:u;return o`
${r("schedule_preview_title",e)}: ${i}${this._schedulePreviewEnded?o` ${r("schedule_preview_ends",e)} `:u}
${n}
`}_buildSchedule(){let e=i=>{let n=parseInt(this._calOffset,10)||0;return n&&(i.offset=Math.max(-15,Math.min(n,15))),i};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((i,n)=>i-n)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});let t={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(t.business=!0),e(t)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((t,i)=>t-i)),this._endsMode==="count"){let t=parseInt(this._endsCount,10);t>=1&&(e.ends={count:t})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(t=>t!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||pt.includes(this._scheduleType)))return u;let i=ks(e);return o`
${r("season_window_label",e)}
${r("season_window_hint",e)}
${i.map((n,d)=>o`
this._toggleSeasonMonth(d+1)}
>${n} `)}
${r("series_end_label",e)}
this._endsMode=n.target.value}>
${r("series_end_never",e)}
${r("series_end_after_count",e)}
${r("series_end_until",e)}
${this._endsMode==="count"?o`
this._endsCount=n.target.value}
> `:u}
${this._endsMode==="until"?o`
this._endsUntil=n.target.value}
> `:u}
`}_renderCalendarFields(){let e=this._lang,t=ws(e);if(this._scheduleType==="weekdays")return o`
${r("recurrence_on_days",e)}
${t.map((i,n)=>o`
this._toggleWeekday(n)}
>${i} `)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let i=[["1",r("ord_1",e)],["2",r("ord_2",e)],["3",r("ord_3",e)],["4",r("ord_4",e)],["5",r("ord_5",e)],["-1",r("ord_last",e)]];return o`
${r("recurrence_occurrence",e)}
this._nth=n.target.value}>
${i.map(([n,d])=>o`${d} `)}
${r("recurrence_weekday",e)}
this._nthWeekday=n.target.value}>
${t.map((n,d)=>o`${n} `)}
${this._renderCalOffsetField()}`}return this._scheduleType==="day_of_month"?o`
${this._domLastDay?u:o`
this._domDay=i.target.value}
> `}
this._domLastDay=i.target.checked} />
${r("recurrence_last_day",e)}
this._domBusiness=i.target.checked} />
${r("recurrence_business_day",e)}
${this._renderCalOffsetField()}`:u}_renderCalOffsetField(){let e=this._lang;return o`
this._calOffset=t.target.value}
> `}_renderTriggerLiveHint(){if(this._triggerType==="compound")return u;let e=this._triggerEntityId||this._triggerEntityIds[0];if(!e||!this.hass?.states)return u;let t=this.hass.states[e];if(!t)return u;let i=this._lang,n=t.attributes?.unit_of_measurement,d=typeof n=="string"&&n?` ${n}`:"",c=this._triggerAttribute?t.attributes?.[this._triggerAttribute]:t.state,h=typeof c=="number"?c:parseFloat(String(c)),_=c!=="unknown"&&c!=="unavailable"&&c!=null&&!isNaN(h),v=y=>Number.isInteger(y)?String(y):String(Math.round(y*10)/10),f=[];if(this._triggerType==="threshold"){let y=parseFloat(this._triggerAbove),g=parseFloat(this._triggerBelow);if(isNaN(y)&&isNaN(g))return u;_&&f.push(r("trigger_hint_now",i).replace("{value}",v(h)+d)),isNaN(y)||f.push(r("trigger_hint_above",i).replace("{target}",v(y)+d)),isNaN(g)||f.push(r("trigger_hint_below",i).replace("{target}",v(g)+d))}else if(this._triggerType==="counter"){let y=parseFloat(this._triggerTargetValue);if(isNaN(y))return u;this._triggerDeltaMode?this._taskId?f.push(r("trigger_hint_counter_delta_edit",i).replace("{target}",v(y)+d)):_?f.push(r("trigger_hint_counter_delta",i).replace("{value}",v(h)+d).replace("{due}",v(h+y)+d).replace("{target}",v(y)+d)):f.push(r("trigger_hint_counter_delta_edit",i).replace("{target}",v(y)+d)):(_&&f.push(r("trigger_hint_now",i).replace("{value}",v(h)+d)),f.push(r("trigger_hint_counter_abs",i).replace("{target}",v(y)+d)))}else if(this._triggerType==="runtime"){let y=parseFloat(this._triggerRuntimeHours);if(isNaN(y))return u;f.push(r("trigger_hint_runtime",i).replace("{hours}",v(y))),f.push(r("trigger_hint_state_now",i).replace("{value}",String(t.state)))}else if(this._triggerType==="state_change"){let y=parseInt(this._triggerTargetChanges,10)||1,g=this._triggerToState.trim();f.push((g?r("trigger_hint_state_change_to",i).replace("{state}",g):r("trigger_hint_state_change",i)).replace("{count}",String(y))),f.push(r("trigger_hint_state_now",i).replace("{value}",String(t.state)))}return f.length?o`${f.join(" ")}
`:u}_renderTriggerTypeFields(){let e=this._lang;return this._triggerType==="threshold"?o`
this._triggerAbove=t.target.value}
>
this._triggerBelow=t.target.value}
>
this._triggerForMinutes=t.target.value}
>
`:this._triggerType==="counter"?o`
this._triggerTargetValue=t.target.value}
>
this._triggerDeltaMode=t.target.checked}
/>
${r("delta_mode",e)}
${this._triggerDeltaMode?o`
this._triggerBaselineValue=t.target.value}
>
${this._taskId?r("baseline_start_help_edit",e):r("baseline_start_help",e)}
${this._taskId&&this._liveBaselineValue!=null?o`
${r("baseline_current_effective",e).replace("{value}",String(this._liveBaselineValue))}
`:u}
`:u}
`:this._triggerType==="state_change"?o`
${this._renderStateField({label:r("from_state_optional",e),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:t=>this._triggerFromState=t})}
${r("state_value_help",e)}
${this._renderStateField({label:r("to_state_optional",e),value:this._triggerToState,entityId:this._triggerEntityId,onInput:t=>this._triggerToState=t})}
this._triggerTargetChanges=t.target.value}
>
${r("target_changes_help",e)}
`:this._triggerType==="runtime"?o`
this._triggerRuntimeHours=t.target.value}
>
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:t=>this._triggerOnStates=t})}
${r("runtime_on_states_help",e)}
`:u}render(){if(!this._open)return o``;let e=this._lang,t=this._taskId?r("edit_task",e):r("new_task",e);return o`
${t}
${this._error?o`
${this._error}
`:u}
${this._objectChoices.length>0?o`
${r("object",e)}
{this._entryId=i.target.value,this._consumesParts={},this._loadParts(),this._loadForeignPools()}}
>
${this._objectChoices.map(i=>o`${i.name} `)}
`:u}
this._name=i.target.value}
>
${r("maintenance_type",e)}
this._type=i.target.value}
>
${gs.map(i=>o`${r(i,e)} `)}
${this._type==="reading"?o`
this._readingUnit=i.target.value}
>
${r("reading_unit_help",e)}
`:u}
${this._partsLoadFailed?o`
${r("parts_load_failed",e)}
`:u}
${this.parts.length||this._foreignOwners.length?o`
${r("consumes_parts_label",e)}
${this.parts.map(i=>this._renderConsumesRow(i))}
${this._foreignOwners.length?o`
${r("shared_parts_other_objects",e)}
${r("shared_parts_help",e)}
${this._foreignOwners.map(i=>o`
${i.name}
${i.parts.map(n=>this._renderConsumesRow(n,i.entry_id))}
`)}
`:u}
`:u}
${r("priority",e)}
this._priority=i.target.value}
>
${ms.map(i=>o`${r("priority_"+i,e)} `)}
${r("schedule_type",e)}
this._scheduleType=i.target.value}
>
${fs.map(i=>o`${r(i,e)} `)}
${this._scheduleType==="time_based"?o`
this._intervalDays=i.target.value}
>
${this._renderUnitSelect()}
${r("interval_anchor",e)}
this._intervalAnchor=i.target.value}
>
${r("anchor_completion",e)}
${r("anchor_planned",e)}
${this.scheduleTimeEnabled?o`
this._scheduleTime=i.target.value}
>
`:u}
`:u}
${this._renderCalendarFields()}
${this._scheduleType==="one_time"?o`
this._dueDate=i.target.value}
>
`:u}
${this._renderRecurrenceExtras()}
${this._renderSchedulePreview()}
this._warningDays=i.target.value}
>
this._earliestCompletionDays=i.target.value}
>
${this.checklistsEnabled?o`
${r("checklist_steps_optional",e)}
${r("checklist_help",e)}
`:u}
${r("require_on_completion",e)}
${si.map(i=>o`
this._toggleRequired(i,n.target.checked)}
/>
${r(ze[i],e)}
`)}
this._lastPerformed=i.target.value}
>
${r("responsible_user",e)}
{let n=i.target.value;this._responsibleUserId=n||null}}
>
${r("no_user_assigned",e)}
${this._availableUsers.map(i=>o`${i.name} `)}
${this._availableUsers.length>=2?o`
${this._assigneePool.length>=2?o`
${r("rotation_strategy",e)}
this._rotationStrategy=i.target.value}
>
${r("rotation_none",e)}
${["round_robin","least_completed","random"].map(i=>o`${r("rotation_"+i,e)} `)}
`:u}
`:u}
${this._renderTriggerFields()}
${this._scheduleType==="sensor_based"?o`
${this._entityPickerFallback?o`
this._environmentalEntity=i.target.value.trim()}
>
`:o`
r("environmental_entity_optional",e)}
.computeHelper=${()=>r("environmental_entity_helper",e)}
@value-changed=${i=>{this._environmentalEntity=(i.detail.value.environmental_entity||"").trim()}}
> `}
${this._environmentalEntity?this._renderEnvironmentalAttribute(e):u}
`:u}
${this._renderAdaptiveSection(e)}
this._notes=i.target.value}
>
this._documentationUrl=i.target.value}
>
this._customIcon=i.detail.value||""}
>
${this._availableTags.length>0?o`
${r("nfc_tag_id_optional",e)}
this._nfcTagId=i.target.value}
>
${r("no_nfc_tag",e)}
${this._availableTags.map(i=>o`${i.name} `)}
↻
`:o`
this._nfcTagId=i.target.value}
>
`}
this._enabled=i.target.checked}
/>
${r("task_enabled",e)}
${this._renderCompletionActionsSection(e)}
${r("cancel",e)}
${this._loading?r("saving",e):r("save",e)}
`}};m._PREVIEW_RELEVANT=new Set(["_open","_scheduleType","_intervalDays","_intervalUnit","_intervalAnchor","_dueDate","_weekdays","_nth","_nthWeekday","_domDay","_domLastDay","_domBusiness","_calOffset","_seasonMonths","_endsMode","_endsCount","_endsUntil","_lastPerformed"]),m.styles=E`
.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;
}
.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);
}
.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;
}
.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;
}
.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 {
color: var(--error-color, #f44336);
font-size: 13px;
}
.toggle-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
cursor: pointer;
}
`,l([b({attribute:!1})],m.prototype,"hass",2),l([b({type:Boolean,attribute:"checklists-enabled"})],m.prototype,"checklistsEnabled",2),l([b({type:Boolean,attribute:"schedule-time-enabled"})],m.prototype,"scheduleTimeEnabled",2),l([b({type:Boolean,attribute:"completion-actions-enabled"})],m.prototype,"completionActionsEnabled",2),l([b({type:Number,attribute:"default-warning-days"})],m.prototype,"defaultWarningDays",2),l([p()],m.prototype,"parts",2),l([p()],m.prototype,"_foreignOwners",2),l([p()],m.prototype,"_open",2),l([p()],m.prototype,"_entityPickerFallback",2),l([p()],m.prototype,"_loading",2),l([p()],m.prototype,"_error",2),l([p()],m.prototype,"_entryId",2),l([p()],m.prototype,"_taskId",2),l([p()],m.prototype,"_objectChoices",2),l([p()],m.prototype,"_name",2),l([p()],m.prototype,"_type",2),l([p()],m.prototype,"_scheduleType",2),l([p()],m.prototype,"_intervalDays",2),l([p()],m.prototype,"_intervalUnit",2),l([p()],m.prototype,"_dueDate",2),l([p()],m.prototype,"_warningDays",2),l([p()],m.prototype,"_earliestCompletionDays",2),l([p()],m.prototype,"_intervalAnchor",2),l([p()],m.prototype,"_weekdays",2),l([p()],m.prototype,"_nth",2),l([p()],m.prototype,"_nthWeekday",2),l([p()],m.prototype,"_domDay",2),l([p()],m.prototype,"_domLastDay",2),l([p()],m.prototype,"_domBusiness",2),l([p()],m.prototype,"_calOffset",2),l([p()],m.prototype,"_seasonMonths",2),l([p()],m.prototype,"_endsMode",2),l([p()],m.prototype,"_endsCount",2),l([p()],m.prototype,"_endsUntil",2),l([p()],m.prototype,"_schedulePreview",2),l([p()],m.prototype,"_schedulePreviewEnded",2),l([p()],m.prototype,"_notes",2),l([p()],m.prototype,"_documentationUrl",2),l([p()],m.prototype,"_customIcon",2),l([p()],m.prototype,"_priority",2),l([p()],m.prototype,"_labels",2),l([p()],m.prototype,"_enabled",2),l([p()],m.prototype,"_triggerEntityId",2),l([p()],m.prototype,"_triggerEntityIds",2),l([p()],m.prototype,"_triggerEntityLogic",2),l([p()],m.prototype,"_triggerAttribute",2),l([p()],m.prototype,"_triggerType",2),l([p()],m.prototype,"_triggerAbove",2),l([p()],m.prototype,"_triggerBelow",2),l([p()],m.prototype,"_triggerForMinutes",2),l([p()],m.prototype,"_triggerTargetValue",2),l([p()],m.prototype,"_triggerDeltaMode",2),l([p()],m.prototype,"_triggerBaselineValue",2),l([p()],m.prototype,"_liveBaselineValue",2),l([p()],m.prototype,"_autoCompleteOnRecovery",2),l([p()],m.prototype,"_triggerFromState",2),l([p()],m.prototype,"_triggerToState",2),l([p()],m.prototype,"_triggerTargetChanges",2),l([p()],m.prototype,"_triggerRuntimeHours",2),l([p()],m.prototype,"_triggerOnStates",2),l([p()],m.prototype,"_compoundLogic",2),l([p()],m.prototype,"_compoundConditions",2),l([p()],m.prototype,"_suggestedAttributes",2),l([p()],m.prototype,"_availableAttributes",2),l([p()],m.prototype,"_entityDomain",2),l([p()],m.prototype,"_lastPerformed",2),l([p()],m.prototype,"_nfcTagId",2),l([p()],m.prototype,"_readingUnit",2),l([p()],m.prototype,"_consumesParts",2),l([p()],m.prototype,"_partsLoadFailed",2),l([p()],m.prototype,"_availableTags",2),l([p()],m.prototype,"_responsibleUserId",2),l([p()],m.prototype,"_assigneePool",2),l([p()],m.prototype,"_rotationStrategy",2),l([p()],m.prototype,"_availableUsers",2),l([p()],m.prototype,"_checklistText",2),l([p()],m.prototype,"_requiredCompletion",2),l([p()],m.prototype,"_scheduleTime",2),l([p()],m.prototype,"_actionService",2),l([p()],m.prototype,"_actionTargetEntity",2),l([p()],m.prototype,"_actionData",2),l([p()],m.prototype,"_actionDataJsonFallback",2),l([p()],m.prototype,"_actionTesting",2),l([p()],m.prototype,"_actionTestResult",2),l([p()],m.prototype,"_actionTestError",2),l([p()],m.prototype,"_qcNotes",2),l([p()],m.prototype,"_qcCost",2),l([p()],m.prototype,"_qcDuration",2),l([p()],m.prototype,"_qcFeedback",2),l([p()],m.prototype,"_environmentalEntity",2),l([p()],m.prototype,"_environmentalAttribute",2),l([p()],m.prototype,"_adaptiveEnabled",2),l([p()],m.prototype,"_adaptiveAlpha",2),l([p()],m.prototype,"_adaptiveMin",2),l([p()],m.prototype,"_adaptiveMax",2),l([p()],m.prototype,"_adaptiveSeasonal",2),l([p()],m.prototype,"_adaptivePrediction",2),l([p()],m.prototype,"_conditionAttrOptions",2);ht=m;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",ht)});var K,ci=$(()=>{"use strict";L();O();C();re();K=class extends k{constructor(){super(...arguments);this._open=!1;this._saving=!1;this._error="";this._draft=null;this._originalSnapshot=null}get _lang(){return this.hass?.language||"en"}openEdit(e){this._draft={...e},this._originalSnapshot={...e},this._error="",this._open=!0}close(){this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null}_set(e,t){this._draft&&(this._draft={...this._draft,[e]:t})}async _save(){if(!(!this._draft||!this._originalSnapshot)){this._saving=!0,this._error="";try{let e={type:"maintenance_supporter/task/history/update",entry_id:this._draft.entry_id,task_id:this._draft.task_id,original_timestamp:this._originalSnapshot.original_timestamp};if(this._draft.timestamp!==this._originalSnapshot.timestamp&&(e.timestamp=this._draft.timestamp),this._draft.notes!==this._originalSnapshot.notes&&(e.notes=this._draft.notes),this._draft.cost!==this._originalSnapshot.cost&&(e.cost=this._draft.cost),this._draft.duration!==this._originalSnapshot.duration&&(e.duration=this._draft.duration),this._draft.completed_by!==this._originalSnapshot.completed_by&&(e.completed_by=this._draft.completed_by),Object.keys(e).filter(i=>!["type","entry_id","task_id","original_timestamp"].includes(i)).length===0){this.close();return}await this.hass.connection.sendMessagePromise(e),this.dispatchEvent(new CustomEvent("history-entry-saved",{detail:{entry_id:this._draft.entry_id,task_id:this._draft.task_id,new_timestamp:this._draft.timestamp},bubbles:!0,composed:!0})),this.close()}catch(e){this._error=P(e,this._lang)}finally{this._saving=!1}}}render(){if(!this._open||!this._draft)return u;let e=this._lang,t=this._draft;return o`
${r("history_edit_title",e)||"Edit history entry"}
${r(t.type,e)||t.type}
${r("history_edit_timestamp",e)||"Timestamp"}
=16?t.timestamp.slice(0,16):t.timestamp}
@change=${i=>{let n=i.target.value;this._set("timestamp",n.length===16?`${n}:00`:n)}} />
${r("notes_label",e)}
${r("cost",e)||"Cost"}
{let n=i.target.value;this._set("cost",n?Number(n):null)}} />
${r("duration",e)||"Duration (min)"}
{let n=i.target.value;this._set("duration",n?Number(n):null)}} />
${this._error?o`
${this._error}
`:u}
${r("cancel",e)||"Cancel"}
${this._saving?r("saving",e)||"Saving\u2026":r("save",e)||"Save"}
`}};K.styles=E`
:host { display: contents; }
.backdrop {
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
z-index: 100;
}
.dialog {
position: fixed; left: 50%; top: 50%;
transform: translate(-50%, -50%);
width: 95vw; max-width: 480px;
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: 12px;
z-index: 101;
max-height: 90vh; overflow: auto;
}
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); }
.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;
}
.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;
}
`,l([b({attribute:!1})],K.prototype,"hass",2),l([p()],K.prototype,"_open",2),l([p()],K.prototype,"_saving",2),l([p()],K.prototype,"_error",2),l([p()],K.prototype,"_draft",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",K)});function ce(a){return a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function pi(a){return!a.startsWith("data:image/svg+xml,")&&!a.startsWith("data:image/png;base64,")?"":ce(a)}function Es(a){return a.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var H,hi=$(()=>{"use strict";L();O();C();H=class extends k{constructor(){super(...arguments);this.lang="en";this._open=!1;this._loading=!1;this._error="";this._viewResult=null;this._completeResult=null;this._urlMode="companion";this._entryId="";this._taskId=null;this._objectName="";this._taskName="";this._generateSeq=0}openForObject(e,t){this._entryId=e,this._taskId=null,this._objectName=t,this._taskName="",this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}openForTask(e,t,i,n){this._entryId=e,this._taskId=t,this._objectName=i,this._taskName=n,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}async _generate(){let e=++this._generateSeq;this._loading=!0,this._error="",this._viewResult=null,this._completeResult=null;try{let t={type:"maintenance_supporter/qr/generate",entry_id:this._entryId,url_mode:this._urlMode};this._taskId&&(t.task_id=this._taskId);let i=[this.hass.connection.sendMessagePromise({...t,action:"view"})];this._taskId&&i.push(this.hass.connection.sendMessagePromise({...t,action:"complete"}));let n=await Promise.all(i);if(e!==this._generateSeq)return;this._viewResult=n[0],n.length>1&&(this._completeResult=n[1])}catch(t){if(e!==this._generateSeq)return;let i=t?.code,n=t?.message;this._error=i==="no_url"||typeof n=="string"&&n.includes("No Home Assistant URL")?r("qr_error_no_url",this.lang):r("qr_error",this.lang)}finally{e===this._generateSeq&&(this._loading=!1)}}_setUrlMode(e){this._urlMode!==e&&(this._urlMode=e,this._generate())}_print(){if(!this._viewResult)return;let e=this._viewResult,t=e.label.task_name?`${e.label.object_name} \u2014 ${e.label.task_name}`:e.label.object_name,i=[e.label.manufacturer,e.label.model].filter(Boolean).join(" "),n=window.open("","_blank","width=600,height=500");if(!n)return;let d=this.lang||"en",c=ce(t),h=ce(i),_=!!this._completeResult,v=ce(r("qr_action_view",d)),f=ce(r("qr_action_complete",d));n.document.write(`
${c}
${c}
${h?`${h}
`:""}
${v}
${_?`
${f}
`:""}
${ce(this._viewResult.url)}