i.id===o)?.name||null}getPerson(o){return Ve(this.getUser(o))}getUser(o){return!o||!this.usersCache?null:this.usersCache.find(e=>e.id===o)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(o){return o?o===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}};function D(r){return`${r.entry_id??""}\0${r.part_id}`}function Be(r,o,e,i){let t=!!r.entry_id&&r.entry_id!==o,n=t?r.entry_id:o,d=e.find(g=>g.entry_id===n),_=(d?.parts||[]).find(g=>g.id===r.part_id)||null,u=t&&d?.object?.name||"",h=_?.name||s("shared_part_unknown",i);return{part:_,foreign:t,ownerName:u,label:u?`${h} (${u})`:h}}function We(r,o,e,i){let{part:t,label:n}=Be(r,o,e,i),d=t&&t.stock!==null&&t.stock!==void 0?` (${t.stock}${t.unit?" "+t.unit:""})`:"",_=t?.storage_location?` \u2014 ${t.storage_location}`:"";return`${r.quantity}\xD7 ${n}${d}${_}`}function Ke(r,o,e,i){let n=(e.find(_=>_.entry_id===o)?.parts||[]).map(_=>({..._})),d=new Set(n.map(_=>D({part_id:_.id})));for(let _ of r?.consumes_parts||[]){if(!_.entry_id||_.entry_id===o)continue;let u=D(_);if(d.has(u))continue;d.add(u);let{part:h,ownerName:g}=Be(_,o,e,i);n.push({id:_.part_id,name:h?.name||s("shared_part_unknown",i),unit:h?.unit,stock:h?.stock??null,storage_location:h?.storage_location,entry_id:_.entry_id,owner_name:g})}return n}var ue=["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"],Ye=["sensor"],Ge=["temperature","humidity","pressure"];async function _e(r,o,e={}){e.busy?.(!0);try{return await r.hass.connection.sendMessagePromise(o)}catch(i){let t=P(r.hass);e.onError?.(T(i,t,e.fallbackKey?s(e.fallbackKey,t):void 0));return}finally{e.busy?.(!1)}}var me=["notes","cost","duration","photo","user"],ie={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"};var Rt=["cleaning","inspection","replacement","calibration","service","reading","custom"],qt=["low","normal","high"],Ht=["time_based","weekdays","nth_weekday","day_of_month","sensor_based","one_time","manual"],oe=["weekdays","nth_weekday","day_of_month"],Qe=["time_based","one_time",...oe],Ze=["threshold","counter","state_change","runtime"],Nt=[...Ze,"compound"],U={alpha:"0.3",min:"7",max:"365"};function Mt(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",equals:"",notEquals:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",carry:{}}}var Ot=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 Dt(r){return{entityIds:(r.entity_ids||(r.entity_id?[r.entity_id]:[])).join(", "),type:r.type||"threshold",attribute:r.attribute||"",above:r.trigger_above?.toString()??"",below:r.trigger_below?.toString()??"",equals:r.trigger_equals?.toString()??"",notEquals:r.trigger_not_equals?.toString()??"",forMinutes:r.trigger_for_minutes?.toString()??"0",targetValue:r.trigger_target_value?.toString()??"",deltaMode:r.trigger_delta_mode||!1,fromState:r.trigger_from_state||"",toState:r.trigger_to_state||"",targetChanges:r.trigger_target_changes?.toString()??"",runtimeHours:r.trigger_runtime_hours?.toString()??"",onStates:(r.trigger_on_states||[]).join(", "),carry:Object.fromEntries(Object.entries(r).filter(([e])=>!Ot.has(e)&&!e.startsWith("_")))}}function Ft(r){let o=r.entityIds.split(",").map(i=>i.trim()).filter(Boolean);if(o.length===0)return null;let e={...r.carry||{},entity_id:o[0],entity_ids:o,type:r.type};if(r.attribute&&(e.attribute=r.attribute),r.type==="threshold"){let i=parseFloat(r.above);isNaN(i)||(e.trigger_above=i);let t=parseFloat(r.below);isNaN(t)||(e.trigger_below=t);let n=parseFloat(r.equals);isNaN(n)||(e.trigger_equals=n);let d=parseFloat(r.notEquals);isNaN(d)||(e.trigger_not_equals=d);let _=parseInt(r.forMinutes,10);isNaN(_)||(e.trigger_for_minutes=_)}else if(r.type==="counter"){let i=parseFloat(r.targetValue);isNaN(i)||(e.trigger_target_value=i),e.trigger_delta_mode=r.deltaMode}else if(r.type==="state_change"){r.fromState&&(e.trigger_from_state=r.fromState),r.toState&&(e.trigger_to_state=r.toState);let i=parseInt(r.targetChanges,10);isNaN(i)||(e.trigger_target_changes=i)}else if(r.type==="runtime"){let i=parseFloat(r.runtimeHours);isNaN(i)||(e.trigger_runtime_hours=i);let t=(r.onStates||"").split(",").map(n=>n.trim()).filter(Boolean);t.length>0&&(e.trigger_on_states=t)}return e}function jt(r){return Array.from({length:7},(o,e)=>he(e,r,"short"))}function Ut(r){return Array.from({length:12},(o,e)=>Oe(e,r,"short"))}var m=class m extends E{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._warning="";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._triggerRuntimeMaxSession="";this._triggerOnStates="";this._compoundLogic="AND";this._compoundConditions=[];this._suggestedAttributes=[];this._availableAttributes=[];this._entityDomain="";this._lastPerformed="";this._nfcTagId="";this._requireTagScan=!1;this._allowSkip=!0;this._notifyEnabled=!0;this._readingUnit="";this._readings=[];this._consumesParts={};this._partsLoadFailed=!1;this._availableTags=[];this._responsibleUserId=null;this._assigneePool=[];this._rotationStrategy="";this._availableUsers=[];this._checklistText="";this._phaseDefs=[];this._phaseSeq=[];this._requiredCompletion=[];this._scheduleTime="";this._scheduleTimeOn=!1;this._actionService="";this._actionTargetEntity="";this._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=U.alpha;this._adaptiveMin=U.min;this._adaptiveMax=U.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 P(this.hass)}async openCreate(e,i){this._entryId=e,this._taskId=null,this._error="",this._warning="",!e&&i&&i.length>0?(this._objectChoices=i.map(t=>({entry_id:t.entry_id,name:t.object.name})).sort((t,n)=>t.name.localeCompare(n.name)),this._entryId=this._objectChoices[0].entry_id):this._objectChoices=[],this._resetFields(),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}async openEdit(e,i){this._entryId=e,this._taskId=i.id,this._error="",this._warning="",this._objectChoices=[],this._name=i.name,this._type=i.type,this._scheduleType=i.schedule_type,this._intervalDays=i.interval_days!=null?String(i.interval_days):"",this._intervalUnit=i.interval_unit||"days",this._dueDate=i.due_date||"";let t=i.schedule;this._weekdays=t?.kind==="weekdays"?[...t.weekdays??[]]:[],this._nth=t?.kind==="nth_weekday"?String(t.nth??1):"1",this._nthWeekday=t?.kind==="nth_weekday"?String(t.weekday??5):"5",this._domDay=t?.kind==="day_of_month"&&(t.day??1)>=1?String(t.day??1):"1",this._domLastDay=t?.kind==="day_of_month"&&t.day===-1,this._domBusiness=t?.kind==="day_of_month"&&t.business===!0,this._calOffset=t?.offset?String(t.offset):"0",this._seasonMonths=Array.isArray(t?.season_months)?[...t.season_months]:[];let n=t?.ends;n&&typeof n.count=="number"?(this._endsMode="count",this._endsCount=String(n.count),this._endsUntil=""):n&&typeof n.until=="string"?(this._endsMode="until",this._endsUntil=n.until,this._endsCount=""):(this._endsMode="never",this._endsCount="",this._endsUntil=""),this._warningDays=i.warning_days.toString(),this._earliestCompletionDays=i.earliest_completion_days!=null?String(i.earliest_completion_days):"",this._intervalAnchor=i.interval_anchor||"completion",this._notes=i.notes||"",this._documentationUrl=i.documentation_url||"",this._customIcon=i.custom_icon||"",this._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._allowSkip=i.allow_skip!==!1,this._notifyEnabled=i.notify_enabled!==!1,this._readingUnit=i.reading_unit||"",this._readings=(i.readings||[]).map(h=>({...h})),this._consumesParts=Object.fromEntries((i.consumes_parts||[]).map(h=>[D(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:f,checklist:x,consumes_parts:y,required_completion_fields:$,...H}=g,B=g.consumes_parts||[],Y=B.findIndex(j=>!j.entry_id),M=Y>=0?B[Y]:void 0;return{id:h,name:g.name||h,checklistText:(g.checklist||[]).join(`
`),partId:M?.part_id||"",partQty:M?.quantity!=null?String(M.quantity):"",reqOverride:g.required_completion_fields!==void 0,reqFields:[...g.required_completion_fields||[]],extraParts:B.filter((j,Q)=>Q!==Y).map(j=>({...j})),carry:H}}),this._phaseSeq=[...i.phase_sequence||[]],this._requiredCompletion=[...i.required_completion_fields||[]],this._scheduleTime=i.schedule_time||"",this._scheduleTimeOn=!!i.schedule_time;let d=i.on_complete_action;if(d&&d.service){this._actionService=d.service;let h=d.target?.entity_id;this._actionTargetEntity=Array.isArray(h)?h[0]||"":h||"",this._actionData=d.data&&typeof d.data=="object"?{...d.data}:{},this._actionDataJsonFallback=""}else this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="";let _=i.quick_complete_defaults;this._qcNotes=_?.notes||"",this._qcCost=_?.cost!=null?String(_.cost):"",this._qcDuration=_?.duration!=null?String(_.duration):"",this._qcFeedback=_?.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()??U.alpha,this._adaptiveMin=u.min_interval_days?.toString()??U.min,this._adaptiveMax=u.max_interval_days?.toString()??U.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._triggerRuntimeMaxSession=h.trigger_runtime_max_session_seconds?.toString()||"",this._triggerOnStates=(h.trigger_on_states||[]).join(", "),h.type==="compound"?(this._compoundLogic=h.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(h.conditions||[]).map(Dt)):(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._allowSkip=!0,this._readingUnit="",this._readings=[],this._consumesParts={},this._responsibleUserId=null,this._assigneePool=[],this._rotationStrategy="",this._checklistText="",this._phaseDefs=[],this._phaseSeq=[],this._requiredCompletion=[],this._scheduleTime="",this._scheduleTimeOn=!1,this._environmentalEntity="",this._environmentalAttribute="",this._environmentalInitial="",this._environmentalAttributeInitial="",this._adaptiveEnabled=!1,this._adaptiveAlpha=U.alpha,this._adaptiveMin=U.min,this._adaptiveMax=U.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._triggerRuntimeMaxSession="",this._triggerOnStates="",this._compoundLogic="AND",this._compoundConditions=[]}async _loadUsers(){this._userService||(this._userService=new ae(this.hass));try{this._availableUsers=await this._userService.getUsers()}catch(e){console.error("Failed to load users:",e),this._availableUsers=[]}}_toggleAssignee(e){this._assigneePool=this._assigneePool.includes(e)?this._assigneePool.filter(i=>i!==e):[...this._assigneePool,e]}async _testAction(){let e=this._actionService.trim();if(!e||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(e)){this._actionTestResult="error",this._actionTestError="Invalid service format (expected 'domain.service')",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[i,t]=e.split(".");if(!this.hass?.services?.[i]?.[t]){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!==i&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(i)){this._actionTestResult="error",this._actionTestError=`Service "${e}" only works on ${i}.* entities; entity "${n}" is in ${d}.* \u2014 pick a service that matches the entity domain (e.g. ${d}.${t})`,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[i,t]=e.split("."),n=this.hass?.services?.[i]?.[t]?.fields;return!n||Object.keys(n).length===0?null:Object.entries(n).map(([d,_])=>({name:d,required:!!_.required,selector:_.selector||{text:{}}}))}_renderCompletionActionsSection(e){if(!this.completionActionsEnabled)return p;let i=this._serviceSchema();return a`
${s("on_complete_action_title",e)}
${s("on_complete_action_desc",e)}
{this._actionService=t.detail.value||"";let n=this._serviceSchema();if(n){let d=new Set(n.map(_=>_.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([_])=>d.has(_)))}}}
>
s("on_complete_action_target",e)}
@value-changed=${t=>{let n=t.detail.value;this._actionTargetEntity=n.target_entity||""}}
>
${s("on_complete_action_target_hint",e)}
${i?a`
{this._actionData={...t.detail.value}}}
>
`:a`
{this._actionDataJsonFallback=t.target.value}}
>
`}
${this._actionTesting?"\u2026":s("on_complete_action_test",e)}
${this._actionTestResult==="ok"?a`
${s("on_complete_action_test_success",e)} `:p}
${this._actionTestResult==="error"?a`
${s("on_complete_action_test_failed",e)}
${this._actionTestError?a`
${this._actionTestError}
`:p}
`:p}
${s("quick_complete_defaults_title",e)}
${s("quick_complete_defaults_desc",e)}
{this._qcNotes=t.target.value}}
>
{this._qcCost=t.target.value}}
>
{this._qcDuration=t.target.value}}
>
{this._qcFeedback=t.target.value}}>
${s("quick_complete_defaults_feedback_none",e)}
${s("quick_complete_defaults_feedback_needed",e)}
${s("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(i=>i.entry_id!==this._entryId&&(i.parts||[]).length>0).map(i=>({entry_id:i.entry_id,name:i.object?.name||i.entry_id,parts:i.parts||[]})).sort((i,t)=>i.name.localeCompare(t.name))}catch{this._foreignOwners=[]}}async _loadTags(){try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/tags/list"});this._availableTags=e.tags||[]}catch{this._availableTags=[]}}_fetchConditionAttributes(e){!e||!this.hass||this._conditionAttrOptions[e]||this._conditionAttrPending.has(e)||(this._conditionAttrPending.add(e),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e}).then(i=>{let t=i;this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:t.suggested_attributes||[],available:t.available_attributes||[]}}}).catch(()=>{this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:[],available:[]}}}))}async _fetchEntityAttributes(e){if(!e||!this.hass){this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="";return}try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e});this._entityDomain=i.domain||"",this._suggestedAttributes=i.suggested_attributes||[],this._availableAttributes=i.available_attributes||[]}catch{this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain=""}}get _hasForeignPick(){return Object.values(this._consumesParts).some(e=>!!e.entry_id)}_renderConsumesRow(e,i){let t=D({part_id:e.id,entry_id:i}),n=this._consumesParts[t],d=i?{part_id:e.id,quantity:1,entry_id:i}:{part_id:e.id,quantity:1};return a`
{let u={...this._consumesParts};_.target.checked?u[t]=u[t]||d:delete u[t],this._consumesParts=u}}
/>
${e.name}${e.unit?` (${e.unit})`:""}
${n!==void 0?a` {let u=parseFloat(_.target.value);this._consumesParts={...this._consumesParts,[t]:{...d,quantity:Number.isFinite(u)&&u>=.01?u:1}}}}
/>`:p}
`}_toggleRequired(e,i){let t=new Set(this._requiredCompletion);i?t.add(e):t.delete(e),this._requiredCompletion=[...t]}_patchReading(e,i){this._readings=this._readings.map(t=>t.id===e?{...t,...i}:t)}_renderReadingsEditor(e){let i=Ae(this._readings);return a`
${s("readings_section",e)}
${s("readings_hint",e)}
${this._readings.map(t=>a`
${i.has(t.id)?a`
${s("reading_duplicate_name",e)}
`:p}
this._patchReading(t.id,{name:n.target.value})}
>
this._patchReading(t.id,{unit:n.target.value})}
>
this._readings=this._readings.filter(n=>n.id!==t.id)}>
`)}
${this._readings.length<20?a`
this._readings=[...this._readings,{id:we(),name:"",unit:this._readings.length?this._readings[this._readings.length-1].unit:this._readingUnit}]}>
${s("reading_add",e)}
`:p}
`}_phaseSlug(e){let i=e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"phase",t=i,n=2;for(;this._phaseDefs.some(d=>d.id===t);)t=`${i}-${n++}`;return t}_addPhaseDef(){let e=this._phaseSlug(`phase-${this._phaseDefs.length+1}`);this._phaseDefs=[...this._phaseDefs,{id:e,name:"",checklistText:"",partId:"",partQty:"",reqOverride:!1,reqFields:[],extraParts:[],carry:{}}]}_removePhaseDef(e){this._phaseDefs=this._phaseDefs.filter(i=>i.id!==e),this._phaseSeq=this._phaseSeq.filter(i=>i!==e)}_patchPhaseDef(e,i){this._phaseDefs=this._phaseDefs.map(t=>t.id===e?{...t,...i}:t)}_renderPhasesEditor(e){let i=t=>this._phaseDefs.find(n=>n.id===t)?.name||t;return a`
${s("phases_section",e)}
${s("phases_hint",e)}
${this._phaseDefs.map(t=>a`
`)}
${s("phase_add",e)}
${this._phaseDefs.some(t=>t.name.trim())?a`
${s("phase_sequence_label",e)}
${this._phaseSeq.map((t,n)=>a`
${n+1}. ${i(t)}
{this._phaseSeq=this._phaseSeq.filter((d,_)=>_!==n)}}>✕
`)}
{let n=t.target.value;n&&(this._phaseSeq=[...this._phaseSeq,n]),t.target.value=""}}
>
+ ${s("phase_sequence_add_step",e)}
${this._phaseDefs.filter(t=>t.name.trim()).map(t=>a`${t.name} `)}
`:p}
`}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),i=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(i)&&e>i){this._error=`${s("adaptive_min_interval",this._lang)} > ${s("adaptive_max_interval",this._lang)}`;return}}if(this._triggerType==="threshold"&&this._thresholdLimitsOverlap()){this._error=s("trigger_hint_overlap",this._lang);return}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))},i=this._earliestCompletionDays.trim();e.earliest_completion_days=i===""?null:Math.max(0,parseInt(i,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):oe.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(u=>u.trim()).filter(Boolean),e.enabled=this._enabled,e.last_performed=this._lastPerformed||null,e.nfc_tag_id=this._nfcTagId||null,e.require_tag_scan=this._requireTagScan,e.allow_skip=this._allowSkip,e.notify_enabled=this._notifyEnabled,e.reading_unit=this._readingUnit.trim()||null,e.readings=Ce(this._readings);{let u={};for(let g of this._phaseDefs){if(!g.name.trim())continue;let f={...g.carry,name:g.name.trim()},x=g.checklistText.split(`
`).map($=>$.trim()).filter(Boolean);x.length&&(f.checklist=x);let y=[];if(g.partId){let $=parseFloat(g.partQty);y.push({part_id:g.partId,quantity:Number.isFinite($)&&$>0?$:1})}for(let $ of g.extraParts)y.push($.entry_id?{part_id:$.part_id,quantity:$.quantity,entry_id:$.entry_id}:{part_id:$.part_id,quantity:$.quantity});y.length&&(f.consumes_parts=y),g.reqOverride&&(f.required_completion_fields=[...g.reqFields]),u[g.id]=f}let h=this._phaseSeq.filter(g=>g in u);e.phases=Object.keys(u).length&&h.length?u:null,e.phase_sequence=e.phases?h:null}if((this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(u=>u.entry_id?{part_id:u.part_id,quantity:u.quantity,entry_id:u.entry_id}:{part_id:u.part_id,quantity:u.quantity})),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 u=this._compoundConditions.map(Ft).filter(h=>h!==null);if(u.length>0){let h={type:"compound",compound_logic:this._compoundLogic,conditions:u};this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(h.trigger_combinator="all"),e.trigger_config=h}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let u=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],h={entity_id:u[0],entity_ids:u,type:this._triggerType};if(this._triggerAttribute&&(h.attribute=this._triggerAttribute),this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(h.trigger_combinator="all"),u.length>1&&(h.entity_logic=this._triggerEntityLogic),this._triggerType==="threshold"){if(this._triggerAbove){let g=parseFloat(this._triggerAbove);isNaN(g)||(h.trigger_above=g)}if(this._triggerBelow){let g=parseFloat(this._triggerBelow);isNaN(g)||(h.trigger_below=g)}if(this._triggerEquals){let g=parseFloat(this._triggerEquals);isNaN(g)||(h.trigger_equals=g)}if(this._triggerNotEquals){let g=parseFloat(this._triggerNotEquals);isNaN(g)||(h.trigger_not_equals=g)}if(this._triggerForMinutes){let g=parseInt(this._triggerForMinutes,10);isNaN(g)||(h.trigger_for_minutes=g)}}else if(this._triggerType==="counter"){if(this._triggerTargetValue){let g=parseFloat(this._triggerTargetValue);isNaN(g)||(h.trigger_target_value=g)}if(h.trigger_delta_mode=this._triggerDeltaMode,this._triggerDeltaMode&&this._triggerBaselineValue){let g=parseFloat(this._triggerBaselineValue);!isNaN(g)&&g>=0&&(h.trigger_baseline_value=g)}}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 g=parseInt(this._triggerTargetChanges,10);isNaN(g)||(h.trigger_target_changes=g)}if(this._triggerForMinutes){let g=parseInt(this._triggerForMinutes,10);isNaN(g)||(h.trigger_for_minutes=g)}}else if(this._triggerType==="runtime"){if(this._triggerRuntimeHours){let f=parseFloat(this._triggerRuntimeHours);isNaN(f)||(h.trigger_runtime_hours=f)}if(this._triggerRuntimeMaxSession){let f=parseInt(this._triggerRuntimeMaxSession,10);!isNaN(f)&&f>0&&(h.trigger_runtime_max_session_seconds=f)}let g=this._triggerOnStates.split(",").map(f=>f.trim()).filter(Boolean);g.length>0&&(h.trigger_on_states=g)}e.trigger_config=h}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&Qe.includes(this._scheduleType)){let u=this._scheduleTimeOn?this._scheduleTime.trim():"";e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(u)?u:null}if(this.checklistsEnabled){let u=this._checklistText.split(`
`).map(h=>h.trim()).filter(Boolean).slice(0,100);e.checklist=u.length?u:null}if(this.completionActionsEnabled){let u=this._actionService.trim();if(u&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(u)){let x={service:u},y=this._actionTargetEntity.trim();y&&(x.target={entity_id:y});let $=this._buildActionData();Object.keys($).length>0&&(x.data=$),e.on_complete_action=x}else e.on_complete_action=null;let h={};this._qcNotes.trim()&&(h.notes=this._qcNotes.trim());let g=parseFloat(this._qcCost);!isNaN(g)&&g>=0&&(h.cost=g);let f=parseInt(this._qcDuration,10);!isNaN(f)&&f>=0&&(h.duration=f),this._qcFeedback&&(h.feedback=this._qcFeedback),e.quick_complete_defaults=Object.keys(h).length?h:null}let t=await this.hass.connection.sendMessagePromise(e),n=this._taskId||t?.task_id,d=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;this._warning="";let _=u=>{this._warning=s("subsave_warning",this._lang).replace("{detail}",u)};if(n&&this._scheduleType==="sensor_based"&&d&&await _e(this,{type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:n,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null},{onError:_})!==void 0&&(this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute),n&&this._adaptiveSnapshot()!==this._adaptiveInitial){let u=parseFloat(this._adaptiveAlpha),h=parseInt(this._adaptiveMin,10),g=parseInt(this._adaptiveMax,10);await _e(this,{type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:n,enabled:this._adaptiveEnabled,...u>=.1&&u<=.9?{ewa_alpha:u}:{},...!isNaN(h)&&h>=1?{min_interval_days:h}:{},...!isNaN(g)&&g>=1?{max_interval_days:g}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction},{onError:_})!==void 0&&(this._adaptiveInitial=this._adaptiveSnapshot())}this._warning?n&&(this._taskId=n):this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}catch(e){this._error=T(e,this._lang,s("save_error",this._lang))}finally{this._loading=!1}}}_close(){this._open=!1,this._warning="",this._pickerProbeTimer!==void 0&&(clearTimeout(this._pickerProbeTimer),this._pickerProbeTimer=void 0),this._pickerProbeStrikes=0}_renderTriggerFields(){if(this._scheduleType!=="sensor_based")return p;let e=this._lang,i=this._triggerType==="compound";return a`
${s("trigger_configuration",e)}
${s("trigger_type",e)}
this._triggerType=t.target.value}
>
${Nt.map(t=>a`${s(t,e)} `)}
${i?this._renderCompoundEditor():a`
${this._entityPickerFallback?a`
0?this._triggerEntityIds.join(", "):this._triggerEntityId}
@input=${t=>{let d=t.target.value.split(",").map(_=>_.trim()).filter(Boolean);this._triggerEntityId=d[0]||"",this._triggerEntityIds=d,d[0]&&this._fetchEntityAttributes(d[0])}}
>
`:a`
0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}}
.computeLabel=${()=>s("entity_id",e)}
@value-changed=${t=>{let n=(t.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=n[0]||"",this._triggerEntityIds=n,n[0]?this._fetchEntityAttributes(n[0]):this._fetchEntityAttributes("")}}
> `}
${this._triggerEntityIds.length>1?a`
${s("entity_logic",e)}
this._triggerEntityLogic=t.target.value}
>
${s("entity_logic_any",e)}
${s("entity_logic_all",e)}
`:p}
${this._renderAttributeSelect({label:s("attribute_optional",e),value:this._triggerAttribute,suggested:this._suggestedAttributes,available:this._availableAttributes,onSelect:t=>this._triggerAttribute=t})}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
this._autoCompleteOnRecovery=t.target.checked}
/>
${s("auto_complete_on_recovery",e)}
${s("auto_complete_on_recovery_help",e)}
this._intervalDays=t.target.value}
>
${this._intervalDays?this._renderUnitSelect():p}
${this._intervalDays?a`
${s("trigger_combinator",e)}
this._triggerCombinator=t.target.value}
>
${s("trigger_combinator_any",e)}
${s("trigger_combinator_all",e)}
`:p}
`}_patchCondition(e,i){this._compoundConditions=this._compoundConditions.map((t,n)=>n===e?{...t,...i}:t)}_addCondition(){this._compoundConditions=[...this._compoundConditions,Mt()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((i,t)=>t!==e)}_renderCompoundEditor(){let e=this._lang;return a`
${s("compound_logic",e)}
this._compoundLogic=i.target.value}
>
${s("compound_logic_and",e)}
${s("compound_logic_or",e)}
${s("compound_help",e)}
${this._compoundConditions.length===0?a`${s("compound_no_conditions",e)}
`:this._compoundConditions.map((i,t)=>this._renderCondition(i,t))}
this._addCondition()}>
+ ${s("compound_add_condition",e)}
`}_renderCondition(e,i){let t=this._lang,n=i+1;return a`
${s("compound_condition",t)} ${n}
this._removeCondition(i)}
>✕
${this._entityPickerFallback?a`
this._patchCondition(i,{entityIds:d.target.value})}
>
`:a`
d.trim()).filter(Boolean)}}
.computeLabel=${()=>s("entity_id",t)}
@value-changed=${d=>{let _=(d.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(i,{entityIds:_.join(", ")})}}
> `}
${this._renderConditionAttribute(e,i)}
${s("trigger_type",t)}
this._patchCondition(i,{type:d.target.value})}
>
${Ze.map(d=>a`${s(d,t)} `)}
${this._renderConditionTypeFields(e,i)}
`}_renderStateField(e){return this._entityPickerFallback||!e.entityId?a`
e.onInput(i.target.value)}
>
`:a`
e.label}
@value-changed=${i=>e.onInput((i.detail.value.s||"").trim())}
>
`}_renderOnStatesField(e){let i=this._lang;return this._entityPickerFallback||!e.entityId?a`
e.onInput(t.target.value)}
>
`:a`
t.trim()).filter(Boolean)}}
.computeLabel=${()=>s("runtime_on_states",i)}
@value-changed=${t=>e.onInput((t.detail.value.s||[]).join(", "))}
>
`}_renderAdaptiveSection(e){return this._scheduleType==="one_time"||this._scheduleType==="manual"?p:a`
${s("adaptive_section_title",e)}
this._adaptiveEnabled=i.target.checked}
/>
${s("adaptive_enabled",e)}
${this._adaptiveEnabled?a`
this._adaptiveMin=i.target.value}
>
this._adaptiveMax=i.target.value}
>
this._adaptiveAlpha=i.target.value}
>
this._adaptiveSeasonal=i.target.checked}
/>
${s("adaptive_seasonal_enabled",e)}
this._adaptivePrediction=i.target.checked}
/>
${s("adaptive_prediction_enabled",e)}
`:p}
`}_renderAttributeSelect(e){let i=this._lang;return e.available.length>0?a`
${e.label}
e.onSelect(t.target.value)}
>
${s("use_entity_state",i)}
${e.suggested.map(t=>a`${t} ★ `)}
${e.available.filter(t=>!e.suggested.includes(t.name)).map(t=>a`${t.name}${t.numeric?"":" (non-numeric)"} `)}
`:a`
e.onSelect(t.target.value.trim())}
>
`}_renderEnvironmentalAttribute(e){this._fetchConditionAttributes(this._environmentalEntity);let i=this._conditionAttrOptions[this._environmentalEntity];return this._renderAttributeSelect({label:s("environmental_attribute_optional",e),value:this._environmentalAttribute,suggested:i?.suggested??[],available:i?.available??[],onSelect:t=>this._environmentalAttribute=t})}_renderConditionAttribute(e,i){let t=e.entityIds.split(",")[0]?.trim()||"";t&&this._fetchConditionAttributes(t);let n=t?this._conditionAttrOptions[t]:void 0;return this._renderAttributeSelect({label:s("attribute_optional",this._lang),value:e.attribute,suggested:n?.suggested??[],available:n?.available??[],onSelect:d=>this._patchCondition(i,{attribute:d})})}_renderConditionTypeFields(e,i){let t=this._lang;if(e.type==="threshold")return a`
this._patchCondition(i,{above:n.target.value})}>
this._patchCondition(i,{below:n.target.value})}>
this._patchCondition(i,{equals:n.target.value})}>
this._patchCondition(i,{notEquals:n.target.value})}>
this._patchCondition(i,{forMinutes:n.target.value})}>
`;if(e.type==="counter")return a`
this._patchCondition(i,{targetValue:n.target.value})}>
this._patchCondition(i,{deltaMode:n.target.checked})} />
${s("delta_mode",t)}
`;if(e.type==="state_change"){let n=e.entityIds.split(",")[0]?.trim()||"";return a`
${this._renderStateField({label:s("from_state_optional",t),value:e.fromState,entityId:n,onInput:d=>this._patchCondition(i,{fromState:d})})}
${this._renderStateField({label:s("to_state_optional",t),value:e.toState,entityId:n,onInput:d=>this._patchCondition(i,{toState:d})})}
this._patchCondition(i,{targetChanges:d.target.value})}>
`}if(e.type==="runtime"){let n=e.entityIds.split(",")[0]?.trim()||"";return a`
this._patchCondition(i,{runtimeHours:d.target.value})}>
${this._renderOnStatesField({value:e.onStates,entityId:n,onInput:d=>this._patchCondition(i,{onStates:d})})}
`}return p}_renderUnitSelect(){let e=this._lang;return a`
${s("interval_unit",e)}
this._intervalUnit=i.target.value}
>
${["days","weeks","months","years"].map(i=>a`${s("unit_"+i,e)} `)}
`}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(i=>i!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(oe.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let e=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!e||e<=0?null:{kind:"interval",every:e,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(e){super.updated?.(e),this._scheduleEntityPickerProbe();for(let i of e.keys())if(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 e=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),i=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!i){this._pickerProbeStrikes=0;return}let t=(u,h,g=0)=>{if(!(!u||g>10)){(u.tagName?.toLowerCase()??"")==="ha-entity-picker"&&h.push(u);for(let f of[u.shadowRoot,u])if(f)for(let x of Array.from(f.children??[]))t(x,h,g+1)}},n=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],d=[];for(let u of n)t(u,d);let _=d.length===0||d.some(u=>u.offsetHeight===0);if(e.offsetHeight===0||_){if(this._pickerProbeStrikes+=1,this._pickerProbeStrikes>=2){this._entityPickerFallback=!0;return}this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),700)}else this._pickerProbeStrikes=0}_schedulePreviewRefresh(){this._previewTimer&&clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._fetchSchedulePreview()},300)}async _fetchSchedulePreview(){let e=this._open?this._previewScheduleDict():null;if(!e){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let i=++this._previewSeq;try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(i!==this._previewSeq)return;this._schedulePreview=t.occurrences||[],this._schedulePreviewEnded=!!t.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return p;let e=this._lang,i=this.scheduleTimeEnabled&&this._scheduleTimeOn&&this._scheduleTime?` ${this._scheduleTime}`:"",t=this._schedulePreview.map((d,_)=>{let u=new Date(`${d}T12:00:00`).getDay();return`${he(u===0?6:u-1,e,"short")} ${G(d,e)}${_===0?i:""}`}).join(" \xB7 "),n=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?a`${s("schedule_preview_ontime",e)}
`:p;return a`
${s("schedule_preview_title",e)}: ${t}${this._schedulePreviewEnded?a` ${s("schedule_preview_ends",e)} `:p}
${n}
`}_buildSchedule(){let e=t=>{let n=parseInt(this._calOffset,10)||0;return n&&(t.offset=Math.max(-15,Math.min(n,15))),t};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((t,n)=>t-n)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});let i={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(i.business=!0),e(i)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((i,t)=>i-t)),this._endsMode==="count"){let i=parseInt(this._endsCount,10);i>=1&&(e.ends={count:i})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(i=>i!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||oe.includes(this._scheduleType)))return p;let t=Ut(e);return a`
${s("season_window_label",e)}
${s("season_window_hint",e)}
${t.map((n,d)=>a`
this._toggleSeasonMonth(d+1)}
>${n} `)}
${s("series_end_label",e)}
this._endsMode=n.target.value}>
${s("series_end_never",e)}
${s("series_end_after_count",e)}
${s("series_end_until",e)}
${this._endsMode==="count"?a`
this._endsCount=n.target.value}
> `:p}
${this._endsMode==="until"?a`
this._endsUntil=n.detail.value}
> `:p}
`}_renderCalendarFields(){let e=this._lang,i=jt(e);if(this._scheduleType==="weekdays")return a`
${s("recurrence_on_days",e)}
${i.map((t,n)=>a`
this._toggleWeekday(n)}
>${t} `)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let t=[["1",s("ord_1",e)],["2",s("ord_2",e)],["3",s("ord_3",e)],["4",s("ord_4",e)],["5",s("ord_5",e)],["-1",s("ord_last",e)]];return a`
${s("recurrence_occurrence",e)}
this._nth=n.target.value}>
${t.map(([n,d])=>a`${d} `)}
${s("recurrence_weekday",e)}
this._nthWeekday=n.target.value}>
${i.map((n,d)=>a`${n} `)}
${this._renderCalOffsetField()}`}return this._scheduleType==="day_of_month"?a`
${this._domLastDay?p:a`
this._domDay=t.target.value}
> `}
this._domLastDay=t.target.checked} />
${s("recurrence_last_day",e)}
this._domBusiness=t.target.checked} />
${s("recurrence_business_day",e)}
${this._renderCalOffsetField()}`:p}_renderCalOffsetField(){let e=this._lang;return a`
this._calOffset=i.target.value}
> `}_thresholdLimitsOverlap(){let e=parseFloat(this._triggerAbove),i=parseFloat(this._triggerBelow);return!isNaN(e)&&!isNaN(i)&&i>e}_renderTriggerLiveHint(){if(this._triggerType==="compound")return p;let e=this._triggerType==="threshold"&&this._thresholdLimitsOverlap()?a`${s("trigger_hint_overlap",this._lang)}
`:p,i=this._triggerEntityId||this._triggerEntityIds[0];if(!i||!this.hass?.states)return e;let t=this.hass.states[i];if(!t)return e;let n=this._lang,d=t.attributes?.unit_of_measurement,_=typeof d=="string"&&d?` ${d}`:"",u=this._triggerAttribute?t.attributes?.[this._triggerAttribute]:t.state,h=typeof u=="number"?u:parseFloat(String(u)),g=u!=="unknown"&&u!=="unavailable"&&u!=null&&!isNaN(h),f=y=>A(y,n,{maximumFractionDigits:1}),x=[];if(this._triggerType==="threshold"){let y=parseFloat(this._triggerAbove),$=parseFloat(this._triggerBelow);if(isNaN(y)&&isNaN($))return p;g&&x.push(s("trigger_hint_now",n).replace("{value}",f(h)+_)),isNaN(y)||x.push(s("trigger_hint_above",n).replace("{target}",f(y)+_)),isNaN($)||x.push(s("trigger_hint_below",n).replace("{target}",f($)+_))}else if(this._triggerType==="counter"){let y=parseFloat(this._triggerTargetValue);if(isNaN(y))return p;this._triggerDeltaMode?this._taskId?x.push(s("trigger_hint_counter_delta_edit",n).replace("{target}",f(y)+_)):g?x.push(s("trigger_hint_counter_delta",n).replace("{value}",f(h)+_).replace("{due}",f(h+y)+_).replace("{target}",f(y)+_)):x.push(s("trigger_hint_counter_delta_edit",n).replace("{target}",f(y)+_)):(g&&x.push(s("trigger_hint_now",n).replace("{value}",f(h)+_)),x.push(s("trigger_hint_counter_abs",n).replace("{target}",f(y)+_)))}else if(this._triggerType==="runtime"){let y=parseFloat(this._triggerRuntimeHours);if(isNaN(y))return p;x.push(s("trigger_hint_runtime",n).replace("{hours}",f(y))),x.push(s("trigger_hint_state_now",n).replace("{value}",String(t.state)))}else if(this._triggerType==="state_change"){let y=parseInt(this._triggerTargetChanges,10)||1,$=this._triggerToState.trim();x.push(($?s("trigger_hint_state_change_to",n).replace("{state}",$):s("trigger_hint_state_change",n)).replace("{count}",String(y))),x.push(s("trigger_hint_state_now",n).replace("{value}",String(t.state)))}return x.length?a`${x.join(" ")}
${e}`:e}_renderTriggerTypeFields(){let e=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=i.target.checked}
/>
${s("delta_mode",e)}
${this._triggerDeltaMode?a`
this._triggerBaselineValue=i.target.value}
>
${this._taskId?s("baseline_start_help_edit",e):s("baseline_start_help",e)}
${this._taskId&&this._liveBaselineValue!=null?a`
${s("baseline_current_effective",e).replace("{value}",String(this._liveBaselineValue))}
`:p}
`:p}
`:this._triggerType==="state_change"?a`
${this._renderStateField({label:s("from_state_optional",e),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:i=>this._triggerFromState=i})}
${s("state_value_help",e)}
${this._renderStateField({label:s("to_state_optional",e),value:this._triggerToState,entityId:this._triggerEntityId,onInput:i=>this._triggerToState=i})}
this._triggerTargetChanges=i.target.value}
>
${s("target_changes_help",e)}
${(this._triggerTargetChanges||"1")==="1"&&(this._triggerFromState||this._triggerToState)?a`${s("state_latch_help",e)}
`:p}
this._triggerForMinutes=i.target.value}
>
${s("for_minutes_state_help",e)}
`:this._triggerType==="runtime"?a`
this._triggerRuntimeHours=i.target.value}
>
this._triggerRuntimeMaxSession=i.target.value}
>
${s("runtime_max_session_help",e)}
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:i=>this._triggerOnStates=i})}
${s("runtime_on_states_help",e)}
`:p}render(){if(!this._open)return a``;let e=this._lang,i=this._taskId?s("edit_task",e):s("new_task",e);return a`
${i}
${this._error?a`
${this._error}
`:p}
${this._warning?a`
${this._warning}
`:p}
${this._taskId===null&&this._objectChoices.length>0?a`
${s("object",e)}
{this._entryId=t.target.value,this._consumesParts={},this._loadParts(),this._loadForeignPools()}}
>
${this._objectChoices.map(t=>a`${t.name} `)}
`:p}
this._name=t.target.value}
>
${s("maintenance_type",e)}
this._type=t.target.value}
>
${Rt.map(t=>a`${s(t,e)} `)}
${this._type==="reading"?a`
this._readingUnit=t.target.value}
>
${s("reading_unit_help",e)}
${this._renderReadingsEditor(e)}
`:p}
${this._partsLoadFailed?a`
${s("parts_load_failed",e)}
`:p}
${this.parts.length||this._foreignOwners.length?a`
${s("consumes_parts_label",e)}
${this.parts.map(t=>this._renderConsumesRow(t))}
${this._foreignOwners.length?a`
${s("shared_parts_other_objects",e)}
${s("shared_parts_help",e)}
${this._foreignOwners.map(t=>a`
${t.name}
${t.parts.map(n=>this._renderConsumesRow(n,t.entry_id))}
`)}
`:p}
`:p}
${s("priority",e)}
this._priority=t.target.value}
>
${qt.map(t=>a`${s("priority_"+t,e)} `)}
${s("schedule_type",e)}
this._scheduleType=t.target.value}
>
${Ht.map(t=>a`${s(t,e)} `)}
${this._scheduleType==="time_based"?a`
this._intervalDays=t.target.value}
>
${this._renderUnitSelect()}
${s("interval_anchor",e)}
this._intervalAnchor=t.target.value}
>
${s("anchor_completion",e)}
${s("anchor_planned",e)}
`:p}
${this._renderCalendarFields()}
${this._scheduleType==="one_time"?a`
this._dueDate=t.detail.value}
>
`:p}
${this.scheduleTimeEnabled&&Qe.includes(this._scheduleType)?a`
this._scheduleTimeOn=t.target.checked} />
${s("schedule_time_toggle",e)}
${this._scheduleTimeOn?a`
this._scheduleTime=t.detail.value}
>
`:p}
`:p}
${this._renderRecurrenceExtras()}
${this._renderSchedulePreview()}
this._warningDays=t.target.value}
>
this._earliestCompletionDays=t.target.value}
>
${this.checklistsEnabled?a`
${s("checklist_steps_optional",e)}
${s("checklist_help",e)}
`:p}
${this._renderPhasesEditor(e)}
${s("require_on_completion",e)}
${me.map(t=>a`
this._toggleRequired(t,n.target.checked)}
/>
${s(ie[t],e)}
`)}
this._lastPerformed=t.detail.value}
>
${s("responsible_user",e)}
{let n=t.target.value;this._responsibleUserId=n||null}}
>
${s("no_user_assigned",e)}
${this._availableUsers.map(t=>a`${t.name} `)}
${this._availableUsers.length>=2?a`
${this._assigneePool.length>=2?a`
${s("rotation_strategy",e)}
this._rotationStrategy=t.target.value}
>
${s("rotation_none",e)}
${["round_robin","least_completed","random"].map(t=>a`${s("rotation_"+t,e)} `)}
`:p}
`:p}
${this._renderTriggerFields()}
${this._scheduleType==="sensor_based"?a`
${this._entityPickerFallback?a`
this._environmentalEntity=t.target.value.trim()}
>
`:a`
s("environmental_entity_optional",e)}
.computeHelper=${()=>s("environmental_entity_helper",e)}
@value-changed=${t=>{this._environmentalEntity=(t.detail.value.environmental_entity||"").trim()}}
> `}
${this._environmentalEntity?this._renderEnvironmentalAttribute(e):p}
`:p}
${this._renderAdaptiveSection(e)}
this._notes=t.target.value}
>
this._documentationUrl=t.target.value}
>
this._customIcon=t.detail.value||""}
>
${this._availableTags.length>0?a`
${s("nfc_tag_id_optional",e)}
this._nfcTagId=t.target.value}
>
${s("no_nfc_tag",e)}
${this._availableTags.map(t=>a`${t.name} `)}
↻
`:a`
this._nfcTagId=t.target.value}
>
`}
this._requireTagScan=t.target.checked}
/>
${s("require_tag_scan",e)}
${this._requireTagScan?a`
${s("require_tag_scan_help",e)}
`:p}
this._allowSkip=!t.target.checked}
/>
${s("disallow_skip",e)}
${this._allowSkip?p:a`
${s("disallow_skip_help",e)}
`}
this._notifyEnabled=!t.target.checked}
/>
${s("no_notifications",e)}
${this._notifyEnabled?p:a`
${s("no_notifications_help",e)}
`}
this._enabled=t.target.checked}
/>
${s("task_enabled",e)}
${this._renderCompletionActionsSection(e)}
${s("cancel",e)}
${this._loading?s("saving",e):s("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=w`
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
/* #129: entity/state pickers in the trigger form (ha-form + selector) */
.entity-picker-form,
.state-picker-form {
display: block;
margin: 8px 0;
}
/* v1.3.0: completion-action sections (.adaptive-section shares the shell
but keeps its own class — tests count .ca-section elements) */
.ca-section,
.adaptive-section {
border: 1px solid var(--divider-color);
border-radius: 6px;
padding: 8px 12px;
margin-top: 8px;
}
.ca-section > summary,
.adaptive-section > summary {
cursor: pointer;
font-weight: 500;
}
.adaptive-section ms-textfield {
width: 100%;
margin-top: 8px;
display: block;
}
.adaptive-section label {
display: block;
margin-top: 8px;
}
.ca-section ms-textfield,
.ca-section ha-entity-picker,
.ca-section ha-service-picker,
.ca-section ha-form,
.ca-section .qc-feedback {
width: 100%;
margin-top: 8px;
display: block;
}
.ca-section .qc-feedback {
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
}
.ca-test-row {
display: flex;
align-items: center;
gap: 12px;
margin-top: 8px;
}
.ca-test-ok { color: var(--success-color, #4caf50); font-size: 13px; }
.ca-test-error { color: var(--error-color, #f44336); font-size: 13px; font-weight: 500; }
.ca-test-error-block { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.ca-test-error-detail {
font-size: 12px;
color: var(--secondary-text-color);
background: rgba(244, 67, 54, 0.08);
padding: 6px 8px; border-radius: 4px;
line-height: 1.4;
word-break: break-word;
}
.content {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 350px;
max-height: 70vh;
overflow-y: auto;
}
@media (max-width: 600px) {
.content {
min-width: 0;
max-height: none;
}
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
}
ms-textfield {
display: block;
}
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.checklist-textarea {
width: 100%;
min-height: 88px;
padding: 8px;
font-family: inherit;
font-size: 14px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
resize: vertical;
box-sizing: border-box;
}
.consumes-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
}
.phase-def {
border: 1px solid var(--divider-color);
border-radius: 6px;
padding: 8px;
margin: 6px 0;
}
.phase-def-head {
display: flex;
align-items: center;
gap: 8px;
}
.phase-def-head ms-textfield {
flex: 1;
min-width: 0;
}
.phase-part {
max-width: 160px;
padding: 6px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.phase-qty {
width: 64px;
padding: 6px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.phase-checklist {
min-height: 56px;
margin-top: 6px;
}
.phase-req-toggle {
margin-top: 6px;
font-size: 13px;
color: var(--secondary-text-color);
}
.phase-req-fields {
margin: 2px 0 0 22px;
font-size: 13px;
}
.phase-remove {
--mdc-icon-button-size: 36px;
color: var(--secondary-text-color);
}
/* #161 phase 2: reading slots — name wide, unit narrow, trash. */
.readings-editor { margin-top: 14px; }
.reading-row {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0;
}
.reading-row .reading-name { flex: 2; min-width: 0; }
.reading-row .reading-unit { flex: 1; min-width: 0; max-width: 140px; }
.reading-dup { color: var(--warning-color, #ff9800); margin-top: 6px; }
.phase-seq-label {
font-size: 12px;
color: var(--secondary-text-color);
margin-top: 8px;
}
.phase-seq {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
padding: 4px 0;
}
.phase-chip {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 12px;
background: var(--secondary-background-color);
font-size: 13px;
}
.phase-chip-x {
border: none;
background: none;
color: var(--secondary-text-color);
cursor: pointer;
padding: 0 2px;
font-size: 12px;
}
.phase-seq-add {
padding: 4px 8px;
border: 1px dashed var(--divider-color);
border-radius: 12px;
background: transparent;
color: var(--secondary-text-color);
font-size: 13px;
}
.consumes-check {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
}
.consumes-qty {
width: 64px;
padding: 4px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
/* #111: other objects' pools sit behind a disclosure so the object's OWN
parts stay the primary list; each group is headed by the owning object's
name, so which pool a checkbox means is never a guess. */
.shared-pools {
margin-top: 6px;
}
.shared-pools > summary {
cursor: pointer;
padding: 2px 0;
font-size: 13px;
color: var(--secondary-text-color);
}
.shared-pool-owner {
margin-top: 6px;
font-size: 12px;
font-weight: 500;
color: var(--secondary-text-color);
}
.field-help {
font-size: 12px;
color: var(--secondary-text-color);
}
.baseline-effective {
margin-top: 2px;
font-weight: 500;
color: var(--primary-text-color);
}
/* Live computed trigger hint — reads the bound sensor and explains what
happens next. Info-accented so it reads as guidance, not an error. */
.trigger-live-hint {
font-size: 12px;
color: var(--secondary-text-color);
border-left: 3px solid var(--info-color, #2196f3);
background: rgba(33, 150, 243, 0.08);
border-radius: 0 6px 6px 0;
padding: 6px 10px;
margin: 4px 0;
}
.trigger-live-hint.warn {
color: var(--primary-text-color);
border-left-color: var(--warning-color, #ff9800);
background: rgba(255, 152, 0, 0.1);
}
.field-help a,
.link-button {
background: none;
border: 0;
padding: 0;
color: var(--primary-color);
cursor: pointer;
font: inherit;
text-decoration: underline;
}
.field-help a:hover,
.link-button:hover {
text-decoration: none;
}
/* Smaller refresh icon-button when shown next to the dropdown. */
.select-row .link-button {
margin-left: 8px;
text-decoration: none;
font-size: 16px;
}
.select-row .link-button:hover {
color: var(--primary-color);
opacity: 0.7;
}
h3 {
margin: 8px 0 0;
font-size: 14px;
color: var(--primary-color);
}
.select-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.assignee-pool {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-top: 4px;
}
.checkbox-row {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
cursor: pointer;
margin: 2px 0;
}
.checkbox-row input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.schedule-time-toggle {
display: flex;
margin: 8px 0 4px;
}
.pool-item {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
cursor: pointer;
}
.pool-item input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.select-row label {
font-size: 12px;
color: var(--secondary-text-color);
}
.select-row select {
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 14px;
}
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.weekday-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.weekday-chip {
padding: 6px 12px;
border: 1px solid var(--divider-color);
border-radius: 16px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
}
.weekday-chip.selected {
background: var(--primary-color, #03a9f4);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color, #03a9f4);
}
.season-chip {
padding: 6px 10px;
border: 1px solid var(--divider-color);
border-radius: 16px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
}
.season-chip.selected {
background: var(--primary-color, #03a9f4);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color, #03a9f4);
}
.error.warning { color: var(--warning-color, #ff9800); }
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
.toggle-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
cursor: pointer;
}
`,l([v({attribute:!1})],m.prototype,"hass",2),l([v({type:Boolean,attribute:"checklists-enabled"})],m.prototype,"checklistsEnabled",2),l([v({type:Boolean,attribute:"schedule-time-enabled"})],m.prototype,"scheduleTimeEnabled",2),l([v({type:Boolean,attribute:"completion-actions-enabled"})],m.prototype,"completionActionsEnabled",2),l([v({type:Number,attribute:"default-warning-days"})],m.prototype,"defaultWarningDays",2),l([c()],m.prototype,"parts",2),l([c()],m.prototype,"_foreignOwners",2),l([c()],m.prototype,"_open",2),l([c()],m.prototype,"_entityPickerFallback",2),l([c()],m.prototype,"_loading",2),l([c()],m.prototype,"_error",2),l([c()],m.prototype,"_warning",2),l([c()],m.prototype,"_entryId",2),l([c()],m.prototype,"_taskId",2),l([c()],m.prototype,"_objectChoices",2),l([c()],m.prototype,"_name",2),l([c()],m.prototype,"_type",2),l([c()],m.prototype,"_scheduleType",2),l([c()],m.prototype,"_intervalDays",2),l([c()],m.prototype,"_intervalUnit",2),l([c()],m.prototype,"_dueDate",2),l([c()],m.prototype,"_warningDays",2),l([c()],m.prototype,"_earliestCompletionDays",2),l([c()],m.prototype,"_intervalAnchor",2),l([c()],m.prototype,"_weekdays",2),l([c()],m.prototype,"_nth",2),l([c()],m.prototype,"_nthWeekday",2),l([c()],m.prototype,"_domDay",2),l([c()],m.prototype,"_domLastDay",2),l([c()],m.prototype,"_domBusiness",2),l([c()],m.prototype,"_calOffset",2),l([c()],m.prototype,"_seasonMonths",2),l([c()],m.prototype,"_endsMode",2),l([c()],m.prototype,"_endsCount",2),l([c()],m.prototype,"_endsUntil",2),l([c()],m.prototype,"_schedulePreview",2),l([c()],m.prototype,"_schedulePreviewEnded",2),l([c()],m.prototype,"_notes",2),l([c()],m.prototype,"_documentationUrl",2),l([c()],m.prototype,"_customIcon",2),l([c()],m.prototype,"_priority",2),l([c()],m.prototype,"_labels",2),l([c()],m.prototype,"_enabled",2),l([c()],m.prototype,"_triggerEntityId",2),l([c()],m.prototype,"_triggerEntityIds",2),l([c()],m.prototype,"_triggerEntityLogic",2),l([c()],m.prototype,"_triggerAttribute",2),l([c()],m.prototype,"_triggerType",2),l([c()],m.prototype,"_triggerAbove",2),l([c()],m.prototype,"_triggerBelow",2),l([c()],m.prototype,"_triggerEquals",2),l([c()],m.prototype,"_triggerNotEquals",2),l([c()],m.prototype,"_triggerForMinutes",2),l([c()],m.prototype,"_triggerCombinator",2),l([c()],m.prototype,"_triggerTargetValue",2),l([c()],m.prototype,"_triggerDeltaMode",2),l([c()],m.prototype,"_triggerBaselineValue",2),l([c()],m.prototype,"_liveBaselineValue",2),l([c()],m.prototype,"_autoCompleteOnRecovery",2),l([c()],m.prototype,"_triggerFromState",2),l([c()],m.prototype,"_triggerToState",2),l([c()],m.prototype,"_triggerTargetChanges",2),l([c()],m.prototype,"_triggerRuntimeHours",2),l([c()],m.prototype,"_triggerRuntimeMaxSession",2),l([c()],m.prototype,"_triggerOnStates",2),l([c()],m.prototype,"_compoundLogic",2),l([c()],m.prototype,"_compoundConditions",2),l([c()],m.prototype,"_suggestedAttributes",2),l([c()],m.prototype,"_availableAttributes",2),l([c()],m.prototype,"_entityDomain",2),l([c()],m.prototype,"_lastPerformed",2),l([c()],m.prototype,"_nfcTagId",2),l([c()],m.prototype,"_requireTagScan",2),l([c()],m.prototype,"_allowSkip",2),l([c()],m.prototype,"_notifyEnabled",2),l([c()],m.prototype,"_readingUnit",2),l([c()],m.prototype,"_readings",2),l([c()],m.prototype,"_consumesParts",2),l([c()],m.prototype,"_partsLoadFailed",2),l([c()],m.prototype,"_availableTags",2),l([c()],m.prototype,"_responsibleUserId",2),l([c()],m.prototype,"_assigneePool",2),l([c()],m.prototype,"_rotationStrategy",2),l([c()],m.prototype,"_availableUsers",2),l([c()],m.prototype,"_checklistText",2),l([c()],m.prototype,"_phaseDefs",2),l([c()],m.prototype,"_phaseSeq",2),l([c()],m.prototype,"_requiredCompletion",2),l([c()],m.prototype,"_scheduleTime",2),l([c()],m.prototype,"_scheduleTimeOn",2),l([c()],m.prototype,"_actionService",2),l([c()],m.prototype,"_actionTargetEntity",2),l([c()],m.prototype,"_actionData",2),l([c()],m.prototype,"_actionDataJsonFallback",2),l([c()],m.prototype,"_actionTesting",2),l([c()],m.prototype,"_actionTestResult",2),l([c()],m.prototype,"_actionTestError",2),l([c()],m.prototype,"_qcNotes",2),l([c()],m.prototype,"_qcCost",2),l([c()],m.prototype,"_qcDuration",2),l([c()],m.prototype,"_qcFeedback",2),l([c()],m.prototype,"_environmentalEntity",2),l([c()],m.prototype,"_environmentalAttribute",2),l([c()],m.prototype,"_adaptiveEnabled",2),l([c()],m.prototype,"_adaptiveAlpha",2),l([c()],m.prototype,"_adaptiveMin",2),l([c()],m.prototype,"_adaptiveMax",2),l([c()],m.prototype,"_adaptiveSeasonal",2),l([c()],m.prototype,"_adaptivePrediction",2),l([c()],m.prototype,"_conditionAttrOptions",2);var ge=m;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",ge);async function zt(r,o,e,i){let t=new FormData;t.append("entry_id",o);for(let _ of i)t.append("tags",_);t.append("file",e,e.name);let n=await fetch("/api/maintenance_supporter/document/upload",{method:"POST",headers:{Authorization:`Bearer ${r.auth?.data?.access_token??""}`},body:t});if(n.status===413)throw new Error("doc_too_large");if(!n.ok)throw new Error("doc_upload_failed");let d=await n.json();if(!d.id)throw new Error("doc_upload_failed");return{id:d.id,deduped:!!d.deduped,duplicate_in_object:d.duplicate_in_object??null}}async function Xe(r,o,e){return(await zt(r,o,e,["photo"])).id}async function ve(r,o){await Promise.all(o.map(e=>r.connection.sendMessagePromise({type:"maintenance_supporter/documents/delete",doc_id:e}).catch(()=>{})))}var X=class{constructor(o,e){this.host=o;this.opts=e;this.photos=[];this.uploadedIds=[];this.uploading=!1;this.errorKey="";this.max=e.max??10,o.addController(this)}hostConnected(){}get ids(){return this.photos.map(o=>o.id)}get remaining(){return Math.max(this.max-this.photos.length,0)}get full(){return this.remaining===0}errorText(o){return this.errorKey?s(this.errorKey,o).replace("{max}",String(this.max)):""}clearError(){this.errorKey=""}reset(o=[]){this._revokeAll(),this.photos=o.map(e=>({id:e,preview:""})),this.uploadedIds=[],this.uploading=!1,this.errorKey="",this.host.requestUpdate()}async addFiles(o){if(o.length===0)return;let e=o.slice(0,this.remaining);this.uploading=!0,this.errorKey="",this.host.requestUpdate();try{for(let i of e){let t=await Xe(this.opts.hass(),this.opts.entryId(),i);this.uploadedIds=[...this.uploadedIds,t],this.photos=[...this.photos,{id:t,preview:URL.createObjectURL(i)}],this.host.requestUpdate()}o.length>e.length&&(this.errorKey="photos_limit")}catch(i){this.errorKey=i instanceof Error&&i.message==="doc_too_large"?"doc_too_large":"doc_upload_failed"}finally{this.uploading=!1,this.host.requestUpdate()}}remove(o){let e=this.photos.find(i=>i.id===o);e?.preview&&URL.revokeObjectURL(e.preview),this.photos=this.photos.filter(i=>i.id!==o),this.uploadedIds.includes(o)&&(this.uploadedIds=this.uploadedIds.filter(i=>i!==o),ve(this.opts.hass(),[o])),this.host.requestUpdate()}discardOrphans(){if(this.uploadedIds.length===0)return;let o=this.uploadedIds;this.uploadedIds=[],ve(this.opts.hass(),o)}markAttached(){this.uploadedIds=[]}_revokeAll(){for(let o of this.photos)o.preview&&URL.revokeObjectURL(o.preview)}};function le(){if(window.externalApp!==void 0)return!0;let o=typeof navigator<"u"&&navigator.userAgent||"";return/Home Assistant\//.test(o)&&/Android/.test(o)}var fe={printOptions:"msp-print-options",batteryRosterOpen:"msp-bf-roster-open",docSort:"msp-doc-sort",cameraDevice:"msp-camera-device",overviewTab:"msp-overview-tab",collapsedSections:"msp-collapsed-sections",chartRange:"msp-chart-range",chartHideOutliers:"msp-chart-hide-outliers",taskSort:"maintenance_supporter_sort",objectSort:"maintenance_supporter_object_sort",groupBy:"maintenance_supporter_groupby",objectView:"maintenance_supporter_object_view",objectsCache:"msp-objects-cache",gettingStartedDismissed:"msp-gs-dismissed",batteryRosterSort:"ms_bf_roster_sort"};function et(r){try{return localStorage.getItem(r)}catch{return null}}function tt(r,o){try{localStorage.setItem(r,o)}catch{}}function it(){if(!le())return!1;let r=typeof navigator<"u"?navigator.mediaDevices:void 0;return!!r&&typeof r.getUserMedia=="function"}var Vt=1920,Bt=.88,W=class extends E{constructor(){super(...arguments);this.lang="en";this._open=!1;this._busy=!1;this._devices=[];this._stream=null}async open(){if(this._open)return;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e||typeof e.getUserMedia!="function"){this._unavailable("no_media_devices");return}let i=et(fe.cameraDevice),t=!1;if(i)try{this._stream=await e.getUserMedia({video:{deviceId:{exact:i}},audio:!1}),t=!0}catch{}if(!t){try{this._stream=await e.getUserMedia({video:{facingMode:{ideal:"environment"},advanced:[{zoom:1}]},audio:!1})}catch(d){this._unavailable(d instanceof Error?d.name||d.message:String(d));return}await this._preferMainBackCamera(e)}await this._applyZoomOne(),await this._listDevices(e),this._open=!0,await this.updateComplete;let n=this._video;if(n&&this._stream){n.srcObject=this._stream;try{await n.play()}catch{}}}async _preferMainBackCamera(e){if(typeof e.enumerateDevices!="function")return;let i=[];try{i=await e.enumerateDevices()}catch{return}let t=u=>{let h=/camera2?\s*(\d+)/i.exec(u.label);return h?Number(h[1]):Number.MAX_SAFE_INTEGER},n=i.filter(u=>u.kind==="videoinput"&&u.deviceId&&/back|rear|environment|rück|hinten/i.test(u.label)).sort((u,h)=>t(u)-t(h)),_=this._stream?.getVideoTracks()[0]?.getSettings().deviceId;if(n.length>1&&n[0].deviceId!==_)try{let u=await e.getUserMedia({video:{deviceId:{exact:n[0].deviceId}},audio:!1});for(let h of this._stream?.getTracks()??[])h.stop();this._stream=u}catch{}}async _applyZoomOne(){let e=this._stream?.getVideoTracks()[0],i=e&&typeof e.getCapabilities=="function"?e.getCapabilities():void 0;if(i?.zoom&&typeof i.zoom.min=="number"&&i.zoom.min<1&&(i.zoom.max??1)>=1)try{await e.applyConstraints({advanced:[{zoom:1}]})}catch{}}async _listDevices(e){if(typeof e.enumerateDevices=="function")try{this._devices=(await e.enumerateDevices()).filter(i=>i.kind==="videoinput"&&!!i.deviceId)}catch{this._devices=[]}}get _currentDeviceId(){return this._stream?.getVideoTracks()[0]?.getSettings().deviceId}async _switchCamera(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e||this._devices.length<2||this._busy)return;let i=this._devices.map(d=>d.deviceId),t=i.indexOf(this._currentDeviceId??""),n=i[(t+1)%i.length];this._busy=!0;try{let d=await e.getUserMedia({video:{deviceId:{exact:n}},audio:!1});for(let u of this._stream?.getTracks()??[])u.stop();this._stream=d,await this._applyZoomOne(),tt(fe.cameraDevice,n);let _=this._video;if(_){_.srcObject=d;try{await _.play()}catch{}}}catch{}finally{this._busy=!1}}close(){this._stopStream(),this._open=!1,this._busy=!1}disconnectedCallback(){super.disconnectedCallback(),this._stopStream()}get _video(){return this.shadowRoot?.querySelector("video")??null}_stopStream(){for(let i of this._stream?.getTracks()??[])i.stop();this._stream=null;let e=this._video;e&&(e.srcObject=null)}_unavailable(e){this._stopStream(),this._open=!1,this.dispatchEvent(new CustomEvent("capture-unavailable",{detail:{reason:e},bubbles:!0,composed:!0}))}async _shoot(){let e=this._video;if(!(!e||this._busy)){this._busy=!0;try{let i=e.videoWidth||640,t=e.videoHeight||480,n=Math.min(1,Vt/Math.max(i,t)),d=document.createElement("canvas");d.width=Math.round(i*n),d.height=Math.round(t*n);let _=d.getContext("2d");if(!_)throw new Error("no_canvas");_.drawImage(e,0,0,d.width,d.height);let u=await new Promise(f=>d.toBlob(f,"image/jpeg",Bt));if(!u)throw new Error("no_blob");let h=new Date().toISOString().replace(/[-:]/g,"").slice(0,15),g=new File([u],`photo-${h}.jpg`,{type:"image/jpeg"});this.close(),this.dispatchEvent(new CustomEvent("photo-captured",{detail:{file:g},bubbles:!0,composed:!0}))}catch(i){this._unavailable(i instanceof Error?i.message:String(i))}finally{this._busy=!1}}}render(){if(!this._open)return p;let e=this.lang;return a`
${s("cancel",e)}
${this._devices.length>1?a`
`:p}
${s("camera_capture_shoot",e)}
`}};W.styles=w`
:host { display: contents; }
.overlay {
position: fixed; inset: 0; z-index: 10000;
background: #000; color: #fff;
display: flex; flex-direction: column;
}
video { flex: 1; min-height: 0; width: 100%; object-fit: contain; background: #000; }
.bar {
display: flex; justify-content: space-between; align-items: center; gap: 16px;
padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));
background: rgba(0, 0, 0, 0.8);
}
button {
font: inherit; border-radius: 24px; padding: 10px 18px; cursor: pointer;
display: inline-flex; align-items: center; gap: 8px;
}
.cancel { background: transparent; color: #fff; border: 1px solid rgba(255, 255, 255, 0.6); }
.switch { background: transparent; color: #fff; border: 1px solid rgba(255, 255, 255, 0.6); padding: 10px 12px; }
.switch ha-icon { --mdc-icon-size: 22px; }
.shoot { background: var(--primary-color, #03a9f4); color: #fff; border: none; font-weight: 600; }
.shoot[disabled] { opacity: 0.6; cursor: default; }
.shoot ha-icon { --mdc-icon-size: 22px; }
`,l([v({type:String})],W.prototype,"lang",2),l([c()],W.prototype,"_open",2),l([c()],W.prototype,"_busy",2),l([c()],W.prototype,"_devices",2);customElements.get("ms-camera-capture")||customElements.define("ms-camera-capture",W);var de=w`
ms-photo-picker { display: contents; }
.photo-pickers {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.photo-pick {
display: inline-flex;
flex-direction: row;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px dashed var(--divider-color);
border-radius: 8px;
cursor: pointer;
font-size: 13px;
color: var(--secondary-text-color);
width: fit-content;
}
.photo-pick:hover { border-color: var(--primary-color); }
.photo-pick:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; }
.photo-pick.disabled { opacity: 0.6; cursor: default; }
.photo-pick input[type="file"] { display: none; }
.photo-android-hint {
font-size: 12px;
color: var(--secondary-text-color);
margin-top: 4px;
}
`,R=class extends E{constructor(){super(...arguments);this.lang="en";this.disabled=!1;this.busy=!1;this.accept="image/*";this.showCamera=!0;this.showGallery=!0;this.compact=!1;this.remaining=1/0;this._singlePick=le();this._inAppCamera=it()}createRenderRoot(){return this}get _locked(){return this.disabled||this.busy}_emit(e){e.length!==0&&this.dispatchEvent(new CustomEvent("files-picked",{detail:{files:e},bubbles:!0,composed:!0}))}_onInput(e){let i=e.target,t=Array.from(i.files??[]);i.value="",this._emit(t)}_onCameraClick(e){!this._inAppCamera||this._locked||(e.preventDefault(),this.querySelector("ms-camera-capture")?.open())}_onCameraUnavailable(){this._inAppCamera=!1,this.querySelector(".photo-pick-camera input")?.click()}_onKeydown(e){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),!this._locked&&e.currentTarget.click())}render(){if(this.remaining<=0||!this.showCamera&&!this.showGallery)return p;let e=this.lang,i=this._locked?"disabled":"",t=this.busy?s("uploading",e):s("doc_camera",e),n=s(this._singlePick?"choose_photo":"choose_photos",e);return a`
${this.showCamera?a`
${this.compact?p:a`${t} `}
`:p}
${this.showGallery?a`
${this.compact?p:a`${n} `}
`:p}
${this.showGallery&&this._singlePick?a`${s("photos_android_hint",e)}
`:p}
${this.showCamera&&this._inAppCamera?a`this._emit([d.detail.file])}
@capture-unavailable=${this._onCameraUnavailable}> `:p}
`}};l([v({type:String})],R.prototype,"lang",2),l([v({type:Boolean})],R.prototype,"disabled",2),l([v({type:Boolean})],R.prototype,"busy",2),l([v({type:String})],R.prototype,"accept",2),l([v({type:Boolean})],R.prototype,"showCamera",2),l([v({type:Boolean})],R.prototype,"showGallery",2),l([v({type:Boolean})],R.prototype,"compact",2),l([v({type:Number})],R.prototype,"remaining",2),l([c()],R.prototype,"_inAppCamera",2);customElements.get("ms-photo-picker")||customElements.define("ms-photo-picker",R);var b=class extends E{constructor(){super(...arguments);this.entryId="";this.taskId="";this.taskName="";this.lang="en";this.checklist=[];this.adaptiveEnabled=!1;this.taskType="";this.readingUnit="";this.readings=[];this.readingHistory=[];this.restockDefault=null;this.restockUnitCost=null;this.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._photos=new X(this,{entryId:()=>this.entryId,hass:()=>this.hass});this._readingValue="";this._readingValues={};this._restockQty="";this._completedAt="";this._usedParts={};this.checklistPrefill={}}open(e={}){this._open||(this._open=!0,this.viaTagScan=!!e.viaTagScan,this._notes="",this._cost="",this._duration="",this._error="",this._checklistState=Object.fromEntries(this.checklist.map((i,t)=>[String(t),!!this.checklistPrefill[i]]).filter(([,i])=>i)),this._feedback="needed",this._photos.reset(),this._readingValue="",this._readingValues={},this._restockQty=this.restockDefault!==null?String(this.restockDefault):"",this._completedAt="",this._usedParts=Object.fromEntries(this.consumesParts.map(i=>[D(i),{...i}])))}_toggleCheck(e){let i=String(e);this._checklistState={...this._checklistState,[i]:!this._checklistState[i]}}_setFeedback(e){this._feedback=e}async _complete(){this._loading=!0,this._error="",this._photos.clearError();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 i=parseFloat(this._cost);!isNaN(i)&&i>=0&&(e.cost=i)}if(this._duration){let i=parseInt(this._duration,10);!isNaN(i)&&i>=0&&(e.duration=i)}if(this.checklist.length>0&&(e.checklist_state=this._checklistState),this.adaptiveEnabled&&(e.feedback=this._feedback),this._photos.photos.length>0&&(e.photo_doc_ids=this._photos.ids),this.viaTagScan&&(e.via_tag_scan=!0),this._completedAt){if(new Date(this._completedAt).getTime()>Date.now()){this._error=s("completed_at_future_error",this.lang),this._loading=!1;return}e.completed_at=this._completedAt.length===16?`${this._completedAt}:00`:this._completedAt}if(this.readings.length>0){let i={};for(let t of this.readings){let n=(this._readingValues[t.id]??"").trim();if(n==="")continue;let d=parseFloat(n.replace(",","."));isNaN(d)||(i[t.id]=d)}Object.keys(i).length>0&&(e.reading_values=i)}else if(this._readingValue!==""){let i=parseFloat(this._readingValue);isNaN(i)||(e.reading_value=i)}if(this.restockDefault!==null&&this._restockQty!==""){let i=parseFloat(this._restockQty);!isNaN(i)&&i>=1&&(e.restock_quantity=i)}this.parts.length>0&&(e.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(e),this._photos.markAttached(),this._open=!1,this.dispatchEvent(new CustomEvent("task-completed"))}catch(e){this._error=T(e,this.lang,s("save_error",this.lang))}finally{this._loading=!1}}_renderReadingField(e,i){let t=this._completedAt?new Date(this._completedAt).getTime():NaN,n=Se(this.readingHistory,e.id,isNaN(t)?void 0:t),d=e.unit||this.readingUnit,_=(this._readingValues[e.id]??"").trim(),u=_===""?NaN:parseFloat(_.replace(",",".")),h=n!==void 0&&!isNaN(u)&&u
${e.name}${d?` (${d})`:""}
{this._readingValues={...this._readingValues,[e.id]:f.target.value}}} />
${h?a`${s("reading_below_last",i).replace("{value}",g)} `:p}
`}get _missingRequired(){let e={notes:this._notes.trim()!=="",cost:this._cost.trim()!=="",duration:this._duration.trim()!=="",photo:this._photos.photos.length>0,user:!!this.hass?.user};return this.requiredFields.filter(i=>!e[i])}_req(e){return this.requiredFields.includes(e)?a`* `:p}_partsCostSuggestion(){if(this.restockDefault!==null){let t=parseFloat(this._restockQty);return this.restockUnitCost==null||!Number.isFinite(t)||t<=0?null:Math.round(this.restockUnitCost*t*100)/100}if(!this.parts.length)return null;let e=0,i=!1;for(let t of Object.values(this._usedParts)){let n=this.parts.find(d=>D({part_id:d.id,entry_id:d.entry_id})===D(t));n?.cost!=null&&(e+=n.cost*(t.quantity||1),i=!0)}return i?Math.round(e*100)/100:null}_renderCostSuggestion(e){if(this._cost.trim()!=="")return p;let i=this._partsCostSuggestion();if(i==null||i<=0)return p;let t=J(i,this.currencySymbol,e);return a`this._cost=String(Math.round(i*100)/100)}
>${s("cost_from_parts",e).replace("{amount}",t)} `}_close(){this._open=!1,this._photos.discardOrphans()}_pickCompletedAt(){let e=new Date,i=t=>String(t).padStart(2,"0");this._completedAt=`${e.getFullYear()}-${i(e.getMonth()+1)}-${i(e.getDate())}T${i(e.getHours())}:${i(e.getMinutes())}:00`}render(){if(!this._open)return a``;let e=this.lang||this.hass?.language||"en",i=this._error||this._photos.errorText(e);return a`
${s("complete_title",e)}${this.taskName}
${this.phaseLabel?a`${s("phase_current",e)}: ${this.phaseLabel}
`:p}
${this.requireTagScan&&!this.viaTagScan?a`${s("require_tag_scan_hint",e)}
`:p}
${i?a`
${i}
`:p}
${this.checklist.length>0?a`
${s("checklist",e)}
${this.checklist.map((t,n)=>a`
this._toggleCheck(n)}>
${t}
`)}
`:p}
${this.readings.length>0?a`
${s("readings_section",e)}
${this.readings.map(t=>this._renderReadingField(t,e))}
`:this.taskType==="reading"?a`
${s("reading_value_label",e)}${this.readingUnit?` (${this.readingUnit})`:""}
this._readingValue=t.target.value} />
`:p}
${this.parts.length?a`
${s("complete_parts_used",e)}
${this.parts.map(t=>{let n=D({part_id:t.id,entry_id:t.entry_id}),d=this._usedParts[n],_=d!==void 0,u=t.entry_id?{part_id:t.id,quantity:1,entry_id:t.entry_id}:{part_id:t.id,quantity:1};return a`
{let g={...this._usedParts};h.target.checked?g[n]=g[n]||u:delete g[n],this._usedParts=g}} />
${t.name}${t.owner_name?a` (${t.owner_name}) `:p}${t.stock!==null&&t.stock!==void 0?` (${t.stock}${t.unit?" "+t.unit:""})`:""}
${_?a` {let g=parseFloat(h.target.value);this._usedParts={...this._usedParts,[n]:{...u,quantity:Number.isFinite(g)&&g>=.01?g:1}}}} />`:p}
`})}
`:this.consumesInfo.length?a`
${this.consumesInfo.map(t=>a`
${t}
`)}
`:p}
${this.restockDefault!==null?a`
${s("restock_quantity_label",e)}
this._restockQty=t.target.value} />
`:p}
${s("notes_optional",e)}${this._req("notes")}
this._notes=t.target.value} />
${s("cost_optional",e)}${this._req("cost")}
this._cost=t.target.value} />
${this._renderCostSuggestion(e)}
${s("duration_minutes",e)}${this._req("duration")}
this._duration=t.target.value} />
${s("completed_at_optional",e)}
${this._completedAt?a`this._completedAt=t.detail.value}
> `:a`
${s("completed_at_pick",e)}
`}
${s("completion_photos_optional",e)}${this._req("photo")}
${this._photos.photos.length>0?a`
${this._photos.photos.map(t=>a`
this._photos.remove(t.id)}
title="${s("remove",e)}">✕
`)}
`:p}
${this._photos.full?a`
${s("photos_limit",e).replace("{max}",String(this._photos.max))}
`:a`
this._photos.addFiles(t.detail.files)}
> `}
${this.adaptiveEnabled?a`
${s("was_maintenance_needed",e)}
this._setFeedback("needed")}
>${s("feedback_needed",e)}
this._setFeedback("not_needed")}
>${s("feedback_not_needed",e)}
this._setFeedback("not_sure")}
>${s("feedback_not_sure",e)}
`:p}
${s("cancel",e)}
0}
title=${this._missingRequired.length?this._missingRequired.map(t=>s("err_required",e).replace("{field}",s(ie[t]??t,e))).join(" \xB7 "):""}
>
${this._loading?s("completing",e):s("complete",e)}
`}};b.styles=[je,de,w`
.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 */
/* #161 phase 2: the per-slot reading fields */
.readings-block { display: flex; flex-direction: column; gap: 8px; }
.readings-block > .field-label { margin-bottom: -4px; }
.reading-warn {
font-size: 12px;
color: var(--warning-color, #ff9800);
}
/* .photo-pick / .photo-pickers / .photo-android-hint come from photoPickerStyles */
/* #163: the backdate moment starts EMPTY (= now); the button seeds the
HA date+time picker with the current minute instead of the picker's
own 00:00 default, so a backdated completion never lands at midnight
by accident. */
.backdate-pick {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px dashed var(--divider-color);
border-radius: 8px;
background: transparent;
cursor: pointer;
font: inherit;
font-size: 13px;
color: var(--secondary-text-color);
width: fit-content;
--mdc-icon-size: 18px;
}
.backdate-pick:hover { border-color: var(--primary-color); }
/* #161: several photos per completion — tiles wrap into a strip,
the two pickers (camera / gallery) sit underneath while there is
room left under the cap. */
.photo-strip {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 8px 0; /* room for the remove badges above the tiles */
}
.photo-limit {
font-size: 12px;
color: var(--secondary-text-color);
}
.photo-preview {
position: relative;
width: fit-content;
}
/* Uniform tiles: a tiny or portrait shot must not collapse the strip. */
.photo-preview img {
width: 96px;
height: 96px;
object-fit: cover;
border-radius: 8px;
display: block;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
}
.photo-remove {
position: absolute;
top: -8px;
right: -8px;
width: 24px;
height: 24px;
border-radius: 50%;
border: none;
background: var(--error-color, #db4437);
color: #fff;
cursor: pointer;
font-size: 12px;
line-height: 1;
}
.checklist-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-bottom: 1px solid var(--divider-color);
margin-bottom: 4px;
}
.checklist-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.checklist-item {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
padding: 4px 0;
font-size: 14px;
}
.checklist-item input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
.feedback-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-top: 1px solid var(--divider-color);
}
.feedback-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.feedback-buttons {
display: flex;
gap: 8px;
}
.feedback-btn {
flex: 1;
padding: 8px 12px;
border: 1px solid var(--divider-color);
border-radius: 8px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
text-align: center;
transition: all 0.2s;
}
.feedback-btn:hover {
background: var(--secondary-background-color, #f5f5f5);
}
.feedback-btn.selected {
background: var(--primary-color);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color);
}
`],l([v({attribute:!1})],b.prototype,"hass",2),l([v()],b.prototype,"entryId",2),l([v()],b.prototype,"taskId",2),l([v()],b.prototype,"taskName",2),l([v()],b.prototype,"lang",2),l([v({type:Array})],b.prototype,"checklist",2),l([v({type:Boolean})],b.prototype,"adaptiveEnabled",2),l([v()],b.prototype,"taskType",2),l([v()],b.prototype,"readingUnit",2),l([v({attribute:!1})],b.prototype,"readings",2),l([v({attribute:!1})],b.prototype,"readingHistory",2),l([v({attribute:!1})],b.prototype,"restockDefault",2),l([v({attribute:!1})],b.prototype,"restockUnitCost",2),l([v()],b.prototype,"currencySymbol",2),l([v({attribute:!1})],b.prototype,"parts",2),l([v({attribute:!1})],b.prototype,"consumesParts",2),l([v({type:Array})],b.prototype,"consumesInfo",2),l([v({type:Array})],b.prototype,"requiredFields",2),l([v()],b.prototype,"phaseLabel",2),l([v({type:Boolean})],b.prototype,"requireTagScan",2),l([v({type:Boolean})],b.prototype,"viaTagScan",2),l([c()],b.prototype,"_open",2),l([c()],b.prototype,"_notes",2),l([c()],b.prototype,"_cost",2),l([c()],b.prototype,"_duration",2),l([c()],b.prototype,"_loading",2),l([c()],b.prototype,"_error",2),l([c()],b.prototype,"_checklistState",2),l([c()],b.prototype,"_feedback",2),l([c()],b.prototype,"_readingValue",2),l([c()],b.prototype,"_readingValues",2),l([c()],b.prototype,"_restockQty",2),l([c()],b.prototype,"_completedAt",2),l([c()],b.prototype,"_usedParts",2),l([v({attribute:!1})],b.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",b);function st(r,o,e){let i=new Blob([r],{type:e}),t=URL.createObjectURL(i),n=document.createElement("a");n.href=t,n.download=o,n.target="_blank",n.rel="noopener",n.style.display="none",document.body.appendChild(n),n.dispatchEvent(new MouseEvent("click")),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),6e4)}async function Wt(r,o,e=300){return(await r.connection.sendMessagePromise({type:"auth/sign_path",path:o,expires:e})).path}async function rt(r,o,e=300){return Wt(r,`/api/maintenance_supporter/document/${o}`,e)}var K=class extends E{constructor(){super(...arguments);this.docId="";this._url="";this._failed=!1;this._signedFor=""}updated(){this.hass&&this.docId&&this._signedFor!==this.docId&&(this._signedFor=this.docId,this._url="",this._failed=!1,this._sign())}async _sign(){try{this._url=await rt(this.hass,this.docId)}catch{this._failed=!0}}render(){return this._failed||!this.docId?p:this._url?a`
this._failed=!0} />
`:a`
`}};K.styles=w`
.wrap { display: inline-block; margin-top: 4px; }
/* #161: uniform 96px tiles — several photos sit in a strip, so a
tiny or portrait shot must not collapse its slot. */
img {
width: 96px;
height: 96px;
object-fit: cover;
border-radius: 6px;
display: block;
border: 1px solid var(--divider-color);
box-sizing: border-box;
}
.ph {
width: 96px;
height: 96px;
border-radius: 6px;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
margin-top: 4px;
}
`,l([v({attribute:!1})],K.prototype,"hass",2),l([v()],K.prototype,"docId",2),l([c()],K.prototype,"_url",2),l([c()],K.prototype,"_failed",2);customElements.get("maintenance-history-photo")||customElements.define("maintenance-history-photo",K);var L=class extends E{constructor(){super(...arguments);this._open=!1;this._saving=!1;this._error="";this._draft=null;this._originalSnapshot=null;this._partOptions=null;this._partQty={};this._partQtyOriginal="";this._photos=new X(this,{entryId:()=>this._draft?.entry_id??"",hass:()=>this.hass});this._photosOriginal="";this._readingRows=[];this._readingText={};this._readingsOriginal=""}get _lang(){return P(this.hass)}openEdit(e){this._draft={...e},this._originalSnapshot={...e},this._error="",this._open=!0,this._partOptions=null,this._partQty={},this._partQtyOriginal="",this._photos.reset(e.photo_doc_ids??[]),this._photosOriginal=JSON.stringify(this._photos.ids),this._seedReadings(e),this._loadPartOptions()}_seedReadings(e){let i=[],t=new Set;for(let d of e.readings??[])t.has(d.id)||(t.add(d.id),i.push({id:d.id,name:d.name,unit:d.unit??null}));for(let d of e.reading_values??[])t.has(d.id)||(t.add(d.id),i.push({id:d.id,name:d.name,unit:d.unit??null}));this._readingRows=i;let n={};for(let d of e.reading_values??[])n[d.id]=String(d.value);this._readingText=n,this._readingsOriginal=JSON.stringify(this._readingNumbers())}_readingNumbers(){let e={};for(let i of this._readingRows){let t=(this._readingText[i.id]??"").trim();if(t==="")continue;let n=parseFloat(t.replace(",","."));isNaN(n)||(e[i.id]=n)}return e}async _loadPartOptions(){let e=this._draft;if(e)try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/parts/overview"}),t=[];for(let d of i.parts||[]){let _=d.entry_id===e.entry_id,u=d.consumers.some(h=>h.entry_id===e.entry_id&&h.task_id===e.task_id);!_&&!u||t.push({part_id:d.part_id,name:d.name,entry_id:d.entry_id,foreign:!_,object_name:d.object_name})}for(let d of e.used_parts||[]){let _=d.entry_id||e.entry_id;t.some(u=>u.part_id===d.part_id&&u.entry_id===_)||t.push({part_id:d.part_id,name:d.name||d.part_id,entry_id:_,foreign:_!==e.entry_id,object_name:null})}let n={};for(let d of e.used_parts||[])n[`${d.entry_id||e.entry_id}:${d.part_id}`]=d.quantity??1;this._partOptions=t,this._partQty=n,this._partQtyOriginal=this._partSelectionKey()}catch{this._partOptions=[]}}_partSelectionKey(){return JSON.stringify(Object.entries(this._partQty).filter(([,e])=>e>0).sort(([e],[i])=>e.localeCompare(i)))}close(){this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null,this._photos.discardOrphans()}_set(e,i){this._draft&&(this._draft={...this._draft,[e]:i})}async _delete(){if(!this._draft||!this._originalSnapshot)return;let e=this._lang;if(window.confirm(s("history_delete_confirm",e))){this._saving=!0,this._error="";try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/history/delete",entry_id:this._draft.entry_id,task_id:this._draft.task_id,timestamp:this._originalSnapshot.original_timestamp}),this.dispatchEvent(new CustomEvent("history-entry-saved",{detail:{entry_id:this._draft.entry_id,task_id:this._draft.task_id,deleted:!0},bubbles:!0,composed:!0})),this.close()}catch(i){this._error=T(i,e)}finally{this._saving=!1}}}async _save(){if(!(!this._draft||!this._originalSnapshot)){this._saving=!0,this._error="",this._photos.clearError();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),this._partOptions!==null&&this._partSelectionKey()!==this._partQtyOriginal&&(e.used_parts=(this._partOptions||[]).filter(t=>(this._partQty[`${t.entry_id}:${t.part_id}`]||0)>0).map(t=>({part_id:t.part_id,quantity:this._partQty[`${t.entry_id}:${t.part_id}`],...t.foreign?{entry_id:t.entry_id}:{}}))),this._draft.reading_value!==this._originalSnapshot.reading_value&&(e.reading_value=this._draft.reading_value??null),this._readingRows.length>0&&JSON.stringify(this._readingNumbers())!==this._readingsOriginal){let t=this._readingNumbers(),n={};for(let d of this._readingRows)n[d.id]=t[d.id]??null;e.reading_values=n}if(JSON.stringify(this._photos.ids)!==this._photosOriginal&&(e.photo_doc_ids=this._photos.ids),Object.keys(e).filter(t=>!["type","entry_id","task_id","original_timestamp"].includes(t)).length===0){this.close();return}await this.hass.connection.sendMessagePromise(e),this._photos.markAttached(),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=T(e,this._lang)}finally{this._saving=!1}}}render(){if(!this._open||!this._draft)return p;let e=this._lang,i=this._draft,t=this._error||this._photos.errorText(e);return a`
${s("history_edit_title",e)}
${s(i.type,e)||i.type}
{let d=n.detail.value;d&&this._set("timestamp",d)}}
>
${s("notes_label",e)}
${s("cost",e)}
{let d=n.target.value;this._set("cost",d?Number(d):null)}} />
${s("duration",e)}
{let d=n.target.value;this._set("duration",d?Number(d):null)}} />
${this._renderReadings(i,e)}
${this._partOptions&&this._partOptions.length>0?a`
${s("complete_parts_used",e)}
${this._partOptions.map(n=>{let d=`${n.entry_id}:${n.part_id}`,_=this._partQty[d]||0;return a`
0}
@change=${u=>{let h=u.target.checked;this._partQty={...this._partQty,[d]:h?1:0}}} />
${n.name}${n.foreign&&n.object_name?` (${n.object_name})`:""}
${_>0?a`
{let h=parseFloat(u.target.value);!isNaN(h)&&h>0&&(this._partQty={...this._partQty,[d]:h})}} />
`:p}
`})}
`:p}
${s("completion_photos",e)}
${this._photos.photos.length>0?a`
${this._photos.photos.map(n=>a`
this._photos.remove(n.id)}>✕
`)}
`:p}
${this._photos.full?a`
${s("photos_limit",e).replace("{max}",String(this._photos.max))} `:a`
this._photos.addFiles(n.detail.files)}
> `}
${s("history_edit_photos_hint",e)}
${t?a`
${t}
`:p}
${s("history_delete_entry",e)}
${s("cancel",e)}
${this._saving?s("saving",e):s("save",e)}
`}_renderReadings(e,i){return this._readingRows.length>0?a`
${s("readings_section",i)}
${this._readingRows.map(t=>a`
${t.name}${t.unit?` (${t.unit})`:""}
{this._readingText={...this._readingText,[t.id]:n.target.value}}} />
`)}
`:e.reading_value==null&&e.task_type!=="reading"?p:a`
${s("reading_value_label",i)}${e.reading_unit?` (${e.reading_unit})`:""}
{let n=t.target.value,d=n===""?NaN:Number(n);this._set("reading_value",isNaN(d)?null:d)}} />
`}};L.styles=[de,w`
: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;
}
.delete-entry { margin-right: auto; color: var(--error-color, #d32f2f); background: transparent; border: 1px solid var(--error-color, #d32f2f); border-radius: 6px; padding: 6px 10px; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
.delete-entry ha-icon { --mdc-icon-size: 18px; }
.actions {
display: flex; gap: 8px; justify-content: flex-end;
margin-top: 8px;
}
button {
padding: 8px 16px; font-size: 14px;
border-radius: 6px; cursor: pointer;
border: none; font-weight: 500;
}
button.cancel {
background: transparent;
color: var(--primary-text-color);
border: 1px solid var(--divider-color);
}
button.save {
background: var(--primary-color);
color: var(--text-primary-color, white);
}
button[disabled] { opacity: 0.5; cursor: wait; }
.error {
color: var(--error-color, #d32f2f);
font-size: 13px; padding: 8px;
background: rgba(211,47,47,0.1);
border-radius: 6px;
}
/* #130: parts on the entry */
.parts-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.parts-title { color: var(--secondary-text-color); font-size: 13px; }
.part-row-edit {
display: flex; flex-direction: row; align-items: center; gap: 8px;
font-size: 14px;
}
.part-row-edit input[type="checkbox"] { width: auto; }
.part-label { flex: 1; color: var(--primary-text-color); }
.part-qty { width: 76px; }
/* #161 phase 2: readings on the entry */
.readings-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.reading-row-edit {
display: flex; flex-direction: row; align-items: center; gap: 8px;
font-size: 14px;
}
.reading-row-name { flex: 1; color: var(--primary-text-color); min-width: 0; }
.reading-row-input { width: 140px; font-variant-numeric: tabular-nums; }
/* #161: photos on the entry */
.photos-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.photo-strip { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 6px; }
.photo-tile { position: relative; width: fit-content; }
.photo-remove {
position: absolute; top: -4px; right: -8px;
width: 22px; height: 22px; border-radius: 50%; border: none;
background: var(--error-color, #db4437); color: #fff;
cursor: pointer; font-size: 11px; line-height: 1; padding: 0;
}
/* the camera / gallery pickers come from photoPickerStyles (ms-photo-picker) */
.photos-hint { font-size: 12px; color: var(--secondary-text-color); }
`],l([v({attribute:!1})],L.prototype,"hass",2),l([c()],L.prototype,"_open",2),l([c()],L.prototype,"_saving",2),l([c()],L.prototype,"_error",2),l([c()],L.prototype,"_draft",2),l([c()],L.prototype,"_partOptions",2),l([c()],L.prototype,"_partQty",2),l([c()],L.prototype,"_readingRows",2),l([c()],L.prototype,"_readingText",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",L);function ee(r){return r.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function nt(r){return!r.startsWith("data:image/svg+xml,")&&!r.startsWith("data:image/png;base64,")?"":ee(r)}function Kt(r){return r.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var q=class extends E{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,i){this._entryId=e,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(e,i,t,n){this._entryId=e,this._taskId=i,this._objectName=t,this._taskName=n,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}async _generate(){let e=++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 t=[this.hass.connection.sendMessagePromise({...i,action:"view"})];this._taskId&&t.push(this.hass.connection.sendMessagePromise({...i,action:"complete"}));let n=await Promise.all(t);if(e!==this._generateSeq)return;this._viewResult=n[0],n.length>1&&(this._completeResult=n[1])}catch(i){if(e!==this._generateSeq)return;let t=i?.code,n=i?.message;this._error=t==="no_url"||typeof n=="string"&&n.includes("No Home Assistant URL")?s("qr_error_no_url",this.lang):s("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,i=e.label.task_name?`${e.label.object_name} \u2014 ${e.label.task_name}`:e.label.object_name,t=[e.label.manufacturer,e.label.model].filter(Boolean).join(" "),n=window.open("","_blank","width=600,height=500");if(!n)return;let d=this.lang||"en",_=ee(i),u=ee(t),h=!!this._completeResult,g=ee(s("qr_action_view",d)),f=ee(s("qr_action_complete",d));n.document.write(`
${_}
${_}
${u?`${u}
`:""}
${g}
${h?`
${f}
`:""}
${ee(this._viewResult.url)}