e.id===_)?.name||null}getUser(_){return!_||!this.usersCache?null:this.usersCache.find(t=>t.id===_)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(_){return _?_===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}};function O(o){return`${o.entry_id??""}\0${o.part_id}`}var tt=["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"],ht=["sensor"],_t=["temperature","humidity","pressure"];var ut=["notes","cost","duration","photo","user"],Y={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"};var Ht=["cleaning","inspection","replacement","calibration","service","reading","custom"],qt=["low","normal","high"],Rt=["time_based","weekdays","nth_weekday","day_of_month","sensor_based","one_time","manual"],et=["weekdays","nth_weekday","day_of_month"],mt=["threshold","counter","state_change","runtime"],Nt=[...mt,"compound"],N={alpha:"0.3",min:"7",max:"365"};function Ft(){return{entityIds:"",type:"threshold",attribute:"",above:"",below:"",equals:"",notEquals:"",forMinutes:"0",targetValue:"",deltaMode:!1,fromState:"",toState:"",targetChanges:"",runtimeHours:"",onStates:"",carry:{}}}var Mt=new Set(["entity_id","entity_ids","type","attribute","trigger_above","trigger_below","trigger_equals","trigger_not_equals","trigger_for_minutes","trigger_target_value","trigger_delta_mode","trigger_from_state","trigger_to_state","trigger_target_changes","trigger_runtime_hours","trigger_on_states"]);function Ot(o){return{entityIds:(o.entity_ids||(o.entity_id?[o.entity_id]:[])).join(", "),type:o.type||"threshold",attribute:o.attribute||"",above:o.trigger_above?.toString()??"",below:o.trigger_below?.toString()??"",equals:o.trigger_equals?.toString()??"",notEquals:o.trigger_not_equals?.toString()??"",forMinutes:o.trigger_for_minutes?.toString()??"0",targetValue:o.trigger_target_value?.toString()??"",deltaMode:o.trigger_delta_mode||!1,fromState:o.trigger_from_state||"",toState:o.trigger_to_state||"",targetChanges:o.trigger_target_changes?.toString()??"",runtimeHours:o.trigger_runtime_hours?.toString()??"",onStates:(o.trigger_on_states||[]).join(", "),carry:Object.fromEntries(Object.entries(o).filter(([t])=>!Mt.has(t)&&!t.startsWith("_")))}}function zt(o){let _=o.entityIds.split(",").map(e=>e.trim()).filter(Boolean);if(_.length===0)return null;let t={...o.carry||{},entity_id:_[0],entity_ids:_,type:o.type};if(o.attribute&&(t.attribute=o.attribute),o.type==="threshold"){let e=parseFloat(o.above);isNaN(e)||(t.trigger_above=e);let i=parseFloat(o.below);isNaN(i)||(t.trigger_below=i);let n=parseFloat(o.equals);isNaN(n)||(t.trigger_equals=n);let d=parseFloat(o.notEquals);isNaN(d)||(t.trigger_not_equals=d);let p=parseInt(o.forMinutes,10);isNaN(p)||(t.trigger_for_minutes=p)}else if(o.type==="counter"){let e=parseFloat(o.targetValue);isNaN(e)||(t.trigger_target_value=e),t.trigger_delta_mode=o.deltaMode}else if(o.type==="state_change"){o.fromState&&(t.trigger_from_state=o.fromState),o.toState&&(t.trigger_to_state=o.toState);let e=parseInt(o.targetChanges,10);isNaN(e)||(t.trigger_target_changes=e)}else if(o.type==="runtime"){let e=parseFloat(o.runtimeHours);isNaN(e)||(t.trigger_runtime_hours=e);let i=(o.onStates||"").split(",").map(n=>n.trim()).filter(Boolean);i.length>0&&(t.trigger_on_states=i)}return t}function Ut(o){return Array.from({length:7},(_,t)=>X(t,o,"short"))}function jt(o){let _=new Intl.DateTimeFormat(o||"en",{month:"short"});return Array.from({length:12},(t,e)=>_.format(new Date(2021,e,1)))}var m=class m extends E{constructor(){super(...arguments);this.checklistsEnabled=!1;this.scheduleTimeEnabled=!1;this.completionActionsEnabled=!1;this.defaultWarningDays=7;this.parts=[];this._foreignOwners=[];this._open=!1;this._entityPickerFallback=!1;this._pickerProbeStrikes=0;this._loading=!1;this._error="";this._entryId="";this._taskId=null;this._objectChoices=[];this._name="";this._type="custom";this._scheduleType="time_based";this._intervalDays="30";this._intervalUnit="days";this._dueDate="";this._warningDays="7";this._earliestCompletionDays="";this._intervalAnchor="completion";this._weekdays=[];this._nth="1";this._nthWeekday="5";this._domDay="1";this._domLastDay=!1;this._domBusiness=!1;this._calOffset="0";this._seasonMonths=[];this._endsMode="never";this._endsCount="";this._endsUntil="";this._schedulePreview=[];this._schedulePreviewEnded=!1;this._previewSeq=0;this._notes="";this._documentationUrl="";this._customIcon="";this._priority="normal";this._labels="";this._enabled=!0;this._triggerEntityId="";this._triggerEntityIds=[];this._triggerEntityLogic="any";this._triggerAttribute="";this._triggerType="threshold";this._triggerAbove="";this._triggerBelow="";this._triggerEquals="";this._triggerNotEquals="";this._triggerForMinutes="0";this._triggerCombinator="any";this._triggerTargetValue="";this._triggerDeltaMode=!1;this._triggerBaselineValue="";this._liveBaselineValue=null;this._autoCompleteOnRecovery=!1;this._triggerFromState="";this._triggerToState="";this._triggerTargetChanges="";this._triggerRuntimeHours="";this._triggerOnStates="";this._compoundLogic="AND";this._compoundConditions=[];this._suggestedAttributes=[];this._availableAttributes=[];this._entityDomain="";this._lastPerformed="";this._nfcTagId="";this._readingUnit="";this._consumesParts={};this._partsLoadFailed=!1;this._availableTags=[];this._responsibleUserId=null;this._assigneePool=[];this._rotationStrategy="";this._availableUsers=[];this._checklistText="";this._requiredCompletion=[];this._scheduleTime="";this._actionService="";this._actionTargetEntity="";this._actionData={};this._actionDataJsonFallback="";this._actionTesting=!1;this._actionTestResult="";this._actionTestError="";this._qcNotes="";this._qcCost="";this._qcDuration="";this._qcFeedback="";this._environmentalEntity="";this._environmentalAttribute="";this._environmentalInitial="";this._environmentalAttributeInitial="";this._adaptiveEnabled=!1;this._adaptiveAlpha=N.alpha;this._adaptiveMin=N.min;this._adaptiveMax=N.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 C(this.hass)}async openCreate(t,e){this._entryId=t,this._taskId=null,this._error="",!t&&e&&e.length>0?(this._objectChoices=e.map(i=>({entry_id:i.entry_id,name:i.object.name})).sort((i,n)=>i.name.localeCompare(n.name)),this._entryId=this._objectChoices[0].entry_id):this._objectChoices=[],this._resetFields(),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}async openEdit(t,e){this._entryId=t,this._taskId=e.id,this._error="",this._name=e.name,this._type=e.type,this._scheduleType=e.schedule_type,this._intervalDays=e.interval_days!=null?String(e.interval_days):"",this._intervalUnit=e.interval_unit||"days",this._dueDate=e.due_date||"";let i=e.schedule;this._weekdays=i?.kind==="weekdays"?[...i.weekdays??[]]:[],this._nth=i?.kind==="nth_weekday"?String(i.nth??1):"1",this._nthWeekday=i?.kind==="nth_weekday"?String(i.weekday??5):"5",this._domDay=i?.kind==="day_of_month"&&(i.day??1)>=1?String(i.day??1):"1",this._domLastDay=i?.kind==="day_of_month"&&i.day===-1,this._domBusiness=i?.kind==="day_of_month"&&i.business===!0,this._calOffset=i?.offset?String(i.offset):"0",this._seasonMonths=Array.isArray(i?.season_months)?[...i.season_months]:[];let n=i?.ends;n&&typeof n.count=="number"?(this._endsMode="count",this._endsCount=String(n.count),this._endsUntil=""):n&&typeof n.until=="string"?(this._endsMode="until",this._endsUntil=n.until,this._endsCount=""):(this._endsMode="never",this._endsCount="",this._endsUntil=""),this._warningDays=e.warning_days.toString(),this._earliestCompletionDays=e.earliest_completion_days!=null?String(e.earliest_completion_days):"",this._intervalAnchor=e.interval_anchor||"completion",this._notes=e.notes||"",this._documentationUrl=e.documentation_url||"",this._customIcon=e.custom_icon||"",this._priority=e.priority||"normal",this._labels=(e.labels||[]).join(", "),this._enabled=e.enabled!==!1,this._lastPerformed=e.last_performed||"",this._nfcTagId=e.nfc_tag_id||"",this._readingUnit=e.reading_unit||"",this._consumesParts=Object.fromEntries((e.consumes_parts||[]).map(u=>[O(u),{...u}])),this._responsibleUserId=e.responsible_user_id||null,this._assigneePool=[...e.assignee_pool||[]],this._rotationStrategy=e.rotation_strategy||"",this._checklistText=(e.checklist||[]).join(`
`),this._requiredCompletion=[...e.required_completion_fields||[]],this._scheduleTime=e.schedule_time||"";let d=e.on_complete_action;if(d&&d.service){this._actionService=d.service;let u=d.target?.entity_id;this._actionTargetEntity=Array.isArray(u)?u[0]||"":u||"",this._actionData=d.data&&typeof d.data=="object"?{...d.data}:{},this._actionDataJsonFallback=""}else this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="";let p=e.quick_complete_defaults;this._qcNotes=p?.notes||"",this._qcCost=p?.cost!=null?String(p.cost):"",this._qcDuration=p?.duration!=null?String(p.duration):"",this._qcFeedback=p?.feedback||"";let h=e.adaptive_config||{};if(this._environmentalEntity=h.environmental_entity||"",this._environmentalAttribute=h.environmental_attribute||"",this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute,this._adaptiveEnabled=!!h.enabled,this._adaptiveAlpha=h.ewa_alpha?.toString()??N.alpha,this._adaptiveMin=h.min_interval_days?.toString()??N.min,this._adaptiveMax=h.max_interval_days?.toString()??N.max,this._adaptiveSeasonal=h.seasonal_enabled!==!1,this._adaptivePrediction=h.sensor_prediction_enabled!==!1,this._adaptiveInitial=this._adaptiveSnapshot(),e.trigger_config){let u=e.trigger_config;this._triggerEntityId=u.entity_id||u.entity_ids&&u.entity_ids[0]||"",this._triggerEntityIds=u.entity_ids||(u.entity_id?[u.entity_id]:[]),this._triggerEntityLogic=u.entity_logic||"any",this._triggerAttribute=u.attribute||"",this._triggerType=u.type||"threshold",this._triggerAbove=u.trigger_above?.toString()||"",this._triggerBelow=u.trigger_below?.toString()||"",this._triggerEquals=u.trigger_equals?.toString()||"",this._triggerNotEquals=u.trigger_not_equals?.toString()||"",this._triggerForMinutes=u.trigger_for_minutes?.toString()||"0",this._triggerCombinator=u.trigger_combinator==="all"?"all":"any",this._triggerTargetValue=u.trigger_target_value?.toString()||"",this._triggerDeltaMode=u.trigger_delta_mode||!1,this._triggerBaselineValue=u.trigger_baseline_value?.toString()||"",this._liveBaselineValue=e.trigger_baseline_value??null,this._autoCompleteOnRecovery=u.auto_complete_on_recovery||!1,this._triggerFromState=u.trigger_from_state||"",this._triggerToState=u.trigger_to_state||"",this._triggerTargetChanges=u.trigger_target_changes?.toString()||"",this._triggerRuntimeHours=u.trigger_runtime_hours?.toString()||"",this._triggerOnStates=(u.trigger_on_states||[]).join(", "),u.type==="compound"?(this._compoundLogic=u.compound_logic==="OR"?"OR":"AND",this._compoundConditions=(u.conditions||[]).map(Ot)):(this._compoundLogic="AND",this._compoundConditions=[])}else this._resetTriggerFields();this._triggerEntityId&&this._fetchEntityAttributes(this._triggerEntityId),await Promise.all([this._loadUsers(),this._loadTags(),this._loadParts(),this._loadForeignPools()]),this._open=!0}_resetFields(){this._name="",this._type="custom",this._scheduleType="time_based",this._intervalDays="30",this._intervalUnit="days",this._dueDate="",this._warningDays=String(this.defaultWarningDays),this._earliestCompletionDays="",this._intervalAnchor="completion",this._weekdays=[],this._nth="1",this._nthWeekday="5",this._domDay="1",this._domLastDay=!1,this._domBusiness=!1,this._calOffset="0",this._seasonMonths=[],this._endsMode="never",this._endsCount="",this._endsUntil="",this._notes="",this._documentationUrl="",this._customIcon="",this._priority="normal",this._labels="",this._enabled=!0,this._lastPerformed="",this._nfcTagId="",this._readingUnit="",this._consumesParts={},this._responsibleUserId=null,this._assigneePool=[],this._rotationStrategy="",this._checklistText="",this._requiredCompletion=[],this._scheduleTime="",this._environmentalEntity="",this._environmentalAttribute="",this._environmentalInitial="",this._environmentalAttributeInitial="",this._adaptiveEnabled=!1,this._adaptiveAlpha=N.alpha,this._adaptiveMin=N.min,this._adaptiveMax=N.max,this._adaptiveSeasonal=!0,this._adaptivePrediction=!0,this._adaptiveInitial=this._adaptiveSnapshot(),this._actionService="",this._actionTargetEntity="",this._actionData={},this._actionDataJsonFallback="",this._actionTesting=!1,this._actionTestResult="",this._qcNotes="",this._qcCost="",this._qcDuration="",this._qcFeedback="",this._resetTriggerFields()}_resetTriggerFields(){this._triggerEntityId="",this._triggerEntityIds=[],this._triggerEntityLogic="any",this._triggerAttribute="",this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="",this._triggerType="threshold",this._triggerAbove="",this._triggerBelow="",this._triggerEquals="",this._triggerNotEquals="",this._triggerForMinutes="0",this._triggerCombinator="any",this._triggerTargetValue="",this._triggerDeltaMode=!1,this._triggerBaselineValue="",this._liveBaselineValue=null,this._autoCompleteOnRecovery=!1,this._triggerFromState="",this._triggerToState="",this._triggerTargetChanges="",this._triggerRuntimeHours="",this._triggerOnStates="",this._compoundLogic="AND",this._compoundConditions=[]}async _loadUsers(){this._userService||(this._userService=new G(this.hass));try{this._availableUsers=await this._userService.getUsers()}catch(t){console.error("Failed to load users:",t),this._availableUsers=[]}}_toggleAssignee(t){this._assigneePool=this._assigneePool.includes(t)?this._assigneePool.filter(e=>e!==t):[...this._assigneePool,t]}async _testAction(){let t=this._actionService.trim();if(!t||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(t)){this._actionTestResult="error",this._actionTestError="Invalid service format (expected 'domain.service')",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3);return}let[e,i]=t.split(".");if(!this.hass?.services?.[e]?.[i]){this._actionTestResult="error",this._actionTestError=`Service "${t}" is not registered in Home Assistant. Check spelling and that the integration providing it is loaded.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}let n=this._actionTargetEntity.trim();if(n){let d=n.split(".")[0];if(d!==e&&!new Set(["homeassistant","scene","notify","persistent_notification"]).has(e)){this._actionTestResult="error",this._actionTestError=`Service "${t}" only works on ${e}.* entities; entity "${n}" is in ${d}.* \u2014 pick a service that matches the entity domain (e.g. ${d}.${i})`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}if(!this.hass.states?.[n]){this._actionTestResult="error",this._actionTestError=`Target entity "${n}" not found in Home Assistant \u2014 the entity may have been renamed or its integration removed.`,setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},8e3);return}}this._actionTestResult="ok",setTimeout(()=>{this._actionTestResult="",this._actionTestError=""},5e3)}_buildActionData(){if(this._actionDataJsonFallback.trim())try{let t=JSON.parse(this._actionDataJsonFallback);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{...this._actionData}}_serviceSchema(){let t=this._actionService.trim();if(!t||!/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(t))return null;let[e,i]=t.split("."),n=this.hass?.services?.[e]?.[i]?.fields;return!n||Object.keys(n).length===0?null:Object.entries(n).map(([d,p])=>({name:d,required:!!p.required,selector:p.selector||{text:{}}}))}_renderCompletionActionsSection(t){if(!this.completionActionsEnabled)return c;let e=this._serviceSchema();return a`
${s("on_complete_action_title",t)}
${s("on_complete_action_desc",t)}
{this._actionService=i.detail.value||"";let n=this._serviceSchema();if(n){let d=new Set(n.map(p=>p.name));this._actionData=Object.fromEntries(Object.entries(this._actionData).filter(([p])=>d.has(p)))}}}
>
s("on_complete_action_target",t)}
@value-changed=${i=>{let n=i.detail.value;this._actionTargetEntity=n.target_entity||""}}
>
${s("on_complete_action_target_hint",t)}
${e?a`
{this._actionData={...i.detail.value}}}
>
`:a`
{this._actionDataJsonFallback=i.target.value}}
>
`}
${this._actionTesting?"\u2026":s("on_complete_action_test",t)}
${this._actionTestResult==="ok"?a`
${s("on_complete_action_test_success",t)} `:c}
${this._actionTestResult==="error"?a`
${s("on_complete_action_test_failed",t)}
${this._actionTestError?a`
${this._actionTestError}
`:c}
`:c}
${s("quick_complete_defaults_title",t)}
${s("quick_complete_defaults_desc",t)}
{this._qcNotes=i.target.value}}
>
{this._qcCost=i.target.value}}
>
{this._qcDuration=i.target.value}}
>
{this._qcFeedback=i.target.value}}>
${s("quick_complete_defaults_feedback_none",t)}
${s("quick_complete_defaults_feedback_needed",t)}
${s("quick_complete_defaults_feedback_not_needed",t)}
`}async _loadParts(){if(this.parts=[],!!this._entryId)try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/object",entry_id:this._entryId});this.parts=t.parts||[],this._partsLoadFailed=!1}catch{this.parts=[],this._partsLoadFailed=!0}}async _loadForeignPools(){if(this._foreignOwners=[],!!this._entryId)try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/objects"});this._foreignOwners=(t.objects||[]).filter(e=>e.entry_id!==this._entryId&&(e.parts||[]).length>0).map(e=>({entry_id:e.entry_id,name:e.object?.name||e.entry_id,parts:e.parts||[]})).sort((e,i)=>e.name.localeCompare(i.name))}catch{this._foreignOwners=[]}}async _loadTags(){try{let t=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/tags/list"});this._availableTags=t.tags||[]}catch{this._availableTags=[]}}_fetchConditionAttributes(t){!t||!this.hass||this._conditionAttrOptions[t]||this._conditionAttrPending.has(t)||(this._conditionAttrPending.add(t),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:t}).then(e=>{let i=e;this._conditionAttrOptions={...this._conditionAttrOptions,[t]:{suggested:i.suggested_attributes||[],available:i.available_attributes||[]}}}).catch(()=>{this._conditionAttrOptions={...this._conditionAttrOptions,[t]:{suggested:[],available:[]}}}))}async _fetchEntityAttributes(t){if(!t||!this.hass){this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain="";return}try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/entity/attributes",entity_id:t});this._entityDomain=e.domain||"",this._suggestedAttributes=e.suggested_attributes||[],this._availableAttributes=e.available_attributes||[]}catch{this._suggestedAttributes=[],this._availableAttributes=[],this._entityDomain=""}}get _hasForeignPick(){return Object.values(this._consumesParts).some(t=>!!t.entry_id)}_renderConsumesRow(t,e){let i=O({part_id:t.id,entry_id:e}),n=this._consumesParts[i],d=e?{part_id:t.id,quantity:1,entry_id:e}:{part_id:t.id,quantity:1};return a`
{let h={...this._consumesParts};p.target.checked?h[i]=h[i]||d:delete h[i],this._consumesParts=h}}
/>
${t.name}${t.unit?` (${t.unit})`:""}
${n!==void 0?a` {let h=parseFloat(p.target.value);this._consumesParts={...this._consumesParts,[i]:{...d,quantity:Number.isFinite(h)&&h>=.01?h:1}}}}
/>`:c}
`}_toggleRequired(t,e){let i=new Set(this._requiredCompletion);e?i.add(t):i.delete(t),this._requiredCompletion=[...i]}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let t=parseInt(this._adaptiveMin,10),e=parseInt(this._adaptiveMax,10);if(!isNaN(t)&&!isNaN(e)&&t>e){this._error=`${s("adaptive_min_interval",this._lang)} > ${s("adaptive_max_interval",this._lang)}`;return}}this._loading=!0,this._error="";try{let t={type:this._taskId?"maintenance_supporter/task/update":"maintenance_supporter/task/create",entry_id:this._entryId,name:this._name,task_type:this._type,schedule_type:this._scheduleType,warning_days:Number.isNaN(parseInt(this._warningDays,10))?this.defaultWarningDays:Math.max(0,parseInt(this._warningDays,10))},e=this._earliestCompletionDays.trim();if(t.earliest_completion_days=e===""?null:Math.max(0,parseInt(e,10)||0),this._taskId&&(t.task_id=this._taskId),this._scheduleType==="one_time"?(t.due_date=this._dueDate||null,t.interval_days=null):et.includes(this._scheduleType)?(t.schedule={...this._buildSchedule(),...this._recurrenceExtras()},t.interval_days=null,this._taskId&&(t.due_date=null)):(this._taskId&&(t.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(t.interval_days=parseInt(this._intervalDays,10),t.interval_unit=this._intervalUnit,t.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(t.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(t.interval_days=null,t.interval_anchor="completion")),t.notes=this._notes||null,t.documentation_url=this._documentationUrl||null,t.custom_icon=this._customIcon||null,t.priority=this._priority,t.labels=this._labels.split(",").map(p=>p.trim()).filter(Boolean),t.enabled=this._enabled,t.last_performed=this._lastPerformed||null,t.nfc_tag_id=this._nfcTagId||null,t.reading_unit=this._readingUnit.trim()||null,(this.parts.length||this._foreignOwners.length)&&(t.consumes_parts=Object.values(this._consumesParts).map(p=>p.entry_id?{part_id:p.part_id,quantity:p.quantity,entry_id:p.entry_id}:{part_id:p.part_id,quantity:p.quantity})),t.responsible_user_id=this._responsibleUserId,t.assignee_pool=this._assigneePool,t.required_completion_fields=this._requiredCompletion,t.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let p=this._compoundConditions.map(zt).filter(h=>h!==null);if(p.length>0){let h={type:"compound",compound_logic:this._compoundLogic,conditions:p};this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(h.trigger_combinator="all"),t.trigger_config=h}else this._taskId&&(t.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let p=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],h={entity_id:p[0],entity_ids:p,type:this._triggerType};if(this._triggerAttribute&&(h.attribute=this._triggerAttribute),this._autoCompleteOnRecovery&&(h.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(h.trigger_combinator="all"),p.length>1&&(h.entity_logic=this._triggerEntityLogic),this._triggerType==="threshold"){if(this._triggerAbove){let u=parseFloat(this._triggerAbove);isNaN(u)||(h.trigger_above=u)}if(this._triggerBelow){let u=parseFloat(this._triggerBelow);isNaN(u)||(h.trigger_below=u)}if(this._triggerEquals){let u=parseFloat(this._triggerEquals);isNaN(u)||(h.trigger_equals=u)}if(this._triggerNotEquals){let u=parseFloat(this._triggerNotEquals);isNaN(u)||(h.trigger_not_equals=u)}if(this._triggerForMinutes){let u=parseInt(this._triggerForMinutes,10);isNaN(u)||(h.trigger_for_minutes=u)}}else if(this._triggerType==="counter"){if(this._triggerTargetValue){let u=parseFloat(this._triggerTargetValue);isNaN(u)||(h.trigger_target_value=u)}if(h.trigger_delta_mode=this._triggerDeltaMode,this._triggerDeltaMode&&this._triggerBaselineValue){let u=parseFloat(this._triggerBaselineValue);!isNaN(u)&&u>=0&&(h.trigger_baseline_value=u)}}else if(this._triggerType==="state_change"){if(this._triggerFromState&&(h.trigger_from_state=this._triggerFromState),this._triggerToState&&(h.trigger_to_state=this._triggerToState),this._triggerTargetChanges){let u=parseInt(this._triggerTargetChanges,10);isNaN(u)||(h.trigger_target_changes=u)}}else if(this._triggerType==="runtime"){if(this._triggerRuntimeHours){let v=parseFloat(this._triggerRuntimeHours);isNaN(v)||(h.trigger_runtime_hours=v)}let u=this._triggerOnStates.split(",").map(v=>v.trim()).filter(Boolean);u.length>0&&(h.trigger_on_states=u)}t.trigger_config=h}else this._taskId&&(t.trigger_config=null);if(this.scheduleTimeEnabled&&this._scheduleType==="time_based"){let p=this._scheduleTime.trim();t.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(p)?p:null}if(this.checklistsEnabled){let p=this._checklistText.split(`
`).map(h=>h.trim()).filter(Boolean).slice(0,100);t.checklist=p.length?p:null}if(this.completionActionsEnabled){let p=this._actionService.trim();if(p&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(p)){let b={service:p},y=this._actionTargetEntity.trim();y&&(b.target={entity_id:y});let $=this._buildActionData();Object.keys($).length>0&&(b.data=$),t.on_complete_action=b}else t.on_complete_action=null;let h={};this._qcNotes.trim()&&(h.notes=this._qcNotes.trim());let u=parseFloat(this._qcCost);!isNaN(u)&&u>=0&&(h.cost=u);let v=parseInt(this._qcDuration,10);!isNaN(v)&&v>=0&&(h.duration=v),this._qcFeedback&&(h.feedback=this._qcFeedback),t.quick_complete_defaults=Object.keys(h).length?h:null}let i=await this.hass.connection.sendMessagePromise(t),n=this._taskId||i?.task_id,d=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;if(n&&this._scheduleType==="sensor_based"&&d)try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:n,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null}),this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute}catch{}if(n&&this._adaptiveSnapshot()!==this._adaptiveInitial){let p=parseFloat(this._adaptiveAlpha),h=parseInt(this._adaptiveMin,10),u=parseInt(this._adaptiveMax,10);try{await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:n,enabled:this._adaptiveEnabled,...p>=.1&&p<=.9?{ewa_alpha:p}:{},...!isNaN(h)&&h>=1?{min_interval_days:h}:{},...!isNaN(u)&&u>=1?{max_interval_days:u}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction}),this._adaptiveInitial=this._adaptiveSnapshot()}catch{}}this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}catch(t){this._error=I(t,this._lang,s("save_error",this._lang))}finally{this._loading=!1}}}_close(){this._open=!1,this._pickerProbeTimer!==void 0&&(clearTimeout(this._pickerProbeTimer),this._pickerProbeTimer=void 0),this._pickerProbeStrikes=0}_renderTriggerFields(){if(this._scheduleType!=="sensor_based")return c;let t=this._lang,e=this._triggerType==="compound";return a`
${s("trigger_configuration",t)}
${s("trigger_type",t)}
this._triggerType=i.target.value}
>
${Nt.map(i=>a`${s(i,t)} `)}
${e?this._renderCompoundEditor():a`
${this._entityPickerFallback?a`
0?this._triggerEntityIds.join(", "):this._triggerEntityId}
@input=${i=>{let d=i.target.value.split(",").map(p=>p.trim()).filter(Boolean);this._triggerEntityId=d[0]||"",this._triggerEntityIds=d,d[0]&&this._fetchEntityAttributes(d[0])}}
>
`:a`
0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}}
.computeLabel=${()=>s("entity_id",t)}
@value-changed=${i=>{let n=(i.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=n[0]||"",this._triggerEntityIds=n,n[0]?this._fetchEntityAttributes(n[0]):this._fetchEntityAttributes("")}}
> `}
${this._triggerEntityIds.length>1?a`
${s("entity_logic",t)}
this._triggerEntityLogic=i.target.value}
>
${s("entity_logic_any",t)}
${s("entity_logic_all",t)}
`:c}
${this._renderAttributeSelect({label:s("attribute_optional",t),value:this._triggerAttribute,suggested:this._suggestedAttributes,available:this._availableAttributes,onSelect:i=>this._triggerAttribute=i})}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
this._autoCompleteOnRecovery=i.target.checked}
/>
${s("auto_complete_on_recovery",t)}
${s("auto_complete_on_recovery_help",t)}
this._intervalDays=i.target.value}
>
${this._intervalDays?this._renderUnitSelect():c}
${this._intervalDays?a`
${s("trigger_combinator",t)}
this._triggerCombinator=i.target.value}
>
${s("trigger_combinator_any",t)}
${s("trigger_combinator_all",t)}
`:c}
`}_patchCondition(t,e){this._compoundConditions=this._compoundConditions.map((i,n)=>n===t?{...i,...e}:i)}_addCondition(){this._compoundConditions=[...this._compoundConditions,Ft()]}_removeCondition(t){this._compoundConditions=this._compoundConditions.filter((e,i)=>i!==t)}_renderCompoundEditor(){let t=this._lang;return a`
${s("compound_logic",t)}
this._compoundLogic=e.target.value}
>
${s("compound_logic_and",t)}
${s("compound_logic_or",t)}
${s("compound_help",t)}
${this._compoundConditions.length===0?a`${s("compound_no_conditions",t)}
`:this._compoundConditions.map((e,i)=>this._renderCondition(e,i))}
this._addCondition()}>
+ ${s("compound_add_condition",t)}
`}_renderCondition(t,e){let i=this._lang,n=e+1;return a`
${s("compound_condition",i)} ${n}
this._removeCondition(e)}
>✕
${this._entityPickerFallback?a`
this._patchCondition(e,{entityIds:d.target.value})}
>
`:a`
d.trim()).filter(Boolean)}}
.computeLabel=${()=>s("entity_id",i)}
@value-changed=${d=>{let p=(d.detail.value.condition_entities||[]).filter(Boolean);this._patchCondition(e,{entityIds:p.join(", ")})}}
> `}
${this._renderConditionAttribute(t,e)}
${s("trigger_type",i)}
this._patchCondition(e,{type:d.target.value})}
>
${mt.map(d=>a`${s(d,i)} `)}
${this._renderConditionTypeFields(t,e)}
`}_renderStateField(t){return this._entityPickerFallback||!t.entityId?a`
t.onInput(e.target.value)}
>
`:a`
t.label}
@value-changed=${e=>t.onInput((e.detail.value.s||"").trim())}
>
`}_renderOnStatesField(t){let e=this._lang;return this._entityPickerFallback||!t.entityId?a`
t.onInput(i.target.value)}
>
`:a`
i.trim()).filter(Boolean)}}
.computeLabel=${()=>s("runtime_on_states",e)}
@value-changed=${i=>t.onInput((i.detail.value.s||[]).join(", "))}
>
`}_renderAdaptiveSection(t){return this._scheduleType==="one_time"||this._scheduleType==="manual"?c:a`
${s("adaptive_section_title",t)}
this._adaptiveEnabled=e.target.checked}
/>
${s("adaptive_enabled",t)}
${this._adaptiveEnabled?a`
this._adaptiveMin=e.target.value}
>
this._adaptiveMax=e.target.value}
>
this._adaptiveAlpha=e.target.value}
>
this._adaptiveSeasonal=e.target.checked}
/>
${s("adaptive_seasonal_enabled",t)}
this._adaptivePrediction=e.target.checked}
/>
${s("adaptive_prediction_enabled",t)}
`:c}
`}_renderAttributeSelect(t){let e=this._lang;return t.available.length>0?a`
${t.label}
t.onSelect(i.target.value)}
>
${s("use_entity_state",e)}
${t.suggested.map(i=>a`${i} ★ `)}
${t.available.filter(i=>!t.suggested.includes(i.name)).map(i=>a`${i.name}${i.numeric?"":" (non-numeric)"} `)}
`:a`
t.onSelect(i.target.value.trim())}
>
`}_renderEnvironmentalAttribute(t){this._fetchConditionAttributes(this._environmentalEntity);let e=this._conditionAttrOptions[this._environmentalEntity];return this._renderAttributeSelect({label:s("environmental_attribute_optional",t),value:this._environmentalAttribute,suggested:e?.suggested??[],available:e?.available??[],onSelect:i=>this._environmentalAttribute=i})}_renderConditionAttribute(t,e){let i=t.entityIds.split(",")[0]?.trim()||"";i&&this._fetchConditionAttributes(i);let n=i?this._conditionAttrOptions[i]:void 0;return this._renderAttributeSelect({label:s("attribute_optional",this._lang),value:t.attribute,suggested:n?.suggested??[],available:n?.available??[],onSelect:d=>this._patchCondition(e,{attribute:d})})}_renderConditionTypeFields(t,e){let i=this._lang;if(t.type==="threshold")return a`
this._patchCondition(e,{above:n.target.value})}>
this._patchCondition(e,{below:n.target.value})}>
this._patchCondition(e,{equals:n.target.value})}>
this._patchCondition(e,{notEquals:n.target.value})}>
this._patchCondition(e,{forMinutes:n.target.value})}>
`;if(t.type==="counter")return a`
this._patchCondition(e,{targetValue:n.target.value})}>
this._patchCondition(e,{deltaMode:n.target.checked})} />
${s("delta_mode",i)}
`;if(t.type==="state_change"){let n=t.entityIds.split(",")[0]?.trim()||"";return a`
${this._renderStateField({label:s("from_state_optional",i),value:t.fromState,entityId:n,onInput:d=>this._patchCondition(e,{fromState:d})})}
${this._renderStateField({label:s("to_state_optional",i),value:t.toState,entityId:n,onInput:d=>this._patchCondition(e,{toState:d})})}
this._patchCondition(e,{targetChanges:d.target.value})}>
`}if(t.type==="runtime"){let n=t.entityIds.split(",")[0]?.trim()||"";return a`
this._patchCondition(e,{runtimeHours:d.target.value})}>
${this._renderOnStatesField({value:t.onStates,entityId:n,onInput:d=>this._patchCondition(e,{onStates:d})})}
`}return c}_renderUnitSelect(){let t=this._lang;return a`
${s("interval_unit",t)}
this._intervalUnit=e.target.value}
>
${["days","weeks","months","years"].map(e=>a`${s("unit_"+e,t)} `)}
`}_toggleWeekday(t){this._weekdays=this._weekdays.includes(t)?this._weekdays.filter(e=>e!==t):[...this._weekdays,t]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(et.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let t=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!t||t<=0?null:{kind:"interval",every:t,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(t){super.updated?.(t),this._scheduleEntityPickerProbe();for(let e of t.keys())if(m._PREVIEW_RELEVANT.has(String(e))){this._schedulePreviewRefresh();return}}_scheduleEntityPickerProbe(){this._entityPickerFallback||this._pickerProbeTimer!==void 0||!this._open||this._scheduleType!=="sensor_based"||(this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),1500))}_probeEntityPickers(){if(this._pickerProbeTimer=void 0,this._entityPickerFallback||!this._open)return;let t=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),e=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!t||!e){this._pickerProbeStrikes=0;return}let i=(h,u,v=0)=>{if(!(!h||v>10)){(h.tagName?.toLowerCase()??"")==="ha-entity-picker"&&u.push(h);for(let b of[h.shadowRoot,h])if(b)for(let y of Array.from(b.children??[]))i(y,u,v+1)}},n=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],d=[];for(let h of n)i(h,d);let p=d.length===0||d.some(h=>h.offsetHeight===0);if(t.offsetHeight===0||p){if(this._pickerProbeStrikes+=1,this._pickerProbeStrikes>=2){this._entityPickerFallback=!0;return}this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),700)}else this._pickerProbeStrikes=0}_schedulePreviewRefresh(){this._previewTimer&&clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._fetchSchedulePreview()},300)}async _fetchSchedulePreview(){let t=this._open?this._previewScheduleDict():null;if(!t){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let e=++this._previewSeq;try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:t,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(e!==this._previewSeq)return;this._schedulePreview=i.occurrences||[],this._schedulePreviewEnded=!!i.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return c;let t=this._lang,e=this.scheduleTimeEnabled&&this._scheduleTime?` ${this._scheduleTime}`:"",i=this._schedulePreview.map((d,p)=>{let h=new Date(`${d}T12:00:00`).getDay();return`${X(h===0?6:h-1,t,"short")} ${z(d,t)}${p===0?e:""}`}).join(" \xB7 "),n=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?a`${s("schedule_preview_ontime",t)}
`:c;return a`
${s("schedule_preview_title",t)}: ${i}${this._schedulePreviewEnded?a` ${s("schedule_preview_ends",t)} `:c}
${n}
`}_buildSchedule(){let t=i=>{let n=parseInt(this._calOffset,10)||0;return n&&(i.offset=Math.max(-15,Math.min(n,15))),i};if(this._scheduleType==="weekdays")return t({kind:"weekdays",weekdays:[...this._weekdays].sort((i,n)=>i-n)});if(this._scheduleType==="nth_weekday")return t({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});let e={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(e.business=!0),t(e)}_recurrenceExtras(){let t={};if(this._seasonMonths.length&&(t.season_months=[...this._seasonMonths].sort((e,i)=>e-i)),this._endsMode==="count"){let e=parseInt(this._endsCount,10);e>=1&&(t.ends={count:e})}else this._endsMode==="until"&&this._endsUntil&&(t.ends={until:this._endsUntil});return t}_toggleSeasonMonth(t){this._seasonMonths=this._seasonMonths.includes(t)?this._seasonMonths.filter(e=>e!==t):[...this._seasonMonths,t]}_renderRecurrenceExtras(){let t=this._lang;if(!(this._scheduleType==="time_based"||et.includes(this._scheduleType)))return c;let i=jt(t);return a`
${s("season_window_label",t)}
${s("season_window_hint",t)}
${i.map((n,d)=>a`
this._toggleSeasonMonth(d+1)}
>${n} `)}
${s("series_end_label",t)}
this._endsMode=n.target.value}>
${s("series_end_never",t)}
${s("series_end_after_count",t)}
${s("series_end_until",t)}
${this._endsMode==="count"?a`
this._endsCount=n.target.value}
> `:c}
${this._endsMode==="until"?a`
this._endsUntil=n.target.value}
> `:c}
`}_renderCalendarFields(){let t=this._lang,e=Ut(t);if(this._scheduleType==="weekdays")return a`
${s("recurrence_on_days",t)}
${e.map((i,n)=>a`
this._toggleWeekday(n)}
>${i} `)}
${this._renderCalOffsetField()}`;if(this._scheduleType==="nth_weekday"){let i=[["1",s("ord_1",t)],["2",s("ord_2",t)],["3",s("ord_3",t)],["4",s("ord_4",t)],["5",s("ord_5",t)],["-1",s("ord_last",t)]];return a`
${s("recurrence_occurrence",t)}
this._nth=n.target.value}>
${i.map(([n,d])=>a`${d} `)}
${s("recurrence_weekday",t)}
this._nthWeekday=n.target.value}>
${e.map((n,d)=>a`${n} `)}
${this._renderCalOffsetField()}`}return this._scheduleType==="day_of_month"?a`
${this._domLastDay?c:a`
this._domDay=i.target.value}
> `}
this._domLastDay=i.target.checked} />
${s("recurrence_last_day",t)}
this._domBusiness=i.target.checked} />
${s("recurrence_business_day",t)}
${this._renderCalOffsetField()}`:c}_renderCalOffsetField(){let t=this._lang;return a`
this._calOffset=e.target.value}
> `}_renderTriggerLiveHint(){if(this._triggerType==="compound")return c;let t=this._triggerEntityId||this._triggerEntityIds[0];if(!t||!this.hass?.states)return c;let e=this.hass.states[t];if(!e)return c;let i=this._lang,n=e.attributes?.unit_of_measurement,d=typeof n=="string"&&n?` ${n}`:"",p=this._triggerAttribute?e.attributes?.[this._triggerAttribute]:e.state,h=typeof p=="number"?p:parseFloat(String(p)),u=p!=="unknown"&&p!=="unavailable"&&p!=null&&!isNaN(h),v=y=>Number.isInteger(y)?String(y):String(Math.round(y*10)/10),b=[];if(this._triggerType==="threshold"){let y=parseFloat(this._triggerAbove),$=parseFloat(this._triggerBelow);if(isNaN(y)&&isNaN($))return c;u&&b.push(s("trigger_hint_now",i).replace("{value}",v(h)+d)),isNaN(y)||b.push(s("trigger_hint_above",i).replace("{target}",v(y)+d)),isNaN($)||b.push(s("trigger_hint_below",i).replace("{target}",v($)+d))}else if(this._triggerType==="counter"){let y=parseFloat(this._triggerTargetValue);if(isNaN(y))return c;this._triggerDeltaMode?this._taskId?b.push(s("trigger_hint_counter_delta_edit",i).replace("{target}",v(y)+d)):u?b.push(s("trigger_hint_counter_delta",i).replace("{value}",v(h)+d).replace("{due}",v(h+y)+d).replace("{target}",v(y)+d)):b.push(s("trigger_hint_counter_delta_edit",i).replace("{target}",v(y)+d)):(u&&b.push(s("trigger_hint_now",i).replace("{value}",v(h)+d)),b.push(s("trigger_hint_counter_abs",i).replace("{target}",v(y)+d)))}else if(this._triggerType==="runtime"){let y=parseFloat(this._triggerRuntimeHours);if(isNaN(y))return c;b.push(s("trigger_hint_runtime",i).replace("{hours}",v(y))),b.push(s("trigger_hint_state_now",i).replace("{value}",String(e.state)))}else if(this._triggerType==="state_change"){let y=parseInt(this._triggerTargetChanges,10)||1,$=this._triggerToState.trim();b.push(($?s("trigger_hint_state_change_to",i).replace("{state}",$):s("trigger_hint_state_change",i)).replace("{count}",String(y))),b.push(s("trigger_hint_state_now",i).replace("{value}",String(e.state)))}return b.length?a`${b.join(" ")}
`:c}_renderTriggerTypeFields(){let t=this._lang;return this._triggerType==="threshold"?a`
this._triggerAbove=e.target.value}
>
this._triggerBelow=e.target.value}
>
this._triggerEquals=e.target.value}
>
this._triggerNotEquals=e.target.value}
>
this._triggerForMinutes=e.target.value}
>
`:this._triggerType==="counter"?a`
this._triggerTargetValue=e.target.value}
>
this._triggerDeltaMode=e.target.checked}
/>
${s("delta_mode",t)}
${this._triggerDeltaMode?a`
this._triggerBaselineValue=e.target.value}
>
${this._taskId?s("baseline_start_help_edit",t):s("baseline_start_help",t)}
${this._taskId&&this._liveBaselineValue!=null?a`
${s("baseline_current_effective",t).replace("{value}",String(this._liveBaselineValue))}
`:c}
`:c}
`:this._triggerType==="state_change"?a`
${this._renderStateField({label:s("from_state_optional",t),value:this._triggerFromState,entityId:this._triggerEntityId,onInput:e=>this._triggerFromState=e})}
${s("state_value_help",t)}
${this._renderStateField({label:s("to_state_optional",t),value:this._triggerToState,entityId:this._triggerEntityId,onInput:e=>this._triggerToState=e})}
this._triggerTargetChanges=e.target.value}
>
${s("target_changes_help",t)}
`:this._triggerType==="runtime"?a`
this._triggerRuntimeHours=e.target.value}
>
${this._renderOnStatesField({value:this._triggerOnStates,entityId:this._triggerEntityId,onInput:e=>this._triggerOnStates=e})}
${s("runtime_on_states_help",t)}
`:c}render(){if(!this._open)return a``;let t=this._lang,e=this._taskId?s("edit_task",t):s("new_task",t);return a`
${e}
${this._error?a`
${this._error}
`:c}
${this._objectChoices.length>0?a`
${s("object",t)}
{this._entryId=i.target.value,this._consumesParts={},this._loadParts(),this._loadForeignPools()}}
>
${this._objectChoices.map(i=>a`${i.name} `)}
`:c}
this._name=i.target.value}
>
${s("maintenance_type",t)}
this._type=i.target.value}
>
${Ht.map(i=>a`${s(i,t)} `)}
${this._type==="reading"?a`
this._readingUnit=i.target.value}
>
${s("reading_unit_help",t)}
`:c}
${this._partsLoadFailed?a`
${s("parts_load_failed",t)}
`:c}
${this.parts.length||this._foreignOwners.length?a`
${s("consumes_parts_label",t)}
${this.parts.map(i=>this._renderConsumesRow(i))}
${this._foreignOwners.length?a`
${s("shared_parts_other_objects",t)}
${s("shared_parts_help",t)}
${this._foreignOwners.map(i=>a`
${i.name}
${i.parts.map(n=>this._renderConsumesRow(n,i.entry_id))}
`)}
`:c}
`:c}
${s("priority",t)}
this._priority=i.target.value}
>
${qt.map(i=>a`${s("priority_"+i,t)} `)}
${s("schedule_type",t)}
this._scheduleType=i.target.value}
>
${Rt.map(i=>a`${s(i,t)} `)}
${this._scheduleType==="time_based"?a`
this._intervalDays=i.target.value}
>
${this._renderUnitSelect()}
${s("interval_anchor",t)}
this._intervalAnchor=i.target.value}
>
${s("anchor_completion",t)}
${s("anchor_planned",t)}
${this.scheduleTimeEnabled?a`
this._scheduleTime=i.target.value}
>
`:c}
`:c}
${this._renderCalendarFields()}
${this._scheduleType==="one_time"?a`
this._dueDate=i.target.value}
>
`:c}
${this._renderRecurrenceExtras()}
${this._renderSchedulePreview()}
this._warningDays=i.target.value}
>
this._earliestCompletionDays=i.target.value}
>
${this.checklistsEnabled?a`
${s("checklist_steps_optional",t)}
${s("checklist_help",t)}
`:c}
${s("require_on_completion",t)}
${ut.map(i=>a`
this._toggleRequired(i,n.target.checked)}
/>
${s(Y[i],t)}
`)}
this._lastPerformed=i.target.value}
>
${s("responsible_user",t)}
{let n=i.target.value;this._responsibleUserId=n||null}}
>
${s("no_user_assigned",t)}
${this._availableUsers.map(i=>a`${i.name} `)}
${this._availableUsers.length>=2?a`
${this._assigneePool.length>=2?a`
${s("rotation_strategy",t)}
this._rotationStrategy=i.target.value}
>
${s("rotation_none",t)}
${["round_robin","least_completed","random"].map(i=>a`${s("rotation_"+i,t)} `)}
`:c}
`:c}
${this._renderTriggerFields()}
${this._scheduleType==="sensor_based"?a`
${this._entityPickerFallback?a`
this._environmentalEntity=i.target.value.trim()}
>
`:a`
s("environmental_entity_optional",t)}
.computeHelper=${()=>s("environmental_entity_helper",t)}
@value-changed=${i=>{this._environmentalEntity=(i.detail.value.environmental_entity||"").trim()}}
> `}
${this._environmentalEntity?this._renderEnvironmentalAttribute(t):c}
`:c}
${this._renderAdaptiveSection(t)}
this._notes=i.target.value}
>
this._documentationUrl=i.target.value}
>
this._customIcon=i.detail.value||""}
>
${this._availableTags.length>0?a`
${s("nfc_tag_id_optional",t)}
this._nfcTagId=i.target.value}
>
${s("no_nfc_tag",t)}
${this._availableTags.map(i=>a`${i.name} `)}
↻
`:a`
this._nfcTagId=i.target.value}
>
`}
this._enabled=i.target.checked}
/>
${s("task_enabled",t)}
${this._renderCompletionActionsSection(t)}
${s("cancel",t)}
${this._loading?s("saving",t):s("save",t)}
`}};m._PREVIEW_RELEVANT=new Set(["_open","_scheduleType","_intervalDays","_intervalUnit","_intervalAnchor","_dueDate","_weekdays","_nth","_nthWeekday","_domDay","_domLastDay","_domBusiness","_calOffset","_seasonMonths","_endsMode","_endsCount","_endsUntil","_lastPerformed"]),m.styles=w`
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
/* #129: entity/state pickers in the trigger form (ha-form + selector) */
.entity-picker-form,
.state-picker-form {
display: block;
margin: 8px 0;
}
/* v1.3.0: completion-action sections (.adaptive-section shares the shell
but keeps its own class — tests count .ca-section elements) */
.ca-section,
.adaptive-section {
border: 1px solid var(--divider-color);
border-radius: 6px;
padding: 8px 12px;
margin-top: 8px;
}
.ca-section > summary,
.adaptive-section > summary {
cursor: pointer;
font-weight: 500;
}
.adaptive-section ms-textfield {
width: 100%;
margin-top: 8px;
display: block;
}
.adaptive-section label {
display: block;
margin-top: 8px;
}
.ca-section ms-textfield,
.ca-section ha-entity-picker,
.ca-section ha-service-picker,
.ca-section ha-form,
.ca-section .qc-feedback {
width: 100%;
margin-top: 8px;
display: block;
}
.ca-section .qc-feedback {
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
}
.ca-test-row {
display: flex;
align-items: center;
gap: 12px;
margin-top: 8px;
}
.ca-test-ok { color: var(--success-color, #4caf50); font-size: 13px; }
.ca-test-error { color: var(--error-color, #f44336); font-size: 13px; font-weight: 500; }
.ca-test-error-block { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.ca-test-error-detail {
font-size: 12px;
color: var(--secondary-text-color);
background: rgba(244, 67, 54, 0.08);
padding: 6px 8px; border-radius: 4px;
line-height: 1.4;
word-break: break-word;
}
.content {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 350px;
max-height: 70vh;
overflow-y: auto;
}
@media (max-width: 600px) {
.content {
min-width: 0;
max-height: none;
}
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
}
ms-textfield {
display: block;
}
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.checklist-textarea {
width: 100%;
min-height: 88px;
padding: 8px;
font-family: inherit;
font-size: 14px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
resize: vertical;
box-sizing: border-box;
}
.consumes-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
}
.consumes-check {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
}
.consumes-qty {
width: 64px;
padding: 4px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
/* #111: other objects' pools sit behind a disclosure so the object's OWN
parts stay the primary list; each group is headed by the owning object's
name, so which pool a checkbox means is never a guess. */
.shared-pools {
margin-top: 6px;
}
.shared-pools > summary {
cursor: pointer;
padding: 2px 0;
font-size: 13px;
color: var(--secondary-text-color);
}
.shared-pool-owner {
margin-top: 6px;
font-size: 12px;
font-weight: 500;
color: var(--secondary-text-color);
}
.field-help {
font-size: 12px;
color: var(--secondary-text-color);
}
.baseline-effective {
margin-top: 2px;
font-weight: 500;
color: var(--primary-text-color);
}
/* Live computed trigger hint — reads the bound sensor and explains what
happens next. Info-accented so it reads as guidance, not an error. */
.trigger-live-hint {
font-size: 12px;
color: var(--secondary-text-color);
border-left: 3px solid var(--info-color, #2196f3);
background: rgba(33, 150, 243, 0.08);
border-radius: 0 6px 6px 0;
padding: 6px 10px;
margin: 4px 0;
}
.field-help a,
.link-button {
background: none;
border: 0;
padding: 0;
color: var(--primary-color);
cursor: pointer;
font: inherit;
text-decoration: underline;
}
.field-help a:hover,
.link-button:hover {
text-decoration: none;
}
/* Smaller refresh icon-button when shown next to the dropdown. */
.select-row .link-button {
margin-left: 8px;
text-decoration: none;
font-size: 16px;
}
.select-row .link-button:hover {
color: var(--primary-color);
opacity: 0.7;
}
h3 {
margin: 8px 0 0;
font-size: 14px;
color: var(--primary-color);
}
.select-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.assignee-pool {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-top: 4px;
}
.checkbox-row {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
cursor: pointer;
margin: 2px 0;
}
.checkbox-row input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.pool-item {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
cursor: pointer;
}
.pool-item input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.select-row label {
font-size: 12px;
color: var(--secondary-text-color);
}
.select-row select {
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 14px;
}
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.weekday-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.weekday-chip {
padding: 6px 12px;
border: 1px solid var(--divider-color);
border-radius: 16px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
}
.weekday-chip.selected {
background: var(--primary-color, #03a9f4);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color, #03a9f4);
}
.season-chip {
padding: 6px 10px;
border: 1px solid var(--divider-color);
border-radius: 16px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
}
.season-chip.selected {
background: var(--primary-color, #03a9f4);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color, #03a9f4);
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
.toggle-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
cursor: pointer;
}
`,r([g({attribute:!1})],m.prototype,"hass",2),r([g({type:Boolean,attribute:"checklists-enabled"})],m.prototype,"checklistsEnabled",2),r([g({type:Boolean,attribute:"schedule-time-enabled"})],m.prototype,"scheduleTimeEnabled",2),r([g({type:Boolean,attribute:"completion-actions-enabled"})],m.prototype,"completionActionsEnabled",2),r([g({type:Number,attribute:"default-warning-days"})],m.prototype,"defaultWarningDays",2),r([l()],m.prototype,"parts",2),r([l()],m.prototype,"_foreignOwners",2),r([l()],m.prototype,"_open",2),r([l()],m.prototype,"_entityPickerFallback",2),r([l()],m.prototype,"_loading",2),r([l()],m.prototype,"_error",2),r([l()],m.prototype,"_entryId",2),r([l()],m.prototype,"_taskId",2),r([l()],m.prototype,"_objectChoices",2),r([l()],m.prototype,"_name",2),r([l()],m.prototype,"_type",2),r([l()],m.prototype,"_scheduleType",2),r([l()],m.prototype,"_intervalDays",2),r([l()],m.prototype,"_intervalUnit",2),r([l()],m.prototype,"_dueDate",2),r([l()],m.prototype,"_warningDays",2),r([l()],m.prototype,"_earliestCompletionDays",2),r([l()],m.prototype,"_intervalAnchor",2),r([l()],m.prototype,"_weekdays",2),r([l()],m.prototype,"_nth",2),r([l()],m.prototype,"_nthWeekday",2),r([l()],m.prototype,"_domDay",2),r([l()],m.prototype,"_domLastDay",2),r([l()],m.prototype,"_domBusiness",2),r([l()],m.prototype,"_calOffset",2),r([l()],m.prototype,"_seasonMonths",2),r([l()],m.prototype,"_endsMode",2),r([l()],m.prototype,"_endsCount",2),r([l()],m.prototype,"_endsUntil",2),r([l()],m.prototype,"_schedulePreview",2),r([l()],m.prototype,"_schedulePreviewEnded",2),r([l()],m.prototype,"_notes",2),r([l()],m.prototype,"_documentationUrl",2),r([l()],m.prototype,"_customIcon",2),r([l()],m.prototype,"_priority",2),r([l()],m.prototype,"_labels",2),r([l()],m.prototype,"_enabled",2),r([l()],m.prototype,"_triggerEntityId",2),r([l()],m.prototype,"_triggerEntityIds",2),r([l()],m.prototype,"_triggerEntityLogic",2),r([l()],m.prototype,"_triggerAttribute",2),r([l()],m.prototype,"_triggerType",2),r([l()],m.prototype,"_triggerAbove",2),r([l()],m.prototype,"_triggerBelow",2),r([l()],m.prototype,"_triggerEquals",2),r([l()],m.prototype,"_triggerNotEquals",2),r([l()],m.prototype,"_triggerForMinutes",2),r([l()],m.prototype,"_triggerCombinator",2),r([l()],m.prototype,"_triggerTargetValue",2),r([l()],m.prototype,"_triggerDeltaMode",2),r([l()],m.prototype,"_triggerBaselineValue",2),r([l()],m.prototype,"_liveBaselineValue",2),r([l()],m.prototype,"_autoCompleteOnRecovery",2),r([l()],m.prototype,"_triggerFromState",2),r([l()],m.prototype,"_triggerToState",2),r([l()],m.prototype,"_triggerTargetChanges",2),r([l()],m.prototype,"_triggerRuntimeHours",2),r([l()],m.prototype,"_triggerOnStates",2),r([l()],m.prototype,"_compoundLogic",2),r([l()],m.prototype,"_compoundConditions",2),r([l()],m.prototype,"_suggestedAttributes",2),r([l()],m.prototype,"_availableAttributes",2),r([l()],m.prototype,"_entityDomain",2),r([l()],m.prototype,"_lastPerformed",2),r([l()],m.prototype,"_nfcTagId",2),r([l()],m.prototype,"_readingUnit",2),r([l()],m.prototype,"_consumesParts",2),r([l()],m.prototype,"_partsLoadFailed",2),r([l()],m.prototype,"_availableTags",2),r([l()],m.prototype,"_responsibleUserId",2),r([l()],m.prototype,"_assigneePool",2),r([l()],m.prototype,"_rotationStrategy",2),r([l()],m.prototype,"_availableUsers",2),r([l()],m.prototype,"_checklistText",2),r([l()],m.prototype,"_requiredCompletion",2),r([l()],m.prototype,"_scheduleTime",2),r([l()],m.prototype,"_actionService",2),r([l()],m.prototype,"_actionTargetEntity",2),r([l()],m.prototype,"_actionData",2),r([l()],m.prototype,"_actionDataJsonFallback",2),r([l()],m.prototype,"_actionTesting",2),r([l()],m.prototype,"_actionTestResult",2),r([l()],m.prototype,"_actionTestError",2),r([l()],m.prototype,"_qcNotes",2),r([l()],m.prototype,"_qcCost",2),r([l()],m.prototype,"_qcDuration",2),r([l()],m.prototype,"_qcFeedback",2),r([l()],m.prototype,"_environmentalEntity",2),r([l()],m.prototype,"_environmentalAttribute",2),r([l()],m.prototype,"_adaptiveEnabled",2),r([l()],m.prototype,"_adaptiveAlpha",2),r([l()],m.prototype,"_adaptiveMin",2),r([l()],m.prototype,"_adaptiveMax",2),r([l()],m.prototype,"_adaptiveSeasonal",2),r([l()],m.prototype,"_adaptivePrediction",2),r([l()],m.prototype,"_conditionAttrOptions",2);var it=m;customElements.get("maintenance-task-dialog")||customElements.define("maintenance-task-dialog",it);var f=class extends E{constructor(){super(...arguments);this.entryId="";this.taskId="";this.taskName="";this.lang="en";this.checklist=[];this.adaptiveEnabled=!1;this.taskType="";this.readingUnit="";this.restockDefault=null;this.restockUnitCost=null;this.currencySymbol="";this.parts=[];this.consumesParts=[];this.consumesInfo=[];this.requiredFields=[];this._open=!1;this._notes="";this._cost="";this._duration="";this._loading=!1;this._error="";this._checklistState={};this._feedback="needed";this._photoDocId="";this._photoPreview="";this._photoUploading=!1;this._readingValue="";this._restockQty="";this._completedAt="";this._usedParts={};this.checklistPrefill={}}open(){this._open||(this._open=!0,this._notes="",this._cost="",this._duration="",this._error="",this._checklistState=Object.fromEntries(this.checklist.map((t,e)=>[String(e),!!this.checklistPrefill[t]]).filter(([,t])=>t)),this._feedback="needed",this._photoDocId="",this._photoPreview="",this._photoUploading=!1,this._readingValue="",this._restockQty=this.restockDefault!==null?String(this.restockDefault):"",this._completedAt="",this._usedParts=Object.fromEntries(this.consumesParts.map(t=>[O(t),{...t}])))}_toggleCheck(t){let e=String(t);this._checklistState={...this._checklistState,[e]:!this._checklistState[e]}}_setFeedback(t){this._feedback=t}async _onPhotoInput(t){let e=t.target,i=e.files?.[0];if(e.value="",!!i){this._photoUploading=!0,this._error="";try{let n=new FormData;n.append("entry_id",this.entryId),n.append("tags","photo"),n.append("file",i,i.name);let d=await fetch("/api/maintenance_supporter/document/upload",{method:"POST",headers:{Authorization:`Bearer ${this.hass.auth?.data?.access_token??""}`},body:n});if(!d.ok){this._error=d.status===413?s("doc_too_large",this.lang):s("doc_upload_failed",this.lang);return}let p=await d.json();p.id&&(this._photoDocId=p.id,this._photoPreview=URL.createObjectURL(i))}catch{this._error=s("doc_upload_failed",this.lang)}finally{this._photoUploading=!1}}}_removePhoto(){this._photoPreview&&URL.revokeObjectURL(this._photoPreview),this._photoDocId="",this._photoPreview=""}async _complete(){this._loading=!0,this._error="";try{let t={type:"maintenance_supporter/task/complete",entry_id:this.entryId,task_id:this.taskId};if(this._notes&&(t.notes=this._notes),this._cost){let e=parseFloat(this._cost);!isNaN(e)&&e>=0&&(t.cost=e)}if(this._duration){let e=parseInt(this._duration,10);!isNaN(e)&&e>=0&&(t.duration=e)}if(this.checklist.length>0&&(t.checklist_state=this._checklistState),this.adaptiveEnabled&&(t.feedback=this._feedback),this._photoDocId&&(t.photo_doc_id=this._photoDocId),this._completedAt){if(new Date(this._completedAt).getTime()>Date.now()){this._error=s("completed_at_future_error",this.lang),this._loading=!1;return}t.completed_at=this._completedAt.length===16?`${this._completedAt}:00`:this._completedAt}if(this._readingValue!==""){let e=parseFloat(this._readingValue);isNaN(e)||(t.reading_value=e)}if(this.restockDefault!==null&&this._restockQty!==""){let e=parseFloat(this._restockQty);!isNaN(e)&&e>=1&&(t.restock_quantity=e)}this.parts.length>0&&(t.used_parts=Object.values(this._usedParts).filter(e=>Number.isFinite(e.quantity)&&e.quantity>0).map(e=>e.entry_id?{part_id:e.part_id,quantity:e.quantity,entry_id:e.entry_id}:{part_id:e.part_id,quantity:e.quantity})),await this.hass.connection.sendMessagePromise(t),this._open=!1,this.dispatchEvent(new CustomEvent("task-completed"))}catch(t){this._error=I(t,this.lang,s("save_error",this.lang))}finally{this._loading=!1}}get _missingRequired(){let t={notes:this._notes.trim()!=="",cost:this._cost.trim()!=="",duration:this._duration.trim()!=="",photo:this._photoDocId!=="",user:!!this.hass?.user};return this.requiredFields.filter(e=>!t[e])}_req(t){return this.requiredFields.includes(t)?a`* `:c}_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 t=0,e=!1;for(let i of Object.values(this._usedParts)){let n=this.parts.find(d=>O({part_id:d.id,entry_id:d.entry_id})===O(i));n?.cost!=null&&(t+=n.cost*(i.quantity||1),e=!0)}return e?Math.round(t*100)/100:null}_renderCostSuggestion(t){if(this._cost.trim()!=="")return c;let e=this._partsCostSuggestion();if(e==null||e<=0)return c;let i=`${e.toFixed(2)}${this.currencySymbol?` ${this.currencySymbol}`:""}`;return a`this._cost=e.toFixed(2)}
>${s("cost_from_parts",t).replace("{amount}",i)} `}_close(){this._open=!1}render(){if(!this._open)return a``;let t=this.lang||this.hass?.language||"en";return a`
${s("complete_title",t)}${this.taskName}
${this._error?a`
${this._error}
`:c}
${this.checklist.length>0?a`
${s("checklist",t)}
${this.checklist.map((e,i)=>a`
this._toggleCheck(i)}>
${e}
`)}
`:c}
${this.taskType==="reading"?a`
${s("reading_value_label",t)}${this.readingUnit?` (${this.readingUnit})`:""}
this._readingValue=e.target.value} />
`:c}
${this.parts.length?a`
${s("complete_parts_used",t)}
${this.parts.map(e=>{let i=O({part_id:e.id,entry_id:e.entry_id}),n=this._usedParts[i],d=n!==void 0,p=e.entry_id?{part_id:e.id,quantity:1,entry_id:e.entry_id}:{part_id:e.id,quantity:1};return a`
{let u={...this._usedParts};h.target.checked?u[i]=u[i]||p:delete u[i],this._usedParts=u}} />
${e.name}${e.owner_name?a` (${e.owner_name}) `:c}${e.stock!==null&&e.stock!==void 0?` (${e.stock}${e.unit?" "+e.unit:""})`:""}
${d?a` {let u=parseFloat(h.target.value);this._usedParts={...this._usedParts,[i]:{...p,quantity:Number.isFinite(u)&&u>=.01?u:1}}}} />`:c}
`})}
`:this.consumesInfo.length?a`
${this.consumesInfo.map(e=>a`
${e}
`)}
`:c}
${this.restockDefault!==null?a`
${s("restock_quantity_label",t)}
this._restockQty=e.target.value} />
`:c}
${s("notes_optional",t)}${this._req("notes")}
this._notes=e.target.value} />
${s("cost_optional",t)}${this._req("cost")}
this._cost=e.target.value} />
${this._renderCostSuggestion(t)}
${s("duration_minutes",t)}${this._req("duration")}
this._duration=e.target.value} />
${s("completed_at_optional",t)}
this._completedAt=e.target.value} />
${s("completion_photo_optional",t)}${this._req("photo")}
${this._photoPreview?a`
✕
`:a`
${this._photoUploading?s("uploading",t):s("add_photo",t)}
`}
${this.adaptiveEnabled?a`
${s("was_maintenance_needed",t)}
this._setFeedback("needed")}
>${s("feedback_needed",t)}
this._setFeedback("not_needed")}
>${s("feedback_not_needed",t)}
this._setFeedback("not_sure")}
>${s("feedback_not_sure",t)}
`:c}
${s("cancel",t)}
0}
title=${this._missingRequired.length?this._missingRequired.map(e=>s("err_required",t).replace("{field}",s(Y[e]??e,t))).join(" \xB7 "):""}
>
${this._loading?s("completing",t):s("complete",t)}
`}};f.styles=[ct,w`
.req-mark {
color: var(--error-color, #f44336);
margin-left: 2px;
font-weight: 600;
}
/* #104: one-click cost suggestion from parts — quiet link-style chip. */
.cost-suggestion {
align-self: flex-start;
margin-top: 4px;
padding: 0;
border: none;
background: none;
color: var(--primary-color);
font-size: 12.5px;
cursor: pointer;
text-decoration: underline dotted;
text-underline-offset: 2px;
}
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
.content {
display: flex;
flex-direction: column;
gap: 16px;
min-width: 300px;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
}
.consumes-hint {
font-size: 13px;
color: var(--secondary-text-color);
border-left: 3px solid var(--primary-color);
padding: 4px 8px;
margin: 4px 0 8px;
}
/* #99: editable per-completion parts selection */
.used-parts { margin: 4px 0 8px; display: flex; flex-direction: column; gap: 4px; }
.used-part-row { display: flex; align-items: center; gap: 8px; }
.used-part-check {
display: flex; align-items: center; gap: 6px; flex: 1;
font-size: 13px; cursor: pointer;
}
.used-part-check input { cursor: pointer; }
/* #111: whose stock this row draws on. Muted but never omitted — an
unlabelled foreign pool is indistinguishable from an own part. */
.used-part-owner { color: var(--secondary-text-color); }
.used-part-qty {
width: 76px; padding: 4px 6px; border-radius: 4px; font: inherit; font-size: 13px;
border: 1px solid var(--divider-color);
background: var(--card-background-color);
color: var(--primary-text-color);
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
/* .field/.field-label/.field-input come from nativeFieldStyles */
.photo-pick {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px dashed var(--divider-color);
border-radius: 8px;
cursor: pointer;
font-size: 13px;
color: var(--secondary-text-color);
width: fit-content;
}
.photo-pick:hover { border-color: var(--primary-color); }
.photo-pick input[type="file"] { display: none; }
.photo-preview {
position: relative;
width: fit-content;
}
.photo-preview img {
max-width: 160px;
max-height: 160px;
border-radius: 8px;
display: block;
}
.photo-remove {
position: absolute;
top: -8px;
right: -8px;
width: 24px;
height: 24px;
border-radius: 50%;
border: none;
background: var(--error-color, #db4437);
color: #fff;
cursor: pointer;
font-size: 12px;
line-height: 1;
}
.checklist-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-bottom: 1px solid var(--divider-color);
margin-bottom: 4px;
}
.checklist-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.checklist-item {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
padding: 4px 0;
font-size: 14px;
}
.checklist-item input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
.feedback-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 0;
border-top: 1px solid var(--divider-color);
}
.feedback-label {
font-weight: 500;
font-size: 13px;
color: var(--secondary-text-color);
}
.feedback-buttons {
display: flex;
gap: 8px;
}
.feedback-btn {
flex: 1;
padding: 8px 12px;
border: 1px solid var(--divider-color);
border-radius: 8px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 13px;
cursor: pointer;
text-align: center;
transition: all 0.2s;
}
.feedback-btn:hover {
background: var(--secondary-background-color, #f5f5f5);
}
.feedback-btn.selected {
background: var(--primary-color);
color: var(--text-primary-color, #fff);
border-color: var(--primary-color);
}
`],r([g({attribute:!1})],f.prototype,"hass",2),r([g()],f.prototype,"entryId",2),r([g()],f.prototype,"taskId",2),r([g()],f.prototype,"taskName",2),r([g()],f.prototype,"lang",2),r([g({type:Array})],f.prototype,"checklist",2),r([g({type:Boolean})],f.prototype,"adaptiveEnabled",2),r([g()],f.prototype,"taskType",2),r([g()],f.prototype,"readingUnit",2),r([g({attribute:!1})],f.prototype,"restockDefault",2),r([g({attribute:!1})],f.prototype,"restockUnitCost",2),r([g()],f.prototype,"currencySymbol",2),r([g({attribute:!1})],f.prototype,"parts",2),r([g({attribute:!1})],f.prototype,"consumesParts",2),r([g({type:Array})],f.prototype,"consumesInfo",2),r([g({type:Array})],f.prototype,"requiredFields",2),r([l()],f.prototype,"_open",2),r([l()],f.prototype,"_notes",2),r([l()],f.prototype,"_cost",2),r([l()],f.prototype,"_duration",2),r([l()],f.prototype,"_loading",2),r([l()],f.prototype,"_error",2),r([l()],f.prototype,"_checklistState",2),r([l()],f.prototype,"_feedback",2),r([l()],f.prototype,"_photoDocId",2),r([l()],f.prototype,"_photoPreview",2),r([l()],f.prototype,"_photoUploading",2),r([l()],f.prototype,"_readingValue",2),r([l()],f.prototype,"_restockQty",2),r([l()],f.prototype,"_completedAt",2),r([l()],f.prototype,"_usedParts",2),r([g({attribute:!1})],f.prototype,"checklistPrefill",2);customElements.get("maintenance-complete-dialog")||customElements.define("maintenance-complete-dialog",f);var L=class extends E{constructor(){super(...arguments);this._open=!1;this._saving=!1;this._error="";this._draft=null;this._originalSnapshot=null;this._partOptions=null;this._partQty={};this._partQtyOriginal=""}get _lang(){return C(this.hass)}openEdit(t){this._draft={...t},this._originalSnapshot={...t},this._error="",this._open=!0,this._partOptions=null,this._partQty={},this._partQtyOriginal="",this._loadPartOptions()}async _loadPartOptions(){let t=this._draft;if(t)try{let e=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/parts/overview"}),i=[];for(let d of e.parts||[]){let p=d.entry_id===t.entry_id,h=d.consumers.some(u=>u.entry_id===t.entry_id&&u.task_id===t.task_id);!p&&!h||i.push({part_id:d.part_id,name:d.name,entry_id:d.entry_id,foreign:!p,object_name:d.object_name})}for(let d of t.used_parts||[]){let p=d.entry_id||t.entry_id;i.some(h=>h.part_id===d.part_id&&h.entry_id===p)||i.push({part_id:d.part_id,name:d.name||d.part_id,entry_id:p,foreign:p!==t.entry_id,object_name:null})}let n={};for(let d of t.used_parts||[])n[`${d.entry_id||t.entry_id}:${d.part_id}`]=d.quantity??1;this._partOptions=i,this._partQty=n,this._partQtyOriginal=this._partSelectionKey()}catch{this._partOptions=[]}}_partSelectionKey(){return JSON.stringify(Object.entries(this._partQty).filter(([,t])=>t>0).sort(([t],[e])=>t.localeCompare(e)))}close(){this._open=!1,this._error="",this._draft=null,this._originalSnapshot=null}_set(t,e){this._draft&&(this._draft={...this._draft,[t]:e})}async _save(){if(!(!this._draft||!this._originalSnapshot)){this._saving=!0,this._error="";try{let t={type:"maintenance_supporter/task/history/update",entry_id:this._draft.entry_id,task_id:this._draft.task_id,original_timestamp:this._originalSnapshot.original_timestamp};if(this._draft.timestamp!==this._originalSnapshot.timestamp&&(t.timestamp=this._draft.timestamp),this._draft.notes!==this._originalSnapshot.notes&&(t.notes=this._draft.notes),this._draft.cost!==this._originalSnapshot.cost&&(t.cost=this._draft.cost),this._draft.duration!==this._originalSnapshot.duration&&(t.duration=this._draft.duration),this._draft.completed_by!==this._originalSnapshot.completed_by&&(t.completed_by=this._draft.completed_by),this._partOptions!==null&&this._partSelectionKey()!==this._partQtyOriginal&&(t.used_parts=(this._partOptions||[]).filter(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}:{}}))),Object.keys(t).filter(i=>!["type","entry_id","task_id","original_timestamp"].includes(i)).length===0){this.close();return}await this.hass.connection.sendMessagePromise(t),this.dispatchEvent(new CustomEvent("history-entry-saved",{detail:{entry_id:this._draft.entry_id,task_id:this._draft.task_id,new_timestamp:this._draft.timestamp},bubbles:!0,composed:!0})),this.close()}catch(t){this._error=I(t,this._lang)}finally{this._saving=!1}}}render(){if(!this._open||!this._draft)return c;let t=this._lang,e=this._draft;return a`
${s("history_edit_title",t)||"Edit history entry"}
${s(e.type,t)||e.type}
${s("history_edit_timestamp",t)||"Timestamp"}
=16?e.timestamp.slice(0,16):e.timestamp}
@change=${i=>{let n=i.target.value;this._set("timestamp",n.length===16?`${n}:00`:n)}} />
${s("notes_label",t)}
${s("cost",t)||"Cost"}
{let n=i.target.value;this._set("cost",n?Number(n):null)}} />
${s("duration",t)||"Duration (min)"}
{let n=i.target.value;this._set("duration",n?Number(n):null)}} />
${this._partOptions&&this._partOptions.length>0?a`
${s("complete_parts_used",t)}
${this._partOptions.map(i=>{let n=`${i.entry_id}:${i.part_id}`,d=this._partQty[n]||0;return a`
0}
@change=${p=>{let h=p.target.checked;this._partQty={...this._partQty,[n]:h?1:0}}} />
${i.name}${i.foreign&&i.object_name?` (${i.object_name})`:""}
${d>0?a`
{let h=parseFloat(p.target.value);!isNaN(h)&&h>0&&(this._partQty={...this._partQty,[n]:h})}} />
`:c}
`})}
`:c}
${this._error?a`
${this._error}
`:c}
${s("cancel",t)||"Cancel"}
${this._saving?s("saving",t)||"Saving\u2026":s("save",t)||"Save"}
`}};L.styles=w`
:host { display: contents; }
.backdrop {
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
z-index: 100;
}
.dialog {
position: fixed; left: 50%; top: 50%;
transform: translate(-50%, -50%);
width: 95vw; max-width: 480px;
background: var(--card-background-color, var(--ha-card-background, #1c1c1c));
color: var(--primary-text-color);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.4);
padding: 20px;
display: flex; flex-direction: column; gap: 12px;
z-index: 101;
max-height: 90vh; overflow: auto;
}
h2 { margin: 0; font-size: 18px; }
.entry-type {
display: flex; align-items: center; gap: 6px;
color: var(--secondary-text-color); font-size: 13px;
}
label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
label span { color: var(--secondary-text-color); }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
input, textarea {
padding: 8px; font-size: 14px;
background: var(--secondary-background-color, #2c2c2c);
color: var(--primary-text-color);
border: 1px solid var(--divider-color, #444);
border-radius: 6px;
width: 100%; box-sizing: border-box;
font-family: inherit;
}
.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; }
`,r([g({attribute:!1})],L.prototype,"hass",2),r([l()],L.prototype,"_open",2),r([l()],L.prototype,"_saving",2),r([l()],L.prototype,"_error",2),r([l()],L.prototype,"_draft",2),r([l()],L.prototype,"_partOptions",2),r([l()],L.prototype,"_partQty",2);customElements.get("maintenance-history-edit-dialog")||customElements.define("maintenance-history-edit-dialog",L);function D(o){return o.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function gt(o){return!o.startsWith("data:image/svg+xml,")&&!o.startsWith("data:image/png;base64,")?"":D(o)}function Dt(o){return o.replace(/[/\\:*?"<>|#%]+/g,"").replace(/\s+/g,"-").toLowerCase().substring(0,100)}var S=class extends E{constructor(){super(...arguments);this.lang="en";this._open=!1;this._loading=!1;this._error="";this._viewResult=null;this._completeResult=null;this._urlMode="companion";this._entryId="";this._taskId=null;this._objectName="";this._taskName="";this._generateSeq=0}openForObject(t,e){this._entryId=t,this._taskId=null,this._objectName=e,this._taskName="",this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}openForTask(t,e,i,n){this._entryId=t,this._taskId=e,this._objectName=i,this._taskName=n,this._urlMode="companion",this._error="",this._viewResult=null,this._completeResult=null,this._open=!0,this._generate()}async _generate(){let t=++this._generateSeq;this._loading=!0,this._error="",this._viewResult=null,this._completeResult=null;try{let e={type:"maintenance_supporter/qr/generate",entry_id:this._entryId,url_mode:this._urlMode};this._taskId&&(e.task_id=this._taskId);let i=[this.hass.connection.sendMessagePromise({...e,action:"view"})];this._taskId&&i.push(this.hass.connection.sendMessagePromise({...e,action:"complete"}));let n=await Promise.all(i);if(t!==this._generateSeq)return;this._viewResult=n[0],n.length>1&&(this._completeResult=n[1])}catch(e){if(t!==this._generateSeq)return;let i=e?.code,n=e?.message;this._error=i==="no_url"||typeof n=="string"&&n.includes("No Home Assistant URL")?s("qr_error_no_url",this.lang):s("qr_error",this.lang)}finally{t===this._generateSeq&&(this._loading=!1)}}_setUrlMode(t){this._urlMode!==t&&(this._urlMode=t,this._generate())}_print(){if(!this._viewResult)return;let t=this._viewResult,e=t.label.task_name?`${t.label.object_name} \u2014 ${t.label.task_name}`:t.label.object_name,i=[t.label.manufacturer,t.label.model].filter(Boolean).join(" "),n=window.open("","_blank","width=600,height=500");if(!n)return;let d=this.lang||"en",p=D(e),h=D(i),u=!!this._completeResult,v=D(s("qr_action_view",d)),b=D(s("qr_action_complete",d));n.document.write(`
${p}
${p}
${h?`${h}
`:""}
${v}
${u?`
${b}
`:""}
${D(this._viewResult.url)}