t.id===r)?.name||null}getPerson(r){return wr(this.getUser(r))}getUser(r){return!r||!this.usersCache?null:this.usersCache.find(e=>e.id===r)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(r){return r?r===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}}});function J(s){return`${s.entry_id??""}\0${s.part_id}`}function Er(s,r,e,t){let i=!!s.entry_id&&s.entry_id!==r,a=i?s.entry_id:r,o=e.find(m=>m.entry_id===a),_=(o?.parts||[]).find(m=>m.id===s.part_id)||null,c=i&&o?.object?.name||"",p=_?.name||n("shared_part_unknown",t);return{part:_,foreign:i,ownerName:c,label:c?`${p} (${c})`:p}}function Sr(s,r,e,t){let{part:i,label:a}=Er(s,r,e,t),o=i&&i.stock!==null&&i.stock!==void 0?` (${i.stock}${i.unit?" "+i.unit:""})`:"",_=i?.storage_location?` \u2014 ${i.storage_location}`:"";return`${s.quantity}\xD7 ${a}${o}${_}`}function Tr(s,r,e,t){let a=(e.find(_=>_.entry_id===r)?.parts||[]).map(_=>({..._})),o=new Set(a.map(_=>J({part_id:_.id})));for(let _ of s?.consumes_parts||[]){if(!_.entry_id||_.entry_id===r)continue;let c=J(_);if(o.has(c))continue;o.add(c);let{part:p,ownerName:m}=Er(_,r,e,t);a.push({id:_.part_id,name:p?.name||n("shared_part_unknown",t),unit:p?.unit,stock:p?.stock??null,storage_location:p?.storage_location,entry_id:_.entry_id,owner_name:m})}return a}var _t=x(()=>{"use strict";C()});var Ft,Ar,Cr,Ir=x(()=>{"use strict";Ft=["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"],Ar=["sensor"],Cr=["temperature","humidity","pressure"]});async function Ut(s,r,e={}){e.busy?.(!0);try{return await s.hass.connection.sendMessagePromise(r)}catch(t){let i=H(s.hass);e.onError?.(N(t,i,e.fallbackKey?n(e.fallbackKey,i):void 0));return}finally{e.busy?.(!1)}}var Pr=x(()=>{"use strict";pe();C()});var Bt,Je,Vt=x(()=>{"use strict";Bt=["notes","cost","duration","photo","user"],Je={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"}});function wn(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",equals:"",notEquals:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",carry:{}}}function kn(s){return{entityIds:(s.entity_ids||(s.entity_id?[s.entity_id]:[])).join(", "),type:s.type||"threshold",attribute:s.attribute||"",above:s.trigger_above?.toString()??"",below:s.trigger_below?.toString()??"",equals:s.trigger_equals?.toString()??"",notEquals:s.trigger_not_equals?.toString()??"",forMinutes:s.trigger_for_minutes?.toString()??"0",targetValue:s.trigger_target_value?.toString()??"",deltaMode:s.trigger_delta_mode||!1,fromState:s.trigger_from_state||"",toState:s.trigger_to_state||"",targetChanges:s.trigger_target_changes?.toString()??"",runtimeHours:s.trigger_runtime_hours?.toString()??"",onStates:(s.trigger_on_states||[]).join(", "),carry:Object.fromEntries(Object.entries(s).filter(([e])=>!$n.has(e)&&!e.startsWith("_")))}}function En(s){let r=s.entityIds.split(",").map(t=>t.trim()).filter(Boolean);if(r.length===0)return null;let e={...s.carry||{},entity_id:r[0],entity_ids:r,type:s.type};if(s.attribute&&(e.attribute=s.attribute),s.type==="threshold"){let t=parseFloat(s.above);isNaN(t)||(e.trigger_above=t);let i=parseFloat(s.below);isNaN(i)||(e.trigger_below=i);let a=parseFloat(s.equals);isNaN(a)||(e.trigger_equals=a);let o=parseFloat(s.notEquals);isNaN(o)||(e.trigger_not_equals=o);let _=parseInt(s.forMinutes,10);isNaN(_)||(e.trigger_for_minutes=_)}else if(s.type==="counter"){let t=parseFloat(s.targetValue);isNaN(t)||(e.trigger_target_value=t),e.trigger_delta_mode=s.deltaMode}else if(s.type==="state_change"){s.fromState&&(e.trigger_from_state=s.fromState),s.toState&&(e.trigger_to_state=s.toState);let t=parseInt(s.targetChanges,10);isNaN(t)||(e.trigger_target_changes=t)}else if(s.type==="runtime"){let t=parseFloat(s.runtimeHours);isNaN(t)||(e.trigger_runtime_hours=t);let i=(s.onStates||"").split(",").map(a=>a.trim()).filter(Boolean);i.length>0&&(e.trigger_on_states=i)}return e}function Sn(s){return Array.from({length:7},(r,e)=>Ae(e,s,"short"))}function Tn(s){return Array.from({length:12},(r,e)=>Dt(e,s,"short"))}var vn,yn,bn,mt,Rr,Lr,xn,ie,$n,g,Wt,Nr=x(()=>{"use strict";I();F();C();kr();_t();xe();Ir();pe();Pr();Vt();zt();Ie();vn=["cleaning","inspection","replacement","calibration","service","reading","custom"],yn=["low","normal","high"],bn=["time_based","weekdays","nth_weekday","day_of_month","sensor_based","one_time","manual"],mt=["weekdays","nth_weekday","day_of_month"],Rr=["time_based","one_time",...mt],Lr=["threshold","counter","state_change","runtime"],xn=[...Lr,"compound"],ie={alpha:"0.3",min:"7",max:"365"};$n=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"]);g=class g extends S{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._isFleetTask=!1;this._objectChoices=[];this._name="";this._type="custom";this._scheduleType="time_based";this._intervalDays="30";this._intervalUnit="days";this._dueDate="";this._warningDays="7";this._earliestCompletionDays="";this._intervalAnchor="completion";this._weekdays=[];this._nth="1";this._nthWeekday="5";this._domDay="1";this._domLastDay=!1;this._domBusiness=!1;this._calOffset="0";this._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._mirrorTodoEntities=[];this._enabled=!0;this._triggerEntityId="";this._triggerEntityIds=[];this._triggerEntityLogic="any";this._triggerAttribute="";this._triggerType="threshold";this._triggerAbove="";this._triggerBelow="";this._triggerEquals="";this._triggerNotEquals="";this._triggerForMinutes="0";this._triggerCombinator="any";this._triggerTargetValue="";this._triggerDeltaMode=!1;this._triggerBaselineValue="";this._liveBaselineValue=null;this._autoCompleteOnRecovery=!1;this._triggerFromState="";this._triggerToState="";this._triggerTargetChanges="";this._triggerRuntimeHours="";this._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=ie.alpha;this._adaptiveMin=ie.min;this._adaptiveMax=ie.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 H(this.hass)}async openCreate(e,t){this._entryId=e,this._taskId=null,this._isFleetTask=!1,this._error="",this._warning="",!e&&t&&t.length>0?(this._objectChoices=t.map(i=>({entry_id:i.entry_id,name:i.object.name})).sort((i,a)=>i.name.localeCompare(a.name)),this._entryId=this._objectChoices[0].entry_id):this._objectChoices=[],this._resetFields(),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}async openEdit(e,t){this._entryId=e,this._taskId=t.id,this._error="",this._warning="",this._objectChoices=[],this._isFleetTask=t.battery_fleet_task===!0,this._name=t.name,this._type=t.type,this._scheduleType=t.schedule_type,this._intervalDays=t.interval_days!=null?String(t.interval_days):"",this._intervalUnit=t.interval_unit||"days",this._dueDate=t.due_date||"";let i=t.schedule;this._weekdays=i?.kind==="weekdays"?[...i.weekdays??[]]:[],this._nth=i?.kind==="nth_weekday"?String(i.nth??1):"1",this._nthWeekday=i?.kind==="nth_weekday"?String(i.weekday??5):"5",this._domDay=i?.kind==="day_of_month"&&(i.day??1)>=1?String(i.day??1):"1",this._domLastDay=i?.kind==="day_of_month"&&i.day===-1,this._domBusiness=i?.kind==="day_of_month"&&i.business===!0,this._calOffset=i?.offset?String(i.offset):"0",this._seasonMonths=Array.isArray(i?.season_months)?[...i.season_months]:[];let a=i?.ends;a&&typeof a.count=="number"?(this._endsMode="count",this._endsCount=String(a.count),this._endsUntil=""):a&&typeof a.until=="string"?(this._endsMode="until",this._endsUntil=a.until,this._endsCount=""):(this._endsMode="never",this._endsCount="",this._endsUntil=""),this._warningDays=t.warning_days.toString(),this._earliestCompletionDays=t.earliest_completion_days!=null?String(t.earliest_completion_days):"",this._intervalAnchor=t.interval_anchor||"completion",this._notes=t.notes||"",this._documentationUrl=t.documentation_url||"",this._customIcon=t.custom_icon||"",this._priority=t.priority||"normal",this._labels=(t.labels||[]).join(", "),this._mirrorTodoEntities=[...t.mirror_todo_entities||[]],this._enabled=t.enabled!==!1,this._lastPerformed=t.last_performed||"",this._nfcTagId=t.nfc_tag_id||"",this._requireTagScan=!!t.require_tag_scan,this._allowSkip=t.allow_skip!==!1,this._notifyEnabled=t.notify_enabled!==!1,this._readingUnit=t.reading_unit||"",this._readings=(t.readings||[]).map(p=>({...p})),this._consumesParts=Object.fromEntries((t.consumes_parts||[]).map(p=>[J(p),{...p}])),this._responsibleUserId=t.responsible_user_id||null,this._assigneePool=[...t.assignee_pool||[]],this._rotationStrategy=t.rotation_strategy||"",this._checklistText=(t.checklist||[]).join(`
`),this._phaseDefs=Object.entries(t.phases||{}).map(([p,m])=>{let{name:f,checklist:w,consumes_parts:y,required_completion_fields:$,...A}=m,z=m.consumes_parts||[],U=z.findIndex(G=>!G.entry_id),D=U>=0?z[U]:void 0;return{id:p,name:m.name||p,checklistText:(m.checklist||[]).join(`
`),partId:D?.part_id||"",partQty:D?.quantity!=null?String(D.quantity):"",reqOverride:m.required_completion_fields!==void 0,reqFields:[...m.required_completion_fields||[]],extraParts:z.filter((G,oe)=>oe!==U).map(G=>({...G})),carry:A}}),this._phaseSeq=[...t.phase_sequence||[]],this._requiredCompletion=[...t.required_completion_fields||[]],this._scheduleTime=t.schedule_time||"",this._scheduleTimeOn=!!t.schedule_time;let o=t.on_complete_action;if(o&&o.service){this._actionService=o.service;let p=o.target?.entity_id;this._actionTargetEntity=Array.isArray(p)?p[0]||"":p||"",this._actionData=o.data&&typeof o.data=="object"?{...o.data}:{},this._actionDataJsonFallback=""}else this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="";let _=t.quick_complete_defaults;this._qcNotes=_?.notes||"",this._qcCost=_?.cost!=null?String(_.cost):"",this._qcDuration=_?.duration!=null?String(_.duration):"",this._qcFeedback=_?.feedback||"";let c=t.adaptive_config||{};if(this._environmentalEntity=c.environmental_entity||"",this._environmentalAttribute=c.environmental_attribute||"",this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute,this._adaptiveEnabled=!!c.enabled,this._adaptiveAlpha=c.ewa_alpha?.toString()??ie.alpha,this._adaptiveMin=c.min_interval_days?.toString()??ie.min,this._adaptiveMax=c.max_interval_days?.toString()??ie.max,this._adaptiveSeasonal=c.seasonal_enabled!==!1,this._adaptivePrediction=c.sensor_prediction_enabled!==!1,this._adaptiveInitial=this._adaptiveSnapshot(),t.trigger_config){let p=t.trigger_config;this._triggerEntityId=p.entity_id||p.entity_ids&&p.entity_ids[0]||"",this._triggerEntityIds=p.entity_ids||(p.entity_id?[p.entity_id]:[]),this._triggerEntityLogic=p.entity_logic||"any",this._triggerAttribute=p.attribute||"",this._triggerType=p.type||"threshold",this._triggerAbove=p.trigger_above?.toString()||"",this._triggerBelow=p.trigger_below?.toString()||"",this._triggerEquals=p.trigger_equals?.toString()||"",this._triggerNotEquals=p.trigger_not_equals?.toString()||"",this._triggerForMinutes=p.trigger_for_minutes?.toString()||"0",this._triggerCombinator=p.trigger_combinator==="all"?"all":"any",this._triggerTargetValue=p.trigger_target_value?.toString()||"",this._triggerDeltaMode=p.trigger_delta_mode||!1,this._triggerBaselineValue=p.trigger_baseline_value?.toString()||"",this._liveBaselineValue=t.trigger_baseline_value??null,this._autoCompleteOnRecovery=p.auto_complete_on_recovery||!1,this._triggerFromState=p.trigger_from_state||"",this._triggerToState=p.trigger_to_state||"",this._triggerTargetChanges=p.trigger_target_changes?.toString()||"",this._triggerRuntimeHours=p.trigger_runtime_hours?.toString()||"",this._triggerRuntimeMaxSession=p.trigger_runtime_max_session_seconds?.toString()||"",this._triggerOnStates=(p.trigger_on_states||[]).join(", "),p.type==="compound"?(this._compoundLogic=p.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(p.conditions||[]).map(kn)):(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._mirrorTodoEntities=[],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=ie.alpha,this._adaptiveMin=ie.min,this._adaptiveMax=ie.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 ht(this.hass));try{this._availableUsers=await this._userService.getUsers()}catch(e){console.error("Failed to load users:",e),this._availableUsers=[]}}_toggleAssignee(e){this._assigneePool=this._assigneePool.includes(e)?this._assigneePool.filter(t=>t!==e):[...this._assigneePool,e]}async _testAction(){let e=this._actionService.trim();if(!e||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(e)){this._actionTestResult="error",this._actionTestError="Invalid service format (expected 'domain.service')",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[t,i]=e.split(".");if(!this.hass?.services?.[t]?.[i]){this._actionTestResult="error",this._actionTestError=`Service "${e}" is not registered in Home Assistant. Check spelling and that the integration providing it is loaded.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}let a=this._actionTargetEntity.trim();if(a){let o=a.split(".")[0];if(o!==t&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(t)){this._actionTestResult="error",this._actionTestError=`Service "${e}" only works on ${t}.* entities; entity "${a}" is in ${o}.* \u2014 pick a service that matches the entity domain (e.g. ${o}.${i})`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}if(!this.hass.states?.[a]){this._actionTestResult="error",this._actionTestError=`Target entity "${a}" not found in Home Assistant \u2014 the entity may have been renamed or its integration removed.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}}this._actionTestResult="ok",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3)}_buildActionData(){if(this._actionDataJsonFallback.trim())try{let e=JSON.parse(this._actionDataJsonFallback);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{...this._actionData}}_serviceSchema(){let e=this._actionService.trim();if(!e||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(e))return null;let[t,i]=e.split("."),a=this.hass?.services?.[t]?.[i]?.fields;return!a||Object.keys(a).length===0?null:Object.entries(a).map(([o,_])=>({name:o,required:!!_.required,selector:_.selector||{text:{}}}))}_renderCompletionActionsSection(e){if(!this.completionActionsEnabled)return u;let t=this._serviceSchema();return l`
${n("on_complete_action_title",e)}
${n("on_complete_action_desc",e)}
{this._actionService=i.detail.value||"";let a=this._serviceSchema();if(a){let o=new Set(a.map(_=>_.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([_])=>o.has(_)))}}}
>
n("on_complete_action_target",e)}
@value-changed=${i=>{let a=i.detail.value;this._actionTargetEntity=a.target_entity||""}}
>
${n("on_complete_action_target_hint",e)}
${t?l`
{this._actionData={...i.detail.value}}}
>
`:l`
{this._actionDataJsonFallback=i.target.value}}
>
`}
${this._actionTestResult==="ok"?l`
${n("on_complete_action_test_success",e)}`:u}
${this._actionTestResult==="error"?l`
${n("on_complete_action_test_failed",e)}
${this._actionTestError?l`
${this._actionTestError}
`:u}
`:u}
${n("quick_complete_defaults_title",e)}
${n("quick_complete_defaults_desc",e)}
{this._qcNotes=i.target.value}}
>
{this._qcCost=i.target.value}}
>
{this._qcDuration=i.target.value}}
>
`}async _loadParts(){if(this.parts=[],!!this._entryId)try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object",entry_id:this._entryId});this.parts=e.parts||[],this._partsLoadFailed=!1}catch{this.parts=[],this._partsLoadFailed=!0}}async _loadForeignPools(){if(this._foreignOwners=[],!!this._entryId)try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/objects"});this._foreignOwners=(e.objects||[]).filter(t=>t.entry_id!==this._entryId&&(t.parts||[]).length>0).map(t=>({entry_id:t.entry_id,name:t.object?.name||t.entry_id,parts:t.parts||[]})).sort((t,i)=>t.name.localeCompare(i.name))}catch{this._foreignOwners=[]}}async _loadTags(){try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/tags/list"});this._availableTags=e.tags||[]}catch{this._availableTags=[]}}_fetchConditionAttributes(e){!e||!this.hass||this._conditionAttrOptions[e]||this._conditionAttrPending.has(e)||(this._conditionAttrPending.add(e),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e}).then(t=>{let i=t;this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:i.suggested_attributes||[],available:i.available_attributes||[]}}}).catch(()=>{this._conditionAttrOptions={...this._conditionAttrOptions,[e]:{suggested:[],available:[]}}}))}async _fetchEntityAttributes(e){if(!e||!this.hass){this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="";return}try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:e});this._entityDomain=t.domain||"",this._suggestedAttributes=t.suggested_attributes||[],this._availableAttributes=t.available_attributes||[]}catch{this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain=""}}get _hasForeignPick(){return Object.values(this._consumesParts).some(e=>!!e.entry_id)}_renderConsumesRow(e,t){let i=J({part_id:e.id,entry_id:t}),a=this._consumesParts[i],o=t?{part_id:e.id,quantity:1,entry_id:t}:{part_id:e.id,quantity:1};return l`
${a!==void 0?l`{let c=parseFloat(_.target.value);this._consumesParts={...this._consumesParts,[i]:{...o,quantity:Number.isFinite(c)&&c>=.01?c:1}}}}
/>`:u}
`}_toggleRequired(e,t){let i=new Set(this._requiredCompletion);t?i.add(e):i.delete(e),this._requiredCompletion=[...i]}_patchReading(e,t){this._readings=this._readings.map(i=>i.id===e?{...i,...t}:i)}_renderReadingsEditor(e){let t=_r(this._readings);return l`
${n("readings_section",e)}
${n("readings_hint",e)}
${this._readings.map(i=>l`
${t.has(i.id)?l`
${n("reading_duplicate_name",e)}
`:u}
this._patchReading(i.id,{name:a.target.value})}
>
this._patchReading(i.id,{unit:a.target.value})}
>
this._readings=this._readings.filter(a=>a.id!==i.id)}>
`)}
${this._readings.length<20?l`
this._readings=[...this._readings,{id:dr(),name:"",unit:this._readings.length?this._readings[this._readings.length-1].unit:this._readingUnit}]}>
${n("reading_add",e)}
`:u}
`}_phaseSlug(e){let t=e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"phase",i=t,a=2;for(;this._phaseDefs.some(o=>o.id===i);)i=`${t}-${a++}`;return i}_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(t=>t.id!==e),this._phaseSeq=this._phaseSeq.filter(t=>t!==e)}_patchPhaseDef(e,t){this._phaseDefs=this._phaseDefs.map(i=>i.id===e?{...i,...t}:i)}_renderPhasesEditor(e){let t=i=>this._phaseDefs.find(a=>a.id===i)?.name||i;return l`
${n("phases_section",e)}
${n("phases_hint",e)}
${this._phaseDefs.map(i=>l`
`)}
${n("phase_add",e)}
${this._phaseDefs.some(i=>i.name.trim())?l`
${n("phase_sequence_label",e)}
${this._phaseSeq.map((i,a)=>l`
${a+1}. ${t(i)}
`)}
`:u}
`}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),t=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(t)&&e>t){this._error=`${n("adaptive_min_interval",this._lang)} > ${n("adaptive_max_interval",this._lang)}`;return}}if(this._triggerType==="threshold"&&this._thresholdLimitsOverlap()){this._error=n("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))},t=this._earliestCompletionDays.trim();e.earliest_completion_days=t===""?null:Math.max(0,parseInt(t,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):mt.includes(this._scheduleType)?(e.schedule={...this._buildSchedule(),...this._recurrenceExtras()},e.interval_days=null,this._taskId&&(e.due_date=null)):(this._taskId&&(e.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(e.interval_days=parseInt(this._intervalDays,10),e.interval_unit=this._intervalUnit,e.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(e.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(e.interval_days=null,e.interval_anchor="completion")),e.notes=this._notes||null,e.documentation_url=this._documentationUrl||null,e.custom_icon=this._customIcon||null,e.priority=this._priority,e.labels=this._labels.split(",").map(c=>c.trim()).filter(Boolean),e.mirror_todo_entities=this._mirrorTodoEntities.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=mr(this._readings);{let c={};for(let m of this._phaseDefs){if(!m.name.trim())continue;let f={...m.carry,name:m.name.trim()},w=m.checklistText.split(`
`).map($=>$.trim()).filter(Boolean);w.length&&(f.checklist=w);let y=[];if(m.partId){let $=parseFloat(m.partQty);y.push({part_id:m.partId,quantity:Number.isFinite($)&&$>0?$:1})}for(let $ of m.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),m.reqOverride&&(f.required_completion_fields=[...m.reqFields]),c[m.id]=f}let p=this._phaseSeq.filter(m=>m in c);e.phases=Object.keys(c).length&&p.length?c:null,e.phase_sequence=e.phases?p:null}if((this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(c=>c.entry_id?{part_id:c.part_id,quantity:c.quantity,entry_id:c.entry_id}:{part_id:c.part_id,quantity:c.quantity})),e.responsible_user_id=this._responsibleUserId,e.assignee_pool=this._assigneePool,e.required_completion_fields=this._requiredCompletion,e.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let c=this._compoundConditions.map(En).filter(p=>p!==null);if(c.length>0){let p={type:"compound",compound_logic:this._compoundLogic,conditions:c};this._autoCompleteOnRecovery&&(p.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(p.trigger_combinator="all"),e.trigger_config=p}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let c=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],p={entity_id:c[0],entity_ids:c,type:this._triggerType};if(this._triggerAttribute&&(p.attribute=this._triggerAttribute),this._autoCompleteOnRecovery&&(p.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(p.trigger_combinator="all"),c.length>1&&(p.entity_logic=this._triggerEntityLogic),this._triggerType==="threshold"){if(this._triggerAbove){let m=parseFloat(this._triggerAbove);isNaN(m)||(p.trigger_above=m)}if(this._triggerBelow){let m=parseFloat(this._triggerBelow);isNaN(m)||(p.trigger_below=m)}if(this._triggerEquals){let m=parseFloat(this._triggerEquals);isNaN(m)||(p.trigger_equals=m)}if(this._triggerNotEquals){let m=parseFloat(this._triggerNotEquals);isNaN(m)||(p.trigger_not_equals=m)}if(this._triggerForMinutes){let m=parseInt(this._triggerForMinutes,10);isNaN(m)||(p.trigger_for_minutes=m)}}else if(this._triggerType==="counter"){if(this._triggerTargetValue){let m=parseFloat(this._triggerTargetValue);isNaN(m)||(p.trigger_target_value=m)}if(p.trigger_delta_mode=this._triggerDeltaMode,this._triggerDeltaMode&&this._triggerBaselineValue){let m=parseFloat(this._triggerBaselineValue);!isNaN(m)&&m>=0&&(p.trigger_baseline_value=m)}}else if(this._triggerType==="state_change"){if(this._triggerFromState&&(p.trigger_from_state=this._triggerFromState),this._triggerToState&&(p.trigger_to_state=this._triggerToState),this._triggerTargetChanges){let m=parseInt(this._triggerTargetChanges,10);isNaN(m)||(p.trigger_target_changes=m)}if(this._triggerForMinutes){let m=parseInt(this._triggerForMinutes,10);isNaN(m)||(p.trigger_for_minutes=m)}}else if(this._triggerType==="runtime"){if(this._triggerRuntimeHours){let f=parseFloat(this._triggerRuntimeHours);isNaN(f)||(p.trigger_runtime_hours=f)}if(this._triggerRuntimeMaxSession){let f=parseInt(this._triggerRuntimeMaxSession,10);!isNaN(f)&&f>0&&(p.trigger_runtime_max_session_seconds=f)}let m=this._triggerOnStates.split(",").map(f=>f.trim()).filter(Boolean);m.length>0&&(p.trigger_on_states=m)}e.trigger_config=p}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&Rr.includes(this._scheduleType)){let c=this._scheduleTimeOn?this._scheduleTime.trim():"";e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(c)?c:null}if(this.checklistsEnabled){let c=this._checklistText.split(`
`).map(p=>p.trim()).filter(Boolean).slice(0,100);e.checklist=c.length?c:null}if(this.completionActionsEnabled){let c=this._actionService.trim();if(c&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(c)){let w={service:c},y=this._actionTargetEntity.trim();y&&(w.target={entity_id:y});let $=this._buildActionData();Object.keys($).length>0&&(w.data=$),e.on_complete_action=w}else e.on_complete_action=null;let p={};this._qcNotes.trim()&&(p.notes=this._qcNotes.trim());let m=parseFloat(this._qcCost);!isNaN(m)&&m>=0&&(p.cost=m);let f=parseInt(this._qcDuration,10);!isNaN(f)&&f>=0&&(p.duration=f),this._qcFeedback&&(p.feedback=this._qcFeedback),e.quick_complete_defaults=Object.keys(p).length?p:null}let i=await this.hass.connection.sendMessagePromise(e),a=this._taskId||i?.task_id,o=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;this._warning="";let _=c=>{this._warning=n("subsave_warning",this._lang).replace("{detail}",c)};if(a&&this._scheduleType==="sensor_based"&&o&&await Ut(this,{type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:a,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null},{onError:_})!==void 0&&(this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute),a&&this._adaptiveSnapshot()!==this._adaptiveInitial){let c=parseFloat(this._adaptiveAlpha),p=parseInt(this._adaptiveMin,10),m=parseInt(this._adaptiveMax,10);await Ut(this,{type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:a,enabled:this._adaptiveEnabled,...c>=.1&&c<=.9?{ewa_alpha:c}:{},...!isNaN(p)&&p>=1?{min_interval_days:p}:{},...!isNaN(m)&&m>=1?{max_interval_days:m}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction},{onError:_})!==void 0&&(this._adaptiveInitial=this._adaptiveSnapshot())}this._warning?a&&(this._taskId=a):this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}catch(e){this._error=N(e,this._lang,n("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 u;let e=this._lang,t=this._triggerType==="compound";return l`
${n("trigger_configuration",e)}
${t?this._renderCompoundEditor():l`
${this._entityPickerFallback?l`
0?this._triggerEntityIds.join(", "):this._triggerEntityId}
@input=${i=>{let o=i.target.value.split(",").map(_=>_.trim()).filter(Boolean);this._triggerEntityId=o[0]||"",this._triggerEntityIds=o,o[0]&&this._fetchEntityAttributes(o[0])}}
>
`:l`
0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}}
.computeLabel=${()=>n("entity_id",e)}
@value-changed=${i=>{let a=(i.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=a[0]||"",this._triggerEntityIds=a,a[0]?this._fetchEntityAttributes(a[0]):this._fetchEntityAttributes("")}}
>`}
${this._triggerEntityIds.length>1?l`
`:u}
${this._renderAttributeSelect({label:n("attribute_optional",e),value:this._triggerAttribute,suggested:this._suggestedAttributes,available:this._availableAttributes,onSelect:i=>this._triggerAttribute=i})}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
${n("auto_complete_on_recovery_help",e)}
this._intervalDays=i.target.value}
>
${this._intervalDays?this._renderUnitSelect():u}
${this._intervalDays?l`
`:u}
`}_patchCondition(e,t){this._compoundConditions=this._compoundConditions.map((i,a)=>a===e?{...i,...t}:i)}_addCondition(){this._compoundConditions=[...this._compoundConditions,wn()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((t,i)=>i!==e)}_renderCompoundEditor(){let e=this._lang;return l`
${n("compound_help",e)}
${this._compoundConditions.length===0?l`${n("compound_no_conditions",e)}
`:this._compoundConditions.map((t,i)=>this._renderCondition(t,i))}
`}_renderCondition(e,t){let i=this._lang,a=t+1;return l`
${n("compound_condition",i)} ${a}
${this._entityPickerFallback?l`
this._patchCondition(t,{entityIds:o.target.value})}
>
`:l`
o.trim()).filter(Boolean)}}
.computeLabel=${()=>n("entity_id",i)}
@value-changed=${o=>{let _=(o.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(t,{entityIds:_.join(", ")})}}
>`}
${this._renderConditionAttribute(e,t)}
${this._renderConditionTypeFields(e,t)}
`}_renderStateField(e){return this._entityPickerFallback||!e.entityId?l`
e.onInput(t.target.value)}
>
`:l`
e.label}
@value-changed=${t=>e.onInput((t.detail.value.s||"").trim())}
>
`}_renderOnStatesField(e){let t=this._lang;return this._entityPickerFallback||!e.entityId?l`
e.onInput(i.target.value)}
>
`:l`
i.trim()).filter(Boolean)}}
.computeLabel=${()=>n("runtime_on_states",t)}
@value-changed=${i=>e.onInput((i.detail.value.s||[]).join(", "))}
>
`}_renderAdaptiveSection(e){return this._scheduleType==="one_time"||this._scheduleType==="manual"?u:l`
${n("adaptive_section_title",e)}
${this._adaptiveEnabled?l`
this._adaptiveMin=t.target.value}
>
this._adaptiveMax=t.target.value}
>
this._adaptiveAlpha=t.target.value}
>
`:u}
`}_renderAttributeSelect(e){let t=this._lang;return e.available.length>0?l`
`:l`
e.onSelect(i.target.value.trim())}
>
`}_renderEnvironmentalAttribute(e){this._fetchConditionAttributes(this._environmentalEntity);let t=this._conditionAttrOptions[this._environmentalEntity];return this._renderAttributeSelect({label:n("environmental_attribute_optional",e),value:this._environmentalAttribute,suggested:t?.suggested??[],available:t?.available??[],onSelect:i=>this._environmentalAttribute=i})}_renderConditionAttribute(e,t){let i=e.entityIds.split(",")[0]?.trim()||"";i&&this._fetchConditionAttributes(i);let a=i?this._conditionAttrOptions[i]:void 0;return this._renderAttributeSelect({label:n("attribute_optional",this._lang),value:e.attribute,suggested:a?.suggested??[],available:a?.available??[],onSelect:o=>this._patchCondition(t,{attribute:o})})}_renderConditionTypeFields(e,t){let i=this._lang;if(e.type==="threshold")return l`
this._patchCondition(t,{above:a.target.value})}>
this._patchCondition(t,{below:a.target.value})}>
this._patchCondition(t,{equals:a.target.value})}>
this._patchCondition(t,{notEquals:a.target.value})}>
this._patchCondition(t,{forMinutes:a.target.value})}>
`;if(e.type==="counter")return l`
this._patchCondition(t,{targetValue:a.target.value})}>
`;if(e.type==="state_change"){let a=e.entityIds.split(",")[0]?.trim()||"";return l`
${this._renderStateField({label:n("from_state_optional",i),value:e.fromState,entityId:a,onInput:o=>this._patchCondition(t,{fromState:o})})}
${this._renderStateField({label:n("to_state_optional",i),value:e.toState,entityId:a,onInput:o=>this._patchCondition(t,{toState:o})})}
this._patchCondition(t,{targetChanges:o.target.value})}>
`}if(e.type==="runtime"){let a=e.entityIds.split(",")[0]?.trim()||"";return l`
this._patchCondition(t,{runtimeHours:o.target.value})}>
${this._renderOnStatesField({value:e.onStates,entityId:a,onInput:o=>this._patchCondition(t,{onStates:o})})}
`}return u}_renderUnitSelect(){let e=this._lang;return l`
`}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(t=>t!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(mt.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let e=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!e||e<=0?null:{kind:"interval",every:e,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(e){super.updated?.(e),this._scheduleEntityPickerProbe();for(let t of e.keys())if(g._PREVIEW_RELEVANT.has(String(t))){this._schedulePreviewRefresh();return}}_scheduleEntityPickerProbe(){this._entityPickerFallback||this._pickerProbeTimer!==void 0||!this._open||this._scheduleType!=="sensor_based"||(this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),1500))}_probeEntityPickers(){if(this._pickerProbeTimer=void 0,this._entityPickerFallback||!this._open)return;let e=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),t=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!t){this._pickerProbeStrikes=0;return}let i=(c,p,m=0)=>{if(!(!c||m>10)){(c.tagName?.toLowerCase()??"")==="ha-entity-picker"&&p.push(c);for(let f of[c.shadowRoot,c])if(f)for(let w of Array.from(f.children??[]))i(w,p,m+1)}},a=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],o=[];for(let c of a)i(c,o);let _=o.length===0||o.some(c=>c.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 t=++this._previewSeq;try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(t!==this._previewSeq)return;this._schedulePreview=i.occurrences||[],this._schedulePreviewEnded=!!i.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return u;let e=this._lang,t=this.scheduleTimeEnabled&&this._scheduleTimeOn&&this._scheduleTime?` ${this._scheduleTime}`:"",i=this._schedulePreview.map((o,_)=>{let c=new Date(`${o}T12:00:00`).getDay();return`${Ae(c===0?6:c-1,e,"short")} ${B(o,e)}${_===0?t:""}`}).join(" \xB7 "),a=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?l`${n("schedule_preview_ontime",e)}
`:u;return l`
${n("schedule_preview_title",e)}: ${i}${this._schedulePreviewEnded?l` ${n("schedule_preview_ends",e)}`:u}
${a}
`}_buildSchedule(){let e=i=>{let a=parseInt(this._calOffset,10)||0;return a&&(i.offset=Math.max(-15,Math.min(a,15))),i};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((i,a)=>i-a)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});let t={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(t.business=!0),e(t)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((t,i)=>t-i)),this._endsMode==="count"){let t=parseInt(this._endsCount,10);t>=1&&(e.ends={count:t})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(t=>t!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||mt.includes(this._scheduleType)))return u;let i=Tn(e);return l`
${n("season_window_hint",e)}
${i.map((a,o)=>l`
`)}
${this._endsMode==="count"?l`
this._endsCount=a.target.value}
>`:u}
${this._endsMode==="until"?l`
this._endsUntil=a.detail.value}
>`:u}
`}_renderCalendarFields(){let e=this._lang,t=Sn(e);if(this._scheduleType==="weekdays")return l`
${t.map((i,a)=>l`
`)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let i=[["1",n("ord_1",e)],["2",n("ord_2",e)],["3",n("ord_3",e)],["4",n("ord_4",e)],["5",n("ord_5",e)],["-1",n("ord_last",e)]];return l`
${this._renderCalOffsetField()}`}return this._scheduleType==="day_of_month"?l`
${this._domLastDay?u:l`
this._domDay=i.target.value}
>`}
${this._renderCalOffsetField()}`:u}_renderCalOffsetField(){let e=this._lang;return l`
this._calOffset=t.target.value}
>`}_thresholdLimitsOverlap(){let e=parseFloat(this._triggerAbove),t=parseFloat(this._triggerBelow);return!isNaN(e)&&!isNaN(t)&&t>e}_renderTriggerLiveHint(){if(this._triggerType==="compound")return u;let e=this._triggerType==="threshold"&&this._thresholdLimitsOverlap()?l`${n("trigger_hint_overlap",this._lang)}
`:u,t=this._triggerEntityId||this._triggerEntityIds[0];if(!t||!this.hass?.states)return e;let i=this.hass.states[t];if(!i)return e;let a=this._lang,o=i.attributes?.unit_of_measurement,_=typeof o=="string"&&o?` ${o}`:"",c=this._triggerAttribute?i.attributes?.[this._triggerAttribute]:i.state,p=typeof c=="number"?c:parseFloat(String(c)),m=c!=="unknown"&&c!=="unavailable"&&c!=null&&!isNaN(p),f=y=>L(y,a,{maximumFractionDigits:1}),w=[];if(this._triggerType==="threshold"){let y=parseFloat(this._triggerAbove),$=parseFloat(this._triggerBelow);if(isNaN(y)&&isNaN($))return u;m&&w.push(n("trigger_hint_now",a).replace("{value}",f(p)+_)),isNaN(y)||w.push(n("trigger_hint_above",a).replace("{target}",f(y)+_)),isNaN($)||w.push(n("trigger_hint_below",a).replace("{target}",f($)+_))}else if(this._triggerType==="counter"){let y=parseFloat(this._triggerTargetValue);if(isNaN(y))return u;this._triggerDeltaMode?this._taskId?w.push(n("trigger_hint_counter_delta_edit",a).replace("{target}",f(y)+_)):m?w.push(n("trigger_hint_counter_delta",a).replace("{value}",f(p)+_).replace("{due}",f(p+y)+_).replace("{target}",f(y)+_)):w.push(n("trigger_hint_counter_delta_edit",a).replace("{target}",f(y)+_)):(m&&w.push(n("trigger_hint_now",a).replace("{value}",f(p)+_)),w.push(n("trigger_hint_counter_abs",a).replace("{target}",f(y)+_)))}else if(this._triggerType==="runtime"){let y=parseFloat(this._triggerRuntimeHours);if(isNaN(y))return u;w.push(n("trigger_hint_runtime",a).replace("{hours}",f(y))),w.push(n("trigger_hint_state_now",a).replace("{value}",String(i.state)))}else if(this._triggerType==="state_change"){let y=parseInt(this._triggerTargetChanges,10)||1,$=this._triggerToState.trim();w.push(($?n("trigger_hint_state_change_to",a).replace("{state}",$):n("trigger_hint_state_change",a)).replace("{count}",String(y))),w.push(n("trigger_hint_state_now",a).replace("{value}",String(i.state)))}return w.length?l`${w.join(" ")}
${e}`:e}_renderTriggerTypeFields(){let e=this._lang;return this._triggerType==="threshold"?l`
this._triggerAbove=t.target.value}
>
this._triggerBelow=t.target.value}
>
this._triggerEquals=t.target.value}
>
this._triggerNotEquals=t.target.value}
>
this._triggerForMinutes=t.target.value}
>
`:this._triggerType==="counter"?l`
this._triggerTargetValue=t.target.value}
>
${this._triggerDeltaMode?l`
this._triggerBaselineValue=t.target.value}
>
${this._taskId?n("baseline_start_help_edit",e):n("baseline_start_help",e)}
${this._taskId&&this._liveBaselineValue!=null?l`
${n("baseline_current_effective",e).replace("{value}",String(this._liveBaselineValue))}
`:u}
`:u}
`:this._triggerType==="state_change"?l`
${this._renderStateField({label:n("from_state_optional",e),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:t=>this._triggerFromState=t})}
${n("state_value_help",e)}
${this._renderStateField({label:n("to_state_optional",e),value:this._triggerToState,entityId:this._triggerEntityId,onInput:t=>this._triggerToState=t})}
this._triggerTargetChanges=t.target.value}
>
${n("target_changes_help",e)}
${(this._triggerTargetChanges||"1")==="1"&&(this._triggerFromState||this._triggerToState)?l`${n("state_latch_help",e)}
`:u}
this._triggerForMinutes=t.target.value}
>
${n("for_minutes_state_help",e)}
`:this._triggerType==="runtime"?l`
this._triggerRuntimeHours=t.target.value}
>
this._triggerRuntimeMaxSession=t.target.value}
>
${n("runtime_max_session_help",e)}
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:t=>this._triggerOnStates=t})}
${n("runtime_on_states_help",e)}
`:u}render(){if(!this._open)return l``;let e=this._lang,t=this._taskId?n("edit_task",e):n("new_task",e);return l`
${t}
${this._error?l`
${this._error}
`:u}
${this._warning?l`
${this._warning}
`:u}
${this._taskId===null&&this._objectChoices.length>0?l`
`:u}
this._name=i.target.value}
>
${this._type==="reading"?l`
this._readingUnit=i.target.value}
>
${n("reading_unit_help",e)}
${this._renderReadingsEditor(e)}
`:u}
${this._partsLoadFailed?l`
${n("parts_load_failed",e)}
`:u}
${this._isFleetTask?l`
${n("task_parts_fleet_hint",e)}
`:this.parts.length||this._foreignOwners.length?l`
${this.parts.map(i=>this._renderConsumesRow(i))}
${this._foreignOwners.length?l`
${n("shared_parts_other_objects",e)}
${n("shared_parts_help",e)}
${this._foreignOwners.map(i=>l`
${i.name}
${i.parts.map(a=>this._renderConsumesRow(a,i.entry_id))}
`)}
`:u}
`:u}
${this._entityPickerFallback?l`
{this._mirrorTodoEntities=i.target.value.split(",").map(a=>a.trim()).filter(Boolean)}}
>
`:l`
n("task_mirror_todo",e)}
@value-changed=${i=>{let a=(i.detail.value.mirror_todo_entities||[]).filter(Boolean);this._mirrorTodoEntities=a}}
>`}
${n("task_mirror_todo_hint",e)}
${this._scheduleType==="time_based"?l`
this._intervalDays=i.target.value}
>
${this._renderUnitSelect()}
`:u}
${this._renderCalendarFields()}
${this._scheduleType==="one_time"?l`
this._dueDate=i.detail.value}
>
`:u}
${this.scheduleTimeEnabled&&Rr.includes(this._scheduleType)?l`
${this._scheduleTimeOn?l`
this._scheduleTime=i.detail.value}
>
`:u}
`:u}
${this._renderRecurrenceExtras()}
${this._renderSchedulePreview()}
this._warningDays=i.target.value}
>
this._earliestCompletionDays=i.target.value}
>
${this.checklistsEnabled?l`
${n("checklist_steps_optional",e)}
${n("checklist_help",e)}
`:u}
${this._renderPhasesEditor(e)}
${n("require_on_completion",e)}
${Bt.map(i=>l`
`)}
this._lastPerformed=i.detail.value}
>
${this._availableUsers.length>=2?l`
${this._assigneePool.length>=2?l`
`:u}
`:u}
${this._renderTriggerFields()}
${this._scheduleType==="sensor_based"?l`
${this._entityPickerFallback?l`
this._environmentalEntity=i.target.value.trim()}
>
`:l`
n("environmental_entity_optional",e)}
.computeHelper=${()=>n("environmental_entity_helper",e)}
@value-changed=${i=>{this._environmentalEntity=(i.detail.value.environmental_entity||"").trim()}}
>`}
${this._environmentalEntity?this._renderEnvironmentalAttribute(e):u}
`:u}
${this._renderAdaptiveSection(e)}
this._notes=i.target.value}
>
this._documentationUrl=i.target.value}
>
this._customIcon=i.detail.value||""}
>
${this._availableTags.length>0?l`
`:l`
this._nfcTagId=i.target.value}
>
`}
${this._requireTagScan?l`
${n("require_tag_scan_help",e)}
`:u}
${this._allowSkip?u:l`
${n("disallow_skip_help",e)}
`}
${this._notifyEnabled?u:l`
${n("no_notifications_help",e)}
`}
${this._renderCompletionActionsSection(e)}
${n("cancel",e)}
${this._loading?n("saving",e):n("save",e)}
`}};g._PREVIEW_RELEVANT=new Set(["_open","_scheduleType","_intervalDays","_intervalUnit","_intervalAnchor","_dueDate","_weekdays","_nth","_nthWeekday","_domDay","_domLastDay","_domBusiness","_calOffset","_seasonMonths","_endsMode","_endsCount","_endsUntil","_lastPerformed"]),g.styles=E`
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
/* #129: entity/state pickers in the trigger form (ha-form + selector) */
.entity-picker-form,
.state-picker-form {
display: block;
margin: 8px 0;
}
/* v1.3.0: completion-action sections (.adaptive-section shares the shell
but keeps its own class — tests count .ca-section elements) */
.ca-section,
.adaptive-section {
border: 1px solid var(--divider-color);
border-radius: 6px;
padding: 8px 12px;
margin-top: 8px;
}
.ca-section > summary,
.adaptive-section > summary {
cursor: pointer;
font-weight: 500;
}
.adaptive-section ms-textfield {
width: 100%;
margin-top: 8px;
display: block;
}
.adaptive-section label {
display: block;
margin-top: 8px;
}
.ca-section ms-textfield,
.ca-section ha-entity-picker,
.ca-section ha-service-picker,
.ca-section ha-form,
.ca-section .qc-feedback {
width: 100%;
margin-top: 8px;
display: block;
}
.ca-section .qc-feedback {
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
}
.ca-test-row {
display: flex;
align-items: center;
gap: 12px;
margin-top: 8px;
}
.ca-test-ok { color: var(--success-color, #4caf50); font-size: 13px; }
.ca-test-error { color: var(--error-color, #f44336); font-size: 13px; font-weight: 500; }
.ca-test-error-block { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.ca-test-error-detail {
font-size: 12px;
color: var(--secondary-text-color);
background: rgba(244, 67, 54, 0.08);
padding: 6px 8px; border-radius: 4px;
line-height: 1.4;
word-break: break-word;
}
.content {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 350px;
max-height: 70vh;
overflow-y: auto;
}
@media (max-width: 600px) {
.content {
min-width: 0;
max-height: none;
}
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
}
ms-textfield {
display: block;
}
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.checklist-textarea {
width: 100%;
min-height: 88px;
padding: 8px;
font-family: inherit;
font-size: 14px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
resize: vertical;
box-sizing: border-box;
}
.consumes-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
}
.phase-def {
border: 1px solid var(--divider-color);
border-radius: 6px;
padding: 8px;
margin: 6px 0;
}
.phase-def-head {
display: flex;
align-items: center;
gap: 8px;
}
.phase-def-head ms-textfield {
flex: 1;
min-width: 0;
}
.phase-part {
max-width: 160px;
padding: 6px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.phase-qty {
width: 64px;
padding: 6px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.phase-checklist {
min-height: 56px;
margin-top: 6px;
}
.phase-req-toggle {
margin-top: 6px;
font-size: 13px;
color: var(--secondary-text-color);
}
.phase-req-fields {
margin: 2px 0 0 22px;
font-size: 13px;
}
.phase-remove {
--mdc-icon-button-size: 36px;
color: var(--secondary-text-color);
}
/* #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;
}
`,d([v({attribute:!1})],g.prototype,"hass",2),d([v({type:Boolean,attribute:"checklists-enabled"})],g.prototype,"checklistsEnabled",2),d([v({type:Boolean,attribute:"schedule-time-enabled"})],g.prototype,"scheduleTimeEnabled",2),d([v({type:Boolean,attribute:"completion-actions-enabled"})],g.prototype,"completionActionsEnabled",2),d([v({type:Number,attribute:"default-warning-days"})],g.prototype,"defaultWarningDays",2),d([h()],g.prototype,"parts",2),d([h()],g.prototype,"_foreignOwners",2),d([h()],g.prototype,"_open",2),d([h()],g.prototype,"_entityPickerFallback",2),d([h()],g.prototype,"_loading",2),d([h()],g.prototype,"_error",2),d([h()],g.prototype,"_warning",2),d([h()],g.prototype,"_entryId",2),d([h()],g.prototype,"_taskId",2),d([h()],g.prototype,"_isFleetTask",2),d([h()],g.prototype,"_objectChoices",2),d([h()],g.prototype,"_name",2),d([h()],g.prototype,"_type",2),d([h()],g.prototype,"_scheduleType",2),d([h()],g.prototype,"_intervalDays",2),d([h()],g.prototype,"_intervalUnit",2),d([h()],g.prototype,"_dueDate",2),d([h()],g.prototype,"_warningDays",2),d([h()],g.prototype,"_earliestCompletionDays",2),d([h()],g.prototype,"_intervalAnchor",2),d([h()],g.prototype,"_weekdays",2),d([h()],g.prototype,"_nth",2),d([h()],g.prototype,"_nthWeekday",2),d([h()],g.prototype,"_domDay",2),d([h()],g.prototype,"_domLastDay",2),d([h()],g.prototype,"_domBusiness",2),d([h()],g.prototype,"_calOffset",2),d([h()],g.prototype,"_seasonMonths",2),d([h()],g.prototype,"_endsMode",2),d([h()],g.prototype,"_endsCount",2),d([h()],g.prototype,"_endsUntil",2),d([h()],g.prototype,"_schedulePreview",2),d([h()],g.prototype,"_schedulePreviewEnded",2),d([h()],g.prototype,"_notes",2),d([h()],g.prototype,"_documentationUrl",2),d([h()],g.prototype,"_customIcon",2),d([h()],g.prototype,"_priority",2),d([h()],g.prototype,"_labels",2),d([h()],g.prototype,"_mirrorTodoEntities",2),d([h()],g.prototype,"_enabled",2),d([h()],g.prototype,"_triggerEntityId",2),d([h()],g.prototype,"_triggerEntityIds",2),d([h()],g.prototype,"_triggerEntityLogic",2),d([h()],g.prototype,"_triggerAttribute",2),d([h()],g.prototype,"_triggerType",2),d([h()],g.prototype,"_triggerAbove",2),d([h()],g.prototype,"_triggerBelow",2),d([h()],g.prototype,"_triggerEquals",2),d([h()],g.prototype,"_triggerNotEquals",2),d([h()],g.prototype,"_triggerForMinutes",2),d([h()],g.prototype,"_triggerCombinator",2),d([h()],g.prototype,"_triggerTargetValue",2),d([h()],g.prototype,"_triggerDeltaMode",2),d([h()],g.prototype,"_triggerBaselineValue",2),d([h()],g.prototype,"_liveBaselineValue",2),d([h()],g.prototype,"_autoCompleteOnRecovery",2),d([h()],g.prototype,"_triggerFromState",2),d([h()],g.prototype,"_triggerToState",2),d([h()],g.prototype,"_triggerTargetChanges",2),d([h()],g.prototype,"_triggerRuntimeHours",2),d([h()],g.prototype,"_triggerRuntimeMaxSession",2),d([h()],g.prototype,"_triggerOnStates",2),d([h()],g.prototype,"_compoundLogic",2),d([h()],g.prototype,"_compoundConditions",2),d([h()],g.prototype,"_suggestedAttributes",2),d([h()],g.prototype,"_availableAttributes",2),d([h()],g.prototype,"_entityDomain",2),d([h()],g.prototype,"_lastPerformed",2),d([h()],g.prototype,"_nfcTagId",2),d([h()],g.prototype,"_requireTagScan",2),d([h()],g.prototype,"_allowSkip",2),d([h()],g.prototype,"_notifyEnabled",2),d([h()],g.prototype,"_readingUnit",2),d([h()],g.prototype,"_readings",2),d([h()],g.prototype,"_consumesParts",2),d([h()],g.prototype,"_partsLoadFailed",2),d([h()],g.prototype,"_availableTags",2),d([h()],g.prototype,"_responsibleUserId",2),d([h()],g.prototype,"_assigneePool",2),d([h()],g.prototype,"_rotationStrategy",2),d([h()],g.prototype,"_availableUsers",2),d([h()],g.prototype,"_checklistText",2),d([h()],g.prototype,"_phaseDefs",2),d([h()],g.prototype,"_phaseSeq",2),d([h()],g.prototype,"_requiredCompletion",2),d([h()],g.prototype,"_scheduleTime",2),d([h()],g.prototype,"_scheduleTimeOn",2),d([h()],g.prototype,"_actionService",2),d([h()],g.prototype,"_actionTargetEntity",2),d([h()],g.prototype,"_actionData",2),d([h()],g.prototype,"_actionDataJsonFallback",2),d([h()],g.prototype,"_actionTesting",2),d([h()],g.prototype,"_actionTestResult",2),d([h()],g.prototype,"_actionTestError",2),d([h()],g.prototype,"_qcNotes",2),d([h()],g.prototype,"_qcCost",2),d([h()],g.prototype,"_qcDuration",2),d([h()],g.prototype,"_qcFeedback",2),d([h()],g.prototype,"_environmentalEntity",2),d([h()],g.prototype,"_environmentalAttribute",2),d([h()],g.prototype,"_adaptiveEnabled",2),d([h()],g.prototype,"_adaptiveAlpha",2),d([h()],g.prototype,"_adaptiveMin",2),d([h()],g.prototype,"_adaptiveMax",2),d([h()],g.prototype,"_adaptiveSeasonal",2),d([h()],g.prototype,"_adaptivePrediction",2),d([h()],g.prototype,"_conditionAttrOptions",2);Wt=g;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",Wt)});async function An(s,r,e,t){let i=new FormData;i.append("entry_id",r);for(let _ of t)i.append("tags",_);i.append("file",e,e.name);let a=await fetch("/api/maintenance_supporter/document/upload",{method:"POST",headers:{Authorization:`Bearer ${s.auth?.data?.access_token??""}`},body:i});if(a.status===413)throw new Error("doc_too_large");if(!a.ok)throw new Error("doc_upload_failed");let o=await a.json();if(!o.id)throw new Error("doc_upload_failed");return{id:o.id,deduped:!!o.deduped,duplicate_in_object:o.duplicate_in_object??null}}async function Hr(s,r,e){return(await An(s,r,e,["photo"])).id}async function Kt(s,r){await Promise.all(r.map(e=>s.connection.sendMessagePromise({type:"maintenance_supporter/documents/delete",doc_id:e}).catch(()=>{})))}var jr=x(()=>{"use strict";ut()});var Pe,Yt=x(()=>{"use strict";C();jr();Pe=class{constructor(r,e){this.host=r;this.opts=e;this.photos=[];this.uploadedIds=[];this.uploading=!1;this.errorKey="";this.max=e.max??10,r.addController(this)}hostConnected(){}get ids(){return this.photos.map(r=>r.id)}get remaining(){return Math.max(this.max-this.photos.length,0)}get full(){return this.remaining===0}errorText(r){return this.errorKey?n(this.errorKey,r).replace("{max}",String(this.max)):""}clearError(){this.errorKey=""}reset(r=[]){this._revokeAll(),this.photos=r.map(e=>({id:e,preview:""})),this.uploadedIds=[],this.uploading=!1,this.errorKey="",this.host.requestUpdate()}async addFiles(r){if(r.length===0)return;let e=r.slice(0,this.remaining);this.uploading=!0,this.errorKey="",this.host.requestUpdate();try{for(let t of e){let i=await Hr(this.opts.hass(),this.opts.entryId(),t);this.uploadedIds=[...this.uploadedIds,i],this.photos=[...this.photos,{id:i,preview:URL.createObjectURL(t)}],this.host.requestUpdate()}r.length>e.length&&(this.errorKey="photos_limit")}catch(t){this.errorKey=t instanceof Error&&t.message==="doc_too_large"?"doc_too_large":"doc_upload_failed"}finally{this.uploading=!1,this.host.requestUpdate()}}remove(r){let e=this.photos.find(t=>t.id===r);e?.preview&&URL.revokeObjectURL(e.preview),this.photos=this.photos.filter(t=>t.id!==r),this.uploadedIds.includes(r)&&(this.uploadedIds=this.uploadedIds.filter(t=>t!==r),Kt(this.opts.hass(),[r])),this.host.requestUpdate()}discardOrphans(){if(this.uploadedIds.length===0)return;let r=this.uploadedIds;this.uploadedIds=[],Kt(this.opts.hass(),r)}markAttached(){this.uploadedIds=[]}_revokeAll(){for(let r of this.photos)r.preview&&URL.revokeObjectURL(r.preview)}}});function gt(){if(window.externalApp!==void 0)return!0;let r=typeof navigator<"u"&&navigator.userAgent||"";return/Home Assistant\//.test(r)&&/Android/.test(r)}var Gt=x(()=>{"use strict"});function Dr(s){try{return localStorage.getItem(s)}catch{return null}}function Or(s,r){try{localStorage.setItem(s,r)}catch{}}var Qt,Mr=x(()=>{"use strict";Qt={objectSections:"msp-object-sections",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 zr(){if(!gt())return!1;let s=typeof navigator<"u"?navigator.mediaDevices:void 0;return!!s&&typeof s.getUserMedia=="function"}var Cn,In,re,Jt=x(()=>{"use strict";I();F();C();Gt();Mr();Cn=1920,In=.88,re=class extends S{constructor(){super(...arguments);this.lang="en";this._open=!1;this._busy=!1;this._devices=[];this._deviceIndex=-1;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 t=Dr(Qt.cameraDevice),i=!1;if(t)try{this._stream=await e.getUserMedia({video:{deviceId:{exact:t}},audio:!1}),i=!0}catch{}if(!i){try{this._stream=await e.getUserMedia({video:{facingMode:{ideal:"environment"},zoom:1,advanced:[{zoom:1}]},audio:!1})}catch(o){this._unavailable(o instanceof Error?o.name||o.message:String(o));return}await this._preferMainBackCamera(e)}await this._applyZoomOne(),await this._listDevices(e),this._deviceIndex=this._indexOfCurrent(t&&i?t:null),this._open=!0,await this.updateComplete;let a=this._video;if(a&&this._stream){a.srcObject=this._stream;try{await a.play()}catch{}}}async _preferMainBackCamera(e){if(typeof e.enumerateDevices!="function")return;let t=[];try{t=await e.enumerateDevices()}catch{return}let i=c=>{let p=/camera2?\s*(\d+)/i.exec(c.label);return p?Number(p[1]):Number.MAX_SAFE_INTEGER},a=t.filter(c=>c.kind==="videoinput"&&c.deviceId&&/back|rear|environment|rück|hinten/i.test(c.label)).sort((c,p)=>i(c)-i(p)),_=this._stream?.getVideoTracks()[0]?.getSettings().deviceId;if(a.length>1&&a[0].deviceId!==_)try{let c=await e.getUserMedia({video:{deviceId:{exact:a[0].deviceId}},audio:!1});for(let p of this._stream?.getTracks()??[])p.stop();this._stream=c}catch{}}async _applyZoomOne(){let e=this._stream?.getVideoTracks()[0],t=e&&typeof e.getCapabilities=="function"?e.getCapabilities():void 0;if(!(!t?.zoom||typeof t.zoom.min!="number"||t.zoom.min>=1||(t.zoom.max??1)<1))for(let i of[{zoom:1},{advanced:[{zoom:1}]}])try{await e.applyConstraints(i);return}catch{}}_indexOfCurrent(e){let t=this._devices.map(a=>a.deviceId),i=this._currentDeviceId;for(let a of[e,i])if(a){let o=t.indexOf(a);if(o>=0)return o}return-1}async _listDevices(e){if(typeof e.enumerateDevices=="function")try{this._devices=(await e.enumerateDevices()).filter(t=>t.kind==="videoinput"&&!!t.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 t=this._devices.map(i=>i.deviceId);this._busy=!0;try{for(let i=1;io.toBlob(f,"image/jpeg",In));if(!c)throw new Error("no_blob");let p=new Date().toISOString().replace(/[-:]/g,"").slice(0,15),m=new File([c],`photo-${p}.jpg`,{type:"image/jpeg"});this.close(),this.dispatchEvent(new CustomEvent("photo-captured",{detail:{file:m},bubbles:!0,composed:!0}))}catch(t){this._unavailable(t instanceof Error?t.message:String(t))}finally{this._busy=!1}}}render(){if(!this._open)return u;let e=this.lang;return l`
${this._devices.length>1?l``:u}
`}};re.styles=E`
: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; }
.switch-pos { font-size: 12px; opacity: 0.85; }
.shoot { background: var(--primary-color, #03a9f4); color: #fff; border: none; font-weight: 600; }
.shoot[disabled] { opacity: 0.6; cursor: default; }
.shoot ha-icon { --mdc-icon-size: 22px; }
`,d([v({type:String})],re.prototype,"lang",2),d([h()],re.prototype,"_open",2),d([h()],re.prototype,"_busy",2),d([h()],re.prototype,"_devices",2),d([h()],re.prototype,"_deviceIndex",2);customElements.get("ms-camera-capture")||customElements.define("ms-camera-capture",re)});var ft,K,Ze=x(()=>{"use strict";I();F();C();Gt();Jt();Jt();ft=E`
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;
}
`,K=class extends S{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=gt();this._inAppCamera=zr()}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 t=e.target,i=Array.from(t.files??[]);t.value="",this._emit(i)}_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 u;let e=this.lang,t=this._locked?"disabled":"",i=this.busy?n("uploading",e):n("doc_camera",e),a=n(this._singlePick?"choose_photo":"choose_photos",e);return l`
${this.showCamera?l``:u}
${this.showGallery?l``:u}
${this.showGallery&&this._singlePick?l`${n("photos_android_hint",e)}
`:u}
${this.showCamera&&this._inAppCamera?l`this._emit([o.detail.file])}
@capture-unavailable=${this._onCameraUnavailable}>`:u}
`}};d([v({type:String})],K.prototype,"lang",2),d([v({type:Boolean})],K.prototype,"disabled",2),d([v({type:Boolean})],K.prototype,"busy",2),d([v({type:String})],K.prototype,"accept",2),d([v({type:Boolean})],K.prototype,"showCamera",2),d([v({type:Boolean})],K.prototype,"showGallery",2),d([v({type:Boolean})],K.prototype,"compact",2),d([v({type:Number})],K.prototype,"remaining",2),d([h()],K.prototype,"_inAppCamera",2);customElements.get("ms-photo-picker")||customElements.define("ms-photo-picker",K)});var k,Fr=x(()=>{"use strict";I();F();xe();C();pe();_t();Vt();Yt();Ie();Ze();Ze();k=class extends S{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 Pe(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((t,i)=>[String(i),!!this.checklistPrefill[t]]).filter(([,t])=>t)),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(t=>[J(t),{...t}])))}_toggleCheck(e){let t=String(e);this._checklistState={...this._checklistState,[t]:!this._checklistState[t]}}_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 t=parseFloat(this._cost);!isNaN(t)&&t>=0&&(e.cost=t)}if(this._duration){let t=parseInt(this._duration,10);!isNaN(t)&&t>=0&&(e.duration=t)}if(this.checklist.length>0&&(e.checklist_state=this._checklistState),this.adaptiveEnabled&&(e.feedback=this._feedback),this._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=n("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 t={};for(let i of this.readings){let a=(this._readingValues[i.id]??"").trim();if(a==="")continue;let o=parseFloat(a.replace(",","."));isNaN(o)||(t[i.id]=o)}Object.keys(t).length>0&&(e.reading_values=t)}else if(this._readingValue!==""){let t=parseFloat(this._readingValue);isNaN(t)||(e.reading_value=t)}if(this.restockDefault!==null&&this._restockQty!==""){let t=parseFloat(this._restockQty);!isNaN(t)&&t>=1&&(e.restock_quantity=t)}this.parts.length>0&&(e.used_parts=Object.values(this._usedParts).filter(t=>Number.isFinite(t.quantity)&&t.quantity>0).map(t=>t.entry_id?{part_id:t.part_id,quantity:t.quantity,entry_id:t.entry_id}:{part_id:t.part_id,quantity:t.quantity})),await this.hass.connection.sendMessagePromise(e),this._photos.markAttached(),this._open=!1,this.dispatchEvent(new CustomEvent("task-completed"))}catch(e){this._error=N(e,this.lang,n("save_error",this.lang))}finally{this._loading=!1}}_renderReadingField(e,t){let i=this._completedAt?new Date(this._completedAt).getTime():NaN,a=ur(this.readingHistory,e.id,isNaN(i)?void 0:i),o=e.unit||this.readingUnit,_=(this._readingValues[e.id]??"").trim(),c=_===""?NaN:parseFloat(_.replace(",",".")),p=a!==void 0&&!isNaN(c)&&c
${e.name}${o?` (${o})`:""}
{this._readingValues={...this._readingValues,[e.id]:f.target.value}}} />
${p?l`${n("reading_below_last",t).replace("{value}",m)}`:u}
`}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(t=>!e[t])}_req(e){return this.requiredFields.includes(e)?l`*`:u}_partsCostSuggestion(){if(this.restockDefault!==null){let i=parseFloat(this._restockQty);return this.restockUnitCost==null||!Number.isFinite(i)||i<=0?null:Math.round(this.restockUnitCost*i*100)/100}if(!this.parts.length)return null;let e=0,t=!1;for(let i of Object.values(this._usedParts)){let a=this.parts.find(o=>J({part_id:o.id,entry_id:o.entry_id})===J(i));a?.cost!=null&&(e+=a.cost*(i.quantity||1),t=!0)}return t?Math.round(e*100)/100:null}_renderCostSuggestion(e){if(this._cost.trim()!=="")return u;let t=this._partsCostSuggestion();if(t==null||t<=0)return u;let i=de(t,this.currencySymbol,e);return l``}_close(){this._open=!1,this._photos.discardOrphans()}_pickCompletedAt(){let e=new Date,t=i=>String(i).padStart(2,"0");this._completedAt=`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:00`}render(){if(!this._open)return l``;let e=this.lang||this.hass?.language||"en",t=this._error||this._photos.errorText(e);return l`
${n("complete_title",e)}${this.taskName}
${this.phaseLabel?l`${n("phase_current",e)}: ${this.phaseLabel}
`:u}
${this.requireTagScan&&!this.viaTagScan?l`${n("require_tag_scan_hint",e)}
`:u}
${t?l`
${t}
`:u}
${this.checklist.length>0?l`
${this.checklist.map((i,a)=>l`
`)}
`:u}
${this.readings.length>0?l`
${n("readings_section",e)}
${this.readings.map(i=>this._renderReadingField(i,e))}
`:this.taskType==="reading"?l`
`:u}
${this.parts.length?l`
${n("complete_parts_used",e)}
${this.parts.map(i=>{let a=J({part_id:i.id,entry_id:i.entry_id}),o=this._usedParts[a],_=o!==void 0,c=i.entry_id?{part_id:i.id,quantity:1,entry_id:i.entry_id}:{part_id:i.id,quantity:1};return l`
${_?l`{let m=parseFloat(p.target.value);this._usedParts={...this._usedParts,[a]:{...c,quantity:Number.isFinite(m)&&m>=.01?m:1}}}} />`:u}
`})}
`:this.consumesInfo.length?l`
${this.consumesInfo.map(i=>l`
${i}
`)}
`:u}
${this.restockDefault!==null?l`
`:u}
${n("completed_at_optional",e)}
${this._completedAt?l`this._completedAt=i.detail.value}
>`:l``}
${n("completion_photos_optional",e)}${this._req("photo")}
${this._photos.photos.length>0?l`
${this._photos.photos.map(i=>l`
`)}
`:u}
${this._photos.full?l`
${n("photos_limit",e).replace("{max}",String(this._photos.max))}
`:l`
this._photos.addFiles(i.detail.files)}
>`}
${this.adaptiveEnabled?l`
`:u}
${n("cancel",e)}
0}
title=${this._missingRequired.length?this._missingRequired.map(i=>n("err_required",e).replace("{field}",n(Je[i]??i,e))).join(" \xB7 "):""}
>
${this._loading?n("completing",e):n("complete",e)}
`}};k.styles=[or,ft,E`
.req-mark {
color: var(--error-color, #f44336);
margin-left: 2px;
font-weight: 600;
}
/* #104: one-click cost suggestion from parts — quiet link-style chip. */
.cost-suggestion {
align-self: flex-start;
margin-top: 4px;
padding: 0;
border: none;
background: none;
color: var(--primary-color);
font-size: 12.5px;
cursor: pointer;
text-decoration: underline dotted;
text-underline-offset: 2px;
}
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
.scan-required-note {
margin: -4px 0 12px;
padding: 8px 10px;
border-radius: 6px;
background: rgba(255, 152, 0, 0.12);
color: var(--primary-text-color);
font-size: 13px;
}
.phase-line {
margin-top: -8px;
padding-bottom: 12px;
font-size: 13px;
color: var(--secondary-text-color);
}
.content {
display: flex;
flex-direction: column;
gap: 16px;
min-width: 300px;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
}
.consumes-hint {
font-size: 13px;
color: var(--secondary-text-color);
border-left: 3px solid var(--primary-color);
padding: 4px 8px;
margin: 4px 0 8px;
}
/* #99: editable per-completion parts selection */
.used-parts { margin: 4px 0 8px; display: flex; flex-direction: column; gap: 4px; }
.used-part-row { display: flex; align-items: center; gap: 8px; }
.used-part-check {
display: flex; align-items: center; gap: 6px; flex: 1;
font-size: 13px; cursor: pointer;
}
.used-part-check input { cursor: pointer; }
/* #111: whose stock this row draws on. Muted but never omitted — an
unlabelled foreign pool is indistinguishable from an own part. */
.used-part-owner { color: var(--secondary-text-color); }
.used-part-qty {
width: 76px; padding: 4px 6px; border-radius: 4px; font: inherit; font-size: 13px;
border: 1px solid var(--divider-color);
background: var(--card-background-color);
color: var(--primary-text-color);
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
/* .field/.field-label/.field-input come from nativeFieldStyles */
/* #161 phase 2: the per-slot reading fields */
.readings-block { display: flex; flex-direction: column; gap: 8px; }
.readings-block > .field-label { margin-bottom: -4px; }
.reading-warn {
font-size: 12px;
color: var(--warning-color, #ff9800);
}
/* .photo-pick / .photo-pickers / .photo-android-hint come from photoPickerStyles */
/* #163: the backdate moment starts EMPTY (= now); the button seeds the
HA date+time picker with the current minute instead of the picker's
own 00:00 default, so a backdated completion never lands at midnight
by accident. */
.backdate-pick {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px dashed var(--divider-color);
border-radius: 8px;
background: transparent;
cursor: pointer;
font: inherit;
font-size: 13px;
color: var(--secondary-text-color);
width: fit-content;
--mdc-icon-size: 18px;
}
.backdate-pick:hover { border-color: var(--primary-color); }
/* #161: several photos per completion — tiles wrap into a strip,
the two pickers (camera / gallery) sit underneath while there is
room left under the cap. */
.photo-strip {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 8px 0; /* room for the remove badges above the tiles */
}
.photo-limit {
font-size: 12px;
color: var(--secondary-text-color);
}
.photo-preview {
position: relative;
width: fit-content;
}
/* Uniform tiles: a tiny or portrait shot must not collapse the strip. */
.photo-preview img {
width: 96px;
height: 96px;
object-fit: cover;
border-radius: 8px;
display: block;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
}
.photo-remove {
position: absolute;
top: -8px;
right: -8px;
width: 24px;
height: 24px;
border-radius: 50%;
border: none;
background: var(--error-color, #db4437);
color: #fff;
cursor: pointer;
font-size: 12px;
line-height: 1;
}
.checklist-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-bottom: 1px solid var(--divider-color);
margin-bottom: 4px;
}
.checklist-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.checklist-item {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
padding: 4px 0;
font-size: 14px;
}
.checklist-item input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
.feedback-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-top: 1px solid var(--divider-color);
}
.feedback-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.feedback-buttons {
display: flex;
gap: 8px;
}
.feedback-btn {
flex: 1;
padding: 8px 12px;
border: 1px solid var(--divider-color);
border-radius: 8px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
text-align: center;
transition: all 0.2s;
}
.feedback-btn:hover {
background: var(--secondary-background-color, #f5f5f5);
}
.feedback-btn.selected {
background: var(--primary-color);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color);
}
`],d([v({attribute:!1})],k.prototype,"hass",2),d([v()],k.prototype,"entryId",2),d([v()],k.prototype,"taskId",2),d([v()],k.prototype,"taskName",2),d([v()],k.prototype,"lang",2),d([v({type:Array})],k.prototype,"checklist",2),d([v({type:Boolean})],k.prototype,"adaptiveEnabled",2),d([v()],k.prototype,"taskType",2),d([v()],k.prototype,"readingUnit",2),d([v({attribute:!1})],k.prototype,"readings",2),d([v({attribute:!1})],k.prototype,"readingHistory",2),d([v({attribute:!1})],k.prototype,"restockDefault",2),d([v({attribute:!1})],k.prototype,"restockUnitCost",2),d([v()],k.prototype,"currencySymbol",2),d([v({attribute:!1})],k.prototype,"parts",2),d([v({attribute:!1})],k.prototype,"consumesParts",2),d([v({type:Array})],k.prototype,"consumesInfo",2),d([v({type:Array})],k.prototype,"requiredFields",2),d([v()],k.prototype,"phaseLabel",2),d([v({type:Boolean})],k.prototype,"requireTagScan",2),d([v({type:Boolean})],k.prototype,"viaTagScan",2),d([h()],k.prototype,"_open",2),d([h()],k.prototype,"_notes",2),d([h()],k.prototype,"_cost",2),d([h()],k.prototype,"_duration",2),d([h()],k.prototype,"_loading",2),d([h()],k.prototype,"_error",2),d([h()],k.prototype,"_checklistState",2),d([h()],k.prototype,"_feedback",2),d([h()],k.prototype,"_readingValue",2),d([h()],k.prototype,"_readingValues",2),d([h()],k.prototype,"_restockQty",2),d([h()],k.prototype,"_completedAt",2),d([h()],k.prototype,"_usedParts",2),d([v({attribute:!1})],k.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",k)});function Ur(s,r,e){let t=new Blob([s],{type:e}),i=URL.createObjectURL(t),a=document.createElement("a");a.href=i,a.download=r,a.target="_blank",a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.dispatchEvent(new MouseEvent("click")),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(i),6e4)}var Zt=x(()=>{"use strict"});async function Pn(s,r,e=300){return(await s.connection.sendMessagePromise({type:"auth/sign_path",path:r,expires:e})).path}async function Br(s,r,e=300){return Pn(s,`/api/maintenance_supporter/document/${r}`,e)}var Vr=x(()=>{"use strict";Zt()});var ue,Xt=x(()=>{"use strict";I();F();Vr();ue=class extends S{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 Br(this.hass,this.docId)}catch{this._failed=!0}}render(){return this._failed||!this.docId?u:this._url?l`
this._failed=!0} />
`:l``}};ue.styles=E`
.wrap { display: inline-block; margin-top: 4px; }
/* #161: uniform 96px tiles — several photos sit in a strip, so a
tiny or portrait shot must not collapse its slot. */
img {
width: 96px;
height: 96px;
object-fit: cover;
border-radius: 6px;
display: block;
border: 1px solid var(--divider-color);
box-sizing: border-box;
}
.ph {
width: 96px;
height: 96px;
border-radius: 6px;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
margin-top: 4px;
}
`,d([v({attribute:!1})],ue.prototype,"hass",2),d([v()],ue.prototype,"docId",2),d([h()],ue.prototype,"_url",2),d([h()],ue.prototype,"_failed",2);customElements.get("maintenance-history-photo")||customElements.define("maintenance-history-photo",ue)});var V,Wr=x(()=>{"use strict";I();F();C();pe();Yt();Ie();Xt();Ze();Ze();V=class extends S{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 Pe(this,{entryId:()=>this._draft?.entry_id??"",hass:()=>this.hass});this._photosOriginal="";this._readingRows=[];this._readingText={};this._readingsOriginal=""}get _lang(){return H(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 t=[],i=new Set;for(let o of e.readings??[])i.has(o.id)||(i.add(o.id),t.push({id:o.id,name:o.name,unit:o.unit??null}));for(let o of e.reading_values??[])i.has(o.id)||(i.add(o.id),t.push({id:o.id,name:o.name,unit:o.unit??null}));this._readingRows=t;let a={};for(let o of e.reading_values??[])a[o.id]=String(o.value);this._readingText=a,this._readingsOriginal=JSON.stringify(this._readingNumbers())}_readingNumbers(){let e={};for(let t of this._readingRows){let i=(this._readingText[t.id]??"").trim();if(i==="")continue;let a=parseFloat(i.replace(",","."));isNaN(a)||(e[t.id]=a)}return e}async _loadPartOptions(){let e=this._draft;if(e)try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/parts/overview"}),i=[];for(let o of t.parts||[]){let _=o.entry_id===e.entry_id,c=o.consumers.some(p=>p.entry_id===e.entry_id&&p.task_id===e.task_id);!_&&!c||i.push({part_id:o.part_id,name:o.name,entry_id:o.entry_id,foreign:!_,object_name:o.object_name})}for(let o of e.used_parts||[]){let _=o.entry_id||e.entry_id;i.some(c=>c.part_id===o.part_id&&c.entry_id===_)||i.push({part_id:o.part_id,name:o.name||o.part_id,entry_id:_,foreign:_!==e.entry_id,object_name:null})}let a={};for(let o of e.used_parts||[])a[`${o.entry_id||e.entry_id}:${o.part_id}`]=o.quantity??1;this._partOptions=i,this._partQty=a,this._partQtyOriginal=this._partSelectionKey()}catch{this._partOptions=[]}}_partSelectionKey(){return JSON.stringify(Object.entries(this._partQty).filter(([,e])=>e>0).sort(([e],[t])=>e.localeCompare(t)))}close(){this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null,this._photos.discardOrphans()}_set(e,t){this._draft&&(this._draft={...this._draft,[e]:t})}async _delete(){if(!this._draft||!this._originalSnapshot)return;let e=this._lang;if(window.confirm(n("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(t){this._error=N(t,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(i=>(this._partQty[`${i.entry_id}:${i.part_id}`]||0)>0).map(i=>({part_id:i.part_id,quantity:this._partQty[`${i.entry_id}:${i.part_id}`],...i.foreign?{entry_id:i.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 i=this._readingNumbers(),a={};for(let o of this._readingRows)a[o.id]=i[o.id]??null;e.reading_values=a}if(JSON.stringify(this._photos.ids)!==this._photosOriginal&&(e.photo_doc_ids=this._photos.ids),Object.keys(e).filter(i=>!["type","entry_id","task_id","original_timestamp"].includes(i)).length===0){this.close();return}await this.hass.connection.sendMessagePromise(e),this._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=N(e,this._lang)}finally{this._saving=!1}}}render(){if(!this._open||!this._draft)return u;let e=this._lang,t=this._draft,i=this._error||this._photos.errorText(e);return l`
${n("history_edit_title",e)}
${n(t.type,e)||t.type}
{let o=a.detail.value;o&&this._set("timestamp",o)}}
>
${this._renderReadings(t,e)}
${this._partOptions&&this._partOptions.length>0?l`
${n("complete_parts_used",e)}
${this._partOptions.map(a=>{let o=`${a.entry_id}:${a.part_id}`,_=this._partQty[o]||0;return l`
`})}
`:u}
${n("completion_photos",e)}
${this._photos.photos.length>0?l`
${this._photos.photos.map(a=>l`
`)}
`:u}
${this._photos.full?l`
${n("photos_limit",e).replace("{max}",String(this._photos.max))}`:l`
this._photos.addFiles(a.detail.files)}
>`}
${n("history_edit_photos_hint",e)}
${i?l`
${i}
`:u}
`}_renderReadings(e,t){return this._readingRows.length>0?l`
${n("readings_section",t)}
${this._readingRows.map(i=>l`
`)}
`:e.reading_value==null&&e.task_type!=="reading"?u:l`
`}};V.styles=[ft,E`
:host { display: contents; }
.backdrop {
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
z-index: 100;
}
.dialog {
position: fixed; left: 50%; top: 50%;
transform: translate(-50%, -50%);
width: 95vw; max-width: 480px;
background: var(--card-background-color, var(--ha-card-background, #1c1c1c));
color: var(--primary-text-color);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.4);
padding: 20px;
display: flex; flex-direction: column; gap: 12px;
z-index: 101;
max-height: 90vh; overflow: auto;
}
h2 { margin: 0; font-size: 18px; }
.entry-type {
display: flex; align-items: center; gap: 6px;
color: var(--secondary-text-color); font-size: 13px;
}
label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
label span { color: var(--secondary-text-color); }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
input, textarea {
padding: 8px; font-size: 14px;
background: var(--secondary-background-color, #2c2c2c);
color: var(--primary-text-color);
border: 1px solid var(--divider-color, #444);
border-radius: 6px;
width: 100%; box-sizing: border-box;
font-family: inherit;
}
.delete-entry { margin-right: auto; color: var(--error-color, #d32f2f); background: transparent; border: 1px solid var(--error-color, #d32f2f); border-radius: 6px; padding: 6px 10px; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
.delete-entry ha-icon { --mdc-icon-size: 18px; }
.actions {
display: flex; gap: 8px; justify-content: flex-end;
margin-top: 8px;
}
button {
padding: 8px 16px; font-size: 14px;
border-radius: 6px; cursor: pointer;
border: none; font-weight: 500;
}
button.cancel {
background: transparent;
color: var(--primary-text-color);
border: 1px solid var(--divider-color);
}
button.save {
background: var(--primary-color);
color: var(--text-primary-color, white);
}
button[disabled] { opacity: 0.5; cursor: wait; }
.error {
color: var(--error-color, #d32f2f);
font-size: 13px; padding: 8px;
background: rgba(211,47,47,0.1);
border-radius: 6px;
}
/* #130: parts on the entry */
.parts-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.parts-title { color: var(--secondary-text-color); font-size: 13px; }
.part-row-edit {
display: flex; flex-direction: row; align-items: center; gap: 8px;
font-size: 14px;
}
.part-row-edit input[type="checkbox"] { width: auto; }
.part-label { flex: 1; color: var(--primary-text-color); }
.part-qty { width: 76px; }
/* #161 phase 2: readings on the entry */
.readings-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.reading-row-edit {
display: flex; flex-direction: row; align-items: center; gap: 8px;
font-size: 14px;
}
.reading-row-name { flex: 1; color: var(--primary-text-color); min-width: 0; }
.reading-row-input { width: 140px; font-variant-numeric: tabular-nums; }
/* #161: photos on the entry */
.photos-block {
display: flex; flex-direction: column; gap: 6px;
border: 1px solid var(--divider-color, #444);
border-radius: 6px; padding: 8px;
}
.photo-strip { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 6px; }
.photo-tile { position: relative; width: fit-content; }
.photo-remove {
position: absolute; top: -4px; right: -8px;
width: 22px; height: 22px; border-radius: 50%; border: none;
background: var(--error-color, #db4437); color: #fff;
cursor: pointer; font-size: 11px; line-height: 1; padding: 0;
}
/* the camera / gallery pickers come from photoPickerStyles (ms-photo-picker) */
.photos-hint { font-size: 12px; color: var(--secondary-text-color); }
`],d([v({attribute:!1})],V.prototype,"hass",2),d([h()],V.prototype,"_open",2),d([h()],V.prototype,"_saving",2),d([h()],V.prototype,"_error",2),d([h()],V.prototype,"_draft",2),d([h()],V.prototype,"_partOptions",2),d([h()],V.prototype,"_partQty",2),d([h()],V.prototype,"_readingRows",2),d([h()],V.prototype,"_readingText",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",V)});function Re(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function Kr(s){return!s.startsWith("data:image/svg+xml,")&&!s.startsWith("data:image/png;base64,")?"":Re(s)}function Rn(s){return s.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var Y,Yr=x(()=>{"use strict";I();F();C();Zt();Y=class extends S{constructor(){super(...arguments);this.lang="en";this._open=!1;this._loading=!1;this._error="";this._viewResult=null;this._completeResult=null;this._urlMode="companion";this._entryId="";this._taskId=null;this._objectName="";this._taskName="";this._generateSeq=0}openForObject(e,t){this._entryId=e,this._taskId=null,this._objectName=t,this._taskName="",this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}openForTask(e,t,i,a){this._entryId=e,this._taskId=t,this._objectName=i,this._taskName=a,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}async _generate(){let e=++this._generateSeq;this._loading=!0,this._error="",this._viewResult=null,this._completeResult=null;try{let t={type:"maintenance_supporter/qr/generate",entry_id:this._entryId,url_mode:this._urlMode};this._taskId&&(t.task_id=this._taskId);let i=[this.hass.connection.sendMessagePromise({...t,action:"view"})];this._taskId&&i.push(this.hass.connection.sendMessagePromise({...t,action:"complete"}));let a=await Promise.all(i);if(e!==this._generateSeq)return;this._viewResult=a[0],a.length>1&&(this._completeResult=a[1])}catch(t){if(e!==this._generateSeq)return;let i=t?.code,a=t?.message;this._error=i==="no_url"||typeof a=="string"&&a.includes("No Home Assistant URL")?n("qr_error_no_url",this.lang):n("qr_error",this.lang)}finally{e===this._generateSeq&&(this._loading=!1)}}_setUrlMode(e){this._urlMode!==e&&(this._urlMode=e,this._generate())}_print(){if(!this._viewResult)return;let e=this._viewResult,t=e.label.task_name?`${e.label.object_name} \u2014 ${e.label.task_name}`:e.label.object_name,i=[e.label.manufacturer,e.label.model].filter(Boolean).join(" "),a=window.open("","_blank","width=600,height=500");if(!a)return;let o=this.lang||"en",_=Re(t),c=Re(i),p=!!this._completeResult,m=Re(n("qr_action_view",o)),f=Re(n("qr_action_complete",o));a.document.write(`
${_}
${_}
${c?`${c}
`:""}
${m}
${p?`
${f}
`:""}
${Re(this._viewResult.url)}