i.id===l)?.name||null}getUser(l){return!l||!this.usersCache?null:this.usersCache.find(t=>t.id===l)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(l){return l?l===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}};function N(n){return`${n.entry_id??""}\0${n.part_id}`}function mt(n,l,t,i){let e=!!n.entry_id&&n.entry_id!==l,r=e?n.entry_id:l,c=t.find(g=>g.entry_id===r),p=(c?.parts||[]).find(g=>g.id===n.part_id)||null,u=e&&c?.object?.name||"",h=p?.name||s("shared_part_unknown",i);return{part:p,foreign:e,ownerName:u,label:u?`${h} (${u})`:h}}function gt(n,l,t,i){let{part:e,label:r}=mt(n,l,t,i),c=e&&e.stock!==null&&e.stock!==void 0?` (${e.stock}${e.unit?" "+e.unit:""})`:"",p=e?.storage_location?` \u2014 ${e.storage_location}`:"";return`${n.quantity}\xD7 ${r}${c}${p}`}function vt(n,l,t,i){let r=(t.find(p=>p.entry_id===l)?.parts||[]).map(p=>({...p})),c=new Set(r.map(p=>N({part_id:p.id})));for(let p of n?.consumes_parts||[]){if(!p.entry_id||p.entry_id===l)continue;let u=N(p);if(c.has(u))continue;c.add(u);let{part:h,ownerName:g}=mt(p,l,t,i);r.push({id:p.part_id,name:h?.name||s("shared_part_unknown",i),unit:h?.unit,stock:h?.stock??null,storage_location:h?.storage_location,entry_id:p.entry_id,owner_name:g})}return r}var et=["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"],ft=["sensor"],bt=["temperature","humidity","pressure"];var it=["notes","cost","duration","photo","user"],Q={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"};var Ut=["cleaning","inspection","replacement","calibration","service","reading","custom"],Vt=["low","normal","high"],Bt=["time_based","weekdays","nth_weekday","day_of_month","sensor_based","one_time","manual"],st=["weekdays","nth_weekday","day_of_month"],yt=["threshold","counter","state_change","runtime"],Wt=[...yt,"compound"],O={alpha:"0.3",min:"7",max:"365"};function Kt(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",equals:"",notEquals:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",carry:{}}}var Qt=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"]);function Yt(n){return{entityIds:(n.entity_ids||(n.entity_id?[n.entity_id]:[])).join(", "),type:n.type||"threshold",attribute:n.attribute||"",above:n.trigger_above?.toString()??"",below:n.trigger_below?.toString()??"",equals:n.trigger_equals?.toString()??"",notEquals:n.trigger_not_equals?.toString()??"",forMinutes:n.trigger_for_minutes?.toString()??"0",targetValue:n.trigger_target_value?.toString()??"",deltaMode:n.trigger_delta_mode||!1,fromState:n.trigger_from_state||"",toState:n.trigger_to_state||"",targetChanges:n.trigger_target_changes?.toString()??"",runtimeHours:n.trigger_runtime_hours?.toString()??"",onStates:(n.trigger_on_states||[]).join(", "),carry:Object.fromEntries(Object.entries(n).filter(([t])=>!Qt.has(t)&&!t.startsWith("_")))}}function Gt(n){let l=n.entityIds.split(",").map(i=>i.trim()).filter(Boolean);if(l.length===0)return null;let t={...n.carry||{},entity_id:l[0],entity_ids:l,type:n.type};if(n.attribute&&(t.attribute=n.attribute),n.type==="threshold"){let i=parseFloat(n.above);isNaN(i)||(t.trigger_above=i);let e=parseFloat(n.below);isNaN(e)||(t.trigger_below=e);let r=parseFloat(n.equals);isNaN(r)||(t.trigger_equals=r);let c=parseFloat(n.notEquals);isNaN(c)||(t.trigger_not_equals=c);let p=parseInt(n.forMinutes,10);isNaN(p)||(t.trigger_for_minutes=p)}else if(n.type==="counter"){let i=parseFloat(n.targetValue);isNaN(i)||(t.trigger_target_value=i),t.trigger_delta_mode=n.deltaMode}else if(n.type==="state_change"){n.fromState&&(t.trigger_from_state=n.fromState),n.toState&&(t.trigger_to_state=n.toState);let i=parseInt(n.targetChanges,10);isNaN(i)||(t.trigger_target_changes=i)}else if(n.type==="runtime"){let i=parseFloat(n.runtimeHours);isNaN(i)||(t.trigger_runtime_hours=i);let e=(n.onStates||"").split(",").map(r=>r.trim()).filter(Boolean);e.length>0&&(t.trigger_on_states=e)}return t}function Zt(n){return Array.from({length:7},(l,t)=>tt(t,n,"short"))}function Jt(n){let l=new Intl.DateTimeFormat(n||"en",{month:"short"});return Array.from({length:12},(t,i)=>l.format(new Date(2021,i,1)))}var m=class m extends I{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._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._triggerOnStates="";this._compoundLogic="AND";this._compoundConditions=[];this._suggestedAttributes=[];this._availableAttributes=[];this._entityDomain="";this._lastPerformed="";this._nfcTagId="";this._requireTagScan=!1;this._readingUnit="";this._consumesParts={};this._partsLoadFailed=!1;this._availableTags=[];this._responsibleUserId=null;this._assigneePool=[];this._rotationStrategy="";this._availableUsers=[];this._checklistText="";this._phaseDefs=[];this._phaseSeq=[];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=O.alpha;this._adaptiveMin=O.min;this._adaptiveMax=O.max;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 S(this.hass)}async openCreate(t,i){this._entryId=t,this._taskId=null,this._error="",!t&&i&&i.length>0?(this._objectChoices=i.map(e=>({entry_id:e.entry_id,name:e.object.name})).sort((e,r)=>e.name.localeCompare(r.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(t,i){this._entryId=t,this._taskId=i.id,this._error="",this._objectChoices=[],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 e=i.schedule;this._weekdays=e?.kind==="weekdays"?[...e.weekdays??[]]:[],this._nth=e?.kind==="nth_weekday"?String(e.nth??1):"1",this._nthWeekday=e?.kind==="nth_weekday"?String(e.weekday??5):"5",this._domDay=e?.kind==="day_of_month"&&(e.day??1)>=1?String(e.day??1):"1",this._domLastDay=e?.kind==="day_of_month"&&e.day===-1,this._domBusiness=e?.kind==="day_of_month"&&e.business===!0,this._calOffset=e?.offset?String(e.offset):"0",this._seasonMonths=Array.isArray(e?.season_months)?[...e.season_months]:[];let r=e?.ends;r&&typeof r.count=="number"?(this._endsMode="count",this._endsCount=String(r.count),this._endsUntil=""):r&&typeof r.until=="string"?(this._endsMode="until",this._endsUntil=r.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._priority=i.priority||"normal",this._labels=(i.labels||[]).join(", "),this._enabled=i.enabled!==!1,this._lastPerformed=i.last_performed||"",this._nfcTagId=i.nfc_tag_id||"",this._requireTagScan=!!i.require_tag_scan,this._readingUnit=i.reading_unit||"",this._consumesParts=Object.fromEntries((i.consumes_parts||[]).map(h=>[N(h),{...h}])),this._responsibleUserId=i.responsible_user_id||null,this._assigneePool=[...i.assignee_pool||[]],this._rotationStrategy=i.rotation_strategy||"",this._checklistText=(i.checklist||[]).join(`
`),this._phaseDefs=Object.entries(i.phases||{}).map(([h,g])=>{let{name:$,checklist:b,consumes_parts:y,required_completion_fields:C,...P}=g,z=g.consumes_parts||[],U=z.findIndex(F=>!F.entry_id),H=U>=0?z[U]:void 0;return{id:h,name:g.name||h,checklistText:(g.checklist||[]).join(`
`),partId:H?.part_id||"",partQty:H?.quantity!=null?String(H.quantity):"",reqOverride:g.required_completion_fields!==void 0,reqFields:[...g.required_completion_fields||[]],extraParts:z.filter((F,B)=>B!==U).map(F=>({...F})),carry:P}}),this._phaseSeq=[...i.phase_sequence||[]],this._requiredCompletion=[...i.required_completion_fields||[]],this._scheduleTime=i.schedule_time||"";let c=i.on_complete_action;if(c&&c.service){this._actionService=c.service;let h=c.target?.entity_id;this._actionTargetEntity=Array.isArray(h)?h[0]||"":h||"",this._actionData=c.data&&typeof c.data=="object"?{...c.data}:{},this._actionDataJsonFallback=""}else this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="";let p=i.quick_complete_defaults;this._qcNotes=p?.notes||"",this._qcCost=p?.cost!=null?String(p.cost):"",this._qcDuration=p?.duration!=null?String(p.duration):"",this._qcFeedback=p?.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()??O.alpha,this._adaptiveMin=u.min_interval_days?.toString()??O.min,this._adaptiveMax=u.max_interval_days?.toString()??O.max,this._adaptiveSeasonal=u.seasonal_enabled!==!1,this._adaptivePrediction=u.sensor_prediction_enabled!==!1,this._adaptiveInitial=this._adaptiveSnapshot(),i.trigger_config){let h=i.trigger_config;this._triggerEntityId=h.entity_id||h.entity_ids&&h.entity_ids[0]||"",this._triggerEntityIds=h.entity_ids||(h.entity_id?[h.entity_id]:[]),this._triggerEntityLogic=h.entity_logic||"any",this._triggerAttribute=h.attribute||"",this._triggerType=h.type||"threshold",this._triggerAbove=h.trigger_above?.toString()||"",this._triggerBelow=h.trigger_below?.toString()||"",this._triggerEquals=h.trigger_equals?.toString()||"",this._triggerNotEquals=h.trigger_not_equals?.toString()||"",this._triggerForMinutes=h.trigger_for_minutes?.toString()||"0",this._triggerCombinator=h.trigger_combinator==="all"?"all":"any",this._triggerTargetValue=h.trigger_target_value?.toString()||"",this._triggerDeltaMode=h.trigger_delta_mode||!1,this._triggerBaselineValue=h.trigger_baseline_value?.toString()||"",this._liveBaselineValue=i.trigger_baseline_value??null,this._autoCompleteOnRecovery=h.auto_complete_on_recovery||!1,this._triggerFromState=h.trigger_from_state||"",this._triggerToState=h.trigger_to_state||"",this._triggerTargetChanges=h.trigger_target_changes?.toString()||"",this._triggerRuntimeHours=h.trigger_runtime_hours?.toString()||"",this._triggerOnStates=(h.trigger_on_states||[]).join(", "),h.type==="compound"?(this._compoundLogic=h.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(h.conditions||[]).map(Yt)):(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._requireTagScan=!1,this._readingUnit="",this._consumesParts={},this._responsibleUserId=null,this._assigneePool=[],this._rotationStrategy="",this._checklistText="",this._phaseDefs=[],this._phaseSeq=[],this._requiredCompletion=[],this._scheduleTime="",this._environmentalEntity="",this._environmentalAttribute="",this._environmentalInitial="",this._environmentalAttributeInitial="",this._adaptiveEnabled=!1,this._adaptiveAlpha=O.alpha,this._adaptiveMin=O.min,this._adaptiveMax=O.max,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._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._triggerOnStates="",this._compoundLogic="AND",this._compoundConditions=[]}async _loadUsers(){this._userService||(this._userService=new Z(this.hass));try{this._availableUsers=await this._userService.getUsers()}catch(t){console.error("Failed to load users:",t),this._availableUsers=[]}}_toggleAssignee(t){this._assigneePool=this._assigneePool.includes(t)?this._assigneePool.filter(i=>i!==t):[...this._assigneePool,t]}async _testAction(){let t=this._actionService.trim();if(!t||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(t)){this._actionTestResult="error",this._actionTestError="Invalid service format (expected 'domain.service')",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[i,e]=t.split(".");if(!this.hass?.services?.[i]?.[e]){this._actionTestResult="error",this._actionTestError=`Service "${t}" is not registered in Home Assistant. Check spelling and that the integration providing it is loaded.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}let r=this._actionTargetEntity.trim();if(r){let c=r.split(".")[0];if(c!==i&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(i)){this._actionTestResult="error",this._actionTestError=`Service "${t}" only works on ${i}.* entities; entity "${r}" is in ${c}.* \u2014 pick a service that matches the entity domain (e.g. ${c}.${e})`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}if(!this.hass.states?.[r]){this._actionTestResult="error",this._actionTestError=`Target entity "${r}" 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 t=JSON.parse(this._actionDataJsonFallback);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{...this._actionData}}_serviceSchema(){let t=this._actionService.trim();if(!t||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(t))return null;let[i,e]=t.split("."),r=this.hass?.services?.[i]?.[e]?.fields;return!r||Object.keys(r).length===0?null:Object.entries(r).map(([c,p])=>({name:c,required:!!p.required,selector:p.selector||{text:{}}}))}_renderCompletionActionsSection(t){if(!this.completionActionsEnabled)return _;let i=this._serviceSchema();return a`
${s("on_complete_action_title",t)}
${s("on_complete_action_desc",t)}
{this._actionService=e.detail.value||"";let r=this._serviceSchema();if(r){let c=new Set(r.map(p=>p.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([p])=>c.has(p)))}}}
>
s("on_complete_action_target",t)}
@value-changed=${e=>{let r=e.detail.value;this._actionTargetEntity=r.target_entity||""}}
>
${s("on_complete_action_target_hint",t)}
${i?a`
{this._actionData={...e.detail.value}}}
>
`:a`
{this._actionDataJsonFallback=e.target.value}}
>
`}
${this._actionTestResult==="ok"?a`
${s("on_complete_action_test_success",t)}`:_}
${this._actionTestResult==="error"?a`
${s("on_complete_action_test_failed",t)}
${this._actionTestError?a`
${this._actionTestError}
`:_}
`:_}
${s("quick_complete_defaults_title",t)}
${s("quick_complete_defaults_desc",t)}
{this._qcNotes=e.target.value}}
>
{this._qcCost=e.target.value}}
>
{this._qcDuration=e.target.value}}
>
`}async _loadParts(){if(this.parts=[],!!this._entryId)try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object",entry_id:this._entryId});this.parts=t.parts||[],this._partsLoadFailed=!1}catch{this.parts=[],this._partsLoadFailed=!0}}async _loadForeignPools(){if(this._foreignOwners=[],!!this._entryId)try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/objects"});this._foreignOwners=(t.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,e)=>i.name.localeCompare(e.name))}catch{this._foreignOwners=[]}}async _loadTags(){try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/tags/list"});this._availableTags=t.tags||[]}catch{this._availableTags=[]}}_fetchConditionAttributes(t){!t||!this.hass||this._conditionAttrOptions[t]||this._conditionAttrPending.has(t)||(this._conditionAttrPending.add(t),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:t}).then(i=>{let e=i;this._conditionAttrOptions={...this._conditionAttrOptions,[t]:{suggested:e.suggested_attributes||[],available:e.available_attributes||[]}}}).catch(()=>{this._conditionAttrOptions={...this._conditionAttrOptions,[t]:{suggested:[],available:[]}}}))}async _fetchEntityAttributes(t){if(!t||!this.hass){this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="";return}try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:t});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(t=>!!t.entry_id)}_renderConsumesRow(t,i){let e=N({part_id:t.id,entry_id:i}),r=this._consumesParts[e],c=i?{part_id:t.id,quantity:1,entry_id:i}:{part_id:t.id,quantity:1};return a`
${r!==void 0?a`{let u=parseFloat(p.target.value);this._consumesParts={...this._consumesParts,[e]:{...c,quantity:Number.isFinite(u)&&u>=.01?u:1}}}}
/>`:_}
`}_toggleRequired(t,i){let e=new Set(this._requiredCompletion);i?e.add(t):e.delete(t),this._requiredCompletion=[...e]}_phaseSlug(t){let i=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"phase",e=i,r=2;for(;this._phaseDefs.some(c=>c.id===e);)e=`${i}-${r++}`;return e}_addPhaseDef(){let t=this._phaseSlug(`phase-${this._phaseDefs.length+1}`);this._phaseDefs=[...this._phaseDefs,{id:t,name:"",checklistText:"",partId:"",partQty:"",reqOverride:!1,reqFields:[],extraParts:[],carry:{}}]}_removePhaseDef(t){this._phaseDefs=this._phaseDefs.filter(i=>i.id!==t),this._phaseSeq=this._phaseSeq.filter(i=>i!==t)}_patchPhaseDef(t,i){this._phaseDefs=this._phaseDefs.map(e=>e.id===t?{...e,...i}:e)}_renderPhasesEditor(t){let i=e=>this._phaseDefs.find(r=>r.id===e)?.name||e;return a`
${s("phases_section",t)}
${s("phases_hint",t)}
${this._phaseDefs.map(e=>a`
`)}
${s("phase_add",t)}
${this._phaseDefs.some(e=>e.name.trim())?a`
${s("phase_sequence_label",t)}
${this._phaseSeq.map((e,r)=>a`
${r+1}. ${i(e)}
`)}
`:_}
`}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let t=parseInt(this._adaptiveMin,10),i=parseInt(this._adaptiveMax,10);if(!isNaN(t)&&!isNaN(i)&&t>i){this._error=`${s("adaptive_min_interval",this._lang)} > ${s("adaptive_max_interval",this._lang)}`;return}}this._loading=!0,this._error="";try{let t={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();t.earliest_completion_days=i===""?null:Math.max(0,parseInt(i,10)||0),this._taskId&&(t.task_id=this._taskId),this._scheduleType==="one_time"?(t.due_date=this._dueDate||null,t.interval_days=null):st.includes(this._scheduleType)?(t.schedule={...this._buildSchedule(),...this._recurrenceExtras()},t.interval_days=null,this._taskId&&(t.due_date=null)):(this._taskId&&(t.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(t.interval_days=parseInt(this._intervalDays,10),t.interval_unit=this._intervalUnit,t.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(t.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(t.interval_days=null,t.interval_anchor="completion")),t.notes=this._notes||null,t.documentation_url=this._documentationUrl||null,t.custom_icon=this._customIcon||null,t.priority=this._priority,t.labels=this._labels.split(",").map(p=>p.trim()).filter(Boolean),t.enabled=this._enabled,t.last_performed=this._lastPerformed||null,t.nfc_tag_id=this._nfcTagId||null,t.require_tag_scan=this._requireTagScan,t.reading_unit=this._readingUnit.trim()||null;{let p={};for(let h of this._phaseDefs){if(!h.name.trim())continue;let g={...h.carry,name:h.name.trim()},$=h.checklistText.split(`
`).map(y=>y.trim()).filter(Boolean);$.length&&(g.checklist=$);let b=[];if(h.partId){let y=parseFloat(h.partQty);b.push({part_id:h.partId,quantity:Number.isFinite(y)&&y>0?y:1})}for(let y of h.extraParts)b.push(y.entry_id?{part_id:y.part_id,quantity:y.quantity,entry_id:y.entry_id}:{part_id:y.part_id,quantity:y.quantity});b.length&&(g.consumes_parts=b),h.reqOverride&&(g.required_completion_fields=[...h.reqFields]),p[h.id]=g}let u=this._phaseSeq.filter(h=>h in p);t.phases=Object.keys(p).length&&u.length?p:null,t.phase_sequence=t.phases?u:null}if((this.parts.length||this._foreignOwners.length)&&(t.consumes_parts=Object.values(this._consumesParts).map(p=>p.entry_id?{part_id:p.part_id,quantity:p.quantity,entry_id:p.entry_id}:{part_id:p.part_id,quantity:p.quantity})),t.responsible_user_id=this._responsibleUserId,t.assignee_pool=this._assigneePool,t.required_completion_fields=this._requiredCompletion,t.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let p=this._compoundConditions.map(Gt).filter(u=>u!==null);if(p.length>0){let u={type:"compound",compound_logic:this._compoundLogic,conditions:p};this._autoCompleteOnRecovery&&(u.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(u.trigger_combinator="all"),t.trigger_config=u}else this._taskId&&(t.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let p=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],u={entity_id:p[0],entity_ids:p,type:this._triggerType};if(this._triggerAttribute&&(u.attribute=this._triggerAttribute),this._autoCompleteOnRecovery&&(u.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(u.trigger_combinator="all"),p.length>1&&(u.entity_logic=this._triggerEntityLogic),this._triggerType==="threshold"){if(this._triggerAbove){let h=parseFloat(this._triggerAbove);isNaN(h)||(u.trigger_above=h)}if(this._triggerBelow){let h=parseFloat(this._triggerBelow);isNaN(h)||(u.trigger_below=h)}if(this._triggerEquals){let h=parseFloat(this._triggerEquals);isNaN(h)||(u.trigger_equals=h)}if(this._triggerNotEquals){let h=parseFloat(this._triggerNotEquals);isNaN(h)||(u.trigger_not_equals=h)}if(this._triggerForMinutes){let h=parseInt(this._triggerForMinutes,10);isNaN(h)||(u.trigger_for_minutes=h)}}else if(this._triggerType==="counter"){if(this._triggerTargetValue){let h=parseFloat(this._triggerTargetValue);isNaN(h)||(u.trigger_target_value=h)}if(u.trigger_delta_mode=this._triggerDeltaMode,this._triggerDeltaMode&&this._triggerBaselineValue){let h=parseFloat(this._triggerBaselineValue);!isNaN(h)&&h>=0&&(u.trigger_baseline_value=h)}}else if(this._triggerType==="state_change"){if(this._triggerFromState&&(u.trigger_from_state=this._triggerFromState),this._triggerToState&&(u.trigger_to_state=this._triggerToState),this._triggerTargetChanges){let h=parseInt(this._triggerTargetChanges,10);isNaN(h)||(u.trigger_target_changes=h)}if(this._triggerForMinutes){let h=parseInt(this._triggerForMinutes,10);isNaN(h)||(u.trigger_for_minutes=h)}}else if(this._triggerType==="runtime"){if(this._triggerRuntimeHours){let g=parseFloat(this._triggerRuntimeHours);isNaN(g)||(u.trigger_runtime_hours=g)}let h=this._triggerOnStates.split(",").map(g=>g.trim()).filter(Boolean);h.length>0&&(u.trigger_on_states=h)}t.trigger_config=u}else this._taskId&&(t.trigger_config=null);if(this.scheduleTimeEnabled&&this._scheduleType==="time_based"){let p=this._scheduleTime.trim();t.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(p)?p:null}if(this.checklistsEnabled){let p=this._checklistText.split(`
`).map(u=>u.trim()).filter(Boolean).slice(0,100);t.checklist=p.length?p:null}if(this.completionActionsEnabled){let p=this._actionService.trim();if(p&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(p)){let $={service:p},b=this._actionTargetEntity.trim();b&&($.target={entity_id:b});let y=this._buildActionData();Object.keys(y).length>0&&($.data=y),t.on_complete_action=$}else t.on_complete_action=null;let u={};this._qcNotes.trim()&&(u.notes=this._qcNotes.trim());let h=parseFloat(this._qcCost);!isNaN(h)&&h>=0&&(u.cost=h);let g=parseInt(this._qcDuration,10);!isNaN(g)&&g>=0&&(u.duration=g),this._qcFeedback&&(u.feedback=this._qcFeedback),t.quick_complete_defaults=Object.keys(u).length?u:null}let e=await this.hass.connection.sendMessagePromise(t),r=this._taskId||e?.task_id,c=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;if(r&&this._scheduleType==="sensor_based"&&c)try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:r,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null}),this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute}catch{}if(r&&this._adaptiveSnapshot()!==this._adaptiveInitial){let p=parseFloat(this._adaptiveAlpha),u=parseInt(this._adaptiveMin,10),h=parseInt(this._adaptiveMax,10);try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:r,enabled:this._adaptiveEnabled,...p>=.1&&p<=.9?{ewa_alpha:p}:{},...!isNaN(u)&&u>=1?{min_interval_days:u}:{},...!isNaN(h)&&h>=1?{max_interval_days:h}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction}),this._adaptiveInitial=this._adaptiveSnapshot()}catch{}}this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}catch(t){this._error=T(t,this._lang,s("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 _;let t=this._lang,i=this._triggerType==="compound";return a`
${s("trigger_configuration",t)}
${i?this._renderCompoundEditor():a`
${this._entityPickerFallback?a`
0?this._triggerEntityIds.join(", "):this._triggerEntityId}
@input=${e=>{let c=e.target.value.split(",").map(p=>p.trim()).filter(Boolean);this._triggerEntityId=c[0]||"",this._triggerEntityIds=c,c[0]&&this._fetchEntityAttributes(c[0])}}
>
`:a`
0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}}
.computeLabel=${()=>s("entity_id",t)}
@value-changed=${e=>{let r=(e.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=r[0]||"",this._triggerEntityIds=r,r[0]?this._fetchEntityAttributes(r[0]):this._fetchEntityAttributes("")}}
>`}
${this._triggerEntityIds.length>1?a`
`:_}
${this._renderAttributeSelect({label:s("attribute_optional",t),value:this._triggerAttribute,suggested:this._suggestedAttributes,available:this._availableAttributes,onSelect:e=>this._triggerAttribute=e})}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
${s("auto_complete_on_recovery_help",t)}
this._intervalDays=e.target.value}
>
${this._intervalDays?this._renderUnitSelect():_}
${this._intervalDays?a`
`:_}
`}_patchCondition(t,i){this._compoundConditions=this._compoundConditions.map((e,r)=>r===t?{...e,...i}:e)}_addCondition(){this._compoundConditions=[...this._compoundConditions,Kt()]}_removeCondition(t){this._compoundConditions=this._compoundConditions.filter((i,e)=>e!==t)}_renderCompoundEditor(){let t=this._lang;return a`
${s("compound_help",t)}
${this._compoundConditions.length===0?a`${s("compound_no_conditions",t)}
`:this._compoundConditions.map((i,e)=>this._renderCondition(i,e))}
`}_renderCondition(t,i){let e=this._lang,r=i+1;return a`
${s("compound_condition",e)} ${r}
${this._entityPickerFallback?a`
this._patchCondition(i,{entityIds:c.target.value})}
>
`:a`
c.trim()).filter(Boolean)}}
.computeLabel=${()=>s("entity_id",e)}
@value-changed=${c=>{let p=(c.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(i,{entityIds:p.join(", ")})}}
>`}
${this._renderConditionAttribute(t,i)}
${this._renderConditionTypeFields(t,i)}
`}_renderStateField(t){return this._entityPickerFallback||!t.entityId?a`
t.onInput(i.target.value)}
>
`:a`
t.label}
@value-changed=${i=>t.onInput((i.detail.value.s||"").trim())}
>
`}_renderOnStatesField(t){let i=this._lang;return this._entityPickerFallback||!t.entityId?a`
t.onInput(e.target.value)}
>
`:a`
e.trim()).filter(Boolean)}}
.computeLabel=${()=>s("runtime_on_states",i)}
@value-changed=${e=>t.onInput((e.detail.value.s||[]).join(", "))}
>
`}_renderAdaptiveSection(t){return this._scheduleType==="one_time"||this._scheduleType==="manual"?_:a`
${s("adaptive_section_title",t)}
${this._adaptiveEnabled?a`
this._adaptiveMin=i.target.value}
>
this._adaptiveMax=i.target.value}
>
this._adaptiveAlpha=i.target.value}
>
`:_}
`}_renderAttributeSelect(t){let i=this._lang;return t.available.length>0?a`
`:a`
t.onSelect(e.target.value.trim())}
>
`}_renderEnvironmentalAttribute(t){this._fetchConditionAttributes(this._environmentalEntity);let i=this._conditionAttrOptions[this._environmentalEntity];return this._renderAttributeSelect({label:s("environmental_attribute_optional",t),value:this._environmentalAttribute,suggested:i?.suggested??[],available:i?.available??[],onSelect:e=>this._environmentalAttribute=e})}_renderConditionAttribute(t,i){let e=t.entityIds.split(",")[0]?.trim()||"";e&&this._fetchConditionAttributes(e);let r=e?this._conditionAttrOptions[e]:void 0;return this._renderAttributeSelect({label:s("attribute_optional",this._lang),value:t.attribute,suggested:r?.suggested??[],available:r?.available??[],onSelect:c=>this._patchCondition(i,{attribute:c})})}_renderConditionTypeFields(t,i){let e=this._lang;if(t.type==="threshold")return a`
this._patchCondition(i,{above:r.target.value})}>
this._patchCondition(i,{below:r.target.value})}>
this._patchCondition(i,{equals:r.target.value})}>
this._patchCondition(i,{notEquals:r.target.value})}>
this._patchCondition(i,{forMinutes:r.target.value})}>
`;if(t.type==="counter")return a`
this._patchCondition(i,{targetValue:r.target.value})}>
`;if(t.type==="state_change"){let r=t.entityIds.split(",")[0]?.trim()||"";return a`
${this._renderStateField({label:s("from_state_optional",e),value:t.fromState,entityId:r,onInput:c=>this._patchCondition(i,{fromState:c})})}
${this._renderStateField({label:s("to_state_optional",e),value:t.toState,entityId:r,onInput:c=>this._patchCondition(i,{toState:c})})}
this._patchCondition(i,{targetChanges:c.target.value})}>
`}if(t.type==="runtime"){let r=t.entityIds.split(",")[0]?.trim()||"";return a`
this._patchCondition(i,{runtimeHours:c.target.value})}>
${this._renderOnStatesField({value:t.onStates,entityId:r,onInput:c=>this._patchCondition(i,{onStates:c})})}
`}return _}_renderUnitSelect(){let t=this._lang;return a`
`}_toggleWeekday(t){this._weekdays=this._weekdays.includes(t)?this._weekdays.filter(i=>i!==t):[...this._weekdays,t]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(st.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let t=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!t||t<=0?null:{kind:"interval",every:t,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(t){super.updated?.(t),this._scheduleEntityPickerProbe();for(let i of t.keys())if(m._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 t=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),i=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!t||!i){this._pickerProbeStrikes=0;return}let e=(u,h,g=0)=>{if(!(!u||g>10)){(u.tagName?.toLowerCase()??"")==="ha-entity-picker"&&h.push(u);for(let $ of[u.shadowRoot,u])if($)for(let b of Array.from($.children??[]))e(b,h,g+1)}},r=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],c=[];for(let u of r)e(u,c);let p=c.length===0||c.some(u=>u.offsetHeight===0);if(t.offsetHeight===0||p){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 t=this._open?this._previewScheduleDict():null;if(!t){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let i=++this._previewSeq;try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:t,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(i!==this._previewSeq)return;this._schedulePreview=e.occurrences||[],this._schedulePreviewEnded=!!e.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return _;let t=this._lang,i=this.scheduleTimeEnabled&&this._scheduleTime?` ${this._scheduleTime}`:"",e=this._schedulePreview.map((c,p)=>{let u=new Date(`${c}T12:00:00`).getDay();return`${tt(u===0?6:u-1,t,"short")} ${V(c,t)}${p===0?i:""}`}).join(" \xB7 "),r=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?a`${s("schedule_preview_ontime",t)}
`:_;return a`
${s("schedule_preview_title",t)}: ${e}${this._schedulePreviewEnded?a` ${s("schedule_preview_ends",t)}`:_}
${r}
`}_buildSchedule(){let t=e=>{let r=parseInt(this._calOffset,10)||0;return r&&(e.offset=Math.max(-15,Math.min(r,15))),e};if(this._scheduleType==="weekdays")return t({kind:"weekdays",weekdays:[...this._weekdays].sort((e,r)=>e-r)});if(this._scheduleType==="nth_weekday")return t({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});let i={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(i.business=!0),t(i)}_recurrenceExtras(){let t={};if(this._seasonMonths.length&&(t.season_months=[...this._seasonMonths].sort((i,e)=>i-e)),this._endsMode==="count"){let i=parseInt(this._endsCount,10);i>=1&&(t.ends={count:i})}else this._endsMode==="until"&&this._endsUntil&&(t.ends={until:this._endsUntil});return t}_toggleSeasonMonth(t){this._seasonMonths=this._seasonMonths.includes(t)?this._seasonMonths.filter(i=>i!==t):[...this._seasonMonths,t]}_renderRecurrenceExtras(){let t=this._lang;if(!(this._scheduleType==="time_based"||st.includes(this._scheduleType)))return _;let e=Jt(t);return a`
${s("season_window_hint",t)}
${e.map((r,c)=>a`
`)}
${this._endsMode==="count"?a`
this._endsCount=r.target.value}
>`:_}
${this._endsMode==="until"?a`
this._endsUntil=r.target.value}
>`:_}
`}_renderCalendarFields(){let t=this._lang,i=Zt(t);if(this._scheduleType==="weekdays")return a`
${i.map((e,r)=>a`
`)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let e=[["1",s("ord_1",t)],["2",s("ord_2",t)],["3",s("ord_3",t)],["4",s("ord_4",t)],["5",s("ord_5",t)],["-1",s("ord_last",t)]];return a`
${this._renderCalOffsetField()}`}return this._scheduleType==="day_of_month"?a`
${this._domLastDay?_:a`
this._domDay=e.target.value}
>`}
${this._renderCalOffsetField()}`:_}_renderCalOffsetField(){let t=this._lang;return a`
this._calOffset=i.target.value}
>`}_renderTriggerLiveHint(){if(this._triggerType==="compound")return _;let t=this._triggerEntityId||this._triggerEntityIds[0];if(!t||!this.hass?.states)return _;let i=this.hass.states[t];if(!i)return _;let e=this._lang,r=i.attributes?.unit_of_measurement,c=typeof r=="string"&&r?` ${r}`:"",p=this._triggerAttribute?i.attributes?.[this._triggerAttribute]:i.state,u=typeof p=="number"?p:parseFloat(String(p)),h=p!=="unknown"&&p!=="unavailable"&&p!=null&&!isNaN(u),g=b=>Number.isInteger(b)?String(b):String(Math.round(b*10)/10),$=[];if(this._triggerType==="threshold"){let b=parseFloat(this._triggerAbove),y=parseFloat(this._triggerBelow);if(isNaN(b)&&isNaN(y))return _;h&&$.push(s("trigger_hint_now",e).replace("{value}",g(u)+c)),isNaN(b)||$.push(s("trigger_hint_above",e).replace("{target}",g(b)+c)),isNaN(y)||$.push(s("trigger_hint_below",e).replace("{target}",g(y)+c))}else if(this._triggerType==="counter"){let b=parseFloat(this._triggerTargetValue);if(isNaN(b))return _;this._triggerDeltaMode?this._taskId?$.push(s("trigger_hint_counter_delta_edit",e).replace("{target}",g(b)+c)):h?$.push(s("trigger_hint_counter_delta",e).replace("{value}",g(u)+c).replace("{due}",g(u+b)+c).replace("{target}",g(b)+c)):$.push(s("trigger_hint_counter_delta_edit",e).replace("{target}",g(b)+c)):(h&&$.push(s("trigger_hint_now",e).replace("{value}",g(u)+c)),$.push(s("trigger_hint_counter_abs",e).replace("{target}",g(b)+c)))}else if(this._triggerType==="runtime"){let b=parseFloat(this._triggerRuntimeHours);if(isNaN(b))return _;$.push(s("trigger_hint_runtime",e).replace("{hours}",g(b))),$.push(s("trigger_hint_state_now",e).replace("{value}",String(i.state)))}else if(this._triggerType==="state_change"){let b=parseInt(this._triggerTargetChanges,10)||1,y=this._triggerToState.trim();$.push((y?s("trigger_hint_state_change_to",e).replace("{state}",y):s("trigger_hint_state_change",e)).replace("{count}",String(b))),$.push(s("trigger_hint_state_now",e).replace("{value}",String(i.state)))}return $.length?a`${$.join(" ")}
`:_}_renderTriggerTypeFields(){let t=this._lang;return this._triggerType==="threshold"?a`
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"?a`
this._triggerTargetValue=i.target.value}
>
${this._triggerDeltaMode?a`
this._triggerBaselineValue=i.target.value}
>
${this._taskId?s("baseline_start_help_edit",t):s("baseline_start_help",t)}
${this._taskId&&this._liveBaselineValue!=null?a`
${s("baseline_current_effective",t).replace("{value}",String(this._liveBaselineValue))}
`:_}
`:_}
`:this._triggerType==="state_change"?a`
${this._renderStateField({label:s("from_state_optional",t),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:i=>this._triggerFromState=i})}
${s("state_value_help",t)}
${this._renderStateField({label:s("to_state_optional",t),value:this._triggerToState,entityId:this._triggerEntityId,onInput:i=>this._triggerToState=i})}
this._triggerTargetChanges=i.target.value}
>
${s("target_changes_help",t)}
this._triggerForMinutes=i.target.value}
>
${s("for_minutes_state_help",t)}
`:this._triggerType==="runtime"?a`
this._triggerRuntimeHours=i.target.value}
>
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:i=>this._triggerOnStates=i})}
${s("runtime_on_states_help",t)}
`:_}render(){if(!this._open)return a``;let t=this._lang,i=this._taskId?s("edit_task",t):s("new_task",t);return a`
${i}
${this._error?a`
${this._error}
`:_}
${this._taskId===null&&this._objectChoices.length>0?a`
`:_}
this._name=e.target.value}
>
${this._type==="reading"?a`
this._readingUnit=e.target.value}
>
${s("reading_unit_help",t)}
`:_}
${this._partsLoadFailed?a`
${s("parts_load_failed",t)}
`:_}
${this.parts.length||this._foreignOwners.length?a`
${this.parts.map(e=>this._renderConsumesRow(e))}
${this._foreignOwners.length?a`
${s("shared_parts_other_objects",t)}
${s("shared_parts_help",t)}
${this._foreignOwners.map(e=>a`
${e.name}
${e.parts.map(r=>this._renderConsumesRow(r,e.entry_id))}
`)}
`:_}
`:_}
${this._scheduleType==="time_based"?a`
this._intervalDays=e.target.value}
>
${this._renderUnitSelect()}
${this.scheduleTimeEnabled?a`
this._scheduleTime=e.target.value}
>
`:_}
`:_}
${this._renderCalendarFields()}
${this._scheduleType==="one_time"?a`
this._dueDate=e.target.value}
>
`:_}
${this._renderRecurrenceExtras()}
${this._renderSchedulePreview()}
this._warningDays=e.target.value}
>
this._earliestCompletionDays=e.target.value}
>
${this.checklistsEnabled?a`
${s("checklist_steps_optional",t)}
${s("checklist_help",t)}
`:_}
${this._renderPhasesEditor(t)}
${s("require_on_completion",t)}
${it.map(e=>a`
`)}
this._lastPerformed=e.target.value}
>
${this._availableUsers.length>=2?a`
${this._assigneePool.length>=2?a`
`:_}
`:_}
${this._renderTriggerFields()}
${this._scheduleType==="sensor_based"?a`
${this._entityPickerFallback?a`
this._environmentalEntity=e.target.value.trim()}
>
`:a`
s("environmental_entity_optional",t)}
.computeHelper=${()=>s("environmental_entity_helper",t)}
@value-changed=${e=>{this._environmentalEntity=(e.detail.value.environmental_entity||"").trim()}}
>`}
${this._environmentalEntity?this._renderEnvironmentalAttribute(t):_}
`:_}
${this._renderAdaptiveSection(t)}
this._notes=e.target.value}
>
this._documentationUrl=e.target.value}
>
this._customIcon=e.detail.value||""}
>
${this._availableTags.length>0?a`
`:a`
this._nfcTagId=e.target.value}
>
`}
${this._requireTagScan?a`
${s("require_tag_scan_help",t)}
`:_}
${this._renderCompletionActionsSection(t)}
${s("cancel",t)}
${this._loading?s("saving",t):s("save",t)}
`}};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;
}
.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 {
--mdc-icon-button-size: 36px;
color: var(--secondary-text-color);
}
.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);
}
.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;
}
`,o([v({attribute:!1})],m.prototype,"hass",2),o([v({type:Boolean,attribute:"checklists-enabled"})],m.prototype,"checklistsEnabled",2),o([v({type:Boolean,attribute:"schedule-time-enabled"})],m.prototype,"scheduleTimeEnabled",2),o([v({type:Boolean,attribute:"completion-actions-enabled"})],m.prototype,"completionActionsEnabled",2),o([v({type:Number,attribute:"default-warning-days"})],m.prototype,"defaultWarningDays",2),o([d()],m.prototype,"parts",2),o([d()],m.prototype,"_foreignOwners",2),o([d()],m.prototype,"_open",2),o([d()],m.prototype,"_entityPickerFallback",2),o([d()],m.prototype,"_loading",2),o([d()],m.prototype,"_error",2),o([d()],m.prototype,"_entryId",2),o([d()],m.prototype,"_taskId",2),o([d()],m.prototype,"_objectChoices",2),o([d()],m.prototype,"_name",2),o([d()],m.prototype,"_type",2),o([d()],m.prototype,"_scheduleType",2),o([d()],m.prototype,"_intervalDays",2),o([d()],m.prototype,"_intervalUnit",2),o([d()],m.prototype,"_dueDate",2),o([d()],m.prototype,"_warningDays",2),o([d()],m.prototype,"_earliestCompletionDays",2),o([d()],m.prototype,"_intervalAnchor",2),o([d()],m.prototype,"_weekdays",2),o([d()],m.prototype,"_nth",2),o([d()],m.prototype,"_nthWeekday",2),o([d()],m.prototype,"_domDay",2),o([d()],m.prototype,"_domLastDay",2),o([d()],m.prototype,"_domBusiness",2),o([d()],m.prototype,"_calOffset",2),o([d()],m.prototype,"_seasonMonths",2),o([d()],m.prototype,"_endsMode",2),o([d()],m.prototype,"_endsCount",2),o([d()],m.prototype,"_endsUntil",2),o([d()],m.prototype,"_schedulePreview",2),o([d()],m.prototype,"_schedulePreviewEnded",2),o([d()],m.prototype,"_notes",2),o([d()],m.prototype,"_documentationUrl",2),o([d()],m.prototype,"_customIcon",2),o([d()],m.prototype,"_priority",2),o([d()],m.prototype,"_labels",2),o([d()],m.prototype,"_enabled",2),o([d()],m.prototype,"_triggerEntityId",2),o([d()],m.prototype,"_triggerEntityIds",2),o([d()],m.prototype,"_triggerEntityLogic",2),o([d()],m.prototype,"_triggerAttribute",2),o([d()],m.prototype,"_triggerType",2),o([d()],m.prototype,"_triggerAbove",2),o([d()],m.prototype,"_triggerBelow",2),o([d()],m.prototype,"_triggerEquals",2),o([d()],m.prototype,"_triggerNotEquals",2),o([d()],m.prototype,"_triggerForMinutes",2),o([d()],m.prototype,"_triggerCombinator",2),o([d()],m.prototype,"_triggerTargetValue",2),o([d()],m.prototype,"_triggerDeltaMode",2),o([d()],m.prototype,"_triggerBaselineValue",2),o([d()],m.prototype,"_liveBaselineValue",2),o([d()],m.prototype,"_autoCompleteOnRecovery",2),o([d()],m.prototype,"_triggerFromState",2),o([d()],m.prototype,"_triggerToState",2),o([d()],m.prototype,"_triggerTargetChanges",2),o([d()],m.prototype,"_triggerRuntimeHours",2),o([d()],m.prototype,"_triggerOnStates",2),o([d()],m.prototype,"_compoundLogic",2),o([d()],m.prototype,"_compoundConditions",2),o([d()],m.prototype,"_suggestedAttributes",2),o([d()],m.prototype,"_availableAttributes",2),o([d()],m.prototype,"_entityDomain",2),o([d()],m.prototype,"_lastPerformed",2),o([d()],m.prototype,"_nfcTagId",2),o([d()],m.prototype,"_requireTagScan",2),o([d()],m.prototype,"_readingUnit",2),o([d()],m.prototype,"_consumesParts",2),o([d()],m.prototype,"_partsLoadFailed",2),o([d()],m.prototype,"_availableTags",2),o([d()],m.prototype,"_responsibleUserId",2),o([d()],m.prototype,"_assigneePool",2),o([d()],m.prototype,"_rotationStrategy",2),o([d()],m.prototype,"_availableUsers",2),o([d()],m.prototype,"_checklistText",2),o([d()],m.prototype,"_phaseDefs",2),o([d()],m.prototype,"_phaseSeq",2),o([d()],m.prototype,"_requiredCompletion",2),o([d()],m.prototype,"_scheduleTime",2),o([d()],m.prototype,"_actionService",2),o([d()],m.prototype,"_actionTargetEntity",2),o([d()],m.prototype,"_actionData",2),o([d()],m.prototype,"_actionDataJsonFallback",2),o([d()],m.prototype,"_actionTesting",2),o([d()],m.prototype,"_actionTestResult",2),o([d()],m.prototype,"_actionTestError",2),o([d()],m.prototype,"_qcNotes",2),o([d()],m.prototype,"_qcCost",2),o([d()],m.prototype,"_qcDuration",2),o([d()],m.prototype,"_qcFeedback",2),o([d()],m.prototype,"_environmentalEntity",2),o([d()],m.prototype,"_environmentalAttribute",2),o([d()],m.prototype,"_adaptiveEnabled",2),o([d()],m.prototype,"_adaptiveAlpha",2),o([d()],m.prototype,"_adaptiveMin",2),o([d()],m.prototype,"_adaptiveMax",2),o([d()],m.prototype,"_adaptiveSeasonal",2),o([d()],m.prototype,"_adaptivePrediction",2),o([d()],m.prototype,"_conditionAttrOptions",2);var rt=m;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",rt);var f=class extends I{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.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._photoDocId="";this._photoPreview="";this._photoUploading=!1;this._readingValue="";this._restockQty="";this._completedAt="";this._usedParts={};this.checklistPrefill={}}open(t={}){this._open||(this._open=!0,this.viaTagScan=!!t.viaTagScan,this._notes="",this._cost="",this._duration="",this._error="",this._checklistState=Object.fromEntries(this.checklist.map((i,e)=>[String(e),!!this.checklistPrefill[i]]).filter(([,i])=>i)),this._feedback="needed",this._photoDocId="",this._photoPreview="",this._photoUploading=!1,this._readingValue="",this._restockQty=this.restockDefault!==null?String(this.restockDefault):"",this._completedAt="",this._usedParts=Object.fromEntries(this.consumesParts.map(i=>[N(i),{...i}])))}_toggleCheck(t){let i=String(t);this._checklistState={...this._checklistState,[i]:!this._checklistState[i]}}_setFeedback(t){this._feedback=t}async _onPhotoInput(t){let i=t.target,e=i.files?.[0];if(i.value="",!!e){this._photoUploading=!0,this._error="";try{let r=new FormData;r.append("entry_id",this.entryId),r.append("tags","photo"),r.append("file",e,e.name);let c=await fetch("/api/maintenance_supporter/document/upload",{method:"POST",headers:{Authorization:`Bearer ${this.hass.auth?.data?.access_token??""}`},body:r});if(!c.ok){this._error=c.status===413?s("doc_too_large",this.lang):s("doc_upload_failed",this.lang);return}let p=await c.json();p.id&&(this._photoDocId=p.id,this._photoPreview=URL.createObjectURL(e))}catch{this._error=s("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 t={type:"maintenance_supporter/task/complete",entry_id:this.entryId,task_id:this.taskId};if(this._notes&&(t.notes=this._notes),this._cost){let i=parseFloat(this._cost);!isNaN(i)&&i>=0&&(t.cost=i)}if(this._duration){let i=parseInt(this._duration,10);!isNaN(i)&&i>=0&&(t.duration=i)}if(this.checklist.length>0&&(t.checklist_state=this._checklistState),this.adaptiveEnabled&&(t.feedback=this._feedback),this._photoDocId&&(t.photo_doc_id=this._photoDocId),this.viaTagScan&&(t.via_tag_scan=!0),this._completedAt){if(new Date(this._completedAt).getTime()>Date.now()){this._error=s("completed_at_future_error",this.lang),this._loading=!1;return}t.completed_at=this._completedAt.length===16?`${this._completedAt}:00`:this._completedAt}if(this._readingValue!==""){let i=parseFloat(this._readingValue);isNaN(i)||(t.reading_value=i)}if(this.restockDefault!==null&&this._restockQty!==""){let i=parseFloat(this._restockQty);!isNaN(i)&&i>=1&&(t.restock_quantity=i)}this.parts.length>0&&(t.used_parts=Object.values(this._usedParts).filter(i=>Number.isFinite(i.quantity)&&i.quantity>0).map(i=>i.entry_id?{part_id:i.part_id,quantity:i.quantity,entry_id:i.entry_id}:{part_id:i.part_id,quantity:i.quantity})),await this.hass.connection.sendMessagePromise(t),this._open=!1,this.dispatchEvent(new CustomEvent("task-completed"))}catch(t){this._error=T(t,this.lang,s("save_error",this.lang))}finally{this._loading=!1}}get _missingRequired(){let t={notes:this._notes.trim()!=="",cost:this._cost.trim()!=="",duration:this._duration.trim()!=="",photo:this._photoDocId!=="",user:!!this.hass?.user};return this.requiredFields.filter(i=>!t[i])}_req(t){return this.requiredFields.includes(t)?a`*`:_}_partsCostSuggestion(){if(this.restockDefault!==null){let e=parseFloat(this._restockQty);return this.restockUnitCost==null||!Number.isFinite(e)||e<=0?null:Math.round(this.restockUnitCost*e*100)/100}if(!this.parts.length)return null;let t=0,i=!1;for(let e of Object.values(this._usedParts)){let r=this.parts.find(c=>N({part_id:c.id,entry_id:c.entry_id})===N(e));r?.cost!=null&&(t+=r.cost*(e.quantity||1),i=!0)}return i?Math.round(t*100)/100:null}_renderCostSuggestion(t){if(this._cost.trim()!=="")return _;let i=this._partsCostSuggestion();if(i==null||i<=0)return _;let e=`${i.toFixed(2)}${this.currencySymbol?` ${this.currencySymbol}`:""}`;return a``}_close(){this._open=!1}render(){if(!this._open)return a``;let t=this.lang||this.hass?.language||"en";return a`
${s("complete_title",t)}${this.taskName}
${this.phaseLabel?a`${s("phase_current",t)}: ${this.phaseLabel}
`:_}
${this.requireTagScan&&!this.viaTagScan?a`${s("require_tag_scan_hint",t)}
`:_}
${this._error?a`
${this._error}
`:_}
${this.checklist.length>0?a`
${this.checklist.map((i,e)=>a`
`)}
`:_}
${this.taskType==="reading"?a`
`:_}
${this.parts.length?a`
${s("complete_parts_used",t)}
${this.parts.map(i=>{let e=N({part_id:i.id,entry_id:i.entry_id}),r=this._usedParts[e],c=r!==void 0,p=i.entry_id?{part_id:i.id,quantity:1,entry_id:i.entry_id}:{part_id:i.id,quantity:1};return a`
${c?a`{let h=parseFloat(u.target.value);this._usedParts={...this._usedParts,[e]:{...p,quantity:Number.isFinite(h)&&h>=.01?h:1}}}} />`:_}
`})}
`:this.consumesInfo.length?a`
${this.consumesInfo.map(i=>a`
${i}
`)}
`:_}
${this.restockDefault!==null?a`
`:_}
${s("completion_photo_optional",t)}${this._req("photo")}
${this._photoPreview?a`
`:a`
`}
${this.adaptiveEnabled?a`
`:_}
${s("cancel",t)}
0}
title=${this._missingRequired.length?this._missingRequired.map(i=>s("err_required",t).replace("{field}",s(Q[i]??i,t))).join(" \xB7 "):""}
>
${this._loading?s("completing",t):s("complete",t)}
`}};f.styles=[ut,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;
}
.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 */
.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);
}
`],o([v({attribute:!1})],f.prototype,"hass",2),o([v()],f.prototype,"entryId",2),o([v()],f.prototype,"taskId",2),o([v()],f.prototype,"taskName",2),o([v()],f.prototype,"lang",2),o([v({type:Array})],f.prototype,"checklist",2),o([v({type:Boolean})],f.prototype,"adaptiveEnabled",2),o([v()],f.prototype,"taskType",2),o([v()],f.prototype,"readingUnit",2),o([v({attribute:!1})],f.prototype,"restockDefault",2),o([v({attribute:!1})],f.prototype,"restockUnitCost",2),o([v()],f.prototype,"currencySymbol",2),o([v({attribute:!1})],f.prototype,"parts",2),o([v({attribute:!1})],f.prototype,"consumesParts",2),o([v({type:Array})],f.prototype,"consumesInfo",2),o([v({type:Array})],f.prototype,"requiredFields",2),o([v()],f.prototype,"phaseLabel",2),o([v({type:Boolean})],f.prototype,"requireTagScan",2),o([v({type:Boolean})],f.prototype,"viaTagScan",2),o([d()],f.prototype,"_open",2),o([d()],f.prototype,"_notes",2),o([d()],f.prototype,"_cost",2),o([d()],f.prototype,"_duration",2),o([d()],f.prototype,"_loading",2),o([d()],f.prototype,"_error",2),o([d()],f.prototype,"_checklistState",2),o([d()],f.prototype,"_feedback",2),o([d()],f.prototype,"_photoDocId",2),o([d()],f.prototype,"_photoPreview",2),o([d()],f.prototype,"_photoUploading",2),o([d()],f.prototype,"_readingValue",2),o([d()],f.prototype,"_restockQty",2),o([d()],f.prototype,"_completedAt",2),o([d()],f.prototype,"_usedParts",2),o([v({attribute:!1})],f.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",f);var q=class extends I{constructor(){super(...arguments);this._open=!1;this._saving=!1;this._error="";this._draft=null;this._originalSnapshot=null;this._partOptions=null;this._partQty={};this._partQtyOriginal=""}get _lang(){return S(this.hass)}openEdit(t){this._draft={...t},this._originalSnapshot={...t},this._error="",this._open=!0,this._partOptions=null,this._partQty={},this._partQtyOriginal="",this._loadPartOptions()}async _loadPartOptions(){let t=this._draft;if(t)try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/parts/overview"}),e=[];for(let c of i.parts||[]){let p=c.entry_id===t.entry_id,u=c.consumers.some(h=>h.entry_id===t.entry_id&&h.task_id===t.task_id);!p&&!u||e.push({part_id:c.part_id,name:c.name,entry_id:c.entry_id,foreign:!p,object_name:c.object_name})}for(let c of t.used_parts||[]){let p=c.entry_id||t.entry_id;e.some(u=>u.part_id===c.part_id&&u.entry_id===p)||e.push({part_id:c.part_id,name:c.name||c.part_id,entry_id:p,foreign:p!==t.entry_id,object_name:null})}let r={};for(let c of t.used_parts||[])r[`${c.entry_id||t.entry_id}:${c.part_id}`]=c.quantity??1;this._partOptions=e,this._partQty=r,this._partQtyOriginal=this._partSelectionKey()}catch{this._partOptions=[]}}_partSelectionKey(){return JSON.stringify(Object.entries(this._partQty).filter(([,t])=>t>0).sort(([t],[i])=>t.localeCompare(i)))}close(){this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null}_set(t,i){this._draft&&(this._draft={...this._draft,[t]:i})}async _save(){if(!(!this._draft||!this._originalSnapshot)){this._saving=!0,this._error="";try{let t={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&&(t.timestamp=this._draft.timestamp),this._draft.notes!==this._originalSnapshot.notes&&(t.notes=this._draft.notes),this._draft.cost!==this._originalSnapshot.cost&&(t.cost=this._draft.cost),this._draft.duration!==this._originalSnapshot.duration&&(t.duration=this._draft.duration),this._draft.completed_by!==this._originalSnapshot.completed_by&&(t.completed_by=this._draft.completed_by),this._partOptions!==null&&this._partSelectionKey()!==this._partQtyOriginal&&(t.used_parts=(this._partOptions||[]).filter(e=>(this._partQty[`${e.entry_id}:${e.part_id}`]||0)>0).map(e=>({part_id:e.part_id,quantity:this._partQty[`${e.entry_id}:${e.part_id}`],...e.foreign?{entry_id:e.entry_id}:{}}))),Object.keys(t).filter(e=>!["type","entry_id","task_id","original_timestamp"].includes(e)).length===0){this.close();return}await this.hass.connection.sendMessagePromise(t),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(t){this._error=T(t,this._lang)}finally{this._saving=!1}}}render(){if(!this._open||!this._draft)return _;let t=this._lang,i=this._draft;return a`
${s("history_edit_title",t)||"Edit history entry"}
${s(i.type,t)||i.type}
${this._partOptions&&this._partOptions.length>0?a`
${s("complete_parts_used",t)}
${this._partOptions.map(e=>{let r=`${e.entry_id}:${e.part_id}`,c=this._partQty[r]||0;return a`
`})}
`:_}
${this._error?a`
${this._error}
`:_}
`}};q.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;
}
/* #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; }
`,o([v({attribute:!1})],q.prototype,"hass",2),o([d()],q.prototype,"_open",2),o([d()],q.prototype,"_saving",2),o([d()],q.prototype,"_error",2),o([d()],q.prototype,"_draft",2),o([d()],q.prototype,"_partOptions",2),o([d()],q.prototype,"_partQty",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",q);function $t(n,l,t){let i=new Blob([n],{type:t}),e=URL.createObjectURL(i),r=document.createElement("a");r.href=e,r.download=l,r.target="_blank",r.rel="noopener",r.style.display="none",document.body.appendChild(r),r.dispatchEvent(new MouseEvent("click")),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(e),6e4)}function K(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function xt(n){return!n.startsWith("data:image/svg+xml,")&&!n.startsWith("data:image/png;base64,")?"":K(n)}function Xt(n){return n.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var A=class extends I{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(t,i){this._entryId=t,this._taskId=null,this._objectName=i,this._taskName="",this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}openForTask(t,i,e,r){this._entryId=t,this._taskId=i,this._objectName=e,this._taskName=r,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}async _generate(){let t=++this._generateSeq;this._loading=!0,this._error="",this._viewResult=null,this._completeResult=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 e=[this.hass.connection.sendMessagePromise({...i,action:"view"})];this._taskId&&e.push(this.hass.connection.sendMessagePromise({...i,action:"complete"}));let r=await Promise.all(e);if(t!==this._generateSeq)return;this._viewResult=r[0],r.length>1&&(this._completeResult=r[1])}catch(i){if(t!==this._generateSeq)return;let e=i?.code,r=i?.message;this._error=e==="no_url"||typeof r=="string"&&r.includes("No Home Assistant URL")?s("qr_error_no_url",this.lang):s("qr_error",this.lang)}finally{t===this._generateSeq&&(this._loading=!1)}}_setUrlMode(t){this._urlMode!==t&&(this._urlMode=t,this._generate())}_print(){if(!this._viewResult)return;let t=this._viewResult,i=t.label.task_name?`${t.label.object_name} \u2014 ${t.label.task_name}`:t.label.object_name,e=[t.label.manufacturer,t.label.model].filter(Boolean).join(" "),r=window.open("","_blank","width=600,height=500");if(!r)return;let c=this.lang||"en",p=K(i),u=K(e),h=!!this._completeResult,g=K(s("qr_action_view",c)),$=K(s("qr_action_complete",c));r.document.write(`
${p}
${p}
${u?`${u}
`:""}
${g}
${h?`
${$}
`:""}
${K(this._viewResult.url)}