@ssgc/alert-console 2.4.1 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),c=require("antd"),Me=require("@ant-design/icons"),pe=require("react-toastify");function ks(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const de=ks(u),Es="#FF3B30",Ms="#FF9500",Os="#FFCC00",Ps="#34C759",qe={critical:Es,high:Ms,medium:Os,low:Ps},Tt={Critical:qe.critical,High:qe.high,Medium:qe.medium,Low:qe.low};function Ds(e){return Tt[e]||Tt.Low}function It(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),f=Number.isFinite(a)?a:0,h=Number.isFinite(o)?o:0,d=Number.isFinite(l)?l:0;return f*3600+h*60+d}function Rt(e){const t=e.thirdPartyIds??e.ThirdPartyIds??e.thirdPartyId??e.ThirdPartyId??"",s=Array.isArray(t)?t.join(","):String(t??"");if(!s||!s.trim())return[];const r=s.split(",").map(o=>parseInt(String(o).trim(),10)).filter(o=>Number.isFinite(o)),i=new Set,a=[];return r.forEach(o=>{i.has(o)||(i.add(o),a.push(o))}),a}const Zt="",Fs=Zt,Us="",Ls="",kt={snl:{alerts:Zt,rules:Fs},schools:{alerts:Us,rules:Ls}};function be(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function $s(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function _e(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function Se(e,t){const s={...t.headers,...$s()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Bs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=be(e.baseUrl,"/api/Alert"),r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=be(e.baseUrl,"/api/Alert/AlertStatusList"),r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]},async getAlertsReport(s){const r=be(e.baseUrl,"/Alerts/GetAlertsReport"),i=_e(r,s),a=await Se(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=be(e.baseUrl,"/api/Alert/status");return Se(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=be(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await Se(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=be(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return Se(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=be(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await Se(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=be(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await Se(r,{method:"POST",headers:t,body:JSON.stringify(s??{})}),a=i?.responseStatus??!0,o=i?.data??i?.message??"Preferences updated successfully.";return{responseStatus:a,errorMessage:a?"":i?.errorMessage??i?.message??"",statusCode:200,data:o}},async getAlertNotifications(s){const r=be(e.baseUrl,"/api/Alert/GetNotifications"),i=_e(r,{alertId:s}),a=await Se(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]},async notifyFamilyMembers(s){const r=be(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=_e(r,{alertId:s});return Se(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=be(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=_e(a,{alertId:s,isEmail:r,isSMS:i});return Se(o,{method:"POST",headers:t})},async getTimeZoneMasters(){const s=be(e.baseUrl,"/api/UserPreference/GetTimeZoneMasters"),r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]}}}function Et(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function qs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Qe(e,t){const s={...t.headers,...qs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function _s(e){const t={"Content-Type":"application/json",...e.headers||{}},s=Et(e.baseUrl,"/api/Rules"),r=Et(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Qe(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Qe(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Qe(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Qe(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Qs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ke={exports:{}},Hs=Ke.exports,Mt;function Gs(){return Mt||(Mt=1,(function(e,t){(function(s,r){e.exports=r()})(Hs,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",f="hour",h="day",d="week",A="month",m="quarter",I="year",w="date",p="Invalid Date",S=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,$=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,F={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(k){var x=["th","st","nd","rd"],y=k%100;return"["+k+(x[(y-20)%10]||x[y]||x[0])+"]"}},L=function(k,x,y){var j=String(k);return!j||j.length>=x?k:""+Array(x+1-j.length).join(y)+k},E={s:L,z:function(k){var x=-k.utcOffset(),y=Math.abs(x),j=Math.floor(y/60),g=y%60;return(x<=0?"+":"-")+L(j,2,"0")+":"+L(g,2,"0")},m:function k(x,y){if(x.date()<y.date())return-k(y,x);var j=12*(y.year()-x.year())+(y.month()-x.month()),g=x.clone().add(j,A),b=y-g<0,v=x.clone().add(j+(b?-1:1),A);return+(-(j+(y-g)/(b?g-v:v-g))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:A,y:I,w:d,d:h,D:w,h:f,m:l,s:o,ms:a,Q:m}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},z="en",H={};H[z]=F;var W="$isDayjsObject",Y=function(k){return k instanceof K||!(!k||!k[W])},T=function k(x,y,j){var g;if(!x)return z;if(typeof x=="string"){var b=x.toLowerCase();H[b]&&(g=b),y&&(H[b]=y,g=b);var v=x.split("-");if(!g&&v.length>1)return k(v[0])}else{var M=x.name;H[M]=x,g=M}return!j&&g&&(z=g),g||!j&&z},C=function(k,x){if(Y(k))return k.clone();var y=typeof x=="object"?x:{};return y.date=k,y.args=arguments,new K(y)},R=E;R.l=T,R.i=Y,R.w=function(k,x){return C(k,{locale:x.$L,utc:x.$u,x:x.$x,$offset:x.$offset})};var K=(function(){function k(y){this.$L=T(y.locale,null,!0),this.parse(y),this.$x=this.$x||y.x||{},this[W]=!0}var x=k.prototype;return x.parse=function(y){this.$d=(function(j){var g=j.date,b=j.utc;if(g===null)return new Date(NaN);if(R.u(g))return new Date;if(g instanceof Date)return new Date(g);if(typeof g=="string"&&!/Z$/i.test(g)){var v=g.match(S);if(v){var M=v[2]-1||0,D=(v[7]||"0").substring(0,3);return b?new Date(Date.UTC(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,D)):new Date(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,D)}}return new Date(g)})(y),this.init()},x.init=function(){var y=this.$d;this.$y=y.getFullYear(),this.$M=y.getMonth(),this.$D=y.getDate(),this.$W=y.getDay(),this.$H=y.getHours(),this.$m=y.getMinutes(),this.$s=y.getSeconds(),this.$ms=y.getMilliseconds()},x.$utils=function(){return R},x.isValid=function(){return this.$d.toString()!==p},x.isSame=function(y,j){var g=C(y);return this.startOf(j)<=g&&g<=this.endOf(j)},x.isAfter=function(y,j){return C(y)<this.startOf(j)},x.isBefore=function(y,j){return this.endOf(j)<C(y)},x.$g=function(y,j,g){return R.u(y)?this[j]:this.set(g,y)},x.unix=function(){return Math.floor(this.valueOf()/1e3)},x.valueOf=function(){return this.$d.getTime()},x.startOf=function(y,j){var g=this,b=!!R.u(j)||j,v=R.p(y),M=function(he,ee){var oe=R.w(g.$u?Date.UTC(g.$y,ee,he):new Date(g.$y,ee,he),g);return b?oe:oe.endOf(h)},D=function(he,ee){return R.w(g.toDate()[he].apply(g.toDate("s"),(b?[0,0,0,0]:[23,59,59,999]).slice(ee)),g)},U=this.$W,B=this.$M,q=this.$D,se="set"+(this.$u?"UTC":"");switch(v){case I:return b?M(1,0):M(31,11);case A:return b?M(1,B):M(0,B+1);case d:var ie=this.$locale().weekStart||0,ae=(U<ie?U+7:U)-ie;return M(b?q-ae:q+(6-ae),B);case h:case w:return D(se+"Hours",0);case f:return D(se+"Minutes",1);case l:return D(se+"Seconds",2);case o:return D(se+"Milliseconds",3);default:return this.clone()}},x.endOf=function(y){return this.startOf(y,!1)},x.$set=function(y,j){var g,b=R.p(y),v="set"+(this.$u?"UTC":""),M=(g={},g[h]=v+"Date",g[w]=v+"Date",g[A]=v+"Month",g[I]=v+"FullYear",g[f]=v+"Hours",g[l]=v+"Minutes",g[o]=v+"Seconds",g[a]=v+"Milliseconds",g)[b],D=b===h?this.$D+(j-this.$W):j;if(b===A||b===I){var U=this.clone().set(w,1);U.$d[M](D),U.init(),this.$d=U.set(w,Math.min(this.$D,U.daysInMonth())).$d}else M&&this.$d[M](D);return this.init(),this},x.set=function(y,j){return this.clone().$set(y,j)},x.get=function(y){return this[R.p(y)]()},x.add=function(y,j){var g,b=this;y=Number(y);var v=R.p(j),M=function(B){var q=C(b);return R.w(q.date(q.date()+Math.round(B*y)),b)};if(v===A)return this.set(A,this.$M+y);if(v===I)return this.set(I,this.$y+y);if(v===h)return M(1);if(v===d)return M(7);var D=(g={},g[l]=r,g[f]=i,g[o]=s,g)[v]||1,U=this.$d.getTime()+y*D;return R.w(U,this)},x.subtract=function(y,j){return this.add(-1*y,j)},x.format=function(y){var j=this,g=this.$locale();if(!this.isValid())return g.invalidDate||p;var b=y||"YYYY-MM-DDTHH:mm:ssZ",v=R.z(this),M=this.$H,D=this.$m,U=this.$M,B=g.weekdays,q=g.months,se=g.meridiem,ie=function(ee,oe,xe,ye){return ee&&(ee[oe]||ee(j,b))||xe[oe].slice(0,ye)},ae=function(ee){return R.s(M%12||12,ee,"0")},he=se||function(ee,oe,xe){var ye=ee<12?"AM":"PM";return xe?ye.toLowerCase():ye};return b.replace($,(function(ee,oe){return oe||(function(xe){switch(xe){case"YY":return String(j.$y).slice(-2);case"YYYY":return R.s(j.$y,4,"0");case"M":return U+1;case"MM":return R.s(U+1,2,"0");case"MMM":return ie(g.monthsShort,U,q,3);case"MMMM":return ie(q,U);case"D":return j.$D;case"DD":return R.s(j.$D,2,"0");case"d":return String(j.$W);case"dd":return ie(g.weekdaysMin,j.$W,B,2);case"ddd":return ie(g.weekdaysShort,j.$W,B,3);case"dddd":return B[j.$W];case"H":return String(M);case"HH":return R.s(M,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return he(M,D,!0);case"A":return he(M,D,!1);case"m":return String(D);case"mm":return R.s(D,2,"0");case"s":return String(j.$s);case"ss":return R.s(j.$s,2,"0");case"SSS":return R.s(j.$ms,3,"0");case"Z":return v}return null})(ee)||v.replace(":","")}))},x.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},x.diff=function(y,j,g){var b,v=this,M=R.p(j),D=C(y),U=(D.utcOffset()-this.utcOffset())*r,B=this-D,q=function(){return R.m(v,D)};switch(M){case I:b=q()/12;break;case A:b=q();break;case m:b=q()/3;break;case d:b=(B-U)/6048e5;break;case h:b=(B-U)/864e5;break;case f:b=B/i;break;case l:b=B/r;break;case o:b=B/s;break;default:b=B}return g?b:R.a(b)},x.daysInMonth=function(){return this.endOf(A).$D},x.$locale=function(){return H[this.$L]},x.locale=function(y,j){if(!y)return this.$L;var g=this.clone(),b=T(y,j,!0);return b&&(g.$L=b),g},x.clone=function(){return R.w(this.$d,this)},x.toDate=function(){return new Date(this.valueOf())},x.toJSON=function(){return this.isValid()?this.toISOString():null},x.toISOString=function(){return this.$d.toISOString()},x.toString=function(){return this.$d.toUTCString()},k})(),X=K.prototype;return C.prototype=X,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",h],["$M",A],["$y",I],["$D",w]].forEach((function(k){X[k[1]]=function(x){return this.$g(x,k[0],k[1])}})),C.extend=function(k,x){return k.$i||(k(x,K,C),k.$i=!0),C},C.locale=T,C.isDayjs=Y,C.unix=function(k){return C(1e3*k)},C.en=H[z],C.Ls=H,C.p={},C}))})(Ke)),Ke.exports}var Ws=Gs();const Vt=Qs(Ws);function Jt(e){if(!e)return"By Severity";const t=e.trim().toLowerCase();return t.includes("created")?"By Created Date":t.includes("updated")||t.includes("modified")?"By Updated Date":"By Severity"}function Xt(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function Ot(e){const{hours:t,minutes:s,seconds:r}=Xt(e);return Vt().hour(t).minute(s).second(r).millisecond(0)}function Ce(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ks(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Pt(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function Te(e,t){const s={...t.headers,...Ks()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const ne=(...e)=>e.find(t=>t!=null);function Ys(e){return{id:String(ne(e?.AlertId,e?.alertId)??""),priority:ne(e?.Priority,e?.priority,"Low"),timestamp:ne(e?.Timestamp,e?.timestamp,""),statusType:ne(e?.Status,e?.statusType,""),description:ne(e?.Description,e?.description,""),eventName:ne(e?.EventName,e?.eventName),ruleName:ne(e?.RuleName,e?.ruleName),spaceName:ne(e?.SpaceName,e?.spaceName),assignTeam:ne(e?.AssignTeam,e?.assignTeam),cameraName:ne(e?.CameraName,e?.cameraName),type:ne(e?.Type,e?.type),mediaDetails:ne(e?.MediaDetails,e?.mediaDetails),additionalMedia:ne(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ne(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ne(e?.TimeRemaining,e?.timeRemaining),anomalyName:ne(e?.AnomalyName,e?.anomalyName),alertDetails:ne(e?.AlertDetails,e?.alertDetails),statusHistory:ne(e?.StatusHistory,e?.statusHistory),isEmailSent:ne(e?.IsEmailSent,e?.isEmailSent),isSMSSent:ne(e?.IsSMSSent,e?.isSMSSent),timeZoneUniqueId:ne(e?.TimeZoneUniqueId,e?.timeZoneUniqueId)}}function zs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(Ys):[]},async getAlertStatusList(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Pt(r,s),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/Log"),i={AlertId:s.alertId??s.alertUniqueId??s.AlertId,Status:s.status??s.Status??"",Notes:s.notes??s.Notes??""};return Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await Te(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await Te(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=h=>{const{hours:d,minutes:A,seconds:m}=Xt(h);return(d*3600+A*60+m)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(h=>String(h)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await Te(r,{method:"POST",headers:t,body:JSON.stringify(a)}),l=o?.responseStatus??!0,f=o?.data??o?.message??"Preferences updated successfully.";return{responseStatus:l,errorMessage:l?"":o?.errorMessage??o?.Message??o?.message??"",statusCode:200,data:f}},async getAlertNotifications(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Pt(r,{alertId:s}),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function Zs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Re(e,t){const s={...t.headers,...Zs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Vs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Re(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Re(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=E=>new URL(E,e.baseUrl).toString(),i=[Re(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,h]=await Promise.allSettled(i),d=E=>E.status==="fulfilled"&&Array.isArray(E.value)?E.value:[],A=d(a),m=d(o),I=d(l),w=d(f),p=d(h),S=A.map(E=>({actionTypeId:Number(E?.ActionTypeId),name:E?.DisplayName??E?.Name??""})),$=m.map(E=>({recordId:E?.AnomalyId,anomalyName:E?.DisplayName??E?.Name??""})),F=I.map(E=>({thirdPartyId:Number(E?.ThirdPartyId),thirdPartyName:E?.ThirdPartyName??E?.Name??""})),L={actionTypes:S,anomalies:$,thirdParties:F};return w.length&&(L.severities=w),p.length&&(L.scheduleTypes=p),L},async updateRule(r,i){const a=`${s}/${r}`;return Re(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const es=u.createContext(null);function ts({tenant:e="snl",override:t,children:s}){const r=u.useMemo(()=>{const a=t?.alertsBaseUrl?.trim()||kt[e]?.alerts||"";let o=t?.rulesBaseUrl?.trim()||kt[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=u.useMemo(()=>{const a=r.tenant==="schools"?zs({baseUrl:r.alertsBaseUrl,headers:r.headers}):Bs({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Vs({baseUrl:r.rulesBaseUrl,headers:r.headers}):_s({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(es.Provider,{value:i,children:s})}function ve(){const e=u.useContext(es);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Js={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Xs={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},ft=6,mt=7;function Dt(e,t,s){const r=e===ft,i=e===mt,a=t.isEmailSent??!1,o=t.isSMSSent??!1,l=r&&a||i&&o,f=r?"Send Email":i?"Send SMS":s,h=r&&a?"Email sent":i&&o?"SMS sent":f,d=r&&a?"Email sent":i&&o?"SMS sent":`Click to ${f}`;return{isDisabled:l,buttonText:h,tooltipTitle:d}}function er(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function tr(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function rt(e,t){return`${e}-${t?"email":"sms"}`}function He(e){return e===ft||e===mt}function Ve({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const sr=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function rr({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[140px]",value:e,onChange:t,options:s||sr})}const nr=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function ir({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||nr})}function ar({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const or=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function lr({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[130px]",value:e,onChange:t,options:s||or})}function ss({columns:e,data:t,loading:s=!1,pageSize:r=10,rowKey:i="id",toolbar:a,tableProps:o}){return n.jsxs("div",{children:[a,n.jsx(c.Table,{rowKey:i,dataSource:t,columns:e,loading:s,pagination:{pageSize:r,showSizeChanger:!0,showTotal:l=>`Total: ${l}`},bordered:!0,...o})]})}function pt({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:f,excludeCompleted:h=!0}){const[d,A]=u.useState("All"),[m,I]=u.useState("All"),[w,p]=u.useState("All"),[S,$]=u.useState("All"),[F,L]=u.useState(""),[E,z]=u.useState([{label:"All",value:"All"}]),[H,W]=u.useState(new Set),{rules:Y,alerts:T}=ve(),C={6:{title:"Email",kind:"icon",icon:n.jsx(Me.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Me.MessageOutlined,{})}},R=u.useMemo(()=>er(e),[e]),K=u.useMemo(()=>tr(e),[e]);u.useEffect(()=>{let b=!0;return(async()=>{try{const v=await Y.getLookups(),D=(Array.isArray(v.thirdParties)?v.thirdParties:[]).map(U=>({label:U.thirdPartyName,value:String(U.thirdPartyId)}));b&&z([{label:"All",value:"All"},...D])}catch(v){console.error("Error loading third party options",v)}})(),()=>{b=!1}},[Y]);const X=u.useMemo(()=>(e||[]).some(b=>Rt(b).length>0),[e]),k=u.useMemo(()=>(e||[]).filter(b=>{const v=d==="All"||b.priority===d,M=`${b.id} ${b.description} ${b.statusType}`.toLowerCase(),D=!F||M.includes(F.toLowerCase()),U=m==="All"||(b.anomalyName||"").toLowerCase()===m.toLowerCase(),B=w==="All"||(b.spaceName||"").toLowerCase()===w.toLowerCase(),q=!X||S==="All"||Rt(b).includes(Number(S)),se=!h||!["completed","false positive"].includes(String(b.statusType||"").toLowerCase());return v&&D&&U&&B&&q&&se}),[e,d,F,m,w,S,X,h]),x=R,y=a&&a.length?a:K,j=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:b=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Xs[b]}`,backgroundColor:Js[b]},children:b})},{title:"Tracker",key:"tracker",width:140,render:(b,v)=>n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{tab:"track",sourceTab:"active"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(b,v)=>{if(o)return n.jsx(n.Fragment,{children:o(v)});const M=async(xe,ye)=>{const De=rt(v.id,xe);W(ce=>new Set(ce).add(De));try{const ce=await T.sendSMSorEmailNotifications?.(v.id,xe,ye);ce?.responseStatus?(pe.toast.success(ce.data||(xe?"Email sent successfully":"SMS sent successfully")),f?.()):pe.toast.error(ce?.data||ce?.errorMessage||"Failed to send notification")}catch(ce){pe.toast.error(ce?.message||"Failed to send notification")}finally{W(ce=>{const we=new Set(ce);return we.delete(De),we})}},D=ft,U=mt,B=C[D],q=C[U],se=Dt(D,v,B?.title),ie=Dt(U,v,q?.title),ae=rt(v.id,!0),he=rt(v.id,!1),ee=He(D)&&H.has(ae),oe=He(U)&&H.has(he);return n.jsxs(c.Space,{size:"middle",children:[n.jsx(c.Tooltip,{title:se.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:se.isDisabled,loading:ee,onClick:He(D)?()=>M(!0,!1):void 0,icon:!ee&&B?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:se.buttonText})},String(D)),n.jsx(c.Tooltip,{title:ie.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:ie.isDisabled,loading:oe,onClick:He(U)?()=>M(!1,!0):void 0,icon:!oe&&q?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:ie.buttonText})},String(U))]})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(b,v)=>{const M=v?.timeElapsed,D=v?.timeRemaining,U=M?It(M):0,B=D?It(D):0,q=Math.round(U/(U+B)*100);return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Elapsed:"}),n.jsx("span",{className:"font-medium",children:M??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Ds(v.priority)}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Remaining"}),n.jsx("span",{className:"font-medium",children:D??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(b,v)=>n.jsxs("div",{children:[n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:v.alertNumber}),n.jsx("div",{className:"text-black/65",children:b})]})}],g=r&&r.length?r:j;return n.jsx("div",{children:n.jsx(ss,{rowKey:"id",data:k,columns:g,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(rr,{value:d,onChange:A,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(ir,{value:m,onChange:I,options:x})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(ar,{value:w,onChange:p,options:y})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(lr,{value:S,onChange:$,options:E})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:L,onChange:b=>L(b.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Ue=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},cr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ur=class{#e=cr;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Ee=new ur;function dr(e){setTimeout(e,0)}var Oe=typeof window>"u"||"Deno"in globalThis;function me(){}function hr(e,t){return typeof e=="function"?e(t):e}function it(e){return typeof e=="number"&&e>=0&&e!==1/0}function rs(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ke(e,t){return typeof e=="function"?e(t):e}function Ae(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==yt(o,t.options))return!1}else if(!Be(t.queryKey,o))return!1}if(s!=="all"){const f=t.isActive();if(s==="active"&&!f||s==="inactive"&&f)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||i&&i!==t.state.fetchStatus||a&&!a(t))}function Ut(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Pe(t.options.mutationKey)!==Pe(a))return!1}else if(!Be(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function yt(e,t){return(t?.queryKeyHashFn||Pe)(e)}function Pe(e){return JSON.stringify(e,(t,s)=>ot(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Be(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Be(e[s],t[s])):!1}var fr=Object.prototype.hasOwnProperty;function at(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Lt(e)&&Lt(t);if(!r&&!(ot(e)&&ot(t)))return t;const a=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),l=o.length,f=r?new Array(l):{};let h=0;for(let d=0;d<l;d++){const A=r?d:o[d],m=e[A],I=t[A];if(m===I){f[A]=m,(r?d<a:fr.call(e,A))&&h++;continue}if(m===null||I===null||typeof m!="object"||typeof I!="object"){f[A]=I;continue}const w=at(m,I,s+1);f[A]=w,w===m&&h++}return a===l&&h===a?e:f}function Ye(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Lt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ot(e){if(!$t(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!$t(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function $t(e){return Object.prototype.toString.call(e)==="[object Object]"}function mr(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function lt(e,t,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(e,t);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return at(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${r}`),r}return at(e,t)}return t}function pr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function yr(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var ze=Symbol();function ns(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===ze&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ze?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function gt(e,t){return typeof e=="function"?e(...t):!!e}function gr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var vr=class extends Ue{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},vt=new vr;function ct(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var xr=dr;function br(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=xr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(f=>{s(f)})})})};return{batch:l=>{let f;t++;try{f=l()}finally{t--,t||o()}return f},batchCalls:l=>(...f)=>{a(()=>{l(...f)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var le=br(),Sr=class extends Ue{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(s=>{s(e)}))}isOnline(){return this.#e}},Ze=new Sr;function Ar(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??"online")==="online"?Ze.isOnline():!0}var ut=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function as(e){let t=!1,s=0,r;const i=ct(),a=()=>i.status!=="pending",o=p=>{if(!a()){const S=new ut(p);m(S),e.onCancel?.(S)}},l=()=>{t=!0},f=()=>{t=!1},h=()=>vt.isFocused()&&(e.networkMode==="always"||Ze.isOnline())&&e.canRun(),d=()=>is(e.networkMode)&&e.canRun(),A=p=>{a()||(r?.(),i.resolve(p))},m=p=>{a()||(r?.(),i.reject(p))},I=()=>new Promise(p=>{r=S=>{(a()||h())&&p(S)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),w=()=>{if(a())return;let p;const S=s===0?e.initialPromise:void 0;try{p=S??e.fn()}catch($){p=Promise.reject($)}Promise.resolve(p).then(A).catch($=>{if(a())return;const F=e.retry??(Oe?0:3),L=e.retryDelay??Ar,E=typeof L=="function"?L(s,$):L,z=F===!0||typeof F=="number"&&s<F||typeof F=="function"&&F(s,$);if(t||!z){m($);return}s++,e.onFail?.(s,$),mr(E).then(()=>h()?void 0:I()).then(()=>{t?m($):w()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:f,canStart:d,start:()=>(d()?w():I().then(w),i)}}var os=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),it(this.gcTime)&&(this.#e=Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Oe?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Ee.clearTimeout(this.#e),this.#e=void 0)}},wr=class extends os{#e;#t;#s;#n;#r;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#n=e.client,this.#s=this.#n.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=qt(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=qt(this.options);t.data!==void 0&&(this.setState(Bt(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=lt(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(me).catch(me):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Ae(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ze||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ke(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!rs(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(f=>f.options.queryFn);l&&this.setOptions(l.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,s.signal)})},i=()=>{const l=ns(this.options,t),h=(()=>{const d={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(l,h,this):l(h)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=as({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof ut&&l.revert&&this.setState({...this.#t,fetchStatus:"idle"}),s.abort()},onFail:(l,f)=>{this.#i({type:"failed",failureCount:l,error:f})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const l=await this.#r.start();if(l===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#s.config.onSuccess?.(l,this),this.#s.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof ut){if(l.silent)return this.#r.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#s.config.onError?.(l,this),this.#s.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ls(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Bt(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?r:void 0,r;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),le.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function ls(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function qt(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var jr=class extends Ue{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=ct(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#a;#o;#i;#p;#h;#f;#c;#u;#l;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),_t(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#S(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ae(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!Ye(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&Qt(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(t.enabled,this.#t)||ke(this.options.staleTime,this.#t)!==ke(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return Cr(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(me)),t}#y(){this.#b();const e=ke(this.options.staleTime,this.#t);if(Oe||this.#n.isStale||!it(e))return;const s=rs(this.#n.dataUpdatedAt,e)+1;this.#c=Ee.setTimeout(()=>{this.#n.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#S(),this.#l=e,!(Oe||Ae(this.options.enabled,this.#t)===!1||!it(this.#l)||this.#l===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||vt.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#b(){this.#c&&(Ee.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#u&&(Ee.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,f=e!==s?e.state:this.#s,{state:h}=e;let d={...h},A=!1,m;if(t._optimisticResults){const Y=this.hasListeners(),T=!Y&&_t(e,t),C=Y&&Qt(e,s,t,r);(T||C)&&(d={...d,...ls(h.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:I,errorUpdatedAt:w,status:p}=d;m=d.data;let S=!1;if(t.placeholderData!==void 0&&m===void 0&&p==="pending"){let Y;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(Y=i.data,S=!0):Y=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,Y!==void 0&&(p="success",m=lt(i?.data,Y,t),A=!0)}if(t.select&&m!==void 0&&!S)if(i&&m===a?.data&&t.select===this.#p)m=this.#h;else try{this.#p=t.select,m=t.select(m),m=lt(i?.data,m,t),this.#h=m,this.#i=null}catch(Y){this.#i=Y}this.#i&&(I=this.#i,m=this.#h,w=Date.now(),p="error");const $=d.fetchStatus==="fetching",F=p==="pending",L=p==="error",E=F&&$,z=m!==void 0,W={status:p,fetchStatus:d.fetchStatus,isPending:F,isSuccess:p==="success",isError:L,isInitialLoading:E,isLoading:E,data:m,dataUpdatedAt:d.dataUpdatedAt,error:I,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>f.dataUpdateCount||d.errorUpdateCount>f.errorUpdateCount,isFetching:$,isRefetching:$&&!F,isLoadingError:L&&!z,isPaused:d.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:L&&z,isStale:xt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ae(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const Y=W.data!==void 0,T=W.status==="error"&&!Y,C=X=>{T?X.reject(W.error):Y&&X.resolve(W.data)},R=()=>{const X=this.#o=W.promise=ct();C(X)},K=this.#o;switch(K.status){case"pending":e.queryHash===s.queryHash&&C(K);break;case"fulfilled":(T||W.data!==K.value)&&R();break;case"rejected":(!T||W.error!==K.reason)&&R();break}}return W}updateResult(){const e=this.#n,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#a=this.options,this.#r.data!==void 0&&(this.#f=this.#t),Ye(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;const a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#n).some(o=>{const l=o;return this.#n[l]!==e[l]&&a.has(l)})};this.#w({listeners:s()})}#A(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#w(e){le.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Nr(e,t){return Ae(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _t(e,t){return Nr(e,t)||e.state.data!==void 0&&dt(e,t,t.refetchOnMount)}function dt(e,t,s){if(Ae(t.enabled,e)!==!1&&ke(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&xt(e,t)}return!1}function Qt(e,t,s,r){return(e!==t||Ae(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&xt(e,s)}function xt(e,t){return Ae(t.enabled,e)!==!1&&e.isStaleByTime(ke(t.staleTime,e))}function Cr(e,t){return!Ye(e.getCurrentResult(),t)}function Ht(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},f=0;const h=async()=>{let d=!1;const A=w=>{gr(w,()=>t.signal,()=>d=!0)},m=ns(t.options,t.fetchOptions),I=async(w,p,S)=>{if(d)return Promise.reject();if(p==null&&w.pages.length)return Promise.resolve(w);const F=(()=>{const H={client:t.client,queryKey:t.queryKey,pageParam:p,direction:S?"backward":"forward",meta:t.options.meta};return A(H),H})(),L=await m(F),{maxPages:E}=t.options,z=S?yr:pr;return{pages:z(w.pages,L,E),pageParams:z(w.pageParams,p,E)}};if(i&&a.length){const w=i==="backward",p=w?Tr:Gt,S={pages:a,pageParams:o},$=p(r,S);l=await I(S,$,w)}else{const w=e??a.length;do{const p=f===0?o[0]??r.initialPageParam:Gt(r,l);if(f>0&&p==null)break;l=await I(l,p),f++}while(f<w)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(h,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=h}}}function Gt(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function Tr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ir=class extends os{#e;#t;#s;#n;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#t=[],this.state=e.state||cs(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=as({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{this.#r({type:"failed",failureCount:a,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const r=this.state.status==="pending",i=!this.#n.canStart();try{if(r)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:i})}const a=await this.#n.start();return await this.#s.config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),this.#r({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#r(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),le.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function cs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Rr=class extends Ue{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Ir({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=Ge(e);if(typeof t=="string"){const s=this.#t.get(t);s?s.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ge(e);if(typeof t=="string"){const s=this.#t.get(t);if(s)if(s.length>1){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ge(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ge(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){le.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Ut(t,s))}findAll(e={}){return this.getAll().filter(t=>Ut(e,t))}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return le.batch(()=>Promise.all(e.map(t=>t.continue().catch(me))))}};function Ge(e){return e.options.scope?.id}var kr=class extends Ue{#e;#t=void 0;#s;#n;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#e.defaultMutationOptions(e),Ye(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Pe(t.mutationKey)!==Pe(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#r(),this.#a()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#r(){const e=this.#s?.state??cs();this.#t={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#a(e){le.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,t,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,t,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#t)})})}},Er=class extends Ue{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??yt(r,t);let a=this.get(i);return a||(a=new wr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){le.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Ft(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Ft(e,s)):t}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){le.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Mr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new Er,this.#t=e.mutationCache||new Rr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=vt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Ze.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#e.build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(ke(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=hr(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return le.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;le.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return le.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=le.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(me).catch(me)}invalidateQueries(e,t={}){return le.batch(()=>(this.#e.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=le.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(me)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(me)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(ke(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(me).catch(me)}fetchInfiniteQuery(e){return e.behavior=Ht(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(me).catch(me)}ensureInfiniteQueryData(e){return e.behavior=Ht(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ze.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Pe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Be(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Pe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Be(e,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=yt(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===ze&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},us=de.createContext(void 0),bt=e=>{const t=de.useContext(us);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Or=({client:e,children:t})=>(de.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(us.Provider,{value:e,children:t})),ds=de.createContext(!1),Pr=()=>de.useContext(ds);ds.Provider;function Dr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Fr=de.createContext(Dr()),Ur=()=>de.useContext(Fr),Lr=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?gt(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},$r=e=>{de.useEffect(()=>{e.clearReset()},[e])},Br=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||gt(s,[e.error,r])),qr=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},_r=(e,t)=>e.isLoading&&e.isFetching&&!t,Qr=(e,t)=>e?.suspense&&t.isPending,Wt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Hr(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Pr(),i=Ur(),a=bt(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",qr(o),Lr(o,i,l),$r(i);const f=!a.getQueryCache().get(o.queryHash),[h]=de.useState(()=>new t(a,o)),d=h.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(de.useSyncExternalStore(de.useCallback(m=>{const I=A?h.subscribe(le.batchCalls(m)):me;return h.updateResult(),I},[h,A]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),de.useEffect(()=>{h.setOptions(o)},[o,h]),Qr(o,d))throw Wt(o,h,i);if(Br({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Oe&&_r(d,r)&&(f?Wt(o,h,i):l?.promise)?.catch(me).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?d:h.trackResult(d)}function Je(e,t){return Hr(e,jr)}function Gr(e,t){const s=bt(),[r]=de.useState(()=>new kr(s,e));de.useEffect(()=>{r.setOptions(e)},[r,e]);const i=de.useSyncExternalStore(de.useCallback(o=>r.subscribe(le.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=de.useCallback((o,l)=>{r.mutate(o,l).catch(me)},[r]);if(i.error&&gt(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function St(){const{alerts:e}=ve(),t=bt();return Gr({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Wr(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function Kr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(f=>f.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Yr(e){if(!e)return"-";try{const t=new Date(e),s=h=>String(h).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),f=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${f}`}catch{return"-"}}function ht(e){if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return"-"}}const zr={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Zr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function hs({alerts:e,loading:t=!1,pageSize:s=10,severityOptions:r,anomalyOptions:i,spaceOptions:a,onAlertIdClick:o}){const l=St(),f=["completed","false positive"],h=async m=>{try{const I=await l.mutateAsync({alertUniqueId:m.alertId??m.id,alertId:m.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(I?.responseStatus){const w=I?.data||"Alert reopened successfully.";pe.toast.success(w)}else{const w=I?.errorMessage||"Failed to reopen alert";pe.toast.error(w)}}catch{pe.toast.error("Failed to reopen alert. Please try again.")}},d=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:m=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${zr[m]}`,backgroundColor:Zr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Yr(m)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(m,I)=>n.jsxs("div",{children:[n.jsx("a",{onClick:w=>{w.preventDefault(),o?.(I,{sourceTab:"archived"})},className:"inline-block mb-1 text-blue-600",children:I.alertNumber}),n.jsx("div",{className:"text-black/65",children:m})]})},{title:"",key:"menu",width:60,align:"right",render:(m,I)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:w})=>{w==="reopen"&&h(I)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(Me.MoreOutlined,{})})})}],A=(e||[]).filter(m=>f.includes((m.statusType||"").toLowerCase()));return n.jsx(pt,{data:A,loading:t,pageSize:s,columns:d,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function Vr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=u.useMemo(()=>{const A=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(A.find(m=>m.type==="hour")?.value||"0",10),minutes:parseInt(A.find(m=>m.type==="minute")?.value||"0",10),seconds:parseInt(A.find(m=>m.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,f=r%12*30+i*.5,h=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((d,A)=>{const m=A*30,I=6,w=h-4,p=w-I,S=(m-90)*(Math.PI/180),$=h+p*Math.cos(S),F=h+p*Math.sin(S),L=h+w*Math.cos(S),E=h+w*Math.sin(S);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:$,y1:F,x2:L,y2:E,stroke:"#9CA3AF",strokeWidth:A%3===0?2:1,strokeLinecap:"round"})},A)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${f}deg)`},children:n.jsx("line",{x1:h,y1:h,x2:h,y2:h-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:h,y1:h,x2:h,y2:h-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:h,y1:h+e*.08,x2:h,y2:h-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:h-4,top:h-4}})]})}function fs({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=u.useState(new Date);u.useEffect(()=>{const h=setInterval(()=>a(new Date),s);return()=>clearInterval(h)},[s]);const o=u.useMemo(()=>Wr(i,t),[i,t]),{abbr:l,offset:f}=u.useMemo(()=>Kr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Vr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),f&&n.jsx("span",{className:"text-xs text-gray-500",children:f})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Jr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Xr=[{RuleId:"0938aa00-dfa7-4258-805a-67396366c776",RuleVersionId:"36d2d581-57c3-45c3-8705-8235935fdf96",Name:"License Plate Recognition",Description:"License Plate Recognition",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"915976ef-4eb6-4f7b-bbe6-e53862517fc9",Level:"global"},{RuleId:"2437286a-db6a-4d35-814e-9ac49f158dde",RuleVersionId:"00000000-0000-0000-0000-000000000000",Name:"Monitor And Track Onsite Vehicle timelog",Description:"Monitor And Track Onsite Vehicle timelog",VersionCount:0,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"9fd651ab-4312-4826-84b6-94d735894477",Level:"global"},{RuleId:"b99120ba-7a83-4ade-b5d9-a420550fe351",RuleVersionId:"d7b14dae-a7b1-474e-a357-199182c02ac3",Name:"Watchlist person detected",Description:"Watchlist person detected",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"bb3a3d3a-73a3-4f5a-8804-1baadbd0d412",Level:"global"},{RuleId:"ffc2c24f-adb7-4aba-ace7-f19c54e21530",RuleVersionId:"6ab3178f-bf77-4a1e-898d-1d5dbef749c5",Name:"Weapon Detection",Description:"Weapon Detection",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"ac82c3a2-72e6-4f9c-88fb-851a3ca3c4de",Level:"global"}],en=[{userRoleId:1,userRoleName:"Super Admin"},{userRoleId:2,userRoleName:"Security Officer"},{userRoleId:3,userRoleName:"Security Admin"},{userRoleId:4,userRoleName:"Regulatory Officer/First Responder"},{userRoleId:5,userRoleName:"User"}],Fe={severities:Jr,rules:Xr,userRoles:en},{Text:tn}=c.Typography;function sn({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(tn,{className:"text-gray-600 whitespace-nowrap",children:"Sort By:"}),n.jsx(c.Select,{placeholder:"By Severity",value:e,onChange:o=>t({sortBy:o}),options:[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],className:"w-full",style:{minWidth:"200px"}})]})}),n.jsx(c.Col,{xs:24,md:8,style:{alignSelf:"end"},children:s?n.jsxs(c.Space,{className:"w-full",direction:"horizontal",size:8,children:[n.jsx(c.Button,{onClick:i,disabled:a,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:r,loading:a,children:"Save"})]}):null})]})}const{Text:Ie}=c.Typography;function rn(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:f,setL1role:h,l2mins:d,setL2mins:A,l2role:m,setL2role:I,l3mins:w,setL3mins:p,l3role:S,setL3role:$,actions:F,setActions:L,thirdPartyIds:E,setThirdPartyIds:z,humanLoop:H,setHumanLoop:W,isAutoExpire:Y,setAutoExpire:T,onClear:C,onSave:R,saving:K,onActionTypesLoaded:X}=e,{rules:k}=ve(),[x,y]=u.useState([]),[j,g]=u.useState([]),[b,v]=u.useState(!1);u.useEffect(()=>{let B=!1;return(async()=>{try{v(!0);const q=await k.getLookups();if(B||!q||!Array.isArray(q.actionTypes))return;const se=q.actionTypes.map(ae=>({label:ae.name,value:String(ae.actionTypeId)}));y(se),X&&X(q.actionTypes);const ie=Array.isArray(q.thirdParties)?q.thirdParties.map(ae=>({label:ae.thirdPartyName,value:ae.thirdPartyId})):[];g(ie)}catch(q){console.error("Error loading lookups",q)}finally{B||v(!1)}})(),()=>{B=!0}},[]);const M=B=>n.jsxs(c.Tag,{children:[n.jsx(Me.PlusOutlined,{})," ",B.length," more"]}),D=typeof o=="number"||typeof f=="number"||typeof d=="number"||typeof m=="number"||typeof w=="number"||typeof S=="number"||Array.isArray(F)&&F.length>0||Array.isArray(E)&&E.length>0||!!H||!!Y,U=!!t&&D&&!K;return n.jsxs(c.Spin,{spinning:!!K||b,children:[n.jsxs(c.Row,{gutter:[16,16],align:"bottom",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Rules"}),n.jsx(c.Select,{placeholder:"Rules",value:t,onChange:s,options:r,className:"w-full"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:f,onChange:h,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:d,onChange:A,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:m,onChange:I,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:w,onChange:p,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:S,onChange:$,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Pick Actions"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Select response actions",className:"w-full",value:F,onChange:L,options:x,maxTagCount:1,maxTagPlaceholder:M})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Third Party App"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Third Party app",className:"w-full",value:E,onChange:z,options:j})]})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4 items-center",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:7,children:n.jsxs("div",{className:"flex items-center h-full gap-8",children:[n.jsx(c.Checkbox,{checked:H,onChange:B=>W(B.target.checked),className:"w-full",children:"Human-In-The-Loop"}),n.jsx(c.Checkbox,{checked:Y,onChange:B=>T(B.target.checked),className:"w-full",children:"Auto-expire in 5 minutes"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:C,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:R,loading:!!K,disabled:!U,children:"Save"})]})})]})]})}function nn({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions?.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify?.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Auto Expire",key:"isAutoExpire",render:(o,l)=>l.isAutoExpire?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(Me.EditOutlined,{})})}]})}const{Title:an}=c.Typography;function ms({userRoles:e,rules:t,rawRules:s}){const{rules:r}=ve(),[i,a]=u.useState(!1),[o,l]=u.useState(s),[f,h]=u.useState({}),d=u.useMemo(()=>e.map(p=>({label:p.userRoleName,value:p.userRoleId})),[e]),A=u.useMemo(()=>(t||[]).map((p,S)=>({key:p.RuleId||p.Name||String(S),ruleName:p.Name||"-",ruleDesc:p.Description||""})),[t]);u.useEffect(()=>{let p=!1;return(async()=>{try{a(!0);const S=await r.getRules();p||(l(Array.isArray(S)?S:[]),h({}))}catch{!p&&Array.isArray(s)&&l(s)}finally{p||a(!1)}})(),()=>{p=!0}},[]),u.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const m=u.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const p={};for(const S of A){const $=o.find(L=>L?.ruleId===S.key||L?.ruleName===S.key||L?.RuleId===S.key||L?.ruleName===S.ruleName||L?.Name===S.ruleName),F=Array.isArray($?.userRoleIds)?$.userRoleIds:[];F.length&&(p[S.key]=F)}return p},[o,A]),I=()=>{h({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){pe.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([S,$])=>{const F=o.find(W=>W?.ruleId===S||W?.ruleName===S||W?.RuleId===S),L=typeof F?.recordId=="number"?F.recordId:void 0;if(!F||typeof L!="number")throw new Error(`Unable to find recordId for rule ${S}`);const E=Array.isArray($)?$:[],z=E.map(W=>{const Y=e.find(T=>T.userRoleId===W);return{id:W,name:Y?.userRoleName??String(W)}}),H={...F,ruleId:S,userRoleIds:E,userRoles:z,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}]};return r.updateRule(L,H)});await Promise.all(p),pe.toast.success("Alert assignment saved");try{const S=await r.getRules();l(Array.isArray(S)?S:[]),h({})}catch(S){console.error("Failed to refresh rules after save",S)}}catch(p){console.error("Failed to save alert assignment",p)}finally{a(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx(an,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:A,loading:i,pagination:!1,columns:[{title:"Rule Name",dataIndex:"ruleName",key:"ruleName"},{title:"Description",dataIndex:"ruleDesc",key:"ruleDesc"},{title:"Alert Notification To",key:"assign",render:(p,S)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:f[S.key]??m[S.key]??[],onChange:$=>h(F=>({...F,[S.key]:$})),options:d})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:I,disabled:i,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:w,loading:i,disabled:i||Object.keys(f).length===0,children:"Save"})]})]})}const{Title:Kt}=c.Typography;function ps({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=ve(),[l,f]=u.useState("By Severity"),[h,d]=u.useState("By severity"),[A,m]=u.useState("By Severity"),[I,w]=u.useState(!1),[p,S]=u.useState(!1),[$,F]=u.useState(!1),[L,E]=u.useState(null),[z,H]=u.useState("rules"),[W,Y]=u.useState(),[T,C]=u.useState(),[R,K]=u.useState(),[X,k]=u.useState(),[x,y]=u.useState(),[j,g]=u.useState(),[b,v]=u.useState(),[M,D]=u.useState(),[U,B]=u.useState([]),[q,se]=u.useState([]),[ie,ae]=u.useState(!1),[he,ee]=u.useState(!1),[oe,xe]=u.useState({}),[ye,De]=u.useState({}),[ce,we]=u.useState(s||[]),[Le,N]=u.useState([]),[G,re]=u.useState(!1),[je,V]=u.useState(!1),[ue,$e]=u.useState(r||[]);u.useEffect(()=>{r&&r.length&&$e(r)},[r]),u.useEffect(()=>{if(!ue||!ue.length)return;const O=Object.keys(oe).length>0||Object.keys(ye).length>0;if(Le.length&&!O)return;const J=ue.map((_,P)=>{const Z=t.find(fe=>fe.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",Q=_.escalationSettings||{},te=typeof Q.level1UserRoleId=="number"&&Q.level1UserRoleId>0?[Q.level1UserRoleId]:[],Ne=typeof Q.level2UserRoleId=="number"&&Q.level2UserRoleId>0?[Q.level2UserRoleId]:[],et=typeof Q.level3UserRoleId=="number"&&Q.level3UserRoleId>0?[Q.level3UserRoleId]:[],jt=(Array.isArray(Q.escalationSettingsActionTypeIds)?Q.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),Ct=(Array.isArray(Q.thirdPartyId)?Q.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),tt=typeof Q.humanLoop=="boolean"?Q.humanLoop:null,st=typeof Q.isAutoExpire=="boolean"?Q.isAutoExpire:null;return{id:String(_.ruleId||_.ruleName||P),ruleOrSeverityLabel:Z,l1:{minutes:Q.level1PostAssistTime??void 0,roles:te},l2:{minutes:Q.level2PostAssistTime??void 0,roles:Ne},l3:{minutes:Q.level3PostAssistTime??void 0,roles:et},actions:jt,notify:Ct,humanLoop:tt,isAutoExpire:st}});N(J)},[ue,t,oe,ye]);const ge=u.useMemo(()=>e.map(O=>({label:O.DisplayName,value:O.SeverityId})),[e]),Xe=u.useMemo(()=>t.map(O=>({label:O.Name,value:O.RuleId})),[t]),ws=u.useMemo(()=>ce.map(O=>({label:O.userRoleName,value:O.userRoleId})),[ce]),js=u.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(O=>({label:`${O}`,value:O})),[]);u.useEffect(()=>{let O=!1;async function J(){try{F(!0),E(null);const _=await o.getAdminSettings();if(!O&&_){const P=Jt(_.sortBy);f(P),m(P),w(!1)}}catch(_){if(!O){const P=_ instanceof Error?_.message:"Failed to load admin settings";E(P)}}finally{O||F(!1)}}return J(),()=>{O=!0}},[]),u.useEffect(()=>{if(!T)return;const O=Z=>{const Q=Number(Z);return!isNaN(Q)&&Q>0?Q:void 0},J=Z=>{const Q=Number(Z);return!isNaN(Q)&&Q>0?Q:void 0},P=(ue||[]).find(Z=>Z?.ruleId===T||Z?.ruleName===T||Z?.RuleId===T)?.escalationSettings;if(P&&typeof P=="object"){K(J(P.level1PostAssistTime)),k(O(P.level1UserRoleId)),y(J(P.level2PostAssistTime)),g(O(P.level2UserRoleId)),v(J(P.level3PostAssistTime)),D(O(P.level3UserRoleId));const Z=Array.isArray(P.escalationSettingsActionTypeIds)?P.escalationSettingsActionTypeIds:[];B(Z.map(Q=>String(Q))),se(Array.isArray(P.thirdPartyId)?P.thirdPartyId:[]),ae(!!P.humanLoop),ee(!!P.isAutoExpire)}},[z,T,ue]);const Ns=async()=>{try{V(!0);const O=await a.getRules(),J=Array.isArray(O)?O:Array.isArray(O?.data)?O.data:[];$e(J);const _=J.map((P,Z)=>{const Q=t.find(fe=>fe.RuleId===(P.ruleId||P.ruleName))?.Name||P.ruleName||P.Name||"-",te=P.escalationSettings||{},Ne=typeof te.level1UserRoleId=="number"&&te.level1UserRoleId>0?[te.level1UserRoleId]:[],et=typeof te.level2UserRoleId=="number"&&te.level2UserRoleId>0?[te.level2UserRoleId]:[],wt=typeof te.level3UserRoleId=="number"&&te.level3UserRoleId>0?[te.level3UserRoleId]:[],Nt=(Array.isArray(te.escalationSettingsActionTypeIds)?te.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),tt=(Array.isArray(te.thirdPartyId)?te.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),st=typeof te.humanLoop=="boolean"?te.humanLoop:null;return{id:String(P.ruleId||P.ruleName||Z),ruleOrSeverityLabel:Q,l1:{minutes:te.level1PostAssistTime??void 0,roles:Ne},l2:{minutes:te.level2PostAssistTime??void 0,roles:et},l3:{minutes:te.level3PostAssistTime??void 0,roles:wt},actions:Nt,notify:tt,humanLoop:st}});N(_)}catch(O){console.error("Failed to refetch entries",O)}finally{V(!1)}};u.useEffect(()=>{let O=!1;return(async()=>{try{const J=await a.getLookups();if(O||!J)return;const _={};if(Array.isArray(J.thirdParties))for(const Z of J.thirdParties)typeof Z.thirdPartyId=="number"&&(_[Z.thirdPartyId]=Z.thirdPartyName);De(_);const P=Array.isArray(J.userRoles)?J.userRoles.map(Z=>({userRoleId:Z.userRoleId??Z.id,userRoleName:Z.userRoleName??Z.name})):[];O||we(P.length?P:s||[])}catch(J){console.error("Error loading lookups",J)}})(),()=>{O=!0}},[]);const Cs=async()=>{S(!0);try{const O=await o.setAdminSettings({sortBy:l,groupBy:"string"});O?.responseStatus&&O?.data&&pe.toast.success(O.data),m(l),w(!1)}catch(O){console.error("Error saving admin settings",O)}finally{S(!1)}},Ts=()=>{f(A),w(!1)},Is=async()=>{re(!0),i?.({ruleId:T,levels:[{minutes:R,role:X},{minutes:x,role:j},{minutes:b,role:M}],actions:U,thirdPartyIds:q,humanLoop:ie,isAutoExpire:he});try{if(T){const _=Array.isArray(U)?U.map(Ne=>Number(Ne)):[],P=(ue||[]).find(Ne=>Ne?.ruleId===T||Ne?.ruleName===T||Ne?.RuleId===T),Z=typeof P?.recordId=="number"?P.recordId:void 0;if(!P||typeof Z!="number"){pe.toast.error("Unable to find rule recordId for update");return}const Q={...P,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}],escalationSettings:{level1UserRoleId:X??0,level1PostAssistTime:R??0,level2UserRoleId:j??0,level2PostAssistTime:x??0,level3UserRoleId:M??0,level3PostAssistTime:b??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:ie,isAutoExpire:he}},te=await a.updateRule(Z,Q);if(te?.responseStatus||te?.ok||te){pe.toast.success("Escalation settings saved"),await Ns(),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),D(void 0),B([]),se([]),ae(!1),ee(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{re(!1)}const J=t.find(_=>_.RuleId===T)?.Name||"-";N(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:J,l1:{minutes:R,roles:X?[X]:[]},l2:{minutes:x,roles:j?[j]:[]},l3:{minutes:b,roles:M?[M]:[]},actions:(Array.isArray(U)?U:[]).map(P=>{const Z=Number(P);return oe[Z]||String(P)}),notify:(Array.isArray(q)?q:[]).map(P=>ye[P]||String(P)),humanLoop:!!ie,isAutoExpire:!!he}])},Rs=()=>{f("By Severity"),d("By severity"),H("rules"),Y(void 0),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),D(void 0),B([]),se([]),ae(!1),ee(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Kt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:$,children:[L?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",L]}):null,n.jsx(sn,{sortBy:l,groupBy:h,onChange:O=>{O.sortBy&&(f(O.sortBy),w(!0)),O.groupBy&&(d(O.groupBy),w(!0))},showActions:I,onSave:Cs,onClear:Ts,saving:p})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Kt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(rn,{escBasis:z,setEscBasis:H,selectedSeverity:W,setSelectedSeverity:Y,selectedRule:T,setSelectedRule:C,severityOptions:ge,ruleOptions:Xe,minsOptions:js,roleOptions:ws,l1mins:R,setL1mins:K,l1role:X,setL1role:k,l2mins:x,setL2mins:y,l2role:j,setL2role:g,l3mins:b,setL3mins:v,l3role:M,setL3role:D,actions:U,setActions:B,thirdPartyIds:q,setThirdPartyIds:se,humanLoop:ie,setHumanLoop:ae,onClear:Rs,onSave:Is,saving:G,onActionTypesLoaded:O=>{const J={};for(const _ of O)typeof _.actionTypeId=="number"&&(J[_.actionTypeId]=_.name);xe(J)},isAutoExpire:he,setAutoExpire:ee})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(nn,{entries:Le,userRoles:ce,loading:je,onEdit:O=>{H("rules");const J=Le.find(P=>P.id===O),_=t.find(P=>P.RuleId===O)||(J?t.find(P=>P.Name===J.ruleOrSeverityLabel):void 0);C(_?_.RuleId:O)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(ms,{userRoles:ce,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:Yt,Text:We}=c.Typography;function ys({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=ve(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,f]=u.useState("By Severity"),[h,d]=u.useState(new Set),[A,m]=u.useState(null),[I,w]=u.useState(null),[p,S]=u.useState({inApp:!1,sms:!1,email:!1}),[$,F]=u.useState([]),[L,E]=u.useState(!0),[z,H]=u.useState(!1);u.useEffect(()=>{let T=!1;return(async()=>{try{const C=await a.getPreferenceSettings();if(T||!C)return;S({inApp:!!C.inApp,sms:!!C.sms,email:!!C.email});const R=Jt(C.sortBy);f(R==="By Created Date"?"By Created Date":"By Severity"),m(Ot(C.doNotDisturbStart)),w(Ot(C.doNotDisturbEnd)),Array.isArray(C.anomalyIds)&&d(new Set(C.anomalyIds.map(K=>String(K))))}catch(C){console.error("Error in loading my preferences: ",C)}})(),()=>{T=!0}},[]),u.useEffect(()=>{let T=!1;return(async()=>{try{E(!0);const C=await i.getLookups();if(T||!C)return;const R=Array.isArray(C.anomalies)?C.anomalies:[];F(R)}catch(C){console.error("Failed to load anomalies lookups",C)}finally{T||E(!1)}})(),()=>{T=!0}},[]);const W=T=>{d(C=>{const R=new Set(C);return R.has(T)?R.delete(T):R.add(T),R})},Y=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(h),dnd:{from:A,to:I},channels:p});try{H(!0);const T=A?A.format?.("HH:mm:ss")??"00:00:00":"00:00:00",C=I?I.format?.("HH:mm:ss")??"00:00:00":"00:00:00",R=Array.from(h).map(X=>Number(X)).filter(X=>Number.isFinite(X)),K=await a.setPreferenceSettings({anomalyIds:R,doNotDisturbStart:T,doNotDisturbEnd:C,inApp:!!p.inApp,sms:!!p.sms,email:!!p.email,sortBy:l});K?.responseStatus&&pe.toast.success(K?.data||"Preferences updated successfully.")}catch(T){console.error("Error in saving my preferences: ",T)}finally{H(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-4",children:n.jsx(c.Col,{xs:24,md:8,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(We,{className:"text-gray-600",children:"Sort By:"}),n.jsx(c.Select,{className:"w-[240px]",value:l,options:o,onChange:f})]})})}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Yt,{level:5,className:"!mb-2",children:"Anomalies"}),L?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray($)?$:[]).map(T=>{const C=String(T.recordId),R=T.anomalyName;return n.jsx(c.Checkbox,{checked:h.has(C),onChange:()=>W(C),children:R},C)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Yt,{level:5,className:"!mb-2",children:"Notification Timing & Channels"}),n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-3",children:n.jsx(c.Col,{xs:24,md:12,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(We,{children:"Do Not Disturb mode:"}),n.jsxs(c.Space,{size:12,className:"w-full",children:[n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(We,{children:"From"}),n.jsx(c.TimePicker,{value:A,onChange:T=>m(T),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(We,{children:"To"}),n.jsx(c.TimePicker,{value:I,onChange:T=>w(T),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.inApp,onChange:T=>S({...p,inApp:T.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.sms,onChange:T=>S({...p,sms:T.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.email,onChange:T=>S({...p,email:T.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:z,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Y,loading:z,children:"Save"})]})]})}function gs({severities:e,rules:t,userRoles:s,rawRules:r}){const[i,a]=u.useState("global");return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden border border-gray-200 mb-4",children:[n.jsx("button",{onClick:()=>a("global"),className:`px-5 py-2 text-base font-medium outline-none ${i==="global"?" bg-black text-white":" bg-white text-black"}`,style:{border:"0"},children:"Global Settings"}),n.jsx("button",{onClick:()=>a("prefs"),className:`px-5 py-2 text-base font-medium outline-none ${i==="prefs"?"bg-black text-white":"bg-white"}`,children:"My Preferences"})]}),i==="global"?n.jsx(ps,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(ys,{severities:e,rules:t})]})}const on="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",ln="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function cn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:on,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:ln,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function un({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md p-4",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(cn)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:Vt(t.sentAt)?.format("MM/DD/YYYY HH:mm:ss")})]}),n.jsxs("span",{className:"text-[11px] px-2 py-1 rounded-full bg-green-50 text-green-700 border border-green-200",children:[t.delivered,"/",t.total," Delivered"]})]}),n.jsxs("div",{className:"mt-4 text-xs",children:[n.jsxs("div",{className:"text-black",children:[" ",t.messageTitle]}),t.messageBody?n.jsx("div",{className:"text-gray-600",children:t.messageBody}):null]}),n.jsxs("div",{className:"mt-4",children:[n.jsxs("div",{className:"text-xs text-black font-medium",children:["Recipients (",t.total,")"]}),n.jsx("div",{className:"mt-2 flex flex-col gap-3 text-xs",children:(t.recipients||[]).map((r,i)=>{const a=String(r?.notificationReceipientType||"").toLowerCase()==="EscalationNotification".toLowerCase();return n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("span",{className:"text-black",children:[r.name," - ",n.jsx("span",{style:{color:a?"#FF3B30":"#FFB86A"},children:a?"Escalation Notification":"Alert Notification"})]}),n.jsxs("span",{className:"text-gray-500",children:[r.role," . ",r.phone]})]}),n.jsx("span",{className:`text-[11px] px-3 py-[2px] rounded ${r.status==="Delivered"?"bg-green-50 text-green-700 border border-green-200":"bg-red-50 text-red-700 border border-red-200"}`,children:r.status})]},i)})})]})]},s)),e?.notifications?.length?null:n.jsx("span",{className:"text-gray-500 text-xs",children:"No notifications."})]})}]})})}const dn=({alertId:e,id:t,priority:s,spaceName:r,alertNumber:i,statusHistory:a,notifGroups:o})=>{const l={alertId:e??String(t??""),incidentId:"-",severity:s||"",location:r||"",alertNumber:i??""},f=a?.length?a.map(d=>{const A=(d?.status||d?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",m=d?.createdDate?ht(d.createdDate):d?.timestamp?ht(d.timestamp):"";return{status:A,title:d?.status||d?.eventStatus||"Status Update",description:d?.description||d?.actionNotes||"",timestamp:m}}):[],h={summary:l,timeline:f,notifications:o??[]};return n.jsx(un,{data:h})};const hn=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fn=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase()),zt=e=>{const t=fn(e);return t.charAt(0).toUpperCase()+t.slice(1)},vs=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim(),mn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var pn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const yn=u.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:i="",children:a,iconNode:o,...l},f)=>u.createElement("svg",{ref:f,...pn,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:vs("lucide",i),...!a&&!mn(l)&&{"aria-hidden":"true"},...l},[...o.map(([h,d])=>u.createElement(h,d)),...Array.isArray(a)?a:[a]]));const xs=(e,t)=>{const s=u.forwardRef(({className:r,...i},a)=>u.createElement(yn,{ref:a,iconNode:t,className:vs(`lucide-${hn(zt(e))}`,`lucide-${e}`,r),...i}));return s.displayName=zt(e),s};const gn=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],bs=xs("maximize-2",gn);const vn=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],xn=xs("minimize-2",vn),bn=({isOpen:e,onClose:t,src:s,type:r="image"})=>{const[i,a]=u.useState(!1),[o,l]=u.useState(!1);return u.useEffect(()=>{e&&l(!1)},[e,s]),u.useEffect(()=>{e&&(!s||o)&&t()},[e,s,o,t]),e?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-70",role:"button",tabIndex:0,"aria-label":"Close media preview",onClick:t,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),t())},onTouchStart:t,children:n.jsxs("div",{className:`relative ${i?"w-full h-full":"max-w-5xl max-h-[90vh] w-full"} flex items-center justify-center`,onClick:f=>f.stopPropagation(),children:[r==="image"?n.jsx("img",{src:s,alt:"preview",className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}):n.jsx("video",{src:s,controls:!0,className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}),n.jsx("button",{onClick:t,className:"absolute top-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:"✕"}),n.jsx("button",{onClick:()=>a(!i),className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:i?n.jsx(xn,{size:20}):n.jsx(bs,{size:20})})]})}):null};function Sn(e){if(!e||typeof e!="string")return!1;const t=e.split("?")[0].toLowerCase();return t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".ogg")||t.endsWith(".m3u8")}function nt(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:Sn(e?.mediaUrl||e)}function An(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const wn={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},jn={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Nn=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details",sourceTab:l})=>{const[f,h]=u.useState(),[d,A]=u.useState(""),[m,I]=u.useState(!1),w=u.useRef(null),[p,S]=u.useState("details"),[$,F]=u.useState(void 0),L=St(),{alerts:E}=ve(),[z,H]=u.useState(!1),[W,Y]=u.useState(void 0),[T,C]=u.useState(void 0),[R,K]=u.useState({}),X=s?.originalData||{},{eventName:k,alertId:x,timestamp:y,description:j,spaceName:g,assignTeam:b,priority:v,statusType:M,id:D,alertDetails:U,statusHistory:B,mediaDetails:q,alertNumber:se}=X,ie=N=>{const G=String(N||"").toLowerCase();return G==="delivered"||G==="sent"?"Delivered":G==="failed"?"Failed":"Queued"},ae=N=>({name:N?.receipientName||N?.recipientName||"-",role:N?.receipientRoleName||"",phone:N?.receipentPhoneNumber||N?.recipientPhoneNumber||N?.receipientEmail||N?.recipientEmail||"",status:ie(N?.messageStatus),notificationReceipientType:N?.notificationReceipientType||""}),he=(N,G)=>{const re=G.map(ae),je=re.filter(ge=>ge.status==="Delivered").length,V=G.map(ge=>ge?.sentAt).filter(Boolean).sort((ge,Xe)=>new Date(Xe).getTime()-new Date(ge).getTime())[0],ue=G[0]||{},$e=[ue?.severityName,ue?.anomalyName].filter(Boolean).join(" - ")||`${N} Notification`;return{channelLabel:`${N} Notification`,sentAt:V||"",messageTitle:$e,messageBody:"",total:re.length,delivered:je,recipients:re}},ee=N=>{const G=new Map;return(N||[]).forEach(re=>{const je=String(re?.notificationType||"Unknown"),V=G.get(je)||[];V.push(re),G.set(je,V)}),Array.from(G.entries()).map(([re,je])=>he(re,je))},oe=async N=>{try{const G=await E.getAlertNotifications(N),re=ee(G);F(re)}catch{F(void 0)}};u.useEffect(()=>{if(p!=="track"||!D)return;let N=!1;return oe(D).then(()=>{N&&F(void 0)}),()=>{N=!0}},[p,D]),u.useEffect(()=>{e&&S(o)},[e,o]);const ye=l==="archived"||["completed","false positive"].includes(String(M||"").toLowerCase()),De=N=>{const G=String(N?.value||"").toLowerCase(),re=String(N?.statusName||"").toLowerCase();return G.includes("reopen")||re.includes("reopen")},ce=(i||[]).filter(N=>{const G=De(N);return typeof l<"u"?l==="archived"?G:!G:ye?G:!G}).map(N=>({value:N.value,label:N.statusName})),we=u.useMemo(()=>An(q),[q]);u.useEffect(()=>{let N=!1;const G=new AbortController,re=async V=>{if(V){N||K(ue=>({...ue,[V]:!1}));try{const ue=await fetch(V,{method:"HEAD",signal:G.signal});if(ue.ok){N||K(ge=>({...ge,[V]:!0}));return}if(ue.status===404){N||K(ge=>({...ge,[V]:!1}));return}if(!(await fetch(V,{method:"GET",signal:G.signal})).ok)throw new Error("Media not available");N||K(ge=>({...ge,[V]:!0}))}catch{N||K(ue=>({...ue,[V]:!1}))}}};return K({}),we.filter(V=>!nt(V)).map(V=>V?.mediaUrl||V).filter(V=>typeof V=="string"&&V.length>0).forEach(V=>re(V)),()=>{N=!0,G.abort()}},[we]);const Le=async()=>{try{I(!0);const N={alertUniqueId:x,alertId:D,status:f?String(f):void 0,notes:d.trim(),modifiedBy:0},G=await L.mutateAsync(N);if(G?.responseStatus){const re=G?.data||"Alert updated successfully.";pe.toast.success(re,{autoClose:1500,onClose:()=>{r(),t()}}),h(void 0),A("")}else{const re=G?.errorMessage||"Failed to update alert status";pe.toast.error(re)}}catch(N){console.error("Error updating alert status:",N),pe.toast.error("Failed to update alert status. Please try again.")}finally{I(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,styles:{body:{maxHeight:"70vh",overflowY:"auto"}},footer:p==="details"?n.jsxs("div",{className:"flex flex-row gap-2 justify-start",children:[n.jsx(c.Button,{onClick:t,className:"bg-[#6C757D] text-white",children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Le,loading:m,children:m?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:p,onChange:N=>S(N),items:[{key:"details",label:"Alert Detail",children:n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{className:"text-sm font-bold",children:k||"Alert Event"}),U?.firstName?n.jsxs("div",{className:"text-sm text-gray-500",children:["Resident ID/Name: ",U?.firstName," ",U?.lastName||"","   ",U?.residentId||""]}):null,n.jsxs("div",{className:"text-sm text-gray-500",children:["Timestamp: ",ht(y)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",j||"No description available"]}),g&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",g]}),b&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",b]}),n.jsxs("div",{className:"flex gap-2 justify-start mt-3",children:[n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:{border:`2px solid ${wn[String(v)]||"#DFE4EA"}`,backgroundColor:jn[String(v)]},children:["Severity: ",v||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(M||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",M||"N/A"]})]}),n.jsx("div",{className:"w-full flex flex-col justify-start items-start mt-2 font-bold",children:n.jsxs("div",{className:"w-full mt-4",children:[n.jsx("div",{className:"flex flex-col gap-2",children:n.jsx(c.Select,{placeholder:"Change Status",className:"w-full text-gray-500",onChange:N=>h(N),value:f,options:ce,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{htmlFor:"action-details-input",className:"text-xs text-gray-500 font-medium",children:"Action Taken (Comments)"}),n.jsx("textarea",{id:"action-details-input",placeholder:"Enter details...",className:"w-full text-gray-500 h-20 border border-grey-500 rounded-md p-2",value:d,onChange:N=>A(N.target.value)})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),we.length>1?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>w.current?.prev?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Previous media",children:n.jsx(Me.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>w.current?.next?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Next media",children:n.jsx(Me.RightOutlined,{style:{fontSize:12}})})]}):null]}),we.length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:we.map((N,G)=>n.jsxs("div",{className:"flex justify-center items-center",children:[nt(N)?n.jsxs("video",{width:"240",height:"200",controls:!0,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg",children:[n.jsx("source",{src:N.mediaUrl||N}),"Your browser does not support the video tag."]}):n.jsx("img",{src:N.mediaUrl||N,alt:N.caption||`media-${G}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),N.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:N.caption}),!nt(N)&&R[String(N.mediaUrl||N)]?n.jsx("button",{onClick:()=>{H(!0),Y(N.mediaUrl||N),C(N.type||"image")},className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:n.jsx(bs,{size:20})}):null]},G))})}):null]})}),n.jsx(bn,{isOpen:z,onClose:()=>H(!1),src:W||"",type:T||"image"})]})},{key:"track",label:"Track Incident",children:n.jsx(dn,{alertId:x,id:D,priority:v,spaceName:g,alertNumber:se,statusHistory:B,notifGroups:$})}]})})};function Ss(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Cn(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","timeZoneMasters"],queryFn:()=>e.getTimeZoneMasters?e.getTimeZoneMasters():Promise.resolve([]),staleTime:30*6e4,enabled:typeof e.getTimeZoneMasters=="function"});return{timeZoneMasters:t.data??[],loading:t.isLoading,error:t.error}}function At({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=u.useState(!1),[o,l]=u.useState(null),[f,h]=u.useState("details"),{list:d,loading:A}=Ss(),{timeZoneMasters:m}=Cn(),I=u.useMemo(()=>{const E="America/New_York";if(!e.length||!m.length)return{label:"USA",ianaTimeZoneId:E};const z=e[0].timeZoneUniqueId;if(!z)return{label:"USA",ianaTimeZoneId:E};const H=m.find(W=>W.timeZoneUniqueId===z);return H?{label:H.timeZoneName,ianaTimeZoneId:H.ianaTimeZoneId}:{label:"USA",ianaTimeZoneId:E}},[e,m]);function w(L,E){l(L),h(E?.tab??"details"),$(E?.sourceTab??"active"),a(!0)}function p(){a(!1)}const[S,$]=u.useState("active"),F=o?{originalData:{...o,alertId:o.alertId??o.id,mediaDetails:o.mediaDetails}}:null;return n.jsxs("div",{className:"p-6 flex flex-col items-start justify-start min-h-screen w-full overflow-auto",children:[n.jsxs("div",{className:"w-1/2 flex items-center justify-between mb-4",children:[n.jsx("h1",{className:"text-xl font-bold text-black",children:"Alert Console"}),n.jsx(fs,{label:I.label,timeZone:I.ianaTimeZoneId})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:L=>{L==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(pt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:w,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(hs,{alerts:e,loading:t,columns:s||[],onAlertIdClick:w})},{key:"settings",label:"Settings",children:n.jsx(Tn,{})}]}),n.jsx(Nn,{isModalOpen:i,handleModalClose:p,selectedRow:F,fetchAlertLogs:()=>{},alertStatusList:d,alertStatusLoading:A,initialTab:f,sourceTab:S})]})}function Tn(){const[e,t]=u.useState([]),[s,r]=u.useState([]),[i,a]=u.useState([]),{rules:o}=ve();return u.useEffect(()=>{let l=!0;return(async()=>{try{const f=await o.getRules();if(!l)return;a(Array.isArray(f)?f:[]);const h=(f||[]).map((d,A)=>({RuleId:d.ruleId||d.ruleName||String(A),Name:d.ruleName||d.Name||"-",Description:d.ruleDesc||d.Description||"",SeverityId:0}));t(h.length?h:Fe.rules);try{const d=await o.getLookups(),A=Array.isArray(d?.userRoles)?d.userRoles.map(m=>({userRoleId:m.userRoleId??m.id,userRoleName:m.userRoleName??m.name})):[];r(A.length?A:Fe.userRoles)}catch{r(Fe.userRoles)}}catch{t(Fe.rules),r(Fe.userRoles)}})(),()=>{l=!1}},[]),n.jsx(gs,{severities:Fe.severities,rules:e,userRoles:s,rawRules:i})}function As(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function In(e){const{alerts:t,loading:s,refetch:r}=As();return n.jsx(At,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function Rn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=u.useState(()=>new Mr),f=u.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Or,{client:l,children:n.jsx(ts,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(At,{alerts:i,loading:!!a,columns:o}):n.jsx(In,{columns:o})})})}function kn(e){const{alerts:t}=ve(),s=Je({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const En=[{title:"ID",dataIndex:"id",key:"id",width:120},{title:"Priority",dataIndex:"priority",key:"priority",width:120},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:220},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description"}];exports.AlertAssignment=ms;exports.AlertConsole=At;exports.AlertConsoleWidget=Rn;exports.AlertsTable=pt;exports.ApiProvider=ts;exports.ArchivedTable=hs;exports.Clock=fs;exports.DataTable=ss;exports.MyPreferencesPanel=ys;exports.SettingsPanel=ps;exports.SettingsTabs=gs;exports.exampleAlertColumns=En;exports.useAlertStatusList=Ss;exports.useAlerts=As;exports.useAlertsReport=kn;exports.useApi=ve;exports.useUpdateAlertStatus=St;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),c=require("antd"),Me=require("@ant-design/icons"),pe=require("react-toastify");function Rs(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const ue=Rs(u),ks="#FF3B30",Es="#FF9500",Ms="#FFCC00",Os="#34C759",Qe={critical:ks,high:Es,medium:Ms,low:Os},Rt={Critical:Qe.critical,High:Qe.high,Medium:Qe.medium,Low:Qe.low};function Ps(e){return Rt[e]||Rt.Low}function kt(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),h=Number.isFinite(a)?a:0,f=Number.isFinite(o)?o:0,d=Number.isFinite(l)?l:0;return h*3600+f*60+d}function Et(e){const t=e.thirdPartyIds??e.ThirdPartyIds??e.thirdPartyId??e.ThirdPartyId??"",s=Array.isArray(t)?t.join(","):String(t??"");if(!s||!s.trim())return[];const r=s.split(",").map(o=>parseInt(String(o).trim(),10)).filter(o=>Number.isFinite(o)),i=new Set,a=[];return r.forEach(o=>{i.has(o)||(i.add(o),a.push(o))}),a}const Jt="",Ds=Jt,Fs="",Us="",Mt={snl:{alerts:Jt,rules:Ds},schools:{alerts:Fs,rules:Us}};function Se(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ls(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function He(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function be(e,t){const s={...t.headers,...Ls()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function $s(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Se(e.baseUrl,"/api/Alert"),r=await be(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=Se(e.baseUrl,"/api/Alert/AlertStatusList"),r=await be(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]},async getAlertsReport(s){const r=Se(e.baseUrl,"/Alerts/GetAlertsReport"),i=He(r,s),a=await be(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Se(e.baseUrl,"/api/Alert/status");return be(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=Se(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await be(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=Se(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return be(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Se(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await be(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=Se(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await be(r,{method:"POST",headers:t,body:JSON.stringify(s??{})}),a=i?.responseStatus??!0,o=i?.data??i?.message??"Preferences updated successfully.";return{responseStatus:a,errorMessage:a?"":i?.errorMessage??i?.message??"",statusCode:200,data:o}},async getAlertNotifications(s){const r=Se(e.baseUrl,"/api/Alert/GetNotifications"),i=He(r,{alertId:s}),a=await be(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]},async notifyFamilyMembers(s){const r=Se(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=He(r,{alertId:s});return be(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=Se(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=He(a,{alertId:s,isEmail:r,isSMS:i});return be(o,{method:"POST",headers:t})},async getTimeZoneMasters(){const s=Se(e.baseUrl,"/api/UserPreference/GetTimeZoneMasters"),r=await be(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]},async getMyAppPreferences(){const s=Se(e.baseUrl,"/api/UserPreference/GetMyAppPreferences"),r=await be(s,{method:"GET",headers:t});if(r&&typeof r=="object"){const i=r.data??r;if(i?.timeZoneUniqueId)return{timeZoneUniqueId:i.timeZoneUniqueId}}return null}}}function Ot(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Bs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Ge(e,t){const s={...t.headers,...Bs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function qs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=Ot(e.baseUrl,"/api/Rules"),r=Ot(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Ge(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Ge(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Ge(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Ge(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function _s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ze={exports:{}},Qs=Ze.exports,Pt;function Hs(){return Pt||(Pt=1,(function(e,t){(function(s,r){e.exports=r()})(Qs,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",h="hour",f="day",d="week",A="month",m="quarter",I="year",w="date",y="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,B=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,F={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(k){var S=["th","st","nd","rd"],p=k%100;return"["+k+(S[(p-20)%10]||S[p]||S[0])+"]"}},$=function(k,S,p){var N=String(k);return!N||N.length>=S?k:""+Array(S+1-N.length).join(p)+k},P={s:$,z:function(k){var S=-k.utcOffset(),p=Math.abs(S),N=Math.floor(p/60),g=p%60;return(S<=0?"+":"-")+$(N,2,"0")+":"+$(g,2,"0")},m:function k(S,p){if(S.date()<p.date())return-k(p,S);var N=12*(p.year()-S.year())+(p.month()-S.month()),g=S.clone().add(N,A),v=p-g<0,x=S.clone().add(N+(v?-1:1),A);return+(-(N+(p-g)/(v?g-x:x-g))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:A,y:I,w:d,d:f,D:w,h,m:l,s:o,ms:a,Q:m}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},G="en",W={};W[G]=F;var K="$isDayjsObject",Y=function(k){return k instanceof z||!(!k||!k[K])},T=function k(S,p,N){var g;if(!S)return G;if(typeof S=="string"){var v=S.toLowerCase();W[v]&&(g=v),p&&(W[v]=p,g=v);var x=S.split("-");if(!g&&x.length>1)return k(x[0])}else{var E=S.name;W[E]=S,g=E}return!N&&g&&(G=g),g||!N&&G},C=function(k,S){if(Y(k))return k.clone();var p=typeof S=="object"?S:{};return p.date=k,p.args=arguments,new z(p)},R=P;R.l=T,R.i=Y,R.w=function(k,S){return C(k,{locale:S.$L,utc:S.$u,x:S.$x,$offset:S.$offset})};var z=(function(){function k(p){this.$L=T(p.locale,null,!0),this.parse(p),this.$x=this.$x||p.x||{},this[K]=!0}var S=k.prototype;return S.parse=function(p){this.$d=(function(N){var g=N.date,v=N.utc;if(g===null)return new Date(NaN);if(R.u(g))return new Date;if(g instanceof Date)return new Date(g);if(typeof g=="string"&&!/Z$/i.test(g)){var x=g.match(b);if(x){var E=x[2]-1||0,U=(x[7]||"0").substring(0,3);return v?new Date(Date.UTC(x[1],E,x[3]||1,x[4]||0,x[5]||0,x[6]||0,U)):new Date(x[1],E,x[3]||1,x[4]||0,x[5]||0,x[6]||0,U)}}return new Date(g)})(p),this.init()},S.init=function(){var p=this.$d;this.$y=p.getFullYear(),this.$M=p.getMonth(),this.$D=p.getDate(),this.$W=p.getDay(),this.$H=p.getHours(),this.$m=p.getMinutes(),this.$s=p.getSeconds(),this.$ms=p.getMilliseconds()},S.$utils=function(){return R},S.isValid=function(){return this.$d.toString()!==y},S.isSame=function(p,N){var g=C(p);return this.startOf(N)<=g&&g<=this.endOf(N)},S.isAfter=function(p,N){return C(p)<this.startOf(N)},S.isBefore=function(p,N){return this.endOf(N)<C(p)},S.$g=function(p,N,g){return R.u(p)?this[N]:this.set(g,p)},S.unix=function(){return Math.floor(this.valueOf()/1e3)},S.valueOf=function(){return this.$d.getTime()},S.startOf=function(p,N){var g=this,v=!!R.u(N)||N,x=R.p(p),E=function(de,ee){var oe=R.w(g.$u?Date.UTC(g.$y,ee,de):new Date(g.$y,ee,de),g);return v?oe:oe.endOf(f)},U=function(de,ee){return R.w(g.toDate()[de].apply(g.toDate("s"),(v?[0,0,0,0]:[23,59,59,999]).slice(ee)),g)},D=this.$W,L=this.$M,q=this.$D,se="set"+(this.$u?"UTC":"");switch(x){case I:return v?E(1,0):E(31,11);case A:return v?E(1,L):E(0,L+1);case d:var ie=this.$locale().weekStart||0,ae=(D<ie?D+7:D)-ie;return E(v?q-ae:q+(6-ae),L);case f:case w:return U(se+"Hours",0);case h:return U(se+"Minutes",1);case l:return U(se+"Seconds",2);case o:return U(se+"Milliseconds",3);default:return this.clone()}},S.endOf=function(p){return this.startOf(p,!1)},S.$set=function(p,N){var g,v=R.p(p),x="set"+(this.$u?"UTC":""),E=(g={},g[f]=x+"Date",g[w]=x+"Date",g[A]=x+"Month",g[I]=x+"FullYear",g[h]=x+"Hours",g[l]=x+"Minutes",g[o]=x+"Seconds",g[a]=x+"Milliseconds",g)[v],U=v===f?this.$D+(N-this.$W):N;if(v===A||v===I){var D=this.clone().set(w,1);D.$d[E](U),D.init(),this.$d=D.set(w,Math.min(this.$D,D.daysInMonth())).$d}else E&&this.$d[E](U);return this.init(),this},S.set=function(p,N){return this.clone().$set(p,N)},S.get=function(p){return this[R.p(p)]()},S.add=function(p,N){var g,v=this;p=Number(p);var x=R.p(N),E=function(L){var q=C(v);return R.w(q.date(q.date()+Math.round(L*p)),v)};if(x===A)return this.set(A,this.$M+p);if(x===I)return this.set(I,this.$y+p);if(x===f)return E(1);if(x===d)return E(7);var U=(g={},g[l]=r,g[h]=i,g[o]=s,g)[x]||1,D=this.$d.getTime()+p*U;return R.w(D,this)},S.subtract=function(p,N){return this.add(-1*p,N)},S.format=function(p){var N=this,g=this.$locale();if(!this.isValid())return g.invalidDate||y;var v=p||"YYYY-MM-DDTHH:mm:ssZ",x=R.z(this),E=this.$H,U=this.$m,D=this.$M,L=g.weekdays,q=g.months,se=g.meridiem,ie=function(ee,oe,ve,ye){return ee&&(ee[oe]||ee(N,v))||ve[oe].slice(0,ye)},ae=function(ee){return R.s(E%12||12,ee,"0")},de=se||function(ee,oe,ve){var ye=ee<12?"AM":"PM";return ve?ye.toLowerCase():ye};return v.replace(B,(function(ee,oe){return oe||(function(ve){switch(ve){case"YY":return String(N.$y).slice(-2);case"YYYY":return R.s(N.$y,4,"0");case"M":return D+1;case"MM":return R.s(D+1,2,"0");case"MMM":return ie(g.monthsShort,D,q,3);case"MMMM":return ie(q,D);case"D":return N.$D;case"DD":return R.s(N.$D,2,"0");case"d":return String(N.$W);case"dd":return ie(g.weekdaysMin,N.$W,L,2);case"ddd":return ie(g.weekdaysShort,N.$W,L,3);case"dddd":return L[N.$W];case"H":return String(E);case"HH":return R.s(E,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return de(E,U,!0);case"A":return de(E,U,!1);case"m":return String(U);case"mm":return R.s(U,2,"0");case"s":return String(N.$s);case"ss":return R.s(N.$s,2,"0");case"SSS":return R.s(N.$ms,3,"0");case"Z":return x}return null})(ee)||x.replace(":","")}))},S.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},S.diff=function(p,N,g){var v,x=this,E=R.p(N),U=C(p),D=(U.utcOffset()-this.utcOffset())*r,L=this-U,q=function(){return R.m(x,U)};switch(E){case I:v=q()/12;break;case A:v=q();break;case m:v=q()/3;break;case d:v=(L-D)/6048e5;break;case f:v=(L-D)/864e5;break;case h:v=L/i;break;case l:v=L/r;break;case o:v=L/s;break;default:v=L}return g?v:R.a(v)},S.daysInMonth=function(){return this.endOf(A).$D},S.$locale=function(){return W[this.$L]},S.locale=function(p,N){if(!p)return this.$L;var g=this.clone(),v=T(p,N,!0);return v&&(g.$L=v),g},S.clone=function(){return R.w(this.$d,this)},S.toDate=function(){return new Date(this.valueOf())},S.toJSON=function(){return this.isValid()?this.toISOString():null},S.toISOString=function(){return this.$d.toISOString()},S.toString=function(){return this.$d.toUTCString()},k})(),Z=z.prototype;return C.prototype=Z,[["$ms",a],["$s",o],["$m",l],["$H",h],["$W",f],["$M",A],["$y",I],["$D",w]].forEach((function(k){Z[k[1]]=function(S){return this.$g(S,k[0],k[1])}})),C.extend=function(k,S){return k.$i||(k(S,z,C),k.$i=!0),C},C.locale=T,C.isDayjs=Y,C.unix=function(k){return C(1e3*k)},C.en=W[G],C.Ls=W,C.p={},C}))})(Ze)),Ze.exports}var Gs=Hs();const Xt=_s(Gs);function es(e){if(!e)return"By Severity";const t=e.trim().toLowerCase();return t.includes("created")?"By Created Date":t.includes("updated")||t.includes("modified")?"By Updated Date":"By Severity"}function ts(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function Dt(e){const{hours:t,minutes:s,seconds:r}=ts(e);return Xt().hour(t).minute(s).second(r).millisecond(0)}function Ce(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ws(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Ft(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function Te(e,t){const s={...t.headers,...Ws()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const ne=(...e)=>e.find(t=>t!=null);function Ks(e){return{id:String(ne(e?.AlertId,e?.alertId)??""),priority:ne(e?.Priority,e?.priority,"Low"),timestamp:ne(e?.Timestamp,e?.timestamp,""),statusType:ne(e?.Status,e?.statusType,""),description:ne(e?.Description,e?.description,""),eventName:ne(e?.EventName,e?.eventName),ruleName:ne(e?.RuleName,e?.ruleName),spaceName:ne(e?.SpaceName,e?.spaceName),assignTeam:ne(e?.AssignTeam,e?.assignTeam),cameraName:ne(e?.CameraName,e?.cameraName),type:ne(e?.Type,e?.type),mediaDetails:ne(e?.MediaDetails,e?.mediaDetails),additionalMedia:ne(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ne(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ne(e?.TimeRemaining,e?.timeRemaining),anomalyName:ne(e?.AnomalyName,e?.anomalyName),alertDetails:ne(e?.AlertDetails,e?.alertDetails),statusHistory:ne(e?.StatusHistory,e?.statusHistory),isEmailSent:ne(e?.IsEmailSent,e?.isEmailSent),isSMSSent:ne(e?.IsSMSSent,e?.isSMSSent),timeZoneUniqueId:ne(e?.TimeZoneUniqueId,e?.timeZoneUniqueId)}}function Ys(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(Ks):[]},async getAlertStatusList(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Ft(r,s),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/Log"),i={AlertId:s.alertId??s.alertUniqueId??s.AlertId,Status:s.status??s.Status??"",Notes:s.notes??s.Notes??""};return Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await Te(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await Te(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=f=>{const{hours:d,minutes:A,seconds:m}=ts(f);return(d*3600+A*60+m)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(f=>String(f)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await Te(r,{method:"POST",headers:t,body:JSON.stringify(a)}),l=o?.responseStatus??!0,h=o?.data??o?.message??"Preferences updated successfully.";return{responseStatus:l,errorMessage:l?"":o?.errorMessage??o?.Message??o?.message??"",statusCode:200,data:h}},async getAlertNotifications(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Ft(r,{alertId:s}),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function Zs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Re(e,t){const s={...t.headers,...Zs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function zs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Re(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Re(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=P=>new URL(P,e.baseUrl).toString(),i=[Re(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,h,f]=await Promise.allSettled(i),d=P=>P.status==="fulfilled"&&Array.isArray(P.value)?P.value:[],A=d(a),m=d(o),I=d(l),w=d(h),y=d(f),b=A.map(P=>({actionTypeId:Number(P?.ActionTypeId),name:P?.DisplayName??P?.Name??""})),B=m.map(P=>({recordId:P?.AnomalyId,anomalyName:P?.DisplayName??P?.Name??""})),F=I.map(P=>({thirdPartyId:Number(P?.ThirdPartyId),thirdPartyName:P?.ThirdPartyName??P?.Name??""})),$={actionTypes:b,anomalies:B,thirdParties:F};return w.length&&($.severities=w),y.length&&($.scheduleTypes=y),$},async updateRule(r,i){const a=`${s}/${r}`;return Re(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const ss=u.createContext(null);function rs({tenant:e="snl",override:t,children:s}){const r=u.useMemo(()=>{const a=t?.alertsBaseUrl?.trim()||Mt[e]?.alerts||"";let o=t?.rulesBaseUrl?.trim()||Mt[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=u.useMemo(()=>{const a=r.tenant==="schools"?Ys({baseUrl:r.alertsBaseUrl,headers:r.headers}):$s({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?zs({baseUrl:r.rulesBaseUrl,headers:r.headers}):qs({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(ss.Provider,{value:i,children:s})}function ge(){const e=u.useContext(ss);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Vs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Js={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},pt=6,yt=7;function Ut(e,t,s){const r=e===pt,i=e===yt,a=t.isEmailSent??!1,o=t.isSMSSent??!1,l=r&&a||i&&o,h=r?"Send Email":i?"Send SMS":s,f=r&&a?"Email sent":i&&o?"SMS sent":h,d=r&&a?"Email sent":i&&o?"SMS sent":`Click to ${h}`;return{isDisabled:l,buttonText:f,tooltipTitle:d}}function Xs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function er(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function it(e,t){return`${e}-${t?"email":"sms"}`}function We(e){return e===pt||e===yt}function Xe({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const tr=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function sr({value:e,onChange:t,options:s}){return n.jsx(Xe,{className:"w-[140px]",value:e,onChange:t,options:s||tr})}const rr=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function nr({value:e,onChange:t,options:s}){return n.jsx(Xe,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||rr})}function ir({value:e,onChange:t,options:s}){return n.jsx(Xe,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const ar=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function or({value:e,onChange:t,options:s}){return n.jsx(Xe,{className:"w-[130px]",value:e,onChange:t,options:s||ar})}function ns({columns:e,data:t,loading:s=!1,pageSize:r=10,rowKey:i="id",toolbar:a,tableProps:o}){return n.jsxs("div",{children:[a,n.jsx(c.Table,{rowKey:i,dataSource:t,columns:e,loading:s,pagination:{pageSize:r,showSizeChanger:!0,showTotal:l=>`Total: ${l}`},bordered:!0,...o})]})}function gt({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:h,excludeCompleted:f=!0}){const[d,A]=u.useState("All"),[m,I]=u.useState("All"),[w,y]=u.useState("All"),[b,B]=u.useState("All"),[F,$]=u.useState(""),[P,G]=u.useState([{label:"All",value:"All"}]),[W,K]=u.useState(new Set),{rules:Y,alerts:T}=ge(),C={6:{title:"Email",kind:"icon",icon:n.jsx(Me.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Me.MessageOutlined,{})}},R=u.useMemo(()=>Xs(e),[e]),z=u.useMemo(()=>er(e),[e]);u.useEffect(()=>{let v=!0;return(async()=>{try{const x=await Y.getLookups(),U=(Array.isArray(x.thirdParties)?x.thirdParties:[]).map(D=>({label:D.thirdPartyName,value:String(D.thirdPartyId)}));v&&G([{label:"All",value:"All"},...U])}catch(x){console.error("Error loading third party options",x)}})(),()=>{v=!1}},[Y]);const Z=u.useMemo(()=>(e||[]).some(v=>Et(v).length>0),[e]),k=u.useMemo(()=>(e||[]).filter(v=>{const x=d==="All"||v.priority===d,E=`${v.id} ${v.description} ${v.statusType}`.toLowerCase(),U=!F||E.includes(F.toLowerCase()),D=m==="All"||(v.anomalyName||"").toLowerCase()===m.toLowerCase(),L=w==="All"||(v.spaceName||"").toLowerCase()===w.toLowerCase(),q=!Z||b==="All"||Et(v).includes(Number(b)),se=!f||!["completed","false positive"].includes(String(v.statusType||"").toLowerCase());return x&&U&&D&&L&&q&&se}),[e,d,F,m,w,b,Z,f]),S=R,p=a&&a.length?a:z,N=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:v=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Js[v]}`,backgroundColor:Vs[v]},children:v})},{title:"Tracker",key:"tracker",width:140,render:(v,x)=>n.jsx("a",{onClick:E=>{E.preventDefault(),l?.(x,{tab:"track",sourceTab:"active"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(v,x)=>{if(o)return n.jsx(n.Fragment,{children:o(x)});const E=async(ve,ye)=>{const Le=it(x.id,ve);K(ce=>new Set(ce).add(Le));try{const ce=await T.sendSMSorEmailNotifications?.(x.id,ve,ye);ce?.responseStatus?(pe.toast.success(ce.data||(ve?"Email sent successfully":"SMS sent successfully")),h?.()):pe.toast.error(ce?.data||ce?.errorMessage||"Failed to send notification")}catch(ce){pe.toast.error(ce?.message||"Failed to send notification")}finally{K(ce=>{const De=new Set(ce);return De.delete(Le),De})}},U=pt,D=yt,L=C[U],q=C[D],se=Ut(U,x,L?.title),ie=Ut(D,x,q?.title),ae=it(x.id,!0),de=it(x.id,!1),ee=We(U)&&W.has(ae),oe=We(D)&&W.has(de);return n.jsxs(c.Space,{size:"middle",children:[n.jsx(c.Tooltip,{title:se.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:se.isDisabled,loading:ee,onClick:We(U)?()=>E(!0,!1):void 0,icon:!ee&&L?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:se.buttonText})},String(U)),n.jsx(c.Tooltip,{title:ie.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:ie.isDisabled,loading:oe,onClick:We(D)?()=>E(!1,!0):void 0,icon:!oe&&q?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:ie.buttonText})},String(D))]})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(v,x)=>{const E=x?.timeElapsed,U=x?.timeRemaining,D=E?kt(E):0,L=U?kt(U):0,q=Math.round(D/(D+L)*100);return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Elapsed:"}),n.jsx("span",{className:"font-medium",children:E??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Ps(x.priority)}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Remaining"}),n.jsx("span",{className:"font-medium",children:U??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(v,x)=>n.jsxs("div",{children:[n.jsx("a",{onClick:E=>{E.preventDefault(),l?.(x,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:x.alertNumber}),n.jsx("div",{className:"text-black/65",children:v})]})}],g=r&&r.length?r:N;return n.jsx("div",{children:n.jsx(ns,{rowKey:"id",data:k,columns:g,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(sr,{value:d,onChange:A,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(nr,{value:m,onChange:I,options:S})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(ir,{value:w,onChange:y,options:p})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(or,{value:b,onChange:B,options:P})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:$,onChange:v=>$(v.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Ue=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},lr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},cr=class{#e=lr;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Ee=new cr;function ur(e){setTimeout(e,0)}var Oe=typeof window>"u"||"Deno"in globalThis;function me(){}function dr(e,t){return typeof e=="function"?e(t):e}function ot(e){return typeof e=="number"&&e>=0&&e!==1/0}function is(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ke(e,t){return typeof e=="function"?e(t):e}function Ae(e,t){return typeof e=="function"?e(t):e}function Lt(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==vt(o,t.options))return!1}else if(!Be(t.queryKey,o))return!1}if(s!=="all"){const h=t.isActive();if(s==="active"&&!h||s==="inactive"&&h)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||i&&i!==t.state.fetchStatus||a&&!a(t))}function $t(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Pe(t.options.mutationKey)!==Pe(a))return!1}else if(!Be(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function vt(e,t){return(t?.queryKeyHashFn||Pe)(e)}function Pe(e){return JSON.stringify(e,(t,s)=>ct(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Be(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Be(e[s],t[s])):!1}var hr=Object.prototype.hasOwnProperty;function lt(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Bt(e)&&Bt(t);if(!r&&!(ct(e)&&ct(t)))return t;const a=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),l=o.length,h=r?new Array(l):{};let f=0;for(let d=0;d<l;d++){const A=r?d:o[d],m=e[A],I=t[A];if(m===I){h[A]=m,(r?d<a:hr.call(e,A))&&f++;continue}if(m===null||I===null||typeof m!="object"||typeof I!="object"){h[A]=I;continue}const w=lt(m,I,s+1);h[A]=w,w===m&&f++}return a===l&&f===a?e:h}function ze(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Bt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ct(e){if(!qt(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!qt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function qt(e){return Object.prototype.toString.call(e)==="[object Object]"}function fr(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function ut(e,t,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(e,t);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return lt(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${r}`),r}return lt(e,t)}return t}function mr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function pr(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var Ve=Symbol();function as(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ve&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ve?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function xt(e,t){return typeof e=="function"?e(...t):!!e}function yr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var gr=class extends Ue{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},St=new gr;function dt(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var vr=ur;function xr(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=vr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(h=>{s(h)})})})};return{batch:l=>{let h;t++;try{h=l()}finally{t--,t||o()}return h},batchCalls:l=>(...h)=>{a(()=>{l(...h)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var le=xr(),Sr=class extends Ue{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(s=>{s(e)}))}isOnline(){return this.#e}},Je=new Sr;function br(e){return Math.min(1e3*2**e,3e4)}function os(e){return(e??"online")==="online"?Je.isOnline():!0}var ht=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ls(e){let t=!1,s=0,r;const i=dt(),a=()=>i.status!=="pending",o=y=>{if(!a()){const b=new ht(y);m(b),e.onCancel?.(b)}},l=()=>{t=!0},h=()=>{t=!1},f=()=>St.isFocused()&&(e.networkMode==="always"||Je.isOnline())&&e.canRun(),d=()=>os(e.networkMode)&&e.canRun(),A=y=>{a()||(r?.(),i.resolve(y))},m=y=>{a()||(r?.(),i.reject(y))},I=()=>new Promise(y=>{r=b=>{(a()||f())&&y(b)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),w=()=>{if(a())return;let y;const b=s===0?e.initialPromise:void 0;try{y=b??e.fn()}catch(B){y=Promise.reject(B)}Promise.resolve(y).then(A).catch(B=>{if(a())return;const F=e.retry??(Oe?0:3),$=e.retryDelay??br,P=typeof $=="function"?$(s,B):$,G=F===!0||typeof F=="number"&&s<F||typeof F=="function"&&F(s,B);if(t||!G){m(B);return}s++,e.onFail?.(s,B),fr(P).then(()=>f()?void 0:I()).then(()=>{t?m(B):w()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:h,canStart:d,start:()=>(d()?w():I().then(w),i)}}var cs=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ot(this.gcTime)&&(this.#e=Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Oe?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Ee.clearTimeout(this.#e),this.#e=void 0)}},Ar=class extends cs{#e;#t;#s;#n;#r;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#n=e.client,this.#s=this.#n.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Qt(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Qt(this.options);t.data!==void 0&&(this.setState(_t(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=ut(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(me).catch(me):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Ae(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ve||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ke(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!is(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(h=>h.options.queryFn);l&&this.setOptions(l.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,s.signal)})},i=()=>{const l=as(this.options,t),f=(()=>{const d={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(l,f,this):l(f)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=ls({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof ht&&l.revert&&this.setState({...this.#t,fetchStatus:"idle"}),s.abort()},onFail:(l,h)=>{this.#i({type:"failed",failureCount:l,error:h})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const l=await this.#r.start();if(l===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#s.config.onSuccess?.(l,this),this.#s.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof ht){if(l.silent)return this.#r.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#s.config.onError?.(l,this),this.#s.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...us(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,..._t(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?r:void 0,r;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),le.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function us(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:os(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function _t(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Qt(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var wr=class extends Ue{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=dt(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#a;#o;#i;#p;#h;#f;#c;#u;#l;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ht(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ft(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ft(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#b(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ae(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!ze(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&Gt(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(t.enabled,this.#t)||ke(this.options.staleTime,this.#t)!==ke(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return Nr(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(me)),t}#y(){this.#S();const e=ke(this.options.staleTime,this.#t);if(Oe||this.#n.isStale||!ot(e))return;const s=is(this.#n.dataUpdatedAt,e)+1;this.#c=Ee.setTimeout(()=>{this.#n.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#b(),this.#l=e,!(Oe||Ae(this.options.enabled,this.#t)===!1||!ot(this.#l)||this.#l===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||St.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#S(){this.#c&&(Ee.clearTimeout(this.#c),this.#c=void 0)}#b(){this.#u&&(Ee.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,h=e!==s?e.state:this.#s,{state:f}=e;let d={...f},A=!1,m;if(t._optimisticResults){const Y=this.hasListeners(),T=!Y&&Ht(e,t),C=Y&&Gt(e,s,t,r);(T||C)&&(d={...d,...us(f.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:I,errorUpdatedAt:w,status:y}=d;m=d.data;let b=!1;if(t.placeholderData!==void 0&&m===void 0&&y==="pending"){let Y;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(Y=i.data,b=!0):Y=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,Y!==void 0&&(y="success",m=ut(i?.data,Y,t),A=!0)}if(t.select&&m!==void 0&&!b)if(i&&m===a?.data&&t.select===this.#p)m=this.#h;else try{this.#p=t.select,m=t.select(m),m=ut(i?.data,m,t),this.#h=m,this.#i=null}catch(Y){this.#i=Y}this.#i&&(I=this.#i,m=this.#h,w=Date.now(),y="error");const B=d.fetchStatus==="fetching",F=y==="pending",$=y==="error",P=F&&B,G=m!==void 0,K={status:y,fetchStatus:d.fetchStatus,isPending:F,isSuccess:y==="success",isError:$,isInitialLoading:P,isLoading:P,data:m,dataUpdatedAt:d.dataUpdatedAt,error:I,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>h.dataUpdateCount||d.errorUpdateCount>h.errorUpdateCount,isFetching:B,isRefetching:B&&!F,isLoadingError:$&&!G,isPaused:d.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:$&&G,isStale:bt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ae(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const Y=K.data!==void 0,T=K.status==="error"&&!Y,C=Z=>{T?Z.reject(K.error):Y&&Z.resolve(K.data)},R=()=>{const Z=this.#o=K.promise=dt();C(Z)},z=this.#o;switch(z.status){case"pending":e.queryHash===s.queryHash&&C(z);break;case"fulfilled":(T||K.data!==z.value)&&R();break;case"rejected":(!T||K.error!==z.reason)&&R();break}}return K}updateResult(){const e=this.#n,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#a=this.options,this.#r.data!==void 0&&(this.#f=this.#t),ze(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;const a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#n).some(o=>{const l=o;return this.#n[l]!==e[l]&&a.has(l)})};this.#w({listeners:s()})}#A(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#w(e){le.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function jr(e,t){return Ae(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ht(e,t){return jr(e,t)||e.state.data!==void 0&&ft(e,t,t.refetchOnMount)}function ft(e,t,s){if(Ae(t.enabled,e)!==!1&&ke(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&bt(e,t)}return!1}function Gt(e,t,s,r){return(e!==t||Ae(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&bt(e,s)}function bt(e,t){return Ae(t.enabled,e)!==!1&&e.isStaleByTime(ke(t.staleTime,e))}function Nr(e,t){return!ze(e.getCurrentResult(),t)}function Wt(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},h=0;const f=async()=>{let d=!1;const A=w=>{yr(w,()=>t.signal,()=>d=!0)},m=as(t.options,t.fetchOptions),I=async(w,y,b)=>{if(d)return Promise.reject();if(y==null&&w.pages.length)return Promise.resolve(w);const F=(()=>{const W={client:t.client,queryKey:t.queryKey,pageParam:y,direction:b?"backward":"forward",meta:t.options.meta};return A(W),W})(),$=await m(F),{maxPages:P}=t.options,G=b?pr:mr;return{pages:G(w.pages,$,P),pageParams:G(w.pageParams,y,P)}};if(i&&a.length){const w=i==="backward",y=w?Cr:Kt,b={pages:a,pageParams:o},B=y(r,b);l=await I(b,B,w)}else{const w=e??a.length;do{const y=h===0?o[0]??r.initialPageParam:Kt(r,l);if(h>0&&y==null)break;l=await I(l,y),h++}while(h<w)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(f,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=f}}}function Kt(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function Cr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Tr=class extends cs{#e;#t;#s;#n;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#t=[],this.state=e.state||ds(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=ls({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{this.#r({type:"failed",failureCount:a,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const r=this.state.status==="pending",i=!this.#n.canStart();try{if(r)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:i})}const a=await this.#n.start();return await this.#s.config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),this.#r({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#r(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),le.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ds(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir=class extends Ue{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Tr({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=Ke(e);if(typeof t=="string"){const s=this.#t.get(t);s?s.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ke(e);if(typeof t=="string"){const s=this.#t.get(t);if(s)if(s.length>1){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ke(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ke(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){le.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>$t(t,s))}findAll(e={}){return this.getAll().filter(t=>$t(e,t))}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return le.batch(()=>Promise.all(e.map(t=>t.continue().catch(me))))}};function Ke(e){return e.options.scope?.id}var Rr=class extends Ue{#e;#t=void 0;#s;#n;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#e.defaultMutationOptions(e),ze(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Pe(t.mutationKey)!==Pe(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#r(),this.#a()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#r(){const e=this.#s?.state??ds();this.#t={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#a(e){le.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,t,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,t,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#t)})})}},kr=class extends Ue{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??vt(r,t);let a=this.get(i);return a||(a=new Ar({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){le.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Lt(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Lt(e,s)):t}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){le.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Er=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new kr,this.#t=e.mutationCache||new Ir,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=St.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Je.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#e.build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(ke(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=dr(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return le.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;le.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return le.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=le.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(me).catch(me)}invalidateQueries(e,t={}){return le.batch(()=>(this.#e.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=le.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(me)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(me)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(ke(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(me).catch(me)}fetchInfiniteQuery(e){return e.behavior=Wt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(me).catch(me)}ensureInfiniteQueryData(e){return e.behavior=Wt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Je.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Pe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Be(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Pe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Be(e,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=vt(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ve&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},hs=ue.createContext(void 0),At=e=>{const t=ue.useContext(hs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Mr=({client:e,children:t})=>(ue.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(hs.Provider,{value:e,children:t})),fs=ue.createContext(!1),Or=()=>ue.useContext(fs);fs.Provider;function Pr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Dr=ue.createContext(Pr()),Fr=()=>ue.useContext(Dr),Ur=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?xt(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Lr=e=>{ue.useEffect(()=>{e.clearReset()},[e])},$r=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||xt(s,[e.error,r])),Br=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},qr=(e,t)=>e.isLoading&&e.isFetching&&!t,_r=(e,t)=>e?.suspense&&t.isPending,Yt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Qr(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Or(),i=Fr(),a=At(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",Br(o),Ur(o,i,l),Lr(i);const h=!a.getQueryCache().get(o.queryHash),[f]=ue.useState(()=>new t(a,o)),d=f.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(ue.useSyncExternalStore(ue.useCallback(m=>{const I=A?f.subscribe(le.batchCalls(m)):me;return f.updateResult(),I},[f,A]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),ue.useEffect(()=>{f.setOptions(o)},[o,f]),_r(o,d))throw Yt(o,f,i);if($r({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Oe&&qr(d,r)&&(h?Yt(o,f,i):l?.promise)?.catch(me).finally(()=>{f.updateResult()}),o.notifyOnChangeProps?d:f.trackResult(d)}function qe(e,t){return Qr(e,wr)}function Hr(e,t){const s=At(),[r]=ue.useState(()=>new Rr(s,e));ue.useEffect(()=>{r.setOptions(e)},[r,e]);const i=ue.useSyncExternalStore(ue.useCallback(o=>r.subscribe(le.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ue.useCallback((o,l)=>{r.mutate(o,l).catch(me)},[r]);if(i.error&&xt(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function wt(){const{alerts:e}=ge(),t=At();return Hr({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Gr(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function Wr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(h=>h.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Kr(e){if(!e)return"-";try{const t=new Date(e),s=f=>String(f).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),h=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${h}`}catch{return"-"}}function mt(e,t="UTC"){if(!e)return"-";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(s)}const Yr={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Zr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function ms({alerts:e,loading:t=!1,pageSize:s=10,severityOptions:r,anomalyOptions:i,spaceOptions:a,onAlertIdClick:o}){const l=wt(),h=["completed","false positive"],f=async m=>{try{const I=await l.mutateAsync({alertUniqueId:m.alertId??m.id,alertId:m.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(I?.responseStatus){const w=I?.data||"Alert reopened successfully.";pe.toast.success(w)}else{const w=I?.errorMessage||"Failed to reopen alert";pe.toast.error(w)}}catch{pe.toast.error("Failed to reopen alert. Please try again.")}},d=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:m=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Yr[m]}`,backgroundColor:Zr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Kr(m)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(m,I)=>n.jsxs("div",{children:[n.jsx("a",{onClick:w=>{w.preventDefault(),o?.(I,{sourceTab:"archived"})},className:"inline-block mb-1 text-blue-600",children:I.alertNumber}),n.jsx("div",{className:"text-black/65",children:m})]})},{title:"",key:"menu",width:60,align:"right",render:(m,I)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:w})=>{w==="reopen"&&f(I)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(Me.MoreOutlined,{})})})}],A=(e||[]).filter(m=>h.includes((m.statusType||"").toLowerCase()));return n.jsx(gt,{data:A,loading:t,pageSize:s,columns:d,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function zr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=u.useMemo(()=>{const A=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(A.find(m=>m.type==="hour")?.value||"0",10),minutes:parseInt(A.find(m=>m.type==="minute")?.value||"0",10),seconds:parseInt(A.find(m=>m.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,h=r%12*30+i*.5,f=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((d,A)=>{const m=A*30,I=6,w=f-4,y=w-I,b=(m-90)*(Math.PI/180),B=f+y*Math.cos(b),F=f+y*Math.sin(b),$=f+w*Math.cos(b),P=f+w*Math.sin(b);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:B,y1:F,x2:$,y2:P,stroke:"#9CA3AF",strokeWidth:A%3===0?2:1,strokeLinecap:"round"})},A)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${h}deg)`},children:n.jsx("line",{x1:f,y1:f,x2:f,y2:f-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:f,y1:f,x2:f,y2:f-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:f,y1:f+e*.08,x2:f,y2:f-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:f-4,top:f-4}})]})}function ps({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=u.useState(new Date);u.useEffect(()=>{const f=setInterval(()=>a(new Date),s);return()=>clearInterval(f)},[s]);const o=u.useMemo(()=>Gr(i,t),[i,t]),{abbr:l,offset:h}=u.useMemo(()=>Wr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(zr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),h&&n.jsx("span",{className:"text-xs text-gray-500",children:h})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Vr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Jr=[{RuleId:"0938aa00-dfa7-4258-805a-67396366c776",RuleVersionId:"36d2d581-57c3-45c3-8705-8235935fdf96",Name:"License Plate Recognition",Description:"License Plate Recognition",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"915976ef-4eb6-4f7b-bbe6-e53862517fc9",Level:"global"},{RuleId:"2437286a-db6a-4d35-814e-9ac49f158dde",RuleVersionId:"00000000-0000-0000-0000-000000000000",Name:"Monitor And Track Onsite Vehicle timelog",Description:"Monitor And Track Onsite Vehicle timelog",VersionCount:0,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"9fd651ab-4312-4826-84b6-94d735894477",Level:"global"},{RuleId:"b99120ba-7a83-4ade-b5d9-a420550fe351",RuleVersionId:"d7b14dae-a7b1-474e-a357-199182c02ac3",Name:"Watchlist person detected",Description:"Watchlist person detected",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"bb3a3d3a-73a3-4f5a-8804-1baadbd0d412",Level:"global"},{RuleId:"ffc2c24f-adb7-4aba-ace7-f19c54e21530",RuleVersionId:"6ab3178f-bf77-4a1e-898d-1d5dbef749c5",Name:"Weapon Detection",Description:"Weapon Detection",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"ac82c3a2-72e6-4f9c-88fb-851a3ca3c4de",Level:"global"}],Xr=[{userRoleId:1,userRoleName:"Super Admin"},{userRoleId:2,userRoleName:"Security Officer"},{userRoleId:3,userRoleName:"Security Admin"},{userRoleId:4,userRoleName:"Regulatory Officer/First Responder"},{userRoleId:5,userRoleName:"User"}],Fe={severities:Vr,rules:Jr,userRoles:Xr},{Text:en}=c.Typography;function tn({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(en,{className:"text-gray-600 whitespace-nowrap",children:"Sort By:"}),n.jsx(c.Select,{placeholder:"By Severity",value:e,onChange:o=>t({sortBy:o}),options:[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],className:"w-full",style:{minWidth:"200px"}})]})}),n.jsx(c.Col,{xs:24,md:8,style:{alignSelf:"end"},children:s?n.jsxs(c.Space,{className:"w-full",direction:"horizontal",size:8,children:[n.jsx(c.Button,{onClick:i,disabled:a,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:r,loading:a,children:"Save"})]}):null})]})}const{Text:Ie}=c.Typography;function sn(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:h,setL1role:f,l2mins:d,setL2mins:A,l2role:m,setL2role:I,l3mins:w,setL3mins:y,l3role:b,setL3role:B,actions:F,setActions:$,thirdPartyIds:P,setThirdPartyIds:G,humanLoop:W,setHumanLoop:K,isAutoExpire:Y,setAutoExpire:T,onClear:C,onSave:R,saving:z,onActionTypesLoaded:Z}=e,{rules:k}=ge(),[S,p]=u.useState([]),[N,g]=u.useState([]),[v,x]=u.useState(!1);u.useEffect(()=>{let L=!1;return(async()=>{try{x(!0);const q=await k.getLookups();if(L||!q||!Array.isArray(q.actionTypes))return;const se=q.actionTypes.map(ae=>({label:ae.name,value:String(ae.actionTypeId)}));p(se),Z&&Z(q.actionTypes);const ie=Array.isArray(q.thirdParties)?q.thirdParties.map(ae=>({label:ae.thirdPartyName,value:ae.thirdPartyId})):[];g(ie)}catch(q){console.error("Error loading lookups",q)}finally{L||x(!1)}})(),()=>{L=!0}},[]);const E=L=>n.jsxs(c.Tag,{children:[n.jsx(Me.PlusOutlined,{})," ",L.length," more"]}),U=typeof o=="number"||typeof h=="number"||typeof d=="number"||typeof m=="number"||typeof w=="number"||typeof b=="number"||Array.isArray(F)&&F.length>0||Array.isArray(P)&&P.length>0||!!W||!!Y,D=!!t&&U&&!z;return n.jsxs(c.Spin,{spinning:!!z||v,children:[n.jsxs(c.Row,{gutter:[16,16],align:"bottom",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Rules"}),n.jsx(c.Select,{placeholder:"Rules",value:t,onChange:s,options:r,className:"w-full"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:h,onChange:f,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:d,onChange:A,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:m,onChange:I,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:w,onChange:y,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:b,onChange:B,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Pick Actions"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Select response actions",className:"w-full",value:F,onChange:$,options:S,maxTagCount:1,maxTagPlaceholder:E})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Third Party App"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Third Party app",className:"w-full",value:P,onChange:G,options:N})]})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4 items-center",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:7,children:n.jsxs("div",{className:"flex items-center h-full gap-8",children:[n.jsx(c.Checkbox,{checked:W,onChange:L=>K(L.target.checked),className:"w-full",children:"Human-In-The-Loop"}),n.jsx(c.Checkbox,{checked:Y,onChange:L=>T(L.target.checked),className:"w-full",children:"Auto-expire in 5 minutes"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:C,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:R,loading:!!z,disabled:!D,children:"Save"})]})})]})]})}function rn({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions?.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify?.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Auto Expire",key:"isAutoExpire",render:(o,l)=>l.isAutoExpire?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(Me.EditOutlined,{})})}]})}const{Title:nn}=c.Typography;function ys({userRoles:e,rules:t,rawRules:s}){const{rules:r}=ge(),[i,a]=u.useState(!1),[o,l]=u.useState(s),[h,f]=u.useState({}),d=u.useMemo(()=>e.map(y=>({label:y.userRoleName,value:y.userRoleId})),[e]),A=u.useMemo(()=>(t||[]).map((y,b)=>({key:y.RuleId||y.Name||String(b),ruleName:y.Name||"-",ruleDesc:y.Description||""})),[t]);u.useEffect(()=>{let y=!1;return(async()=>{try{a(!0);const b=await r.getRules();y||(l(Array.isArray(b)?b:[]),f({}))}catch{!y&&Array.isArray(s)&&l(s)}finally{y||a(!1)}})(),()=>{y=!0}},[]),u.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const m=u.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const y={};for(const b of A){const B=o.find($=>$?.ruleId===b.key||$?.ruleName===b.key||$?.RuleId===b.key||$?.ruleName===b.ruleName||$?.Name===b.ruleName),F=Array.isArray(B?.userRoleIds)?B.userRoleIds:[];F.length&&(y[b.key]=F)}return y},[o,A]),I=()=>{f({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(h).length===0){pe.toast.info("No changes to save");return}a(!0);const y=Object.entries(h).map(async([b,B])=>{const F=o.find(K=>K?.ruleId===b||K?.ruleName===b||K?.RuleId===b),$=typeof F?.recordId=="number"?F.recordId:void 0;if(!F||typeof $!="number")throw new Error(`Unable to find recordId for rule ${b}`);const P=Array.isArray(B)?B:[],G=P.map(K=>{const Y=e.find(T=>T.userRoleId===K);return{id:K,name:Y?.userRoleName??String(K)}}),W={...F,ruleId:b,userRoleIds:P,userRoles:G,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}]};return r.updateRule($,W)});await Promise.all(y),pe.toast.success("Alert assignment saved");try{const b=await r.getRules();l(Array.isArray(b)?b:[]),f({})}catch(b){console.error("Failed to refresh rules after save",b)}}catch(y){console.error("Failed to save alert assignment",y)}finally{a(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx(nn,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:A,loading:i,pagination:!1,columns:[{title:"Rule Name",dataIndex:"ruleName",key:"ruleName"},{title:"Description",dataIndex:"ruleDesc",key:"ruleDesc"},{title:"Alert Notification To",key:"assign",render:(y,b)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:h[b.key]??m[b.key]??[],onChange:B=>f(F=>({...F,[b.key]:B})),options:d})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:I,disabled:i,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:w,loading:i,disabled:i||Object.keys(h).length===0,children:"Save"})]})]})}const{Title:Zt}=c.Typography;function gs({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=ge(),[l,h]=u.useState("By Severity"),[f,d]=u.useState("By severity"),[A,m]=u.useState("By Severity"),[I,w]=u.useState(!1),[y,b]=u.useState(!1),[B,F]=u.useState(!1),[$,P]=u.useState(null),[G,W]=u.useState("rules"),[K,Y]=u.useState(),[T,C]=u.useState(),[R,z]=u.useState(),[Z,k]=u.useState(),[S,p]=u.useState(),[N,g]=u.useState(),[v,x]=u.useState(),[E,U]=u.useState(),[D,L]=u.useState([]),[q,se]=u.useState([]),[ie,ae]=u.useState(!1),[de,ee]=u.useState(!1),[oe,ve]=u.useState({}),[ye,Le]=u.useState({}),[ce,De]=u.useState(s||[]),[$e,je]=u.useState([]),[et,j]=u.useState(!1),[H,re]=u.useState(!1),[he,J]=u.useState(r||[]);u.useEffect(()=>{r&&r.length&&J(r)},[r]),u.useEffect(()=>{if(!he||!he.length)return;const M=Object.keys(oe).length>0||Object.keys(ye).length>0;if($e.length&&!M)return;const X=he.map((_,O)=>{const V=t.find(fe=>fe.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",Q=_.escalationSettings||{},te=typeof Q.level1UserRoleId=="number"&&Q.level1UserRoleId>0?[Q.level1UserRoleId]:[],Ne=typeof Q.level2UserRoleId=="number"&&Q.level2UserRoleId>0?[Q.level2UserRoleId]:[],st=typeof Q.level3UserRoleId=="number"&&Q.level3UserRoleId>0?[Q.level3UserRoleId]:[],Ct=(Array.isArray(Q.escalationSettingsActionTypeIds)?Q.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),It=(Array.isArray(Q.thirdPartyId)?Q.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),rt=typeof Q.humanLoop=="boolean"?Q.humanLoop:null,nt=typeof Q.isAutoExpire=="boolean"?Q.isAutoExpire:null;return{id:String(_.ruleId||_.ruleName||O),ruleOrSeverityLabel:V,l1:{minutes:Q.level1PostAssistTime??void 0,roles:te},l2:{minutes:Q.level2PostAssistTime??void 0,roles:Ne},l3:{minutes:Q.level3PostAssistTime??void 0,roles:st},actions:Ct,notify:It,humanLoop:rt,isAutoExpire:nt}});je(X)},[he,t,oe,ye]);const we=u.useMemo(()=>e.map(M=>({label:M.DisplayName,value:M.SeverityId})),[e]),_e=u.useMemo(()=>t.map(M=>({label:M.Name,value:M.RuleId})),[t]),xe=u.useMemo(()=>ce.map(M=>({label:M.userRoleName,value:M.userRoleId})),[ce]),tt=u.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(M=>({label:`${M}`,value:M})),[]);u.useEffect(()=>{let M=!1;async function X(){try{F(!0),P(null);const _=await o.getAdminSettings();if(!M&&_){const O=es(_.sortBy);h(O),m(O),w(!1)}}catch(_){if(!M){const O=_ instanceof Error?_.message:"Failed to load admin settings";P(O)}}finally{M||F(!1)}}return X(),()=>{M=!0}},[]),u.useEffect(()=>{if(!T)return;const M=V=>{const Q=Number(V);return!isNaN(Q)&&Q>0?Q:void 0},X=V=>{const Q=Number(V);return!isNaN(Q)&&Q>0?Q:void 0},O=(he||[]).find(V=>V?.ruleId===T||V?.ruleName===T||V?.RuleId===T)?.escalationSettings;if(O&&typeof O=="object"){z(X(O.level1PostAssistTime)),k(M(O.level1UserRoleId)),p(X(O.level2PostAssistTime)),g(M(O.level2UserRoleId)),x(X(O.level3PostAssistTime)),U(M(O.level3UserRoleId));const V=Array.isArray(O.escalationSettingsActionTypeIds)?O.escalationSettingsActionTypeIds:[];L(V.map(Q=>String(Q))),se(Array.isArray(O.thirdPartyId)?O.thirdPartyId:[]),ae(!!O.humanLoop),ee(!!O.isAutoExpire)}},[G,T,he]);const js=async()=>{try{re(!0);const M=await a.getRules(),X=Array.isArray(M)?M:Array.isArray(M?.data)?M.data:[];J(X);const _=X.map((O,V)=>{const Q=t.find(fe=>fe.RuleId===(O.ruleId||O.ruleName))?.Name||O.ruleName||O.Name||"-",te=O.escalationSettings||{},Ne=typeof te.level1UserRoleId=="number"&&te.level1UserRoleId>0?[te.level1UserRoleId]:[],st=typeof te.level2UserRoleId=="number"&&te.level2UserRoleId>0?[te.level2UserRoleId]:[],Nt=typeof te.level3UserRoleId=="number"&&te.level3UserRoleId>0?[te.level3UserRoleId]:[],Tt=(Array.isArray(te.escalationSettingsActionTypeIds)?te.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),rt=(Array.isArray(te.thirdPartyId)?te.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),nt=typeof te.humanLoop=="boolean"?te.humanLoop:null;return{id:String(O.ruleId||O.ruleName||V),ruleOrSeverityLabel:Q,l1:{minutes:te.level1PostAssistTime??void 0,roles:Ne},l2:{minutes:te.level2PostAssistTime??void 0,roles:st},l3:{minutes:te.level3PostAssistTime??void 0,roles:Nt},actions:Tt,notify:rt,humanLoop:nt}});je(_)}catch(M){console.error("Failed to refetch entries",M)}finally{re(!1)}};u.useEffect(()=>{let M=!1;return(async()=>{try{const X=await a.getLookups();if(M||!X)return;const _={};if(Array.isArray(X.thirdParties))for(const V of X.thirdParties)typeof V.thirdPartyId=="number"&&(_[V.thirdPartyId]=V.thirdPartyName);Le(_);const O=Array.isArray(X.userRoles)?X.userRoles.map(V=>({userRoleId:V.userRoleId??V.id,userRoleName:V.userRoleName??V.name})):[];M||De(O.length?O:s||[])}catch(X){console.error("Error loading lookups",X)}})(),()=>{M=!0}},[]);const Ns=async()=>{b(!0);try{const M=await o.setAdminSettings({sortBy:l,groupBy:"string"});M?.responseStatus&&M?.data&&pe.toast.success(M.data),m(l),w(!1)}catch(M){console.error("Error saving admin settings",M)}finally{b(!1)}},Cs=()=>{h(A),w(!1)},Ts=async()=>{j(!0),i?.({ruleId:T,levels:[{minutes:R,role:Z},{minutes:S,role:N},{minutes:v,role:E}],actions:D,thirdPartyIds:q,humanLoop:ie,isAutoExpire:de});try{if(T){const _=Array.isArray(D)?D.map(Ne=>Number(Ne)):[],O=(he||[]).find(Ne=>Ne?.ruleId===T||Ne?.ruleName===T||Ne?.RuleId===T),V=typeof O?.recordId=="number"?O.recordId:void 0;if(!O||typeof V!="number"){pe.toast.error("Unable to find rule recordId for update");return}const Q={...O,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}],escalationSettings:{level1UserRoleId:Z??0,level1PostAssistTime:R??0,level2UserRoleId:N??0,level2PostAssistTime:S??0,level3UserRoleId:E??0,level3PostAssistTime:v??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:ie,isAutoExpire:de}},te=await a.updateRule(V,Q);if(te?.responseStatus||te?.ok||te){pe.toast.success("Escalation settings saved"),await js(),C(void 0),z(void 0),k(void 0),p(void 0),g(void 0),x(void 0),U(void 0),L([]),se([]),ae(!1),ee(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{j(!1)}const X=t.find(_=>_.RuleId===T)?.Name||"-";je(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:X,l1:{minutes:R,roles:Z?[Z]:[]},l2:{minutes:S,roles:N?[N]:[]},l3:{minutes:v,roles:E?[E]:[]},actions:(Array.isArray(D)?D:[]).map(O=>{const V=Number(O);return oe[V]||String(O)}),notify:(Array.isArray(q)?q:[]).map(O=>ye[O]||String(O)),humanLoop:!!ie,isAutoExpire:!!de}])},Is=()=>{h("By Severity"),d("By severity"),W("rules"),Y(void 0),C(void 0),z(void 0),k(void 0),p(void 0),g(void 0),x(void 0),U(void 0),L([]),se([]),ae(!1),ee(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Zt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:B,children:[$?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",$]}):null,n.jsx(tn,{sortBy:l,groupBy:f,onChange:M=>{M.sortBy&&(h(M.sortBy),w(!0)),M.groupBy&&(d(M.groupBy),w(!0))},showActions:I,onSave:Ns,onClear:Cs,saving:y})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Zt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(sn,{escBasis:G,setEscBasis:W,selectedSeverity:K,setSelectedSeverity:Y,selectedRule:T,setSelectedRule:C,severityOptions:we,ruleOptions:_e,minsOptions:tt,roleOptions:xe,l1mins:R,setL1mins:z,l1role:Z,setL1role:k,l2mins:S,setL2mins:p,l2role:N,setL2role:g,l3mins:v,setL3mins:x,l3role:E,setL3role:U,actions:D,setActions:L,thirdPartyIds:q,setThirdPartyIds:se,humanLoop:ie,setHumanLoop:ae,onClear:Is,onSave:Ts,saving:et,onActionTypesLoaded:M=>{const X={};for(const _ of M)typeof _.actionTypeId=="number"&&(X[_.actionTypeId]=_.name);ve(X)},isAutoExpire:de,setAutoExpire:ee})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(rn,{entries:$e,userRoles:ce,loading:H,onEdit:M=>{W("rules");const X=$e.find(O=>O.id===M),_=t.find(O=>O.RuleId===M)||(X?t.find(O=>O.Name===X.ruleOrSeverityLabel):void 0);C(_?_.RuleId:M)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(ys,{userRoles:ce,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:zt,Text:Ye}=c.Typography;function an({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=ge(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,h]=u.useState("By Severity"),[f,d]=u.useState(new Set),[A,m]=u.useState(null),[I,w]=u.useState(null),[y,b]=u.useState({inApp:!1,sms:!1,email:!1}),[B,F]=u.useState([]),[$,P]=u.useState(!0),[G,W]=u.useState(!1);u.useEffect(()=>{let T=!1;return(async()=>{try{const C=await a.getPreferenceSettings();if(T||!C)return;b({inApp:!!C.inApp,sms:!!C.sms,email:!!C.email});const R=es(C.sortBy);h(R==="By Created Date"?"By Created Date":"By Severity"),m(Dt(C.doNotDisturbStart)),w(Dt(C.doNotDisturbEnd)),Array.isArray(C.anomalyIds)&&d(new Set(C.anomalyIds.map(z=>String(z))))}catch(C){console.error("Error in loading my preferences: ",C)}})(),()=>{T=!0}},[]),u.useEffect(()=>{let T=!1;return(async()=>{try{P(!0);const C=await i.getLookups();if(T||!C)return;const R=Array.isArray(C.anomalies)?C.anomalies:[];F(R)}catch(C){console.error("Failed to load anomalies lookups",C)}finally{T||P(!1)}})(),()=>{T=!0}},[]);const K=T=>{d(C=>{const R=new Set(C);return R.has(T)?R.delete(T):R.add(T),R})},Y=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(f),dnd:{from:A,to:I},channels:y});try{W(!0);const T=A?A.format?.("HH:mm:ss")??"00:00:00":"00:00:00",C=I?I.format?.("HH:mm:ss")??"00:00:00":"00:00:00",R=Array.from(f).map(Z=>Number(Z)).filter(Z=>Number.isFinite(Z)),z=await a.setPreferenceSettings({anomalyIds:R,doNotDisturbStart:T,doNotDisturbEnd:C,inApp:!!y.inApp,sms:!!y.sms,email:!!y.email,sortBy:l});z?.responseStatus&&pe.toast.success(z?.data||"Preferences updated successfully.")}catch(T){console.error("Error in saving my preferences: ",T)}finally{W(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-4",children:n.jsx(c.Col,{xs:24,md:8,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(Ye,{className:"text-gray-600",children:"Sort By:"}),n.jsx(c.Select,{className:"w-[240px]",value:l,options:o,onChange:h})]})})}),n.jsxs("div",{className:"mb-4",children:[n.jsx(zt,{level:5,className:"!mb-2",children:"Anomalies"}),$?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray(B)?B:[]).map(T=>{const C=String(T.recordId),R=T.anomalyName;return n.jsx(c.Checkbox,{checked:f.has(C),onChange:()=>K(C),children:R},C)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(zt,{level:5,className:"!mb-2",children:"Notification Timing & Channels"}),n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-3",children:n.jsx(c.Col,{xs:24,md:12,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(Ye,{children:"Do Not Disturb mode:"}),n.jsxs(c.Space,{size:12,className:"w-full",children:[n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(Ye,{children:"From"}),n.jsx(c.TimePicker,{value:A,onChange:T=>m(T),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(Ye,{children:"To"}),n.jsx(c.TimePicker,{value:I,onChange:T=>w(T),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:y.inApp,onChange:T=>b({...y,inApp:T.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:y.sms,onChange:T=>b({...y,sms:T.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:y.email,onChange:T=>b({...y,email:T.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:G,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Y,loading:G,children:"Save"})]})]})}function vs({severities:e,rules:t,userRoles:s,rawRules:r}){return n.jsx("div",{className:"w-full",children:n.jsx(gs,{severities:e,rules:t,userRoles:s,rawRules:r})})}const on="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",ln="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function cn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:on,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:ln,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function un({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md p-4",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(cn)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:Xt(t.sentAt)?.format("MM/DD/YYYY HH:mm:ss")})]}),n.jsxs("span",{className:"text-[11px] px-2 py-1 rounded-full bg-green-50 text-green-700 border border-green-200",children:[t.delivered,"/",t.total," Delivered"]})]}),n.jsxs("div",{className:"mt-4 text-xs",children:[n.jsxs("div",{className:"text-black",children:[" ",t.messageTitle]}),t.messageBody?n.jsx("div",{className:"text-gray-600",children:t.messageBody}):null]}),n.jsxs("div",{className:"mt-4",children:[n.jsxs("div",{className:"text-xs text-black font-medium",children:["Recipients (",t.total,")"]}),n.jsx("div",{className:"mt-2 flex flex-col gap-3 text-xs",children:(t.recipients||[]).map((r,i)=>{const a=String(r?.notificationReceipientType||"").toLowerCase()==="EscalationNotification".toLowerCase();return n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("span",{className:"text-black",children:[r.name," - ",n.jsx("span",{style:{color:a?"#FF3B30":"#FFB86A"},children:a?"Escalation Notification":"Alert Notification"})]}),n.jsxs("span",{className:"text-gray-500",children:[r.role," . ",r.phone]})]}),n.jsx("span",{className:`text-[11px] px-3 py-[2px] rounded ${r.status==="Delivered"?"bg-green-50 text-green-700 border border-green-200":"bg-red-50 text-red-700 border border-red-200"}`,children:r.status})]},i)})})]})]},s)),e?.notifications?.length?null:n.jsx("span",{className:"text-gray-500 text-xs",children:"No notifications."})]})}]})})}const dn=({alertId:e,id:t,priority:s,spaceName:r,alertNumber:i,statusHistory:a,notifGroups:o})=>{const l={alertId:e??String(t??""),incidentId:"-",severity:s||"",location:r||"",alertNumber:i??""},h=a?.length?a.map(d=>{const A=(d?.status||d?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",m=d?.createdDate?mt(d.createdDate):d?.timestamp?mt(d.timestamp):"";return{status:A,title:d?.status||d?.eventStatus||"Status Update",description:d?.description||d?.actionNotes||"",timestamp:m}}):[],f={summary:l,timeline:h,notifications:o??[]};return n.jsx(un,{data:f})};const hn=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fn=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase()),Vt=e=>{const t=fn(e);return t.charAt(0).toUpperCase()+t.slice(1)},xs=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim(),mn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var pn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const yn=u.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:i="",children:a,iconNode:o,...l},h)=>u.createElement("svg",{ref:h,...pn,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:xs("lucide",i),...!a&&!mn(l)&&{"aria-hidden":"true"},...l},[...o.map(([f,d])=>u.createElement(f,d)),...Array.isArray(a)?a:[a]]));const Ss=(e,t)=>{const s=u.forwardRef(({className:r,...i},a)=>u.createElement(yn,{ref:a,iconNode:t,className:xs(`lucide-${hn(Vt(e))}`,`lucide-${e}`,r),...i}));return s.displayName=Vt(e),s};const gn=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],bs=Ss("maximize-2",gn);const vn=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],xn=Ss("minimize-2",vn),Sn=({isOpen:e,onClose:t,src:s,type:r="image"})=>{const[i,a]=u.useState(!1),[o,l]=u.useState(!1);return u.useEffect(()=>{e&&l(!1)},[e,s]),u.useEffect(()=>{e&&(!s||o)&&t()},[e,s,o,t]),e?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-70",role:"button",tabIndex:0,"aria-label":"Close media preview",onClick:t,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),t())},onTouchStart:t,children:n.jsxs("div",{className:`relative ${i?"w-full h-full":"max-w-5xl max-h-[90vh] w-full"} flex items-center justify-center`,onClick:h=>h.stopPropagation(),children:[r==="image"?n.jsx("img",{src:s,alt:"preview",className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}):n.jsx("video",{src:s,controls:!0,className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}),n.jsx("button",{onClick:t,className:"absolute top-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:"✕"}),n.jsx("button",{onClick:()=>a(!i),className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:i?n.jsx(xn,{size:20}):n.jsx(bs,{size:20})})]})}):null};function bn(e){if(!e||typeof e!="string")return!1;const t=e.split("?")[0].toLowerCase();return t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".ogg")||t.endsWith(".m3u8")}function at(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:bn(e?.mediaUrl||e)}function An(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}function wn(){const{alerts:e}=ge(),t=qe({queryKey:["alerts","timeZoneMasters"],queryFn:()=>e.getTimeZoneMasters?e.getTimeZoneMasters():Promise.resolve([]),staleTime:30*6e4,enabled:typeof e.getTimeZoneMasters=="function"});return{timeZoneMasters:t.data??[],loading:t.isLoading,error:t.error}}const jn={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Nn={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Cn=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details",sourceTab:l})=>{const[h,f]=u.useState(),[d,A]=u.useState(""),[m,I]=u.useState(!1),w=u.useRef(null),[y,b]=u.useState("details"),[B,F]=u.useState(void 0),$=wt(),{alerts:P}=ge(),{timeZoneMasters:G}=wn(),[W,K]=u.useState(!1),[Y,T]=u.useState(void 0),[C,R]=u.useState(void 0),[z,Z]=u.useState({}),k=s?.originalData||{},{eventName:S,alertId:p,timestamp:N,description:g,spaceName:v,assignTeam:x,priority:E,statusType:U,id:D,alertDetails:L,statusHistory:q,mediaDetails:se,alertNumber:ie,timeZoneUniqueId:ae}=k,de=j=>{const H=String(j||"").toLowerCase();return H==="delivered"||H==="sent"?"Delivered":H==="failed"?"Failed":"Queued"},ee=j=>({name:j?.receipientName||j?.recipientName||"-",role:j?.receipientRoleName||"",phone:j?.receipentPhoneNumber||j?.recipientPhoneNumber||j?.receipientEmail||j?.recipientEmail||"",status:de(j?.messageStatus),notificationReceipientType:j?.notificationReceipientType||""}),oe=(j,H)=>{const re=H.map(ee),he=re.filter(xe=>xe.status==="Delivered").length,J=H.map(xe=>xe?.sentAt).filter(Boolean).sort((xe,tt)=>new Date(tt).getTime()-new Date(xe).getTime())[0],we=H[0]||{},_e=[we?.severityName,we?.anomalyName].filter(Boolean).join(" - ")||`${j} Notification`;return{channelLabel:`${j} Notification`,sentAt:J||"",messageTitle:_e,messageBody:"",total:re.length,delivered:he,recipients:re}},ve=j=>{const H=new Map;return(j||[]).forEach(re=>{const he=String(re?.notificationType||"Unknown"),J=H.get(he)||[];J.push(re),H.set(he,J)}),Array.from(H.entries()).map(([re,he])=>oe(re,he))},ye=async j=>{try{const H=await P.getAlertNotifications(j),re=ve(H);F(re)}catch{F(void 0)}};u.useEffect(()=>{if(y!=="track"||!D)return;let j=!1;return ye(D).then(()=>{j&&F(void 0)}),()=>{j=!0}},[y,D]),u.useEffect(()=>{e&&b(o)},[e,o]);const ce=l==="archived"||["completed","false positive"].includes(String(U||"").toLowerCase()),De=j=>{const H=String(j?.value||"").toLowerCase(),re=String(j?.statusName||"").toLowerCase();return H.includes("reopen")||re.includes("reopen")},$e=(i||[]).filter(j=>{const H=De(j);return typeof l<"u"?l==="archived"?H:!H:ce?H:!H}).map(j=>({value:j.value,label:j.statusName})),je=u.useMemo(()=>An(se),[se]);u.useEffect(()=>{let j=!1;const H=new AbortController,re=async J=>{if(J){j||Z(we=>({...we,[J]:!1}));try{const we=await fetch(J,{method:"HEAD",signal:H.signal});if(we.ok){j||Z(xe=>({...xe,[J]:!0}));return}if(we.status===404){j||Z(xe=>({...xe,[J]:!1}));return}if(!(await fetch(J,{method:"GET",signal:H.signal})).ok)throw new Error("Media not available");j||Z(xe=>({...xe,[J]:!0}))}catch{j||Z(we=>({...we,[J]:!1}))}}};return Z({}),je.filter(J=>!at(J)).map(J=>J?.mediaUrl||J).filter(J=>typeof J=="string"&&J.length>0).forEach(J=>re(J)),()=>{j=!0,H.abort()}},[je]);const et=async()=>{try{I(!0);const j={alertUniqueId:p,alertId:D,status:h?String(h):void 0,notes:d.trim(),modifiedBy:0},H=await $.mutateAsync(j);if(H?.responseStatus){const re=H?.data||"Alert updated successfully.";pe.toast.success(re,{autoClose:1500,onClose:()=>{r(),t()}}),f(void 0),A("")}else{const re=H?.errorMessage||"Failed to update alert status";pe.toast.error(re)}}catch(j){console.error("Error updating alert status:",j),pe.toast.error("Failed to update alert status. Please try again.")}finally{I(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,styles:{body:{maxHeight:"70vh",overflowY:"auto"}},footer:y==="details"?n.jsxs("div",{className:"flex flex-row gap-2 justify-start",children:[n.jsx(c.Button,{onClick:t,className:"bg-[#6C757D] text-white",children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:et,loading:m,children:m?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:y,onChange:j=>b(j),items:[{key:"details",label:"Alert Detail",children:n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{className:"text-sm font-bold",children:S||"Alert Event"}),L?.firstName?n.jsxs("div",{className:"text-sm text-gray-500",children:["Resident ID/Name: ",L?.firstName," ",L?.lastName||"","   ",L?.residentId||""]}):null,n.jsxs("div",{className:"text-sm text-gray-500",children:["Timestamp: ",mt(N,G.find(j=>j.timeZoneUniqueId===ae)?.ianaTimeZoneId)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",g||"No description available"]}),v&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",v]}),x&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",x]}),n.jsxs("div",{className:"flex gap-2 justify-start mt-3",children:[n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:{border:`2px solid ${jn[String(E)]||"#DFE4EA"}`,backgroundColor:Nn[String(E)]},children:["Severity: ",E||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(U||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",U||"N/A"]})]}),n.jsx("div",{className:"w-full flex flex-col justify-start items-start mt-2 font-bold",children:n.jsxs("div",{className:"w-full mt-4",children:[n.jsx("div",{className:"flex flex-col gap-2",children:n.jsx(c.Select,{placeholder:"Change Status",className:"w-full text-gray-500",onChange:j=>f(j),value:h,options:$e,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{htmlFor:"action-details-input",className:"text-xs text-gray-500 font-medium",children:"Action Taken (Comments)"}),n.jsx("textarea",{id:"action-details-input",placeholder:"Enter details...",className:"w-full text-gray-500 h-20 border border-grey-500 rounded-md p-2",value:d,onChange:j=>A(j.target.value)})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),je.length>1?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>w.current?.prev?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Previous media",children:n.jsx(Me.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>w.current?.next?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Next media",children:n.jsx(Me.RightOutlined,{style:{fontSize:12}})})]}):null]}),je.length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:je.map((j,H)=>n.jsxs("div",{className:"flex justify-center items-center",children:[at(j)?n.jsxs("video",{width:"240",height:"200",controls:!0,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg",children:[n.jsx("source",{src:j.mediaUrl||j}),"Your browser does not support the video tag."]}):n.jsx("img",{src:j.mediaUrl||j,alt:j.caption||`media-${H}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),j.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:j.caption}),!at(j)&&z[String(j.mediaUrl||j)]?n.jsx("button",{onClick:()=>{K(!0),T(j.mediaUrl||j),R(j.type||"image")},className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:n.jsx(bs,{size:20})}):null]},H))})}):null]})}),n.jsx(Sn,{isOpen:W,onClose:()=>K(!1),src:Y||"",type:C||"image"})]})},{key:"track",label:"Track Incident",children:n.jsx(dn,{alertId:p,id:D,priority:E,spaceName:v,alertNumber:ie,statusHistory:q,notifGroups:B})}]})})};function As(){const{alerts:e}=ge(),t=qe({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Tn(){const{alerts:e}=ge(),{data:t,isLoading:s}=qe({queryKey:["userTimeZone"],queryFn:async()=>{const[r,i]=await Promise.all([e.getMyAppPreferences?.()??Promise.resolve(null),e.getTimeZoneMasters?.()??Promise.resolve([])]),a=Intl.DateTimeFormat().resolvedOptions().timeZone,o={timeZoneUniqueId:"",ianaTimeZoneId:a,timeZoneName:a,offset:""};if(!r?.timeZoneUniqueId||!i.length)return o;const l=i.find(h=>h.timeZoneUniqueId===r.timeZoneUniqueId);return l?.ianaTimeZoneId?{timeZoneUniqueId:l.timeZoneUniqueId,ianaTimeZoneId:l.ianaTimeZoneId,timeZoneName:l.timeZoneName,offset:l.offset}:o},staleTime:5*6e4});return{timeZoneDetails:t,loading:s}}function jt({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=u.useState(!1),[o,l]=u.useState(null),[h,f]=u.useState("details"),{list:d,loading:A}=As(),{timeZoneDetails:m,loading:I}=Tn(),w=m?.timeZoneName??"UTC",y=m?.ianaTimeZoneId??"UTC";function b(G,W){l(G),f(W?.tab??"details"),$(W?.sourceTab??"active"),a(!0)}function B(){a(!1)}const[F,$]=u.useState("active"),P=o?{originalData:{...o,alertId:o.alertId??o.id,mediaDetails:o.mediaDetails}}:null;return n.jsxs("div",{className:"p-6 flex flex-col items-start justify-start min-h-screen w-full overflow-auto",children:[n.jsxs("div",{className:"w-1/2 flex items-center justify-between mb-4",children:[n.jsx("h1",{className:"text-xl font-bold text-black",children:"Alert Console"}),I?n.jsx(c.Spin,{size:"small"}):n.jsx(ps,{label:w,timeZone:y})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:G=>{G==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(gt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:b,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(ms,{alerts:e,loading:t,columns:s||[],onAlertIdClick:b})},{key:"settings",label:"Settings",children:n.jsx(In,{})}]}),n.jsx(Cn,{isModalOpen:i,handleModalClose:B,selectedRow:P,fetchAlertLogs:()=>{},alertStatusList:d,alertStatusLoading:A,initialTab:h,sourceTab:F})]})}function In(){const[e,t]=u.useState([]),[s,r]=u.useState([]),[i,a]=u.useState([]),{rules:o}=ge();return u.useEffect(()=>{let l=!0;return(async()=>{try{const h=await o.getRules();if(!l)return;a(Array.isArray(h)?h:[]);const f=(h||[]).map((d,A)=>({RuleId:d.ruleId||d.ruleName||String(A),Name:d.ruleName||d.Name||"-",Description:d.ruleDesc||d.Description||"",SeverityId:0}));t(f.length?f:Fe.rules);try{const d=await o.getLookups(),A=Array.isArray(d?.userRoles)?d.userRoles.map(m=>({userRoleId:m.userRoleId??m.id,userRoleName:m.userRoleName??m.name})):[];r(A.length?A:Fe.userRoles)}catch{r(Fe.userRoles)}}catch{t(Fe.rules),r(Fe.userRoles)}})(),()=>{l=!1}},[]),n.jsx(vs,{severities:Fe.severities,rules:e,userRoles:s,rawRules:i})}function ws(){const{alerts:e}=ge(),t=qe({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Rn(e){const{alerts:t,loading:s,refetch:r}=ws();return n.jsx(jt,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function kn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=u.useState(()=>new Er),h=u.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Mr,{client:l,children:n.jsx(rs,{tenant:e,override:h,children:Array.isArray(i)?n.jsx(jt,{alerts:i,loading:!!a,columns:o}):n.jsx(Rn,{columns:o})})})}function En(e){const{alerts:t}=ge(),s=qe({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const Mn=[{title:"ID",dataIndex:"id",key:"id",width:120},{title:"Priority",dataIndex:"priority",key:"priority",width:120},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:220},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description"}];exports.AlertAssignment=ys;exports.AlertConsole=jt;exports.AlertConsoleWidget=kn;exports.AlertsTable=gt;exports.ApiProvider=rs;exports.ArchivedTable=ms;exports.Clock=ps;exports.DataTable=ns;exports.MyPreferencesPanel=an;exports.SettingsPanel=gs;exports.SettingsTabs=vs;exports.exampleAlertColumns=Mn;exports.useAlertStatusList=As;exports.useAlerts=ws;exports.useAlertsReport=En;exports.useApi=ge;exports.useUpdateAlertStatus=wt;
2
2
  //# sourceMappingURL=index.cjs.map