meyi-insight-ui-dev 1.0.32 → 1.0.33

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.js CHANGED
@@ -55,7 +55,7 @@ React keys must be passed directly to JSX without using spread:
55
55
 
56
56
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
57
57
 
58
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return y.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},l8="DialogDescriptionWarning",c8=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${r_(l8).contentName}}.`;return y.useEffect(()=>{const a=e.current?.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},rg=zA,u8=VA,ag=qA,ld=YA,cd=KA,sg=ZA,ig=JA,og=t_;const kt=rg,d8=ag,a_=y.forwardRef(({className:e,...t},n)=>s.jsx(ld,{ref:n,className:Fe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));a_.displayName=ld.displayName;const It=y.forwardRef(({className:e,children:t,...n},r)=>s.jsxs(d8,{children:[s.jsx(a_,{}),s.jsxs(cd,{ref:r,onInteractOutside:a=>a.preventDefault(),className:Fe("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[t,s.jsxs(og,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));It.displayName=cd.displayName;const jt=({className:e,...t})=>s.jsx("div",{className:Fe("flex flex-col space-y-1.5 text-start",e),...t});jt.displayName="DialogHeader";const $t=({className:e,...t})=>s.jsx("div",{className:Fe("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});$t.displayName="DialogFooter";const Mt=y.forwardRef(({className:e,...t},n)=>s.jsx(sg,{ref:n,className:Fe("text-lg font-semibold leading-none tracking-tight",e),...t}));Mt.displayName=sg.displayName;const Kt=y.forwardRef(({className:e,...t},n)=>s.jsx(ig,{ref:n,className:Fe("text-sm text-muted-foreground",e),...t}));Kt.displayName=ig.displayName;function _m(e,[t,n]){return Math.min(n,Math.max(t,e))}function p8(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var lg="ScrollArea",[s_]=Zr(lg),[f8,tr]=s_(lg),i_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...o}=e,[l,c]=y.useState(null),[u,p]=y.useState(null),[d,f]=y.useState(null),[m,h]=y.useState(null),[g,b]=y.useState(null),[x,S]=y.useState(0),[T,N]=y.useState(0),[A,C]=y.useState(!1),[k,O]=y.useState(!1),M=xt(t,j=>c(j)),R=cl(a);return s.jsx(f8,{scope:n,type:r,dir:R,scrollHideDelay:i,scrollArea:l,viewport:u,onViewportChange:p,content:d,onContentChange:f,scrollbarX:m,onScrollbarXChange:h,scrollbarXEnabled:A,onScrollbarXEnabledChange:C,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:k,onScrollbarYEnabledChange:O,onCornerWidthChange:S,onCornerHeightChange:N,children:s.jsx(it.div,{dir:R,...o,ref:M,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});i_.displayName=lg;var o_="ScrollAreaViewport",l_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=e,o=tr(o_,n),l=y.useRef(null),c=xt(t,l,o.onViewportChange);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),s.jsx(it.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...e.style},children:s.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});l_.displayName=o_;var Ir="ScrollAreaScrollbar",cg=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:o}=a,l=e.orientation==="horizontal";return y.useEffect(()=>(l?i(!0):o(!0),()=>{l?i(!1):o(!1)}),[l,i,o]),a.type==="hover"?s.jsx(m8,{...r,ref:t,forceMount:n}):a.type==="scroll"?s.jsx(h8,{...r,ref:t,forceMount:n}):a.type==="auto"?s.jsx(c_,{...r,ref:t,forceMount:n}):a.type==="always"?s.jsx(ug,{...r,ref:t}):null});cg.displayName=Ir;var m8=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),[i,o]=y.useState(!1);return y.useEffect(()=>{const l=a.scrollArea;let c=0;if(l){const u=()=>{window.clearTimeout(c),o(!0)},p=()=>{c=window.setTimeout(()=>o(!1),a.scrollHideDelay)};return l.addEventListener("pointerenter",u),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(c),l.removeEventListener("pointerenter",u),l.removeEventListener("pointerleave",p)}}},[a.scrollArea,a.scrollHideDelay]),s.jsx(er,{present:n||i,children:s.jsx(c_,{"data-state":i?"visible":"hidden",...r,ref:t})})}),h8=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),i=e.orientation==="horizontal",o=dd(()=>c("SCROLL_END"),100),[l,c]=p8("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return y.useEffect(()=>{if(l==="idle"){const u=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(u)}},[l,a.scrollHideDelay,c]),y.useEffect(()=>{const u=a.viewport,p=i?"scrollLeft":"scrollTop";if(u){let d=u[p];const f=()=>{const m=u[p];d!==m&&(c("SCROLL"),o()),d=m};return u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[a.viewport,i,c,o]),s.jsx(er,{present:n||l!=="hidden",children:s.jsx(ug,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ve(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Ve(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),c_=y.forwardRef((e,t)=>{const n=tr(Ir,e.__scopeScrollArea),{forceMount:r,...a}=e,[i,o]=y.useState(!1),l=e.orientation==="horizontal",c=dd(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,p=n.viewport.offsetHeight<n.viewport.scrollHeight;o(l?u:p)}},10);return fi(n.viewport,c),fi(n.content,c),s.jsx(er,{present:r||i,children:s.jsx(ug,{"data-state":i?"visible":"hidden",...a,ref:t})})}),ug=y.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,a=tr(Ir,e.__scopeScrollArea),i=y.useRef(null),o=y.useRef(0),[l,c]=y.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=m_(l.viewport,l.content),p={...r,sizes:l,onSizesChange:c,hasThumb:u>0&&u<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>o.current=0,onThumbPointerDown:f=>o.current=f};function d(f,m){return v8(f,o.current,l,m)}return n==="horizontal"?s.jsx(g8,{...p,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollLeft,m=d1(f,l,a.dir);i.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollLeft=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollLeft=d(f,a.dir))}}):n==="vertical"?s.jsx(b8,{...p,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollTop,m=d1(f,l);i.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollTop=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollTop=d(f))}}):null}),g8=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...a}=e,i=tr(Ir,e.__scopeScrollArea),[o,l]=y.useState(),c=y.useRef(null),u=xt(t,c,i.onScrollbarXChange);return y.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),s.jsx(d_,{"data-orientation":"horizontal",...a,ref:u,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ud(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,d)=>{if(i.viewport){const f=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(f),g_(f,d)&&p.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:fu(o.paddingLeft),paddingEnd:fu(o.paddingRight)}})}})}),b8=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...a}=e,i=tr(Ir,e.__scopeScrollArea),[o,l]=y.useState(),c=y.useRef(null),u=xt(t,c,i.onScrollbarYChange);return y.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),s.jsx(d_,{"data-orientation":"vertical",...a,ref:u,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ud(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,d)=>{if(i.viewport){const f=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(f),g_(f,d)&&p.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:fu(o.paddingTop),paddingEnd:fu(o.paddingBottom)}})}})}),[x8,u_]=s_(Ir),d_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:o,onThumbPointerDown:l,onThumbPositionChange:c,onDragScroll:u,onWheelScroll:p,onResize:d,...f}=e,m=tr(Ir,n),[h,g]=y.useState(null),b=xt(t,M=>g(M)),x=y.useRef(null),S=y.useRef(""),T=m.viewport,N=r.content-r.viewport,A=nn(p),C=nn(c),k=dd(d,10);function O(M){if(x.current){const R=M.clientX-x.current.left,j=M.clientY-x.current.top;u({x:R,y:j})}}return y.useEffect(()=>{const M=R=>{const j=R.target;h?.contains(j)&&A(R,N)};return document.addEventListener("wheel",M,{passive:!1}),()=>document.removeEventListener("wheel",M,{passive:!1})},[T,h,N,A]),y.useEffect(C,[r,C]),fi(h,k),fi(m.content,k),s.jsx(x8,{scope:n,scrollbar:h,hasThumb:a,onThumbChange:nn(i),onThumbPointerUp:nn(o),onThumbPositionChange:C,onThumbPointerDown:nn(l),children:s.jsx(it.div,{...f,ref:b,style:{position:"absolute",...f.style},onPointerDown:Ve(e.onPointerDown,M=>{M.button===0&&(M.target.setPointerCapture(M.pointerId),x.current=h.getBoundingClientRect(),S.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),O(M))}),onPointerMove:Ve(e.onPointerMove,O),onPointerUp:Ve(e.onPointerUp,M=>{const R=M.target;R.hasPointerCapture(M.pointerId)&&R.releasePointerCapture(M.pointerId),document.body.style.webkitUserSelect=S.current,m.viewport&&(m.viewport.style.scrollBehavior=""),x.current=null})})})}),pu="ScrollAreaThumb",p_=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=u_(pu,e.__scopeScrollArea);return s.jsx(er,{present:n||a.hasThumb,children:s.jsx(y8,{ref:t,...r})})}),y8=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...a}=e,i=tr(pu,n),o=u_(pu,n),{onThumbPositionChange:l}=o,c=xt(t,d=>o.onThumbChange(d)),u=y.useRef(void 0),p=dd(()=>{u.current&&(u.current(),u.current=void 0)},100);return y.useEffect(()=>{const d=i.viewport;if(d){const f=()=>{if(p(),!u.current){const m=S8(d,l);u.current=m,l()}};return l(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[i.viewport,p,l]),s.jsx(it.div,{"data-state":o.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ve(e.onPointerDownCapture,d=>{const m=d.target.getBoundingClientRect(),h=d.clientX-m.left,g=d.clientY-m.top;o.onThumbPointerDown({x:h,y:g})}),onPointerUp:Ve(e.onPointerUp,o.onThumbPointerUp)})});p_.displayName=pu;var dg="ScrollAreaCorner",f_=y.forwardRef((e,t)=>{const n=tr(dg,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?s.jsx(E8,{...e,ref:t}):null});f_.displayName=dg;var E8=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,a=tr(dg,n),[i,o]=y.useState(0),[l,c]=y.useState(0),u=!!(i&&l);return fi(a.scrollbarX,()=>{const p=a.scrollbarX?.offsetHeight||0;a.onCornerHeightChange(p),c(p)}),fi(a.scrollbarY,()=>{const p=a.scrollbarY?.offsetWidth||0;a.onCornerWidthChange(p),o(p)}),u?s.jsx(it.div,{...r,ref:t,style:{width:i,height:l,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function fu(e){return e?parseInt(e,10):0}function m_(e,t){const n=e/t;return isNaN(n)?0:n}function ud(e){const t=m_(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function v8(e,t,n,r="ltr"){const a=ud(n),i=a/2,o=t||i,l=a-o,c=n.scrollbar.paddingStart+o,u=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,d=r==="ltr"?[0,p]:[p*-1,0];return h_([c,u],d)(e)}function d1(e,t,n="ltr"){const r=ud(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,o=t.content-t.viewport,l=i-r,c=n==="ltr"?[0,o]:[o*-1,0],u=_m(e,c);return h_([0,o],[0,l])(u)}function h_(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function g_(e,t){return e>0&&e<t}var S8=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function a(){const i={left:e.scrollLeft,top:e.scrollTop},o=n.left!==i.left,l=n.top!==i.top;(o||l)&&t(),n=i,r=window.requestAnimationFrame(a)})(),()=>window.cancelAnimationFrame(r)};function dd(e,t){const n=nn(e),r=y.useRef(0);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),y.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fi(e,t){const n=nn(t);an(()=>{let r=0;if(e){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(e),()=>{window.cancelAnimationFrame(r),a.unobserve(e)}}},[e,n])}var b_=i_,w8=l_,T8=f_;const x_=y.forwardRef(({className:e,children:t,...n},r)=>s.jsxs(b_,{ref:r,className:Fe("relative overflow-hidden",e),...n,children:[s.jsx(w8,{className:"h-full w-full rounded-[inherit]",children:t}),s.jsx(y_,{}),s.jsx(T8,{})]}));x_.displayName=b_.displayName;const y_=y.forwardRef(({className:e,orientation:t="vertical",...n},r)=>s.jsx(cg,{ref:r,orientation:t,className:Fe("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:s.jsx(p_,{className:"relative flex-1 rounded-full bg-border"})}));y_.displayName=cg.displayName;function N8({open:e,onOpenChange:t,assigneeIds:n=[],onAssign:r}){const{isAdmin:a}=ur(),{users:i,loading:o,refetch:l}=Jh(),[c,u]=w.useState(!1),[p,d]=w.useState([]);if(w.useEffect(()=>{e&&(d(n||[]),l().catch(console.error))},[e,n,l]),!a)return null;const f=h=>{d(g=>g.includes(h)?g.filter(b=>b!==h):[...g,h])},m=async()=>{try{u(!0),await r(p),t(!1)}finally{u(!1)}};return s.jsx(kt,{open:e,onOpenChange:t,children:s.jsxs(It,{className:"sm:max-w-[425px]",children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Assign Users"})}),s.jsx("div",{className:"py-4",children:o?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.jsx(x_,{className:"h-[300px] pr-4",children:s.jsxs("div",{className:"space-y-2",children:[i.map(h=>{const g=p.includes(h.id);return s.jsxs("div",{onClick:()=>f(h.id),className:Fe("flex items-center justify-between p-3 rounded-md border cursor-pointer hover:bg-accent transition-colors",g&&"border-primary/50 bg-primary/5"),children:[s.jsxs("div",{className:"flex items-center gap-3 overflow-hidden",children:[s.jsx(_C,{className:"h-5 w-5 text-muted-foreground flex-shrink-0"}),s.jsxs("div",{className:"flex flex-col overflow-hidden",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:h.full_name||h.email}),h.full_name&&s.jsx("span",{className:"text-xs text-muted-foreground truncate",children:h.email})]})]}),s.jsx("div",{className:Fe("h-5 w-5 rounded border flex items-center justify-center flex-shrink-0",g?"bg-primary border-primary text-primary-foreground":"border-input"),children:g&&s.jsx(Yt,{className:"h-3.5 w-3.5"})})]},h.id)}),i.length===0&&s.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No users found."})]})})}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(ie,{variant:"outline",onClick:()=>t(!1),disabled:c,children:"Cancel"}),s.jsxs(ie,{onClick:m,disabled:c||o,children:[c&&s.jsx(Qe,{className:"mr-2 h-4 w-4 animate-spin"}),"Save Assignment"]})]})]})})}function E_({assigneeIds:e=[],className:t}){const{users:n}=Jh();let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{r=[e]}if(Array.isArray(r)||(r=[]),!r||r.length===0)return s.jsxs("div",{className:Fe("text-muted-foreground text-sm flex items-center gap-1.5",t),children:[s.jsx(MC,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Unassigned"})]});const a=r.map(l=>n.find(c=>c.id===l)||{id:l,email:"Loading...",full_name:"Loading..."}),i=a[0],o=a.length-1;return s.jsxs("div",{className:Fe("flex items-center gap-1.5 text-sm",t),children:[s.jsx(_C,{className:"h-3.5 w-3.5 text-primary"}),s.jsx("span",{className:"font-medium truncate max-w-[150px]",title:i?.email||i?.id,children:i?.full_name||i?.email||"Assigned"}),o>0&&s.jsxs("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded-full ml-1",children:["+",o]})]})}function Je({className:e,...t}){return s.jsx("div",{className:Fe("animate-pulse rounded-md bg-primary/10",e),...t})}function p1({count:e,wide:t}){return s.jsx("div",{className:`im-dashboard-stats${t?" im-six-stats":""}`,children:Array.from({length:e}).map((n,r)=>s.jsxs("div",{className:"im-stat",children:[s.jsx(Je,{className:"h-3 w-20"}),s.jsx(Je,{className:"mt-2 h-6 w-12"})]},r))})}function f1({rows:e}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[s.jsx(Je,{className:"h-5 w-9 rounded-full"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(Je,{className:"h-3.5 w-1/2"}),s.jsx(Je,{className:"mt-1.5 h-2.5 w-3/4"})]}),s.jsx(Je,{className:"h-5 w-16 rounded-full"})]},n))})}function m1({rows:e}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"mt-2 h-2.5 w-full rounded-full"})]},n))})}function C8({rows:e=8,cols:t=6}){return s.jsxs("div",{className:"im-table-card",children:[s.jsx("div",{style:{display:"flex",gap:16,padding:"12px 16px",borderBottom:"1px solid var(--im-border)",background:"var(--im-surface-2)"},children:Array.from({length:t}).map((n,r)=>s.jsx(Je,{className:"h-3 flex-1"},r))}),Array.from({length:e}).map((n,r)=>s.jsx("div",{style:{display:"flex",gap:16,padding:"14px 16px",borderBottom:"1px solid var(--im-border)"},children:Array.from({length:t}).map((a,i)=>s.jsx(Je,{className:"h-4 flex-1"},i))},r))]})}function A8({count:e=8}){return s.jsx("div",{className:"grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:14},children:[s.jsx(Je,{className:"h-9 w-9 rounded-lg"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(Je,{className:"h-3.5 w-3/4"}),s.jsx(Je,{className:"mt-1.5 h-2.5 w-1/2"})]})]}),s.jsx(Je,{className:"h-2.5 w-full"}),s.jsx(Je,{className:"mt-2 h-2.5 w-5/6"}),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:14},children:[s.jsx(Je,{className:"h-5 w-14 rounded-full"}),s.jsx(Je,{className:"h-5 w-16 rounded-full"})]})]},n))})}function h1({titleW:e=32,rows:t=5}){return s.jsxs("div",{className:"im-inc-card",children:[s.jsx(Je,{className:"mb-4 h-4",style:{width:e*4}}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:t}).map((n,r)=>s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"h-3 w-24"})]},r))})]})}function _8(){return s.jsxs("div",{className:"im-inc-detail -m-4",children:[s.jsxs("div",{className:"im-inc-header",children:[s.jsxs("div",{className:"im-inc-header-row1",children:[s.jsx(Je,{className:"h-7 w-7 rounded-md"}),s.jsx(Je,{className:"h-3.5 w-14"}),s.jsx(Je,{className:"h-5 w-48"}),s.jsx(Je,{className:"h-5 w-10 rounded-full"}),s.jsx(Je,{className:"h-5 w-20 rounded-full"})]}),s.jsxs("div",{className:"im-inc-header-row2",style:{marginTop:8},children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"h-3 w-24"}),s.jsx(Je,{className:"h-3 w-16"})]}),s.jsxs("div",{className:"im-inc-actions",children:[s.jsx(Je,{className:"h-8 w-28"}),s.jsx(Je,{className:"h-8 w-24"}),s.jsx(Je,{className:"h-8 w-24"})]})]}),s.jsxs("div",{className:"im-inc-body",children:[s.jsxs("div",{className:"im-inc-main",children:[s.jsx("div",{className:"im-inc-tabs",style:{gap:20},children:Array.from({length:6}).map((e,t)=>s.jsx(Je,{className:"my-2.5 h-4 w-20"},t))}),s.jsx("div",{className:"im-inc-tab-content",children:s.jsxs("div",{className:"im-inc-overview",children:[s.jsx(h1,{titleW:36,rows:6}),s.jsx(h1,{titleW:24,rows:5})]})})]}),s.jsx("aside",{className:"im-inc-sidebar",children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx(Je,{className:"mb-2 h-2.5 w-20"}),s.jsx(Je,{className:"h-4 w-32"})]},t))})]})]})}function R8(){return s.jsxs("div",{className:"flex flex-col h-full overflow-hidden p-4",children:[s.jsxs("div",{className:"shrink-0 mb-6 flex flex-col md:flex-row md:items-start justify-between gap-4",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx(Je,{className:"h-9 w-9 rounded-md"}),s.jsxs("div",{children:[s.jsx(Je,{className:"h-6 w-64"}),s.jsxs("div",{className:"flex items-center gap-4 mt-3",children:[s.jsx(Je,{className:"h-3 w-24"}),s.jsx(Je,{className:"h-3 w-20"}),s.jsx(Je,{className:"h-3 w-28"})]})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[s.jsx(Je,{className:"h-5 w-16 rounded-full"}),s.jsx(Je,{className:"h-5 w-20 rounded-full"})]})]}),s.jsxs("div",{className:"rounded-xl border bg-card p-4 mb-4",children:[s.jsx(Je,{className:"mb-3 h-4 w-32"}),s.jsx(Je,{className:"h-3 w-full"}),s.jsx(Je,{className:"mt-2 h-3 w-11/12"}),s.jsx(Je,{className:"mt-2 h-3 w-4/5"})]}),s.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[s.jsx(Je,{className:"mb-4 h-4 w-28"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{style:{display:"flex",gap:10},children:[s.jsx(Je,{className:"h-5 w-5 rounded-full"}),s.jsx(Je,{className:"h-3 flex-1"})]},t))})]})]})}function qr({variant:e}){return e==="dashboard"?s.jsxs(s.Fragment,{children:[s.jsx(p1,{count:5}),s.jsxs("div",{className:"im-dashboard-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(f1,{rows:4})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-28"}),s.jsx(f1,{rows:5})]})]})]}):e==="analytics"?s.jsxs(s.Fragment,{children:[s.jsx(p1,{count:6,wide:!0}),s.jsxs("div",{className:"im-analytics-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(Je,{className:"h-40 w-full"})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(m1,{rows:4})]})]}),s.jsxs("section",{className:"im-panel im-resource-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-40"}),s.jsx(m1,{rows:5})]})]}):e==="cards"?s.jsx(A8,{}):e==="incident-detail"?s.jsx(_8,{}):e==="sop-detail"?s.jsx(R8,{}):s.jsx(C8,{})}const Rm=new Set(["triggered","processing","queued","fetching_ec2","fetching_metrics","fetching_logs","compressing_logs","building_prompt","finding_rca","storing_results","triage_started","infra_analysis","logs_analysis","ai_reasoning","remediation_generated"]);function rf(e){return e?Rm.has(e):!1}function k8(e,t,n="pending"){const[r,a]=w.useState(n),[i,o]=w.useState(0),l=w.useRef(null),c=r==="completed",u=r==="failed",p=w.useCallback(()=>{a("triggered"),o(0)},[]),d=w.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),a("failed"),o(0)},[]);return w.useEffect(()=>{Rm.has(r)||a(n)},[n]),w.useEffect(()=>{if(!(e&&(t||Rm.has(r)))){l.current&&(clearInterval(l.current),l.current=null);return}const m=async()=>{try{const h=await Ie.getIncidentStatus(e),g=h.analysisStatus??"pending";a(g),o(h.progressPercent??0),(h.isComplete||h.isFailed)&&l.current&&(clearInterval(l.current),l.current=null)}catch{}};return m(),l.current=setInterval(m,5e3),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[e,t,r]),{status:r,progressPercent:i,isComplete:c,isFailed:u,optimisticTrigger:p,markFailed:d}}function I8(e,t=globalThis?.document){const n=nn(e);y.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var D8="DismissableLayer",km="dismissableLayer.update",O8="dismissableLayer.pointerDownOutside",L8="dismissableLayer.focusOutside",g1,v_=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),pd=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:o,onDismiss:l,...c}=e,u=y.useContext(v_),[p,d]=y.useState(null),f=p?.ownerDocument??globalThis?.document,[,m]=y.useState({}),h=xt(t,k=>d(k)),g=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(b),S=p?g.indexOf(p):-1,T=u.layersWithOutsidePointerEventsDisabled.size>0,N=S>=x,A=P8(k=>{const O=k.target,M=[...u.branches].some(R=>R.contains(O));!N||M||(a?.(k),o?.(k),k.defaultPrevented||l?.())},f),C=F8(k=>{const O=k.target;[...u.branches].some(R=>R.contains(O))||(i?.(k),o?.(k),k.defaultPrevented||l?.())},f);return I8(k=>{S===u.layers.size-1&&(r?.(k),!k.defaultPrevented&&l&&(k.preventDefault(),l()))},f),y.useEffect(()=>{if(p)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(g1=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),b1(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=g1)}},[p,f,n,u]),y.useEffect(()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),b1())},[p,u]),y.useEffect(()=>{const k=()=>m({});return document.addEventListener(km,k),()=>document.removeEventListener(km,k)},[]),s.jsx(it.div,{...c,ref:h,style:{pointerEvents:T?N?"auto":"none":void 0,...e.style},onFocusCapture:Ve(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Ve(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Ve(e.onPointerDownCapture,A.onPointerDownCapture)})});pd.displayName=D8;var j8="DismissableLayerBranch",M8=y.forwardRef((e,t)=>{const n=y.useContext(v_),r=y.useRef(null),a=xt(t,r);return y.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(it.div,{...e,ref:a})});M8.displayName=j8;function P8(e,t=globalThis?.document){const n=nn(e),r=y.useRef(!1),a=y.useRef(()=>{});return y.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let c=function(){S_(O8,n,u,{discrete:!0})};const u={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},o=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function F8(e,t=globalThis?.document){const n=nn(e),r=y.useRef(!1);return y.useEffect(()=>{const a=i=>{i.target&&!r.current&&S_(L8,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function b1(){const e=new CustomEvent(km);document.dispatchEvent(e)}function S_(e,t,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(e,t,{once:!0}),r?aA(a,i):a.dispatchEvent(i)}var af=0;function pg(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??x1()),document.body.insertAdjacentElement("beforeend",e[1]??x1()),af++,()=>{af===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),af--}},[])}function x1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sf="focusScope.autoFocusOnMount",of="focusScope.autoFocusOnUnmount",y1={bubbles:!1,cancelable:!0},B8="FocusScope",fd=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...o}=e,[l,c]=y.useState(null),u=nn(a),p=nn(i),d=y.useRef(null),f=xt(t,g=>c(g)),m=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let g=function(T){if(m.paused||!l)return;const N=T.target;l.contains(N)?d.current=N:ca(d.current,{select:!0})},b=function(T){if(m.paused||!l)return;const N=T.relatedTarget;N!==null&&(l.contains(N)||ca(d.current,{select:!0}))},x=function(T){if(document.activeElement===document.body)for(const A of T)A.removedNodes.length>0&&ca(l)};document.addEventListener("focusin",g),document.addEventListener("focusout",b);const S=new MutationObserver(x);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",b),S.disconnect()}}},[r,l,m.paused]),y.useEffect(()=>{if(l){v1.add(m);const g=document.activeElement;if(!l.contains(g)){const x=new CustomEvent(sf,y1);l.addEventListener(sf,u),l.dispatchEvent(x),x.defaultPrevented||(U8(V8(w_(l)),{select:!0}),document.activeElement===g&&ca(l))}return()=>{l.removeEventListener(sf,u),setTimeout(()=>{const x=new CustomEvent(of,y1);l.addEventListener(of,p),l.dispatchEvent(x),x.defaultPrevented||ca(g??document.body,{select:!0}),l.removeEventListener(of,p),v1.remove(m)},0)}}},[l,u,p,m]);const h=y.useCallback(g=>{if(!n&&!r||m.paused)return;const b=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(b&&x){const S=g.currentTarget,[T,N]=$8(S);T&&N?!g.shiftKey&&x===N?(g.preventDefault(),n&&ca(T,{select:!0})):g.shiftKey&&x===T&&(g.preventDefault(),n&&ca(N,{select:!0})):x===S&&g.preventDefault()}},[n,r,m.paused]);return s.jsx(it.div,{tabIndex:-1,...o,ref:f,onKeyDown:h})});fd.displayName=B8;function U8(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ca(r,{select:t}),document.activeElement!==n)return}function $8(e){const t=w_(e),n=E1(t,e),r=E1(t.reverse(),e);return[n,r]}function w_(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function E1(e,t){for(const n of e)if(!H8(n,{upTo:t}))return n}function H8(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function z8(e){return e instanceof HTMLInputElement&&"select"in e}function ca(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&z8(e)&&t&&e.select()}}var v1=G8();function G8(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=S1(e,t),e.unshift(t)},remove(t){e=S1(e,t),e[0]?.resume()}}}function S1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function V8(e){return e.filter(t=>t.tagName!=="A")}const W8=["top","right","bottom","left"],Na=Math.min,Mn=Math.max,mu=Math.round,ic=Math.floor,Ar=e=>({x:e,y:e}),q8={left:"right",right:"left",bottom:"top",top:"bottom"};function Im(e,t,n){return Mn(e,Na(t,n))}function Yr(e,t){return typeof e=="function"?e(t):e}function Kr(e){return e.split("-")[0]}function Si(e){return e.split("-")[1]}function fg(e){return e==="x"?"y":"x"}function mg(e){return e==="y"?"height":"width"}function Cr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function hg(e){return fg(Cr(e))}function Y8(e,t,n){n===void 0&&(n=!1);const r=Si(e),a=hg(e),i=mg(a);let o=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(o=hu(o)),[o,hu(o)]}function K8(e){const t=hu(e);return[Dm(e),t,Dm(t)]}function Dm(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const w1=["left","right"],T1=["right","left"],X8=["top","bottom"],Z8=["bottom","top"];function Q8(e,t,n){switch(e){case"top":case"bottom":return n?t?T1:w1:t?w1:T1;case"left":case"right":return t?X8:Z8;default:return[]}}function J8(e,t,n,r){const a=Si(e);let i=Q8(Kr(e),n==="start",r);return a&&(i=i.map(o=>o+"-"+a),t&&(i=i.concat(i.map(Dm)))),i}function hu(e){const t=Kr(e);return q8[t]+e.slice(t.length)}function eU(e){return{top:0,right:0,bottom:0,left:0,...e}}function T_(e){return typeof e!="number"?eU(e):{top:e,right:e,bottom:e,left:e}}function gu(e){const{x:t,y:n,width:r,height:a}=e;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}function N1(e,t,n){let{reference:r,floating:a}=e;const i=Cr(t),o=hg(t),l=mg(o),c=Kr(t),u=i==="y",p=r.x+r.width/2-a.width/2,d=r.y+r.height/2-a.height/2,f=r[l]/2-a[l]/2;let m;switch(c){case"top":m={x:p,y:r.y-a.height};break;case"bottom":m={x:p,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:d};break;case"left":m={x:r.x-a.width,y:d};break;default:m={x:r.x,y:r.y}}switch(Si(t)){case"start":m[o]-=f*(n&&u?-1:1);break;case"end":m[o]+=f*(n&&u?-1:1);break}return m}async function tU(e,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:l,strategy:c}=e,{boundary:u="clippingAncestors",rootBoundary:p="viewport",elementContext:d="floating",altBoundary:f=!1,padding:m=0}=Yr(t,e),h=T_(m),b=l[f?d==="floating"?"reference":"floating":d],x=gu(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:u,rootBoundary:p,strategy:c})),S=d==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),N=await(i.isElement==null?void 0:i.isElement(T))?await(i.getScale==null?void 0:i.getScale(T))||{x:1,y:1}:{x:1,y:1},A=gu(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:S,offsetParent:T,strategy:c}):S);return{top:(x.top-A.top+h.top)/N.y,bottom:(A.bottom-x.bottom+h.bottom)/N.y,left:(x.left-A.left+h.left)/N.x,right:(A.right-x.right+h.right)/N.x}}const nU=50,rU=async(e,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:tU},c=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:p,y:d}=N1(u,r,c),f=r,m=0;const h={};for(let g=0;g<i.length;g++){const b=i[g];if(!b)continue;const{name:x,fn:S}=b,{x:T,y:N,data:A,reset:C}=await S({x:p,y:d,initialPlacement:r,placement:f,strategy:a,middlewareData:h,rects:u,platform:l,elements:{reference:e,floating:t}});p=T??p,d=N??d,h[x]={...h[x],...A},C&&m<nU&&(m++,typeof C=="object"&&(C.placement&&(f=C.placement),C.rects&&(u=C.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):C.rects),{x:p,y:d}=N1(u,f,c)),g=-1)}return{x:p,y:d,placement:f,strategy:a,middlewareData:h}},aU=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:a,rects:i,platform:o,elements:l,middlewareData:c}=t,{element:u,padding:p=0}=Yr(e,t)||{};if(u==null)return{};const d=T_(p),f={x:n,y:r},m=hg(a),h=mg(m),g=await o.getDimensions(u),b=m==="y",x=b?"top":"left",S=b?"bottom":"right",T=b?"clientHeight":"clientWidth",N=i.reference[h]+i.reference[m]-f[m]-i.floating[h],A=f[m]-i.reference[m],C=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let k=C?C[T]:0;(!k||!await(o.isElement==null?void 0:o.isElement(C)))&&(k=l.floating[T]||i.floating[h]);const O=N/2-A/2,M=k/2-g[h]/2-1,R=Na(d[x],M),j=Na(d[S],M),U=R,G=k-g[h]-j,q=k/2-g[h]/2+O,P=Im(U,q,G),z=!c.arrow&&Si(a)!=null&&q!==P&&i.reference[h]/2-(q<U?R:j)-g[h]/2<0,re=z?q<U?q-U:q-G:0;return{[m]:f[m]+re,data:{[m]:P,centerOffset:q-P-re,...z&&{alignmentOffset:re}},reset:z}}}),sU=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:l,platform:c,elements:u}=t,{mainAxis:p=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:g=!0,...b}=Yr(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const x=Kr(a),S=Cr(l),T=Kr(l)===l,N=await(c.isRTL==null?void 0:c.isRTL(u.floating)),A=f||(T||!g?[hu(l)]:K8(l)),C=h!=="none";!f&&C&&A.push(...J8(l,g,h,N));const k=[l,...A],O=await c.detectOverflow(t,b),M=[];let R=((r=i.flip)==null?void 0:r.overflows)||[];if(p&&M.push(O[x]),d){const q=Y8(a,o,N);M.push(O[q[0]],O[q[1]])}if(R=[...R,{placement:a,overflows:M}],!M.every(q=>q<=0)){var j,U;const q=(((j=i.flip)==null?void 0:j.index)||0)+1,P=k[q];if(P&&(!(d==="alignment"?S!==Cr(P):!1)||R.every(B=>Cr(B.placement)===S?B.overflows[0]>0:!0)))return{data:{index:q,overflows:R},reset:{placement:P}};let z=(U=R.filter(re=>re.overflows[0]<=0).sort((re,B)=>re.overflows[1]-B.overflows[1])[0])==null?void 0:U.placement;if(!z)switch(m){case"bestFit":{var G;const re=(G=R.filter(B=>{if(C){const H=Cr(B.placement);return H===S||H==="y"}return!0}).map(B=>[B.placement,B.overflows.filter(H=>H>0).reduce((H,I)=>H+I,0)]).sort((B,H)=>B[1]-H[1])[0])==null?void 0:G[0];re&&(z=re);break}case"initialPlacement":z=l;break}if(a!==z)return{reset:{placement:z}}}return{}}}};function C1(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function A1(e){return W8.some(t=>e[t]>=0)}const iU=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=Yr(e,t);switch(a){case"referenceHidden":{const o=await r.detectOverflow(t,{...i,elementContext:"reference"}),l=C1(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:A1(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...i,altBoundary:!0}),l=C1(o,n.floating);return{data:{escapedOffsets:l,escaped:A1(l)}}}default:return{}}}}},N_=new Set(["left","top"]);async function oU(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=Kr(n),l=Si(n),c=Cr(n)==="y",u=N_.has(o)?-1:1,p=i&&c?-1:1,d=Yr(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:h}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return l&&typeof h=="number"&&(m=l==="end"?h*-1:h),c?{x:m*p,y:f*u}:{x:f*u,y:m*p}}const lU=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:a,y:i,placement:o,middlewareData:l}=t,c=await oU(t,e);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:o}}}}},cU=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:a,platform:i}=t,{mainAxis:o=!0,crossAxis:l=!1,limiter:c={fn:x=>{let{x:S,y:T}=x;return{x:S,y:T}}},...u}=Yr(e,t),p={x:n,y:r},d=await i.detectOverflow(t,u),f=Cr(Kr(a)),m=fg(f);let h=p[m],g=p[f];if(o){const x=m==="y"?"top":"left",S=m==="y"?"bottom":"right",T=h+d[x],N=h-d[S];h=Im(T,h,N)}if(l){const x=f==="y"?"top":"left",S=f==="y"?"bottom":"right",T=g+d[x],N=g-d[S];g=Im(T,g,N)}const b=c.fn({...t,[m]:h,[f]:g});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[m]:o,[f]:l}}}}}},uU=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:a,rects:i,middlewareData:o}=t,{offset:l=0,mainAxis:c=!0,crossAxis:u=!0}=Yr(e,t),p={x:n,y:r},d=Cr(a),f=fg(d);let m=p[f],h=p[d];const g=Yr(l,t),b=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const T=f==="y"?"height":"width",N=i.reference[f]-i.floating[T]+b.mainAxis,A=i.reference[f]+i.reference[T]-b.mainAxis;m<N?m=N:m>A&&(m=A)}if(u){var x,S;const T=f==="y"?"width":"height",N=N_.has(Kr(a)),A=i.reference[d]-i.floating[T]+(N&&((x=o.offset)==null?void 0:x[d])||0)+(N?0:b.crossAxis),C=i.reference[d]+i.reference[T]+(N?0:((S=o.offset)==null?void 0:S[d])||0)-(N?b.crossAxis:0);h<A?h=A:h>C&&(h=C)}return{[f]:m,[d]:h}}}},dU=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:a,rects:i,platform:o,elements:l}=t,{apply:c=()=>{},...u}=Yr(e,t),p=await o.detectOverflow(t,u),d=Kr(a),f=Si(a),m=Cr(a)==="y",{width:h,height:g}=i.floating;let b,x;d==="top"||d==="bottom"?(b=d,x=f===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(x=d,b=f==="end"?"top":"bottom");const S=g-p.top-p.bottom,T=h-p.left-p.right,N=Na(g-p[b],S),A=Na(h-p[x],T),C=!t.middlewareData.shift;let k=N,O=A;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(k=S),C&&!f){const R=Mn(p.left,0),j=Mn(p.right,0),U=Mn(p.top,0),G=Mn(p.bottom,0);m?O=h-2*(R!==0||j!==0?R+j:Mn(p.left,p.right)):k=g-2*(U!==0||G!==0?U+G:Mn(p.top,p.bottom))}await c({...t,availableWidth:O,availableHeight:k});const M=await o.getDimensions(l.floating);return h!==M.width||g!==M.height?{reset:{rects:!0}}:{}}}};function md(){return typeof window<"u"}function wi(e){return C_(e)?(e.nodeName||"").toLowerCase():"#document"}function Fn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dr(e){var t;return(t=(C_(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function C_(e){return md()?e instanceof Node||e instanceof Fn(e).Node:!1}function or(e){return md()?e instanceof Element||e instanceof Fn(e).Element:!1}function Jr(e){return md()?e instanceof HTMLElement||e instanceof Fn(e).HTMLElement:!1}function _1(e){return!md()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Fn(e).ShadowRoot}function pl(e){const{overflow:t,overflowX:n,overflowY:r,display:a}=lr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function pU(e){return/^(table|td|th)$/.test(wi(e))}function hd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const fU=/transform|translate|scale|rotate|perspective|filter/,mU=/paint|layout|strict|content/,$a=e=>!!e&&e!=="none";let lf;function gg(e){const t=or(e)?lr(e):e;return $a(t.transform)||$a(t.translate)||$a(t.scale)||$a(t.rotate)||$a(t.perspective)||!bg()&&($a(t.backdropFilter)||$a(t.filter))||fU.test(t.willChange||"")||mU.test(t.contain||"")}function hU(e){let t=Ca(e);for(;Jr(t)&&!mi(t);){if(gg(t))return t;if(hd(t))return null;t=Ca(t)}return null}function bg(){return lf==null&&(lf=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),lf}function mi(e){return/^(html|body|#document)$/.test(wi(e))}function lr(e){return Fn(e).getComputedStyle(e)}function gd(e){return or(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ca(e){if(wi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_1(e)&&e.host||Dr(e);return _1(t)?t.host:t}function A_(e){const t=Ca(e);return mi(t)?e.ownerDocument?e.ownerDocument.body:e.body:Jr(t)&&pl(t)?t:A_(t)}function Po(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=A_(e),i=a===((r=e.ownerDocument)==null?void 0:r.body),o=Fn(a);if(i){const l=Om(o);return t.concat(o,o.visualViewport||[],pl(a)?a:[],l&&n?Po(l):[])}else return t.concat(a,Po(a,[],n))}function Om(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function __(e){const t=lr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Jr(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,l=mu(n)!==i||mu(r)!==o;return l&&(n=i,r=o),{width:n,height:r,$:l}}function xg(e){return or(e)?e:e.contextElement}function ni(e){const t=xg(e);if(!Jr(t))return Ar(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=__(t);let o=(i?mu(n.width):n.width)/r,l=(i?mu(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const gU=Ar(0);function R_(e){const t=Fn(e);return!bg()||!t.visualViewport?gU:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function bU(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Fn(e)?!1:t}function os(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=xg(e);let o=Ar(1);t&&(r?or(r)&&(o=ni(r)):o=ni(e));const l=bU(i,n,r)?R_(i):Ar(0);let c=(a.left+l.x)/o.x,u=(a.top+l.y)/o.y,p=a.width/o.x,d=a.height/o.y;if(i){const f=Fn(i),m=r&&or(r)?Fn(r):r;let h=f,g=Om(h);for(;g&&r&&m!==h;){const b=ni(g),x=g.getBoundingClientRect(),S=lr(g),T=x.left+(g.clientLeft+parseFloat(S.paddingLeft))*b.x,N=x.top+(g.clientTop+parseFloat(S.paddingTop))*b.y;c*=b.x,u*=b.y,p*=b.x,d*=b.y,c+=T,u+=N,h=Fn(g),g=Om(h)}}return gu({width:p,height:d,x:c,y:u})}function bd(e,t){const n=gd(e).scrollLeft;return t?t.left+n:os(Dr(e)).left+n}function k_(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-bd(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function xU(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=Dr(r),l=t?hd(t.floating):!1;if(r===o||l&&i)return n;let c={scrollLeft:0,scrollTop:0},u=Ar(1);const p=Ar(0),d=Jr(r);if((d||!d&&!i)&&((wi(r)!=="body"||pl(o))&&(c=gd(r)),d)){const m=os(r);u=ni(r),p.x=m.x+r.clientLeft,p.y=m.y+r.clientTop}const f=o&&!d&&!i?k_(o,c):Ar(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-c.scrollLeft*u.x+p.x+f.x,y:n.y*u.y-c.scrollTop*u.y+p.y+f.y}}function yU(e){return Array.from(e.getClientRects())}function EU(e){const t=Dr(e),n=gd(e),r=e.ownerDocument.body,a=Mn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Mn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+bd(e);const l=-n.scrollTop;return lr(r).direction==="rtl"&&(o+=Mn(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:l}}const R1=25;function vU(e,t){const n=Fn(e),r=Dr(e),a=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const p=bg();(!p||p&&t==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const u=bd(r);if(u<=0){const p=r.ownerDocument,d=p.body,f=getComputedStyle(d),m=p.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,h=Math.abs(r.clientWidth-d.clientWidth-m);h<=R1&&(i-=h)}else u<=R1&&(i+=u);return{width:i,height:o,x:l,y:c}}function SU(e,t){const n=os(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=Jr(e)?ni(e):Ar(1),o=e.clientWidth*i.x,l=e.clientHeight*i.y,c=a*i.x,u=r*i.y;return{width:o,height:l,x:c,y:u}}function k1(e,t,n){let r;if(t==="viewport")r=vU(e,n);else if(t==="document")r=EU(Dr(e));else if(or(t))r=SU(t,n);else{const a=R_(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return gu(r)}function I_(e,t){const n=Ca(e);return n===t||!or(n)||mi(n)?!1:lr(n).position==="fixed"||I_(n,t)}function wU(e,t){const n=t.get(e);if(n)return n;let r=Po(e,[],!1).filter(l=>or(l)&&wi(l)!=="body"),a=null;const i=lr(e).position==="fixed";let o=i?Ca(e):e;for(;or(o)&&!mi(o);){const l=lr(o),c=gg(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&(a.position==="absolute"||a.position==="fixed")||pl(o)&&!c&&I_(e,o))?r=r.filter(p=>p!==o):a=l,o=Ca(o)}return t.set(e,r),r}function TU(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?hd(t)?[]:wU(t,this._c):[].concat(n),r],l=k1(t,o[0],a);let c=l.top,u=l.right,p=l.bottom,d=l.left;for(let f=1;f<o.length;f++){const m=k1(t,o[f],a);c=Mn(m.top,c),u=Na(m.right,u),p=Na(m.bottom,p),d=Mn(m.left,d)}return{width:u-d,height:p-c,x:d,y:c}}function NU(e){const{width:t,height:n}=__(e);return{width:t,height:n}}function CU(e,t,n){const r=Jr(t),a=Dr(t),i=n==="fixed",o=os(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=Ar(0);function u(){c.x=bd(a)}if(r||!r&&!i)if((wi(t)!=="body"||pl(a))&&(l=gd(t)),r){const m=os(t,!0,i,t);c.x=m.x+t.clientLeft,c.y=m.y+t.clientTop}else a&&u();i&&!r&&a&&u();const p=a&&!r&&!i?k_(a,l):Ar(0),d=o.left+l.scrollLeft-c.x-p.x,f=o.top+l.scrollTop-c.y-p.y;return{x:d,y:f,width:o.width,height:o.height}}function cf(e){return lr(e).position==="static"}function I1(e,t){if(!Jr(e)||lr(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dr(e)===n&&(n=n.ownerDocument.body),n}function D_(e,t){const n=Fn(e);if(hd(e))return n;if(!Jr(e)){let a=Ca(e);for(;a&&!mi(a);){if(or(a)&&!cf(a))return a;a=Ca(a)}return n}let r=I1(e,t);for(;r&&pU(r)&&cf(r);)r=I1(r,t);return r&&mi(r)&&cf(r)&&!gg(r)?n:r||hU(e)||n}const AU=async function(e){const t=this.getOffsetParent||D_,n=this.getDimensions,r=await n(e.floating);return{reference:CU(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function _U(e){return lr(e).direction==="rtl"}const RU={convertOffsetParentRelativeRectToViewportRelativeRect:xU,getDocumentElement:Dr,getClippingRect:TU,getOffsetParent:D_,getElementRects:AU,getClientRects:yU,getDimensions:NU,getScale:ni,isElement:or,isRTL:_U};function O_(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function kU(e,t){let n=null,r;const a=Dr(e);function i(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function o(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const u=e.getBoundingClientRect(),{left:p,top:d,width:f,height:m}=u;if(l||t(),!f||!m)return;const h=ic(d),g=ic(a.clientWidth-(p+f)),b=ic(a.clientHeight-(d+m)),x=ic(p),T={rootMargin:-h+"px "+-g+"px "+-b+"px "+-x+"px",threshold:Mn(0,Na(1,c))||1};let N=!0;function A(C){const k=C[0].intersectionRatio;if(k!==c){if(!N)return o();k?o(!1,k):r=setTimeout(()=>{o(!1,1e-7)},1e3)}k===1&&!O_(u,e.getBoundingClientRect())&&o(),N=!1}try{n=new IntersectionObserver(A,{...T,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,T)}n.observe(e)}return o(!0),i}function IU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,u=xg(e),p=a||i?[...u?Po(u):[],...t?Po(t):[]]:[];p.forEach(x=>{a&&x.addEventListener("scroll",n,{passive:!0}),i&&x.addEventListener("resize",n)});const d=u&&l?kU(u,n):null;let f=-1,m=null;o&&(m=new ResizeObserver(x=>{let[S]=x;S&&S.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var T;(T=m)==null||T.observe(t)})),n()}),u&&!c&&m.observe(u),t&&m.observe(t));let h,g=c?os(e):null;c&&b();function b(){const x=os(e);g&&!O_(g,x)&&n(),g=x,h=requestAnimationFrame(b)}return n(),()=>{var x;p.forEach(S=>{a&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),d?.(),(x=m)==null||x.disconnect(),m=null,c&&cancelAnimationFrame(h)}}const DU=lU,OU=cU,LU=sU,jU=dU,MU=iU,D1=aU,PU=uU,FU=(e,t,n)=>{const r=new Map,a={platform:RU,...n},i={...a.platform,_c:r};return rU(e,t,{...a,platform:i})};var BU=typeof document<"u",UU=function(){},zc=BU?w.useLayoutEffect:UU;function bu(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,a;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!bu(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!bu(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function L_(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function O1(e,t){const n=L_(e);return Math.round(t*n)/n}function uf(e){const t=y.useRef(e);return zc(()=>{t.current=e}),t}function $U(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:u}=e,[p,d]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=y.useState(r);bu(f,r)||m(r);const[h,g]=y.useState(null),[b,x]=y.useState(null),S=y.useCallback(B=>{B!==C.current&&(C.current=B,g(B))},[]),T=y.useCallback(B=>{B!==k.current&&(k.current=B,x(B))},[]),N=i||h,A=o||b,C=y.useRef(null),k=y.useRef(null),O=y.useRef(p),M=c!=null,R=uf(c),j=uf(a),U=uf(u),G=y.useCallback(()=>{if(!C.current||!k.current)return;const B={placement:t,strategy:n,middleware:f};j.current&&(B.platform=j.current),FU(C.current,k.current,B).then(H=>{const I={...H,isPositioned:U.current!==!1};q.current&&!bu(O.current,I)&&(O.current=I,yi.flushSync(()=>{d(I)}))})},[f,t,n,j,U]);zc(()=>{u===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,d(B=>({...B,isPositioned:!1})))},[u]);const q=y.useRef(!1);zc(()=>(q.current=!0,()=>{q.current=!1}),[]),zc(()=>{if(N&&(C.current=N),A&&(k.current=A),N&&A){if(R.current)return R.current(N,A,G);G()}},[N,A,G,R,M]);const P=y.useMemo(()=>({reference:C,floating:k,setReference:S,setFloating:T}),[S,T]),z=y.useMemo(()=>({reference:N,floating:A}),[N,A]),re=y.useMemo(()=>{const B={position:n,left:0,top:0};if(!z.floating)return B;const H=O1(z.floating,p.x),I=O1(z.floating,p.y);return l?{...B,transform:"translate("+H+"px, "+I+"px)",...L_(z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:I}},[n,l,z.floating,p.x,p.y]);return y.useMemo(()=>({...p,update:G,refs:P,elements:z,floatingStyles:re}),[p,G,P,z,re])}const HU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:a}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?D1({element:r.current,padding:a}).fn(n):{}:r?D1({element:r,padding:a}).fn(n):{}}}},zU=(e,t)=>{const n=DU(e);return{name:n.name,fn:n.fn,options:[e,t]}},GU=(e,t)=>{const n=OU(e);return{name:n.name,fn:n.fn,options:[e,t]}},VU=(e,t)=>({fn:PU(e).fn,options:[e,t]}),WU=(e,t)=>{const n=LU(e);return{name:n.name,fn:n.fn,options:[e,t]}},qU=(e,t)=>{const n=jU(e);return{name:n.name,fn:n.fn,options:[e,t]}},YU=(e,t)=>{const n=MU(e);return{name:n.name,fn:n.fn,options:[e,t]}},KU=(e,t)=>{const n=HU(e);return{name:n.name,fn:n.fn,options:[e,t]}};var XU="Arrow",j_=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:a=5,...i}=e;return s.jsx(it.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});j_.displayName=XU;var ZU=j_;function QU(e){const[t,n]=y.useState(void 0);return an(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;o=u.inlineSize,l=u.blockSize}else o=e.offsetWidth,l=e.offsetHeight;n({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var yg="Popper",[M_,Ti]=Zr(yg),[JU,P_]=M_(yg),F_=e=>{const{__scopePopper:t,children:n}=e,[r,a]=y.useState(null);return s.jsx(JU,{scope:t,anchor:r,onAnchorChange:a,children:n})};F_.displayName=yg;var B_="PopperAnchor",U_=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...a}=e,i=P_(B_,n),o=y.useRef(null),l=xt(t,o),c=y.useRef(null);return y.useEffect(()=>{const u=c.current;c.current=r?.current||o.current,u!==c.current&&i.onAnchorChange(c.current)}),r?null:s.jsx(it.div,{...a,ref:l})});U_.displayName=B_;var Eg="PopperContent",[e7,t7]=M_(Eg),$_=y.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:o=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:h,...g}=e,b=P_(Eg,n),[x,S]=y.useState(null),T=xt(t,K=>S(K)),[N,A]=y.useState(null),C=QU(N),k=C?.width??0,O=C?.height??0,M=r+(i!=="center"?"-"+i:""),R=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},j=Array.isArray(u)?u:[u],U=j.length>0,G={padding:R,boundary:j.filter(r7),altBoundary:U},{refs:q,floatingStyles:P,placement:z,isPositioned:re,middlewareData:B}=$U({strategy:"fixed",placement:M,whileElementsMounted:(...K)=>IU(...K,{animationFrame:m==="always"}),elements:{reference:b.anchor},middleware:[zU({mainAxis:a+O,alignmentAxis:o}),c&&GU({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?VU():void 0,...G}),c&&WU({...G}),qU({...G,apply:({elements:K,rects:Y,availableWidth:J,availableHeight:Ne})=>{const{width:pe,height:te}=Y.reference,Ae=K.floating.style;Ae.setProperty("--radix-popper-available-width",`${J}px`),Ae.setProperty("--radix-popper-available-height",`${Ne}px`),Ae.setProperty("--radix-popper-anchor-width",`${pe}px`),Ae.setProperty("--radix-popper-anchor-height",`${te}px`)}}),N&&KU({element:N,padding:l}),a7({arrowWidth:k,arrowHeight:O}),f&&YU({strategy:"referenceHidden",...G})]}),[H,I]=G_(z),V=nn(h);an(()=>{re&&V?.()},[re,V]);const Z=B.arrow?.x,D=B.arrow?.y,se=B.arrow?.centerOffset!==0,[Q,ne]=y.useState();return an(()=>{x&&ne(window.getComputedStyle(x).zIndex)},[x]),s.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...P,transform:re?P.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[B.transformOrigin?.x,B.transformOrigin?.y].join(" "),...B.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(e7,{scope:n,placedSide:H,onArrowChange:A,arrowX:Z,arrowY:D,shouldHideArrow:se,children:s.jsx(it.div,{"data-side":H,"data-align":I,...g,ref:T,style:{...g.style,animation:re?void 0:"none"}})})})});$_.displayName=Eg;var H_="PopperArrow",n7={top:"bottom",right:"left",bottom:"top",left:"right"},z_=y.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=t7(H_,r),o=n7[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:s.jsx(ZU,{...a,ref:n,style:{...a.style,display:"block"}})})});z_.displayName=H_;function r7(e){return e!==null}var a7=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:a}=t,o=a.arrow?.centerOffset!==0,l=o?0:e.arrowWidth,c=o?0:e.arrowHeight,[u,p]=G_(n),d={start:"0%",center:"50%",end:"100%"}[p],f=(a.arrow?.x??0)+l/2,m=(a.arrow?.y??0)+c/2;let h="",g="";return u==="bottom"?(h=o?d:`${f}px`,g=`${-c}px`):u==="top"?(h=o?d:`${f}px`,g=`${r.floating.height+c}px`):u==="right"?(h=`${-c}px`,g=o?d:`${m}px`):u==="left"&&(h=`${r.floating.width+c}px`,g=o?d:`${m}px`),{data:{x:h,y:g}}}});function G_(e){const[t,n="center"]=e.split("-");return[t,n]}var vg=F_,xd=U_,Sg=$_,wg=z_,s7="Portal",yd=y.forwardRef((e,t)=>{const{container:n,...r}=e,[a,i]=y.useState(!1);an(()=>i(!0),[]);const o=n||a&&globalThis?.document?.body;return o?Fu.createPortal(s.jsx(it.div,{...r,ref:t}),o):null});yd.displayName=s7;function i7(e){const t=o7(e),n=y.forwardRef((r,a)=>{const{children:i,...o}=r,l=y.Children.toArray(i),c=l.find(c7);if(c){const u=c.props.children,p=l.map(d=>d===c?y.Children.count(u)>1?y.Children.only(null):y.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...o,ref:a,children:y.isValidElement(u)?y.cloneElement(u,void 0,p):null})}return s.jsx(t,{...o,ref:a,children:i})});return n.displayName=`${e}.Slot`,n}function o7(e){const t=y.forwardRef((n,r)=>{const{children:a,...i}=n;if(y.isValidElement(a)){const o=d7(a),l=u7(i,a.props);return a.type!==y.Fragment&&(l.ref=r?Rn(r,o):o),y.cloneElement(a,l)}return y.Children.count(a)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var l7=Symbol("radix.slottable");function c7(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===l7}function u7(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function d7(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function p7(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var V_=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),f7="VisuallyHidden",m7=y.forwardRef((e,t)=>s.jsx(it.span,{...e,ref:t,style:{...V_,...e.style}}));m7.displayName=f7;var h7=[" ","Enter","ArrowUp","ArrowDown"],g7=[" ","Enter"],ls="Select",[Ed,vd,b7]=Xh(ls),[Ni]=Zr(ls,[b7,Ti]),Sd=Ti(),[x7,Ia]=Ni(ls),[y7,E7]=Ni(ls),W_=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:o,defaultValue:l,onValueChange:c,dir:u,name:p,autoComplete:d,disabled:f,required:m,form:h}=e,g=Sd(t),[b,x]=y.useState(null),[S,T]=y.useState(null),[N,A]=y.useState(!1),C=cl(u),[k,O]=pi({prop:r,defaultProp:a??!1,onChange:i,caller:ls}),[M,R]=pi({prop:o,defaultProp:l,onChange:c,caller:ls}),j=y.useRef(null),U=b?h||!!b.closest("form"):!0,[G,q]=y.useState(new Set),P=Array.from(G).map(z=>z.props.value).join(";");return s.jsx(vg,{...g,children:s.jsxs(x7,{required:m,scope:t,trigger:b,onTriggerChange:x,valueNode:S,onValueNodeChange:T,valueNodeHasChildren:N,onValueNodeHasChildrenChange:A,contentId:_n(),value:M,onValueChange:R,open:k,onOpenChange:O,dir:C,triggerPointerDownPosRef:j,disabled:f,children:[s.jsx(Ed.Provider,{scope:t,children:s.jsx(y7,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(z=>{q(re=>new Set(re).add(z))},[]),onNativeOptionRemove:y.useCallback(z=>{q(re=>{const B=new Set(re);return B.delete(z),B})},[]),children:n})}),U?s.jsxs(mR,{"aria-hidden":!0,required:m,tabIndex:-1,name:p,autoComplete:d,value:M,onChange:z=>R(z.target.value),disabled:f,form:h,children:[M===void 0?s.jsx("option",{value:""}):null,Array.from(G)]},P):null]})})};W_.displayName=ls;var q_="SelectTrigger",Y_=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=e,i=Sd(n),o=Ia(q_,n),l=o.disabled||r,c=xt(t,o.onTriggerChange),u=vd(n),p=y.useRef("touch"),[d,f,m]=gR(g=>{const b=u().filter(T=>!T.disabled),x=b.find(T=>T.value===o.value),S=bR(b,g,x);S!==void 0&&o.onValueChange(S.value)}),h=g=>{l||(o.onOpenChange(!0),m()),g&&(o.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return s.jsx(xd,{asChild:!0,...i,children:s.jsx(it.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":hR(o.value)?"":void 0,...a,ref:c,onClick:Ve(a.onClick,g=>{g.currentTarget.focus(),p.current!=="mouse"&&h(g)}),onPointerDown:Ve(a.onPointerDown,g=>{p.current=g.pointerType;const b=g.target;b.hasPointerCapture(g.pointerId)&&b.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(h(g),g.preventDefault())}),onKeyDown:Ve(a.onKeyDown,g=>{const b=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&f(g.key),!(b&&g.key===" ")&&h7.includes(g.key)&&(h(),g.preventDefault())})})})});Y_.displayName=q_;var K_="SelectValue",X_=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:o="",...l}=e,c=Ia(K_,n),{onValueNodeHasChildrenChange:u}=c,p=i!==void 0,d=xt(t,c.onValueNodeChange);return an(()=>{u(p)},[u,p]),s.jsx(it.span,{...l,ref:d,style:{pointerEvents:"none"},children:hR(c.value)?s.jsx(s.Fragment,{children:o}):i})});X_.displayName=K_;var v7="SelectIcon",Z_=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...a}=e;return s.jsx(it.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});Z_.displayName=v7;var S7="SelectPortal",Q_=e=>s.jsx(yd,{asChild:!0,...e});Q_.displayName=S7;var cs="SelectContent",J_=y.forwardRef((e,t)=>{const n=Ia(cs,e.__scopeSelect),[r,a]=y.useState();if(an(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?yi.createPortal(s.jsx(eR,{scope:e.__scopeSelect,children:s.jsx(Ed.Slot,{scope:e.__scopeSelect,children:s.jsx("div",{children:e.children})})}),i):null}return s.jsx(tR,{...e,ref:t})});J_.displayName=cs;var rr=10,[eR,Da]=Ni(cs),w7="SelectContentImpl",T7=i7("SelectContent.RemoveScroll"),tR=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:o,side:l,sideOffset:c,align:u,alignOffset:p,arrowPadding:d,collisionBoundary:f,collisionPadding:m,sticky:h,hideWhenDetached:g,avoidCollisions:b,...x}=e,S=Ia(cs,n),[T,N]=y.useState(null),[A,C]=y.useState(null),k=xt(t,K=>N(K)),[O,M]=y.useState(null),[R,j]=y.useState(null),U=vd(n),[G,q]=y.useState(!1),P=y.useRef(!1);y.useEffect(()=>{if(T)return id(T)},[T]),pg();const z=y.useCallback(K=>{const[Y,...J]=U().map(te=>te.ref.current),[Ne]=J.slice(-1),pe=document.activeElement;for(const te of K)if(te===pe||(te?.scrollIntoView({block:"nearest"}),te===Y&&A&&(A.scrollTop=0),te===Ne&&A&&(A.scrollTop=A.scrollHeight),te?.focus(),document.activeElement!==pe))return},[U,A]),re=y.useCallback(()=>z([O,T]),[z,O,T]);y.useEffect(()=>{G&&re()},[G,re]);const{onOpenChange:B,triggerPointerDownPosRef:H}=S;y.useEffect(()=>{if(T){let K={x:0,y:0};const Y=Ne=>{K={x:Math.abs(Math.round(Ne.pageX)-(H.current?.x??0)),y:Math.abs(Math.round(Ne.pageY)-(H.current?.y??0))}},J=Ne=>{K.x<=10&&K.y<=10?Ne.preventDefault():T.contains(Ne.target)||B(!1),document.removeEventListener("pointermove",Y),H.current=null};return H.current!==null&&(document.addEventListener("pointermove",Y),document.addEventListener("pointerup",J,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",J,{capture:!0})}}},[T,B,H]),y.useEffect(()=>{const K=()=>B(!1);return window.addEventListener("blur",K),window.addEventListener("resize",K),()=>{window.removeEventListener("blur",K),window.removeEventListener("resize",K)}},[B]);const[I,V]=gR(K=>{const Y=U().filter(pe=>!pe.disabled),J=Y.find(pe=>pe.ref.current===document.activeElement),Ne=bR(Y,K,J);Ne&&setTimeout(()=>Ne.ref.current.focus())}),Z=y.useCallback((K,Y,J)=>{const Ne=!P.current&&!J;(S.value!==void 0&&S.value===Y||Ne)&&(M(K),Ne&&(P.current=!0))},[S.value]),D=y.useCallback(()=>T?.focus(),[T]),se=y.useCallback((K,Y,J)=>{const Ne=!P.current&&!J;(S.value!==void 0&&S.value===Y||Ne)&&j(K)},[S.value]),Q=r==="popper"?Lm:nR,ne=Q===Lm?{side:l,sideOffset:c,align:u,alignOffset:p,arrowPadding:d,collisionBoundary:f,collisionPadding:m,sticky:h,hideWhenDetached:g,avoidCollisions:b}:{};return s.jsx(eR,{scope:n,content:T,viewport:A,onViewportChange:C,itemRefCallback:Z,selectedItem:O,onItemLeave:D,itemTextRefCallback:se,focusSelectedItem:re,selectedItemText:R,position:r,isPositioned:G,searchRef:I,children:s.jsx(dl,{as:T7,allowPinchZoom:!0,children:s.jsx(fd,{asChild:!0,trapped:S.open,onMountAutoFocus:K=>{K.preventDefault()},onUnmountAutoFocus:Ve(a,K=>{S.trigger?.focus({preventScroll:!0}),K.preventDefault()}),children:s.jsx(pd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:K=>K.preventDefault(),onDismiss:()=>S.onOpenChange(!1),children:s.jsx(Q,{role:"listbox",id:S.contentId,"data-state":S.open?"open":"closed",dir:S.dir,onContextMenu:K=>K.preventDefault(),...x,...ne,onPlaced:()=>q(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:Ve(x.onKeyDown,K=>{const Y=K.ctrlKey||K.altKey||K.metaKey;if(K.key==="Tab"&&K.preventDefault(),!Y&&K.key.length===1&&V(K.key),["ArrowUp","ArrowDown","Home","End"].includes(K.key)){let Ne=U().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);if(["ArrowUp","End"].includes(K.key)&&(Ne=Ne.slice().reverse()),["ArrowUp","ArrowDown"].includes(K.key)){const pe=K.target,te=Ne.indexOf(pe);Ne=Ne.slice(te+1)}setTimeout(()=>z(Ne)),K.preventDefault()}})})})})})})});tR.displayName=w7;var N7="SelectItemAlignedPosition",nR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=e,i=Ia(cs,n),o=Da(cs,n),[l,c]=y.useState(null),[u,p]=y.useState(null),d=xt(t,k=>p(k)),f=vd(n),m=y.useRef(!1),h=y.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:S}=o,T=y.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&u&&g&&b&&x){const k=i.trigger.getBoundingClientRect(),O=u.getBoundingClientRect(),M=i.valueNode.getBoundingClientRect(),R=x.getBoundingClientRect();if(i.dir!=="rtl"){const pe=R.left-O.left,te=M.left-pe,Ae=k.left-te,$e=k.width+Ae,Ee=Math.max($e,O.width),Ze=window.innerWidth-rr,Ye=_m(te,[rr,Math.max(rr,Ze-Ee)]);l.style.minWidth=$e+"px",l.style.left=Ye+"px"}else{const pe=O.right-R.right,te=window.innerWidth-M.right-pe,Ae=window.innerWidth-k.right-te,$e=k.width+Ae,Ee=Math.max($e,O.width),Ze=window.innerWidth-rr,Ye=_m(te,[rr,Math.max(rr,Ze-Ee)]);l.style.minWidth=$e+"px",l.style.right=Ye+"px"}const j=f(),U=window.innerHeight-rr*2,G=g.scrollHeight,q=window.getComputedStyle(u),P=parseInt(q.borderTopWidth,10),z=parseInt(q.paddingTop,10),re=parseInt(q.borderBottomWidth,10),B=parseInt(q.paddingBottom,10),H=P+z+G+B+re,I=Math.min(b.offsetHeight*5,H),V=window.getComputedStyle(g),Z=parseInt(V.paddingTop,10),D=parseInt(V.paddingBottom,10),se=k.top+k.height/2-rr,Q=U-se,ne=b.offsetHeight/2,K=b.offsetTop+ne,Y=P+z+K,J=H-Y;if(Y<=se){const pe=j.length>0&&b===j[j.length-1].ref.current;l.style.bottom="0px";const te=u.clientHeight-g.offsetTop-g.offsetHeight,Ae=Math.max(Q,ne+(pe?D:0)+te+re),$e=Y+Ae;l.style.height=$e+"px"}else{const pe=j.length>0&&b===j[0].ref.current;l.style.top="0px";const Ae=Math.max(se,P+g.offsetTop+(pe?Z:0)+ne)+J;l.style.height=Ae+"px",g.scrollTop=Y-se+g.offsetTop}l.style.margin=`${rr}px 0`,l.style.minHeight=I+"px",l.style.maxHeight=U+"px",r?.(),requestAnimationFrame(()=>m.current=!0)}},[f,i.trigger,i.valueNode,l,u,g,b,x,i.dir,r]);an(()=>T(),[T]);const[N,A]=y.useState();an(()=>{u&&A(window.getComputedStyle(u).zIndex)},[u]);const C=y.useCallback(k=>{k&&h.current===!0&&(T(),S?.(),h.current=!1)},[T,S]);return s.jsx(A7,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:m,onScrollButtonChange:C,children:s.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:s.jsx(it.div,{...a,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});nR.displayName=N7;var C7="SelectPopperPosition",Lm=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=rr,...i}=e,o=Sd(n);return s.jsx(Sg,{...o,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Lm.displayName=C7;var[A7,Tg]=Ni(cs,{}),jm="SelectViewport",rR=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...a}=e,i=Da(jm,n),o=Tg(jm,n),l=xt(t,i.onViewportChange),c=y.useRef(0);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),s.jsx(Ed.Slot,{scope:n,children:s.jsx(it.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Ve(a.onScroll,u=>{const p=u.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:f}=o;if(f?.current&&d){const m=Math.abs(c.current-p.scrollTop);if(m>0){const h=window.innerHeight-rr*2,g=parseFloat(d.style.minHeight),b=parseFloat(d.style.height),x=Math.max(g,b);if(x<h){const S=x+m,T=Math.min(h,S),N=S-T;d.style.height=T+"px",d.style.bottom==="0px"&&(p.scrollTop=N>0?N:0,d.style.justifyContent="flex-end")}}}c.current=p.scrollTop})})})]})});rR.displayName=jm;var aR="SelectGroup",[_7,R7]=Ni(aR),k7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=_n();return s.jsx(_7,{scope:n,id:a,children:s.jsx(it.div,{role:"group","aria-labelledby":a,...r,ref:t})})});k7.displayName=aR;var sR="SelectLabel",I7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=R7(sR,n);return s.jsx(it.div,{id:a.id,...r,ref:t})});I7.displayName=sR;var xu="SelectItem",[D7,iR]=Ni(xu),oR=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...o}=e,l=Ia(xu,n),c=Da(xu,n),u=l.value===r,[p,d]=y.useState(i??""),[f,m]=y.useState(!1),h=xt(t,S=>c.itemRefCallback?.(S,r,a)),g=_n(),b=y.useRef("touch"),x=()=>{a||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return s.jsx(D7,{scope:n,value:r,disabled:a,textId:g,isSelected:u,onItemTextChange:y.useCallback(S=>{d(T=>T||(S?.textContent??"").trim())},[]),children:s.jsx(Ed.ItemSlot,{scope:n,value:r,disabled:a,textValue:p,children:s.jsx(it.div,{role:"option","aria-labelledby":g,"data-highlighted":f?"":void 0,"aria-selected":u&&f,"data-state":u?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...o,ref:h,onFocus:Ve(o.onFocus,()=>m(!0)),onBlur:Ve(o.onBlur,()=>m(!1)),onClick:Ve(o.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:Ve(o.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:Ve(o.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Ve(o.onPointerMove,S=>{b.current=S.pointerType,a?c.onItemLeave?.():b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ve(o.onPointerLeave,S=>{S.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:Ve(o.onKeyDown,S=>{c.searchRef?.current!==""&&S.key===" "||(g7.includes(S.key)&&x(),S.key===" "&&S.preventDefault())})})})})});oR.displayName=xu;var co="SelectItemText",lR=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=e,o=Ia(co,n),l=Da(co,n),c=iR(co,n),u=E7(co,n),[p,d]=y.useState(null),f=xt(t,x=>d(x),c.onItemTextChange,x=>l.itemTextRefCallback?.(x,c.value,c.disabled)),m=p?.textContent,h=y.useMemo(()=>s.jsx("option",{value:c.value,disabled:c.disabled,children:m},c.value),[c.disabled,c.value,m]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return an(()=>(g(h),()=>b(h)),[g,b,h]),s.jsxs(s.Fragment,{children:[s.jsx(it.span,{id:c.textId,...i,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?yi.createPortal(i.children,o.valueNode):null]})});lR.displayName=co;var cR="SelectItemIndicator",uR=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return iR(cR,n).isSelected?s.jsx(it.span,{"aria-hidden":!0,...r,ref:t}):null});uR.displayName=cR;var Mm="SelectScrollUpButton",dR=y.forwardRef((e,t)=>{const n=Da(Mm,e.__scopeSelect),r=Tg(Mm,e.__scopeSelect),[a,i]=y.useState(!1),o=xt(t,r.onScrollButtonChange);return an(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollTop>0;i(u)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),a?s.jsx(fR,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});dR.displayName=Mm;var Pm="SelectScrollDownButton",pR=y.forwardRef((e,t)=>{const n=Da(Pm,e.__scopeSelect),r=Tg(Pm,e.__scopeSelect),[a,i]=y.useState(!1),o=xt(t,r.onScrollButtonChange);return an(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,p=Math.ceil(c.scrollTop)<u;i(p)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),a?s.jsx(fR,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});pR.displayName=Pm;var fR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=e,i=Da("SelectScrollButton",n),o=y.useRef(null),l=vd(n),c=y.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return y.useEffect(()=>()=>c(),[c]),an(()=>{l().find(p=>p.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[l]),s.jsx(it.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Ve(a.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Ve(a.onPointerMove,()=>{i.onItemLeave?.(),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Ve(a.onPointerLeave,()=>{c()})})}),O7="SelectSeparator",L7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return s.jsx(it.div,{"aria-hidden":!0,...r,ref:t})});L7.displayName=O7;var Fm="SelectArrow",j7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=Sd(n),i=Ia(Fm,n),o=Da(Fm,n);return i.open&&o.position==="popper"?s.jsx(wg,{...a,...r,ref:t}):null});j7.displayName=Fm;var M7="SelectBubbleInput",mR=y.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const a=y.useRef(null),i=xt(r,a),o=p7(t);return y.useEffect(()=>{const l=a.current;if(!l)return;const c=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==t&&p){const d=new Event("change",{bubbles:!0});p.call(l,t),l.dispatchEvent(d)}},[o,t]),s.jsx(it.select,{...n,style:{...V_,...n.style},ref:i,defaultValue:t})});mR.displayName=M7;function hR(e){return e===""||e===void 0}function gR(e){const t=nn(e),n=y.useRef(""),r=y.useRef(0),a=y.useCallback(o=>{const l=n.current+o;t(l),(function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))})(l)},[t]),i=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function bR(e,t,n){const a=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=P7(e,Math.max(i,0));a.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function P7(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var F7=W_,B7=Y_,U7=X_,$7=Z_,H7=Q_,z7=J_,G7=rR,V7=oR,W7=lR,q7=uR,Y7=dR,K7=pR;function Fo({...e}){return s.jsx(F7,{"data-slot":"select",...e})}function Bo({...e}){return s.jsx(U7,{"data-slot":"select-value",...e})}function Uo({className:e,size:t="default",children:n,...r}){return s.jsxs(B7,{"data-slot":"select-trigger","data-size":t,className:Fe("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[n,s.jsx($7,{asChild:!0,children:s.jsx(Ku,{className:"size-4 opacity-50"})})]})}function $o({className:e,children:t,position:n="popper",...r}){return s.jsx(H7,{children:s.jsxs(z7,{"data-slot":"select-content",className:Fe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[s.jsx(X7,{}),s.jsx(G7,{className:Fe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),s.jsx(Z7,{})]})})}function ba({className:e,children:t,...n}){return s.jsxs(V7,{"data-slot":"select-item",className:Fe("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[s.jsx("span",{className:"absolute end-2 flex size-3.5 items-center justify-center",children:s.jsx(q7,{children:s.jsx(Yt,{className:"size-4"})})}),s.jsx(W7,{children:t})]})}function X7({className:e,...t}){return s.jsx(Y7,{"data-slot":"select-scroll-up-button",className:Fe("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(rF,{className:"size-4"})})}function Z7({className:e,...t}){return s.jsx(K7,{"data-slot":"select-scroll-down-button",className:Fe("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(Ku,{className:"size-4"})})}const Ho=y.forwardRef(({className:e,...t},n)=>s.jsx("textarea",{className:Fe("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Ho.displayName="Textarea";function Bm({status:e}){const t="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-semibold border uppercase tracking-wider whitespace-nowrap";switch(e){case"open":return s.jsx("span",{className:Fe(t,"bg-red-500/15 text-red-600 border-red-500/30"),children:"Open"});case"in_progress":return s.jsx("span",{className:Fe(t,"bg-blue-500/15 text-blue-600 border-blue-500/30"),children:"In Progress"});case"resolved":return s.jsx("span",{className:Fe(t,"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"),children:"Resolved"});case"closed":return s.jsx("span",{className:Fe(t,"bg-gray-500/15 text-gray-600 border-gray-500/30"),children:"Closed"});default:return s.jsx("span",{className:Fe(t,"bg-secondary text-secondary-foreground"),children:e})}}function xR(e){if(!e)return"—";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function yR(e){if(!e)return"—";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);return n<60?`${n}m`:`${Math.floor(n/60)}h ${n%60}m`}function Va(e){const t=String(e.tags?.priority||e.tags?.severity||"").toUpperCase();return t==="P1"||t==="CRITICAL"||e.status==="in_progress"?"P1":t==="P2"?"P2":t==="P3"||t==="LOW"||e.status==="resolved"||e.status==="closed"?"P3":"P2"}function ER(e){const t=String(e||"").toLowerCase();return t==="critical"||t==="p1"?{ack:10,resolve:60}:t==="high"||t==="p2"?{ack:30,resolve:120}:{ack:30,resolve:120}}function L1(e,t){return!e||!t?null:Math.max(0,Math.floor((new Date(t).getTime()-new Date(e).getTime())/6e4))}function j1(e,t){const{ack:n,resolve:r}=ER(e.tags?.severity||e.tags?.priority),a=t==="ack"?n:r,i=e.status!=="open",o=e.status==="resolved"||e.status==="closed";if(t==="ack"?i:o){const p=t==="ack"?e.analysisTriggeredAt||e.updatedAt:e.resolvedAt,d=L1(e.createdAt,p);return d==null?{label:"✓ met",cls:"ok"}:d<=a?{label:`✓ ${d}m`,cls:"ok"}:{label:`⚠ ${d}m`,cls:"breach"}}const c=L1(e.createdAt,new Date().toISOString())??0,u=a-c;return u>=0?{label:`⏱ ${u}m left`,cls:"pending"}:{label:`⚠ ${Math.abs(u)}m over`,cls:"breach"}}function Um(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`}function Q7(e){if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return"—";const n=r=>r.toString().padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const yu={open:"Open",in_progress:"Investigating",resolved:"Resolved",closed:"Closed"};function J7(e){if(e.events&&e.events.length){const n=e.events.map(r=>{const a=r.type==="status_change"&&r.afterValue==="in_progress",i=r.type==="created"?"created":r.type==="analysis"?"ai":r.type==="assigned"?"state":r.type==="status_change"?r.afterValue==="resolved"||r.afterValue==="closed"?"resolved":a?"ack":"state":"comment";let o,l;if(r.type==="status_change")if(a)o="Acknowledged",l=r.actor?`by ${r.actor}`:null;else if(r.afterValue==="resolved"){o="Incident resolved";const c=r.actor?`by ${r.actor}`:"",u=r.message&&r.message!=="State changed"?r.message:null;l=u?`${u}${c?` · ${c}`:""}`:c||null}else r.afterValue==="closed"?(o="Incident closed",l=r.actor?`by ${r.actor}`:null):(o="State changed",l=`${yu[r.beforeValue??""]??r.beforeValue} → ${yu[r.afterValue??""]??r.afterValue}${r.actor?` · by ${r.actor}`:""}`);else r.type==="assigned"?(o=r.message||"Assignment changed",l=r.actor?`by ${r.actor}`:null):r.type==="analysis"?(o="AI Insight ran",l=r.message||"RCA analysis requested"):r.type==="created"?(o="Incident created",l=r.message?`${r.message}${r.actor?` · ${r.actor}`:""}`:e.source?`Source ${e.source}`:null):(o=r.message||r.type,l=r.actor?`by ${r.actor}`:null);return{t:r.createdAt,title:o,detail:l,kind:i}});e.events.some(r=>r.type==="created")||n.push({t:e.createdAt,title:"Incident created",detail:e.source?`Source ${e.source}`:null,kind:"created"});for(const r of e.comments||[])n.push({t:r.createdAt,title:"Note added",detail:r.message,kind:"comment"});return n.filter(r=>r.t).sort((r,a)=>new Date(r.t).getTime()-new Date(a.t).getTime())}const t=[];t.push({t:e.createdAt,title:"Incident created",detail:e.source?`Source ${e.source}${e.alertId?" · alarm linked":""}`:null,kind:"created"}),e.analysisTriggeredAt&&t.push({t:e.analysisTriggeredAt,title:"AI Insight triggered",detail:"RCA analysis requested",kind:"ai"}),e.analysisCompletedAt&&t.push({t:e.analysisCompletedAt,title:"AI Insight completed",detail:e.aiModelUsed?`Model ${e.aiModelUsed}`:null,kind:"ai"}),e.analysisStatus==="failed"&&t.push({t:e.updatedAt,title:"AI Insight failed",detail:"Analysis did not complete",kind:"failed"});for(const n of e.comments||[])t.push({t:n.createdAt,title:"Note added",detail:n.message,kind:"comment"});return e.resolvedAt&&t.push({t:e.resolvedAt,title:"Incident resolved",detail:null,kind:"resolved"}),t.filter(n=>n.t).sort((n,r)=>new Date(n.t).getTime()-new Date(r.t).getTime())}const e9={created:"#922B21",ack:"#1A5276",ai:"#7048C4",state:"#E67E22",comment:"#5a6b7b",resolved:"#1E8449",failed:"#C0392B"};function t9(e){if(e.events&&e.events.length){const n=e.events.map(r=>({ts:r.createdAt,actor:r.actor||"—",action:r.message||r.type,before:r.beforeValue?(yu[r.beforeValue]??r.beforeValue).toUpperCase():"—",after:r.afterValue?(yu[r.afterValue]??r.afterValue).toUpperCase():"—"}));return e.events.some(r=>r.type==="created")||n.push({ts:e.createdAt,actor:"System",action:"Incident created",before:"—",after:"OPEN"}),n.sort((r,a)=>new Date(r.ts).getTime()-new Date(a.ts).getTime())}const t=[];return t.push({ts:e.createdAt,actor:"System",action:e.alertId?"Incident created from alarm":"Incident created",before:"—",after:"OPEN"}),e.analysisTriggeredAt&&t.push({ts:e.analysisTriggeredAt,actor:"AI Insight",action:"Analysis triggered",before:"pending",after:"processing"}),e.analysisCompletedAt&&t.push({ts:e.analysisCompletedAt,actor:"AI Insight",action:"Analysis generated",before:"—",after:"completed"}),e.status==="in_progress"&&t.push({ts:e.analysisTriggeredAt||e.updatedAt,actor:"—",action:"State changed",before:"OPEN",after:"INVESTIGATING"}),e.resolvedAt&&t.push({ts:e.resolvedAt,actor:"—",action:"State changed",before:"INVESTIGATING",after:"RESOLVED"}),t.filter(n=>n.ts).sort((n,r)=>new Date(n.ts).getTime()-new Date(r.ts).getTime())}const n9=[{id:"overview",label:"Overview"},{id:"alarms",label:"Alarm group"},{id:"ai",label:"AI Insight"},{id:"timeline",label:"Timeline"},{id:"notifications",label:"Notifications"},{id:"audit",label:"Audit"}];function r9({incident:e}){const t=Va(e),n=e.analysisTriggeredAt&&e.createdAt?Math.max(0,Math.floor((new Date(e.analysisTriggeredAt).getTime()-new Date(e.createdAt).getTime())/6e4)):null;return s.jsxs("div",{className:"im-inc-overview",children:[s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Incident summary"}),e.description&&s.jsxs("div",{className:"mt-4 p-4 border rounded bg-secondary/20",children:[s.jsx("h4",{className:"font-semibold text-sm mb-2 text-primary flex items-center",children:"Short Description"}),s.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed text-muted-foreground",children:e.description})]}),s.jsxs("div",{className:"im-inc-meta-rows",children:[s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Affected resource"}),s.jsxs("span",{className:"im-mono",children:[e.resourceType," · ",e.resourceName]})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Priority"}),s.jsx("span",{children:s.jsx("span",{className:`im-priority-pill im-priority-${t.toLowerCase()}`,children:t})})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Source"}),s.jsx("span",{className:"im-mono",children:e.source||"—"})]}),(e.accountName||e.account_name)&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Account Name"}),s.jsx("span",{className:"im-mono font-medium",children:e.accountName||e.account_name})]}),(e.accountId||e.account_id)&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Account ID"}),s.jsx("span",{className:"im-mono",children:e.accountId||e.account_id})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Created"}),s.jsx("span",{children:e.createdAt?new Date(e.createdAt).toLocaleString():"—"})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Tags"}),s.jsx("div",{className:"flex flex-wrap gap-1 justify-end",children:e.tags&&Object.keys(e.tags).length>0?Object.entries(e.tags).map(([r,a])=>s.jsxs("span",{className:"im-inc-label-chip font-mono text-[11px]",children:[r,":",a]},r)):s.jsx("span",{children:"—"})})]}),e.alertId&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Source alarm"}),s.jsxs("span",{className:"im-mono",children:[e.alertId.slice(0,8),"…"]})]})]})]}),s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Quick stats"}),s.jsxs("div",{className:"im-inc-quick-stats",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Time open"}),s.jsx("strong",{children:yR(e.createdAt)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Time to acknowledge"}),s.jsx("strong",{children:n!=null?`${n}m`:"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Analysis status"}),s.jsx("strong",{style:{textTransform:"capitalize"},children:e.analysisStatus})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Alarm group size"}),s.jsx("strong",{children:(()=>{const r=e.name.match(/^(\d+) alerts? on/);return r?parseInt(r[1]):e.alertId?1:0})()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Comments"}),s.jsx("strong",{children:e.comments?.length??0})]}),e.resolvedAt&&s.jsxs("div",{children:[s.jsx("span",{children:"Resolved"}),s.jsx("strong",{children:xR(e.resolvedAt)})]})]})]})]})}function a9({incident:e,onViewAlert:t}){const[n,r]=w.useState([]),[a,i]=w.useState(!1);w.useEffect(()=>{e.id&&(i(!0),Ie.listAlerts({incidentId:e.id,limit:100}).then(c=>r(c.alerts)).catch(()=>{}).finally(()=>i(!1)))},[e.id]);const o=n[0]?.sourceType??e.source??"—",l=n.length?`${n.length} alarm${n.length>1?"s":""} across 1 resource · Source: ${o} · First alarm ${Um(n[n.length-1]?.createdAt)}`:"No alarms are linked to this incident yet.";return s.jsxs("div",{className:"im-inc-alarm-group",children:[s.jsxs("div",{className:"im-inc-group-banner",children:[s.jsx("span",{children:l}),n.length>0&&t&&s.jsx("button",{type:"button",onClick:()=>t(n[0].id),children:"View group timeline"})]}),s.jsxs("div",{className:"im-inc-alarm-table",children:[s.jsxs("div",{className:"im-inc-alarm-thead",children:[s.jsx("span",{style:{flex:"0 0 80px"},children:"Time"}),s.jsx("span",{style:{flex:"0 0 90px"},children:"Severity"}),s.jsx("span",{style:{flex:"0 0 90px"},children:"State"}),s.jsx("span",{style:{flex:"0 0 120px"},children:"Source"}),s.jsx("span",{style:{flex:1},children:"Metric"}),s.jsx("span",{style:{flex:"0 0 80px"},children:"Value"}),s.jsx("span",{style:{flex:"0 0 60px",textAlign:"right"},children:"Raw"})]}),a?s.jsx("div",{className:"im-inc-alarm-empty",children:s.jsx(Qe,{className:"h-5 w-5 animate-spin"})}):n.length===0?s.jsx("div",{className:"im-inc-alarm-empty",children:"No alarms in this group."}):n.map(c=>{const u=c.metricName||c.alertName,p=c.metricValue??c.value??"—";return s.jsxs("div",{className:"im-inc-alarm-trow",children:[s.jsx("span",{style:{flex:"0 0 80px"},className:"im-mono im-muted",children:Um(c.createdAt)}),s.jsx("span",{style:{flex:"0 0 90px"},children:s.jsx("span",{className:`im-sev-badge im-sev-${c.severity}`,children:c.severity})}),s.jsx("span",{style:{flex:"0 0 90px"},children:s.jsxs("span",{className:`im-alarm-state im-alarm-state-${String(c.status).toLowerCase()}`,children:[s.jsx("i",{}),c.status]})}),s.jsx("span",{style:{flex:"0 0 120px"},className:"im-muted",children:c.sourceType??"—"}),s.jsx("span",{style:{flex:1},className:"im-mono",children:u}),s.jsx("span",{style:{flex:"0 0 80px",fontWeight:700},children:p}),s.jsx("span",{style:{flex:"0 0 60px",textAlign:"right"},children:t&&s.jsx("button",{type:"button",className:"im-link-button",onClick:()=>t(c.id),children:"View"})})]},c.id)})]})]})}function s9({incident:e,readOnly:t,submitting:n,onSubmit:r}){const[a,i]=w.useState(""),o=J7(e),l=()=>{a.trim()&&(r(a.trim()),i(""))};return s.jsxs("div",{className:"im-inc-timeline-tab",children:[s.jsx("div",{className:"im-inc-card",children:s.jsx("div",{className:"im-inc-timeline",children:o.map((c,u)=>s.jsxs("div",{className:"im-inc-tl-row",children:[s.jsxs("div",{className:"im-inc-tl-rail",children:[s.jsx("span",{className:"im-inc-tl-dot",style:{borderColor:e9[c.kind]}}),u<o.length-1&&s.jsx("span",{className:"im-inc-tl-line"})]}),s.jsxs("div",{className:"im-inc-tl-body",children:[s.jsxs("div",{className:"im-inc-tl-head",children:[s.jsx("strong",{children:c.title}),s.jsx("span",{className:"im-mono im-inc-tl-time",children:Um(c.t)})]}),c.detail&&s.jsx("div",{className:"im-inc-tl-detail",children:c.detail})]})]},u))})}),!t&&s.jsxs("div",{className:"im-inc-note-box",children:[s.jsx("textarea",{placeholder:"Add a note… (Markdown, @mention supported)",value:a,onChange:c=>i(c.target.value)}),s.jsx(ie,{onClick:l,disabled:n||!a.trim(),children:n?"Posting…":"Post note"})]})]})}function i9({incident:e,isActive:t,isCompleted:n,isFailed:r,isPending:a,polled:i,validAnalysisResult:o,analysisError:l,backendError:c,sopId:u,isReadOnly:p,onRunAnalysis:d,getStatusLabel:f}){return s.jsxs("div",{className:"im-ai-tab",children:[a&&s.jsxs("div",{className:"im-ai-idle-card",children:[s.jsx("div",{className:"im-ai-idle-icon",children:"✦"}),s.jsx("div",{className:"im-ai-idle-title",children:"AI Insight"}),s.jsx("p",{children:"Run AI Insight to get root cause hints, SOP steps, and recommendations for this incident."}),!p&&s.jsxs(ie,{onClick:d,children:[s.jsx(ho,{className:"mr-2 h-4 w-4"})," Run AI Insight"]}),s.jsxs("div",{className:"im-ai-context-list",children:[s.jsx("span",{children:"✓ Incident data"}),s.jsxs("span",{children:["✓ Resource metadata (",e.resourceType," · ",e.resourceName,")"]}),e.alertId&&s.jsx("span",{children:"✓ Source alarm linked"})]})]}),t&&!o&&s.jsxs("div",{className:"im-ai-running-card",children:[s.jsx(Qe,{className:"h-8 w-8 animate-spin",style:{color:"var(--im-primary)"}}),s.jsx("div",{className:"im-ai-running-title",children:"Generating analysis…"}),s.jsx("div",{className:"im-ai-running-sub",children:f(i?.status)}),i?.progressPercent>0&&s.jsx("div",{className:"im-ai-progress-bar",children:s.jsx("div",{style:{width:`${i.progressPercent}%`}})})]}),r&&s.jsxs("div",{className:"im-ai-failed-card",children:[s.jsx(bs,{size:24,style:{color:"var(--im-danger)"}}),s.jsx("div",{children:"Analysis failed"}),s.jsx("p",{children:l||c||"Something went wrong with the AI pipeline."}),!p&&s.jsxs(ie,{variant:"outline",onClick:d,children:[s.jsx(Ra,{className:"mr-2 h-4 w-4"})," Retry"]})]}),(n||t&&o)&&o&&s.jsxs("div",{className:"im-ai-results",children:[typeof o=="string"?s.jsxs("div",{className:"im-inc-card",children:[s.jsxs("div",{className:"im-inc-card-title",children:["🔍 Root cause analysis",s.jsx("span",{className:"im-ai-badge",children:"✦ AI-generated"})]}),e.confidenceScore!=null&&s.jsxs("div",{className:"im-ai-confidence",children:["Confidence: ",e.confidenceScore,"%"]}),s.jsx("pre",{className:"im-ai-text-result",children:o})]}):s.jsx(C5,{result:o,remediationSteps:e.remediationSteps,confidenceScore:e.confidenceScore,aiModelUsed:e.aiModelUsed,isCompleted:n}),u&&s.jsxs("div",{className:"im-inc-card",children:[s.jsxs("div",{className:"im-inc-card-title",children:["📋 Related SOP",s.jsx("span",{className:"im-ai-badge",children:"✦ AI-matched"})]}),s.jsxs(Ei,{to:`/sops/${u}`,className:"im-ai-sop-link",children:["View SOP ",s.jsx(ui,{size:13,style:{display:"inline-block",marginLeft:4}})]})]})]})]})}function o9({incident:e}){const[t,n]=w.useState([]),[r,a]=w.useState([]),[i,o]=w.useState(`${Va(e)} ${e.aliasId?`INC-${String(e.aliasId).padStart(3,"0")}`:e.id.slice(0,7)} — ${e.name}.`);w.useEffect(()=>{Ie.getNotificationProviders().then(c=>{const u=(c.providers||[]).map(p=>p.type||p.name).filter(Boolean);n(u),u[0]&&a([u[0]])}).catch(()=>{})},[]);const l=c=>a(u=>u.includes(c)?u.filter(p=>p!==c):[...u,c]);return s.jsxs("div",{className:"im-inc-notifs",children:[s.jsxs("div",{className:"im-inc-card im-inc-notifs-sent",children:[s.jsx("div",{className:"im-inc-card-title",children:"Sent notifications"}),s.jsx("div",{className:"im-inc-empty-inline",children:s.jsx("p",{children:"No notifications have been sent for this incident yet."})})]}),s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Send manual notification"}),s.jsxs("div",{className:"im-inc-notif-field",children:[s.jsx("label",{children:"Channels"}),s.jsx("div",{className:"im-chip-row",children:t.length===0?s.jsx("span",{className:"im-muted",style:{fontSize:12},children:"No notification providers configured."}):t.map(c=>s.jsx("button",{type:"button",className:`im-notif-chip ${r.includes(c)?"is-on":""}`,onClick:()=>l(c),children:c},c))})]}),s.jsx("textarea",{className:"im-inc-notif-textarea",value:i,onChange:c=>o(c.target.value)}),s.jsx(ie,{disabled:r.length===0||!i.trim(),onClick:()=>ae.info("Manual notification sending is not yet wired to a backend endpoint."),children:"Send now"})]})]})}function l9({incident:e}){const t=t9(e);return s.jsxs("div",{className:"im-inc-card im-inc-audit-card",children:[s.jsx("div",{className:"im-inc-audit-head",children:s.jsx("span",{children:"Audit trail · derived from incident events"})}),s.jsxs("div",{className:"im-inc-audit-thead",children:[s.jsx("span",{style:{flex:"0 0 170px"},children:"Timestamp"}),s.jsx("span",{style:{flex:"0 0 130px"},children:"Actor"}),s.jsx("span",{style:{flex:1},children:"Action"}),s.jsx("span",{style:{flex:"0 0 180px"},children:"Before → After"})]}),t.map((n,r)=>s.jsxs("div",{className:"im-inc-audit-trow",children:[s.jsx("span",{style:{flex:"0 0 170px"},className:"im-mono im-muted",children:Q7(n.ts)}),s.jsx("span",{style:{flex:"0 0 130px"},children:n.actor}),s.jsx("span",{style:{flex:1},className:"im-muted",children:n.action}),s.jsxs("span",{style:{flex:"0 0 180px"},className:"im-mono im-muted",children:[n.before," → ",n.after]})]},r))]})}function c9({incidentId:e,onBack:t,onViewAlert:n}){const{isReadOnly:r}=ur(),a=St(),[i,o]=w.useState(null),[l,c]=w.useState(null),[u,p]=w.useState(!0),[d,f]=w.useState("overview"),[m,h]=w.useState(null),[g,b]=w.useState(!1),[x,S]=w.useState(!1),[T,N]=w.useState(!1),[A,C]=w.useState(""),[k,O]=w.useState(null),[M,R]=w.useState([]),j=w.useCallback(async()=>{try{const Y=await Ie.getIncident(e);o(Y.incident)}catch{ae.error("Failed to load incident")}finally{p(!1)}},[e]);w.useEffect(()=>{j()},[j]),w.useEffect(()=>{i?.name&&Tr.lookupByAlertName(i.name).then(Y=>{Y&&c(Y)}).catch(()=>{})},[i?.name]),w.useEffect(()=>{i?.resourceName&&Ie.listIncidents({page:1,limit:6,search:i.resourceName}).then(Y=>R((Y.incidents??[]).filter(J=>J.id!==i.id).slice(0,4))).catch(()=>{})},[i?.resourceName,i?.id]);const U=rf(i?.analysisStatus),G=k8(e,!!U,i?.analysisStatus??"pending");w.useEffect(()=>{(G.isComplete||G.isFailed)&&j()},[G.isComplete,G.isFailed,j]);const q=async Y=>{h(null),G.optimisticTrigger();try{await Ie.triggerAnalysis(Y),ae.success("Analysis triggered"),j()}catch(J){const Ne=J?.response?.data?.error??"Failed to trigger analysis";h(Ne),G.markFailed(),j(),ae.error(Ne)}},P=async Y=>{if(i){b(!0);try{const J=await Ie.addIncidentComment(i.id,{message:Y});o({...i,comments:[...i.comments||[],J.comment]}),ae.success("Comment added")}catch(J){ae.error(J?.response?.data?.error??"Failed to add comment")}finally{b(!1)}}},z=async Y=>{if(!i)return;const J=i.assigneeIds;o({...i,assigneeIds:Y});try{await Ie.assignIncident(i.id,Y),ae.success("Assignees updated"),j()}catch(Ne){o({...i,assigneeIds:J}),ae.error(Ne?.response?.data?.error??"Failed to assign users")}},re=async(Y,J)=>{if(!i)return;const Ne=i.status;o({...i,status:Y});try{await Ie.updateIncident(i.id,{status:Y,statusMessage:J}),ae.success("Status updated"),j()}catch(pe){o({...i,status:Ne}),ae.error(pe?.response?.data?.error??"Failed to update status")}},B=async()=>{if(i)try{await re("resolved",A.trim()||void 0),N(!1),C("")}catch(Y){ae.error(Y?.response?.data?.error??"Failed to resolve incident")}},H=Y=>({queued:"Queued for analysis...",triage_started:"Triaging incident...",infra_analysis:"Analysing infrastructure...",logs_analysis:"Analysing logs...",ai_reasoning:"AI reasoning in progress...",remediation_generated:"Generating remediation steps...",fetching_ec2:"Fetching EC2 details...",fetching_metrics:"Fetching metrics...",fetching_logs:"Fetching logs...",finding_rca:"Finding Root Cause..."})[Y??""]??"Analysis in progress...";if(u)return s.jsx(qr,{variant:"incident-detail"});if(!i)return s.jsx("div",{className:"im-page",children:s.jsxs("div",{className:"im-inc-empty",children:[s.jsx("h2",{children:"Incident Not Found"}),s.jsxs(ie,{variant:"outline",onClick:t,children:[s.jsx(Vr,{className:"mr-2 h-4 w-4"})," Back"]})]})});const I=U||rf(G.status)?G.status??i.analysisStatus:i.analysisStatus,V=typeof i.analysisResult=="object"&&i.analysisResult?.error?i.analysisResult.error:null,Z=V?null:i.analysisResult,D=!m&&rf(I),se=I==="completed",Q=!D&&(I==="failed"||!!m||!!V),ne=I==="pending",K=i.aliasId?`INC-${String(i.aliasId).padStart(3,"0")}`:i.id.slice(0,8);return s.jsxs("div",{className:"im-inc-detail -m-4",children:[s.jsxs("div",{className:"im-inc-header",children:[s.jsxs("div",{className:"im-inc-header-row1",children:[s.jsx("button",{className:"im-back-button",type:"button",onClick:t,"aria-label":"Back",children:s.jsx(Vr,{size:16})}),s.jsx("span",{className:"im-inc-id im-mono",children:K}),s.jsx("h1",{className:"im-inc-title",children:i.name}),s.jsx("span",{className:`im-priority-pill im-priority-${Va(i).toLowerCase()}`,children:Va(i)}),s.jsx(Bm,{status:i.status})]}),s.jsxs("div",{className:"im-inc-header-row2",children:[s.jsxs("span",{className:"im-inc-time",children:[s.jsx(rs,{size:13})," opened ",xR(i.createdAt)]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsxs("span",{className:"im-inc-resource im-mono",children:[i.resourceType," · ",i.resourceName]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsx("span",{children:i.alertId?"1 alarm":"0 alarms"}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsxs("span",{className:"im-inc-dur",children:["⏱ ",yR(i.createdAt)]})]}),s.jsxs("div",{className:"im-inc-actions",children:[!r&&s.jsxs(s.Fragment,{children:[s.jsx(ie,{size:"sm",onClick:()=>re("in_progress"),disabled:i.status==="in_progress"||i.status==="resolved",children:"Acknowledge"}),s.jsx(ie,{size:"sm",variant:"outline",style:{borderColor:"var(--im-success)",color:"var(--im-success)"},onClick:()=>N(!0),disabled:i.status==="resolved"||i.status==="closed",children:"Resolve"}),s.jsxs(ie,{size:"sm",variant:"outline",onClick:()=>S(!0),children:[s.jsx(MC,{size:13,className:"mr-1"})," Assign"]})]}),r&&s.jsxs(Fo,{value:i.status,onValueChange:re,children:[s.jsx(Uo,{className:"h-7 text-xs w-36 px-2.5",children:s.jsx(Bo,{placeholder:"Status"})}),s.jsxs($o,{children:[s.jsx(ba,{value:"open",children:"Open"}),s.jsx(ba,{value:"in_progress",children:"In Progress"}),s.jsx(ba,{value:"resolved",children:"Resolved"}),s.jsx(ba,{value:"closed",children:"Closed"})]})]})]})]}),s.jsxs("div",{className:"im-inc-body",children:[s.jsxs("div",{className:"im-inc-main",children:[s.jsx("div",{className:"im-inc-tabs",children:n9.map(({id:Y,label:J})=>s.jsxs("button",{type:"button",className:d===Y?"is-active":"",onClick:()=>f(Y),children:[J,Y==="ai"&&se&&s.jsx("span",{className:"im-ai-done-dot"})]},Y))}),s.jsxs("div",{className:"im-inc-tab-content",children:[d==="overview"&&s.jsx(r9,{incident:i}),d==="alarms"&&s.jsx(a9,{incident:i,onViewAlert:O}),d==="ai"&&s.jsx(i9,{incident:i,isActive:D,isCompleted:se,isFailed:Q,isPending:ne,polled:G,validAnalysisResult:Z,analysisError:m,backendError:V,sopId:l,isReadOnly:r,onRunAnalysis:()=>q(i.id),getStatusLabel:H}),d==="timeline"&&s.jsx(s9,{incident:i,readOnly:r,submitting:g,onSubmit:P}),d==="notifications"&&s.jsx(o9,{incident:i}),d==="audit"&&s.jsx(l9,{incident:i})]})]}),s.jsxs("aside",{className:"im-inc-sidebar",children:[s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Incident ID"}),s.jsx("div",{className:"im-mono",style:{fontSize:12},children:K})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Status"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(Bm,{status:i.status}),s.jsx("span",{className:`im-priority-pill im-priority-${Va(i).toLowerCase()}`,children:Va(i)})]})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Assignees"}),s.jsx("div",{className:r?"":"im-inc-assignee-click",onClick:()=>!r&&S(!0),children:s.jsx(E_,{assigneeIds:i.assigneeIds})}),!r&&s.jsx("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>S(!0),children:"Reassign"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Resource"}),s.jsxs("div",{className:"im-mono",style:{fontSize:11},children:[i.resourceType," · ",i.resourceName]})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Source"}),s.jsx("div",{style:{fontSize:12},children:i.source||"—"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"SLA"}),(()=>{const{ack:Y,resolve:J}=ER(i.tags?.severity||i.tags?.priority),Ne=j1(i,"ack"),pe=j1(i,"resolve");return s.jsxs("div",{className:"im-inc-sla",children:[s.jsxs("div",{className:"im-inc-sla-row",children:[s.jsxs("span",{children:["Ack in ",Y,"m"]}),s.jsx("span",{className:`im-inc-sla-val im-inc-sla-${Ne.cls}`,children:Ne.label})]}),s.jsxs("div",{className:"im-inc-sla-row",children:[s.jsxs("span",{children:["Resolve in ",J,"m"]}),s.jsx("span",{className:`im-inc-sla-val im-inc-sla-${pe.cls}`,children:pe.label})]})]})})()]}),M.length>0&&s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Related incidents"}),s.jsx("div",{className:"im-inc-related",children:M.map(Y=>s.jsxs("button",{type:"button",className:"im-inc-related-row",onClick:()=>a({to:`/incidents/${Y.id}`}),children:[s.jsxs("span",{className:"im-mono im-inc-related-id",children:["#",Y.aliasId?`INC-${String(Y.aliasId).padStart(3,"0")}`:Y.id.slice(0,7)]}),s.jsxs("span",{className:"im-muted",children:[Y.resourceName," · ",Va(Y)]})]},Y.id))})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Tags"}),i.tags&&Object.keys(i.tags).length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(i.tags).map(([Y,J])=>s.jsxs("span",{className:"im-inc-label-chip font-mono text-[11px]",children:[Y,":",J]},Y))}):s.jsx("div",{style:{fontSize:12,color:"var(--im-fg-subtle)"},children:"None"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Quick actions"}),s.jsxs("div",{className:"im-inc-sidebar-actions",children:[i.alertId&&s.jsxs("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>O(i.alertId),children:[s.jsx(ui,{size:12})," View source alarm"]}),l&&s.jsxs(Ei,{to:`/sops/${l}`,className:"im-inc-sidebar-action",children:[s.jsx(ed,{size:12})," View SOP"]}),!r&&!D&&s.jsxs("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>q(i.id),children:[s.jsx(ho,{size:12})," ",se?"Re-run AI":"Run AI Insight"]})]})]})]})]}),x&&s.jsx(N8,{open:x,onOpenChange:S,assigneeIds:i.assigneeIds,onAssign:z}),s.jsx(kt,{open:T,onOpenChange:N,children:s.jsxs(It,{children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Resolve Incident"})}),s.jsxs("div",{className:"py-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"You are about to mark this incident as resolved. You can optionally leave a comment explaining the resolution."}),s.jsx(Ho,{placeholder:"Optional resolution comment...",value:A,onChange:Y=>C(Y.target.value),className:"min-h-[100px]"})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),s.jsx(ie,{onClick:B,children:"Resolve Incident"})]})]})}),s.jsx(kt,{open:!!k,onOpenChange:Y=>!Y&&O(null),children:s.jsx(It,{className:"max-w-[600px] w-full max-h-[90vh] overflow-y-auto",children:k&&s.jsx(u9,{alertId:k,onClose:()=>O(null)})})})]})}function u9({alertId:e,onClose:t}){const n=St(),[r,a]=w.useState(null),[i,o]=w.useState(!0);if(w.useEffect(()=>{Ie.getAlert(e).then(c=>a(c.alert)).catch(()=>ae.error("Failed to load alert details")).finally(()=>o(!1))},[e]),i)return s.jsx("div",{className:"p-8 text-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin mx-auto text-muted-foreground"})});if(!r)return s.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Alert not found"});const l=r.severity==="critical"?"var(--im-priority-p1)":r.severity==="high"?"var(--im-priority-p2)":r.severity==="medium"?"var(--im-priority-p3)":"var(--im-priority-p4)";return s.jsxs("div",{className:"flex flex-col gap-4 py-2",children:[s.jsx(jt,{children:s.jsxs(Mt,{className:"flex items-center gap-2 text-lg",children:[s.jsx(bs,{className:"h-5 w-5",style:{color:l}}),r.alertName]})}),(()=>{if(!r.description)return s.jsx("div",{className:"text-sm text-muted-foreground",children:"No description provided."});const c=r.description.match(/^(.+?)\s+by\s+(arn:aws:[^\s]+)(?:\s+from\s+([0-9.]+))?/);if(c){const[,u,p,d]=c;return s.jsxs("div",{className:"bg-muted/30 border rounded-md p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Action"}),s.jsx("div",{className:"text-sm font-medium",children:u})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Identity"}),s.jsx("div",{className:"text-xs font-mono text-muted-foreground break-all bg-muted/50 px-2 py-1.5 rounded border border-muted/50",children:p})]}),d&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Source IP"}),s.jsx("div",{className:"text-xs font-mono text-muted-foreground",children:d})]})]})}return s.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.description})})(),s.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Source"}),s.jsx("div",{className:"text-sm im-mono bg-muted px-2 py-1 rounded inline-block",children:r.sourceType})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Status"}),s.jsx("div",{className:"text-sm bg-muted px-2 py-1 rounded inline-block capitalize",children:r.status})]}),s.jsxs("div",{className:"col-span-2",children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Resource"}),s.jsxs("div",{className:"text-sm im-mono bg-muted px-2 py-1 rounded",children:[r.resourceType," · ",r.resourceName]})]})]}),s.jsxs($t,{className:"mt-6 border-t pt-4",children:[s.jsx(ie,{variant:"outline",onClick:t,children:"Close"}),s.jsxs(ie,{onClick:()=>{t(),n({to:`/alerts/${r.id}`})},children:[s.jsx(ui,{className:"w-4 h-4 mr-2"}),"View Full Alert"]})]})]})}const Xe=y.forwardRef(({className:e,type:t,...n},r)=>s.jsx("input",{type:t,className:Fe("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));Xe.displayName="Input";var d9=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],p9=d9.reduce((e,t)=>{const n=Yh(`Primitive.${t}`),r=y.forwardRef((a,i)=>{const{asChild:o,...l}=a,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),f9="Label",vR=y.forwardRef((e,t)=>s.jsx(p9.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));vR.displayName=f9;var SR=vR;const Pe=y.forwardRef(({className:e,...t},n)=>s.jsx(SR,{ref:n,className:Fe("block text-sm font-medium leading-snug peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));Pe.displayName=SR.displayName;function m9(e){const t=h9(e),n=y.forwardRef((r,a)=>{const{children:i,...o}=r,l=y.Children.toArray(i),c=l.find(b9);if(c){const u=c.props.children,p=l.map(d=>d===c?y.Children.count(u)>1?y.Children.only(null):y.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...o,ref:a,children:y.isValidElement(u)?y.cloneElement(u,void 0,p):null})}return s.jsx(t,{...o,ref:a,children:i})});return n.displayName=`${e}.Slot`,n}function h9(e){const t=y.forwardRef((n,r)=>{const{children:a,...i}=n;if(y.isValidElement(a)){const o=y9(a),l=x9(i,a.props);return a.type!==y.Fragment&&(l.ref=r?Rn(r,o):o),y.cloneElement(a,l)}return y.Children.count(a)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var g9=Symbol("radix.slottable");function b9(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===g9}function x9(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function y9(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var $m=["Enter"," "],E9=["ArrowDown","PageUp","Home"],wR=["ArrowUp","PageDown","End"],v9=[...E9,...wR],S9={ltr:[...$m,"ArrowRight"],rtl:[...$m,"ArrowLeft"]},w9={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fl="Menu",[zo,T9,N9]=Xh(fl),[Es,TR]=Zr(fl,[N9,Ti,td]),wd=Ti(),NR=td(),[C9,vs]=Es(fl),[A9,ml]=Es(fl),CR=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:o=!0}=e,l=wd(t),[c,u]=y.useState(null),p=y.useRef(!1),d=nn(i),f=cl(a);return y.useEffect(()=>{const m=()=>{p.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>p.current=!1;return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),s.jsx(vg,{...l,children:s.jsx(C9,{scope:t,open:n,onOpenChange:d,content:c,onContentChange:u,children:s.jsx(A9,{scope:t,onClose:y.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:p,dir:f,modal:o,children:r})})})};CR.displayName=fl;var _9="MenuAnchor",Ng=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=wd(n);return s.jsx(xd,{...a,...r,ref:t})});Ng.displayName=_9;var Cg="MenuPortal",[R9,AR]=Es(Cg,{forceMount:void 0}),_R=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,i=vs(Cg,t);return s.jsx(R9,{scope:t,forceMount:n,children:s.jsx(er,{present:n||i.open,children:s.jsx(yd,{asChild:!0,container:a,children:r})})})};_R.displayName=Cg;var Jn="MenuContent",[k9,Ag]=Es(Jn),RR=y.forwardRef((e,t)=>{const n=AR(Jn,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,i=vs(Jn,e.__scopeMenu),o=ml(Jn,e.__scopeMenu);return s.jsx(zo.Provider,{scope:e.__scopeMenu,children:s.jsx(er,{present:r||i.open,children:s.jsx(zo.Slot,{scope:e.__scopeMenu,children:o.modal?s.jsx(I9,{...a,ref:t}):s.jsx(D9,{...a,ref:t})})})})}),I9=y.forwardRef((e,t)=>{const n=vs(Jn,e.__scopeMenu),r=y.useRef(null),a=xt(t,r);return y.useEffect(()=>{const i=r.current;if(i)return id(i)},[]),s.jsx(_g,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ve(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),D9=y.forwardRef((e,t)=>{const n=vs(Jn,e.__scopeMenu);return s.jsx(_g,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),O9=m9("MenuContent.ScrollLock"),_g=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:d,onInteractOutside:f,onDismiss:m,disableOutsideScroll:h,...g}=e,b=vs(Jn,n),x=ml(Jn,n),S=wd(n),T=NR(n),N=T9(n),[A,C]=y.useState(null),k=y.useRef(null),O=xt(t,k,b.onContentChange),M=y.useRef(0),R=y.useRef(""),j=y.useRef(0),U=y.useRef(null),G=y.useRef("right"),q=y.useRef(0),P=h?dl:y.Fragment,z=h?{as:O9,allowPinchZoom:!0}:void 0,re=H=>{const I=R.current+H,V=N().filter(K=>!K.disabled),Z=document.activeElement,D=V.find(K=>K.ref.current===Z)?.textValue,se=V.map(K=>K.textValue),Q=V9(se,I,D),ne=V.find(K=>K.textValue===Q)?.ref.current;(function K(Y){R.current=Y,window.clearTimeout(M.current),Y!==""&&(M.current=window.setTimeout(()=>K(""),1e3))})(I),ne&&setTimeout(()=>ne.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),pg();const B=y.useCallback(H=>G.current===U.current?.side&&q9(H,U.current?.area),[]);return s.jsx(k9,{scope:n,searchRef:R,onItemEnter:y.useCallback(H=>{B(H)&&H.preventDefault()},[B]),onItemLeave:y.useCallback(H=>{B(H)||(k.current?.focus(),C(null))},[B]),onTriggerLeave:y.useCallback(H=>{B(H)&&H.preventDefault()},[B]),pointerGraceTimerRef:j,onPointerGraceIntentChange:y.useCallback(H=>{U.current=H},[]),children:s.jsx(P,{...z,children:s.jsx(fd,{asChild:!0,trapped:a,onMountAutoFocus:Ve(i,H=>{H.preventDefault(),k.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:s.jsx(pd,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:d,onInteractOutside:f,onDismiss:m,children:s.jsx(uA,{asChild:!0,...T,dir:x.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:C,onEntryFocus:Ve(c,H=>{x.isUsingKeyboardRef.current||H.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(Sg,{role:"menu","aria-orientation":"vertical","data-state":VR(b.open),"data-radix-menu-content":"",dir:x.dir,...S,...g,ref:O,style:{outline:"none",...g.style},onKeyDown:Ve(g.onKeyDown,H=>{const V=H.target.closest("[data-radix-menu-content]")===H.currentTarget,Z=H.ctrlKey||H.altKey||H.metaKey,D=H.key.length===1;V&&(H.key==="Tab"&&H.preventDefault(),!Z&&D&&re(H.key));const se=k.current;if(H.target!==se||!v9.includes(H.key))return;H.preventDefault();const ne=N().filter(K=>!K.disabled).map(K=>K.ref.current);wR.includes(H.key)&&ne.reverse(),z9(ne)}),onBlur:Ve(e.onBlur,H=>{H.currentTarget.contains(H.target)||(window.clearTimeout(M.current),R.current="")}),onPointerMove:Ve(e.onPointerMove,Go(H=>{const I=H.target,V=q.current!==H.clientX;if(H.currentTarget.contains(I)&&V){const Z=H.clientX>q.current?"right":"left";G.current=Z,q.current=H.clientX}}))})})})})})})});RR.displayName=Jn;var L9="MenuGroup",Rg=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{role:"group",...r,ref:t})});Rg.displayName=L9;var j9="MenuLabel",kR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{...r,ref:t})});kR.displayName=j9;var Eu="MenuItem",M1="menu.itemSelect",Td=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,i=y.useRef(null),o=ml(Eu,e.__scopeMenu),l=Ag(Eu,e.__scopeMenu),c=xt(t,i),u=y.useRef(!1),p=()=>{const d=i.current;if(!n&&d){const f=new CustomEvent(M1,{bubbles:!0,cancelable:!0});d.addEventListener(M1,m=>r?.(m),{once:!0}),aA(d,f),f.defaultPrevented?u.current=!1:o.onClose()}};return s.jsx(IR,{...a,ref:c,disabled:n,onClick:Ve(e.onClick,p),onPointerDown:d=>{e.onPointerDown?.(d),u.current=!0},onPointerUp:Ve(e.onPointerUp,d=>{u.current||d.currentTarget?.click()}),onKeyDown:Ve(e.onKeyDown,d=>{const f=l.searchRef.current!=="";n||f&&d.key===" "||$m.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});Td.displayName=Eu;var IR=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=e,o=Ag(Eu,n),l=NR(n),c=y.useRef(null),u=xt(t,c),[p,d]=y.useState(!1),[f,m]=y.useState("");return y.useEffect(()=>{const h=c.current;h&&m((h.textContent??"").trim())},[i.children]),s.jsx(zo.ItemSlot,{scope:n,disabled:r,textValue:a??f,children:s.jsx(dA,{asChild:!0,...l,focusable:!r,children:s.jsx(it.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:u,onPointerMove:Ve(e.onPointerMove,Go(h=>{r?o.onItemLeave(h):(o.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ve(e.onPointerLeave,Go(h=>o.onItemLeave(h))),onFocus:Ve(e.onFocus,()=>d(!0)),onBlur:Ve(e.onBlur,()=>d(!1))})})})}),M9="MenuCheckboxItem",DR=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return s.jsx(PR,{scope:e.__scopeMenu,checked:n,children:s.jsx(Td,{role:"menuitemcheckbox","aria-checked":vu(n)?"mixed":n,...a,ref:t,"data-state":Ig(n),onSelect:Ve(a.onSelect,()=>r?.(vu(n)?!0:!n),{checkForDefaultPrevented:!1})})})});DR.displayName=M9;var OR="MenuRadioGroup",[P9,F9]=Es(OR,{value:void 0,onValueChange:()=>{}}),LR=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,i=nn(r);return s.jsx(P9,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(Rg,{...a,ref:t})})});LR.displayName=OR;var jR="MenuRadioItem",MR=y.forwardRef((e,t)=>{const{value:n,...r}=e,a=F9(jR,e.__scopeMenu),i=n===a.value;return s.jsx(PR,{scope:e.__scopeMenu,checked:i,children:s.jsx(Td,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":Ig(i),onSelect:Ve(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});MR.displayName=jR;var kg="MenuItemIndicator",[PR,B9]=Es(kg,{checked:!1}),FR=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,i=B9(kg,n);return s.jsx(er,{present:r||vu(i.checked)||i.checked===!0,children:s.jsx(it.span,{...a,ref:t,"data-state":Ig(i.checked)})})});FR.displayName=kg;var U9="MenuSeparator",BR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});BR.displayName=U9;var $9="MenuArrow",UR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=wd(n);return s.jsx(wg,{...a,...r,ref:t})});UR.displayName=$9;var H9="MenuSub",[ude,$R]=Es(H9),uo="MenuSubTrigger",HR=y.forwardRef((e,t)=>{const n=vs(uo,e.__scopeMenu),r=ml(uo,e.__scopeMenu),a=$R(uo,e.__scopeMenu),i=Ag(uo,e.__scopeMenu),o=y.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,u={__scopeMenu:e.__scopeMenu},p=y.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return y.useEffect(()=>p,[p]),y.useEffect(()=>{const d=l.current;return()=>{window.clearTimeout(d),c(null)}},[l,c]),s.jsx(Ng,{asChild:!0,...u,children:s.jsx(IR,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":VR(n.open),...e,ref:Rn(t,a.onTriggerChange),onClick:d=>{e.onClick?.(d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ve(e.onPointerMove,Go(d=>{i.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(i.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:Ve(e.onPointerLeave,Go(d=>{p();const f=n.content?.getBoundingClientRect();if(f){const m=n.content?.dataset.side,h=m==="right",g=h?-5:5,b=f[h?"left":"right"],x=f[h?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+g,y:d.clientY},{x:b,y:f.top},{x,y:f.top},{x,y:f.bottom},{x:b,y:f.bottom}],side:m}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ve(e.onKeyDown,d=>{const f=i.searchRef.current!=="";e.disabled||f&&d.key===" "||S9[r.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});HR.displayName=uo;var zR="MenuSubContent",GR=y.forwardRef((e,t)=>{const n=AR(Jn,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,i=vs(Jn,e.__scopeMenu),o=ml(Jn,e.__scopeMenu),l=$R(zR,e.__scopeMenu),c=y.useRef(null),u=xt(t,c);return s.jsx(zo.Provider,{scope:e.__scopeMenu,children:s.jsx(er,{present:r||i.open,children:s.jsx(zo.Slot,{scope:e.__scopeMenu,children:s.jsx(_g,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:u,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{o.isUsingKeyboardRef.current&&c.current?.focus(),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:Ve(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ve(e.onEscapeKeyDown,p=>{o.onClose(),p.preventDefault()}),onKeyDown:Ve(e.onKeyDown,p=>{const d=p.currentTarget.contains(p.target),f=w9[o.dir].includes(p.key);d&&f&&(i.onOpenChange(!1),l.trigger?.focus(),p.preventDefault())})})})})})});GR.displayName=zR;function VR(e){return e?"open":"closed"}function vu(e){return e==="indeterminate"}function Ig(e){return vu(e)?"indeterminate":e?"checked":"unchecked"}function z9(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function G9(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function V9(e,t,n){const a=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=G9(e,Math.max(i,0));a.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function W9(e,t){const{x:n,y:r}=e;let a=!1;for(let i=0,o=t.length-1;i<t.length;o=i++){const l=t[i],c=t[o],u=l.x,p=l.y,d=c.x,f=c.y;p>r!=f>r&&n<(d-u)*(r-p)/(f-p)+u&&(a=!a)}return a}function q9(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return W9(n,t)}function Go(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Y9=CR,K9=Ng,X9=_R,Z9=RR,Q9=Rg,J9=kR,e$=Td,t$=DR,n$=LR,r$=MR,a$=FR,s$=BR,i$=UR,o$=HR,l$=GR,Nd="DropdownMenu",[c$]=Zr(Nd,[TR]),vn=TR(),[u$,WR]=c$(Nd),qR=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:o,modal:l=!0}=e,c=vn(t),u=y.useRef(null),[p,d]=pi({prop:a,defaultProp:i??!1,onChange:o,caller:Nd});return s.jsx(u$,{scope:t,triggerId:_n(),triggerRef:u,contentId:_n(),open:p,onOpenChange:d,onOpenToggle:y.useCallback(()=>d(f=>!f),[d]),modal:l,children:s.jsx(Y9,{...c,open:p,onOpenChange:d,dir:r,modal:l,children:n})})};qR.displayName=Nd;var YR="DropdownMenuTrigger",Dg=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,i=WR(YR,n),o=vn(n);return s.jsx(K9,{asChild:!0,...o,children:s.jsx(it.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Rn(t,i.triggerRef),onPointerDown:Ve(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:Ve(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});Dg.displayName=YR;var d$="DropdownMenuPortal",KR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=vn(t);return s.jsx(X9,{...r,...n})};KR.displayName=d$;var XR="DropdownMenuContent",ZR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=WR(XR,n),i=vn(n),o=y.useRef(!1);return s.jsx(Z9,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:Ve(e.onCloseAutoFocus,l=>{o.current||a.triggerRef.current?.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:Ve(e.onInteractOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,p=c.button===2||u;(!a.modal||p)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ZR.displayName=XR;var p$="DropdownMenuGroup",f$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(Q9,{...a,...r,ref:t})});f$.displayName=p$;var m$="DropdownMenuLabel",QR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(J9,{...a,...r,ref:t})});QR.displayName=m$;var h$="DropdownMenuItem",JR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(e$,{...a,...r,ref:t})});JR.displayName=h$;var g$="DropdownMenuCheckboxItem",ek=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(t$,{...a,...r,ref:t})});ek.displayName=g$;var b$="DropdownMenuRadioGroup",x$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(n$,{...a,...r,ref:t})});x$.displayName=b$;var y$="DropdownMenuRadioItem",E$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(r$,{...a,...r,ref:t})});E$.displayName=y$;var v$="DropdownMenuItemIndicator",tk=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(a$,{...a,...r,ref:t})});tk.displayName=v$;var S$="DropdownMenuSeparator",nk=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(s$,{...a,...r,ref:t})});nk.displayName=S$;var w$="DropdownMenuArrow",T$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(i$,{...a,...r,ref:t})});T$.displayName=w$;var N$="DropdownMenuSubTrigger",C$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(o$,{...a,...r,ref:t})});C$.displayName=N$;var A$="DropdownMenuSubContent",_$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(l$,{...a,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_$.displayName=A$;var R$=qR,k$=Dg,I$=KR,D$=ZR,O$=QR,L$=JR,j$=ek,M$=tk,P$=nk;function Or({...e}){return s.jsx(R$,{"data-slot":"dropdown-menu",...e})}function ea({...e}){return s.jsx(k$,{"data-slot":"dropdown-menu-trigger",...e})}function Lr({className:e,sideOffset:t=4,...n}){return s.jsx(I$,{children:s.jsx(D$,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Fe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...n})})}function Lt({className:e,inset:t,variant:n="default",...r}){return s.jsx(L$,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:Fe("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:ps-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r})}function rk({className:e,children:t,checked:n,...r}){return s.jsxs(j$,{"data-slot":"dropdown-menu-checkbox-item",className:Fe("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:n,...r,children:[s.jsx("span",{className:"pointer-events-none absolute start-2 flex size-3.5 items-center justify-center",children:s.jsx(M$,{children:s.jsx(Yt,{className:"size-4"})})}),t]})}function ak({className:e,inset:t,...n}){return s.jsx(O$,{"data-slot":"dropdown-menu-label","data-inset":t,className:Fe("px-2 py-1.5 text-sm font-medium data-[inset]:ps-8",e),...n})}function Ci({className:e,...t}){return s.jsx(P$,{"data-slot":"dropdown-menu-separator",className:Fe("bg-border -mx-1 my-1 h-px",e),...t})}function Bn({label:e,value:t,options:n,onValueChange:r,disabled:a,className:i,minWidth:o=132}){const c=(n.find(u=>u.value===t)??n[0])?.label??"";return s.jsxs(Or,{modal:!1,children:[s.jsx(ea,{asChild:!0,disabled:a,children:s.jsxs(ie,{type:"button",variant:"outline",size:"sm",className:Fe("h-9 justify-between gap-2 px-3 font-normal",i),style:{minWidth:o},disabled:a,children:[s.jsx("span",{children:c}),s.jsx(Ku,{className:"size-4 opacity-60","aria-hidden":"true"})]})}),s.jsxs(Lr,{align:"start",className:"w-[150px]",style:{minWidth:o},children:[e&&s.jsxs(s.Fragment,{children:[s.jsx(ak,{children:e}),s.jsx(Ci,{})]}),n.map(u=>s.jsx(rk,{className:"capitalize",checked:u.value===t,onSelect:()=>r(u.value),children:s.jsx("span",{children:u.label})},u.value||"all"))]})]})}function F$({open:e,incident:t,submitting:n,onClose:r,onSubmit:a}){const[i,o]=w.useState(""),[l,c]=w.useState(""),[u,p]=w.useState("Manual"),[d,f]=w.useState("P1"),[m,h]=w.useState(""),[g,b]=w.useState("open");w.useEffect(()=>{if(e){if(t){o(t.name||""),c(t.downMessage||""),p(t.source||"Manual"),f(t.tags?.priority||t.priority||"P2"),h(t.resourceName||""),b(t.status||"open");return}o(""),c(""),p("Manual"),f("P1"),h(""),b("open")}},[e,t]);const x=S=>{if(S.preventDefault(),!i.trim()){ae.error("Title is required");return}if(!t&&!m.trim()){ae.error("Affected resource is required");return}const T=t?.tags||{};a({name:i.trim(),downMessage:l.trim()||void 0,tags:{...T,priority:d},source:u.trim()||"Manual",resourceName:m.trim()||t?.resourceName,resourceType:"service",status:g})};return s.jsx(kt,{open:e,onOpenChange:S=>!S&&!n&&r(),children:s.jsxs(It,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:t?"Edit Incident":"Create Incident"}),s.jsx(Kt,{children:t?"Update incident details":"Manual incident raised outside the alarm pipeline"})]}),s.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4 mt-2",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Title ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{value:i,onChange:S=>o(S.target.value),placeholder:"Short description of the incident",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx("textarea",{value:l,onChange:S=>c(S.target.value),placeholder:"Markdown supported",rows:4,disabled:n,className:"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50 resize-none"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Priority ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Bn,{label:"Select priority",className:"im-single-select-full w-full",value:d,onValueChange:f,disabled:n,options:[{label:"P1",value:"P1"},{label:"P2",value:"P2"},{label:"P3",value:"P3"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source"}),s.jsx(Bn,{label:"Select source",className:"im-single-select-full w-full",value:u,onValueChange:p,disabled:n,options:[{label:"Manual",value:"Manual"},{label:"CloudWatch",value:"CloudWatch"},{label:"Prometheus",value:"Prometheus"},{label:"Datadog",value:"Datadog"},{label:"Grafana",value:"Grafana"}]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Affected Resource"}),s.jsx(Xe,{value:m,onChange:S=>h(S.target.value),placeholder:"Resource name or ID",disabled:n,className:"font-mono"})]}),t&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"State"}),s.jsx(Bn,{label:"Select state",className:"im-single-select-full w-full",value:g,onValueChange:S=>b(S),disabled:n,options:[{label:"Open",value:"open"},{label:"Investigating",value:"in_progress"},{label:"Resolved",value:"resolved"},{label:"Closed",value:"closed"}]})]})]}),s.jsxs($t,{children:[s.jsx(ie,{type:"button",variant:"outline",onClick:r,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",disabled:n,children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):t?"Save Changes":"Create Incident"})]})]})]})})}function xa(e,t){return typeof e=="function"?e(t):e}function zn(e,t){return n=>{t.setState(r=>({...r,[e]:xa(n,r[e])}))}}function Cd(e){return e instanceof Function}function B$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function U$(e,t){const n=[],r=a=>{a.forEach(i=>{n.push(i);const o=t(i);o!=null&&o.length&&r(o)})};return r(e),n}function rt(e,t,n){let r=[],a;return i=>{let o;n.key&&n.debug&&(o=Date.now());const l=e(i);if(!(l.length!==r.length||l.some((p,d)=>r[d]!==p)))return a;r=l;let u;if(n.key&&n.debug&&(u=Date.now()),a=t(...l),n==null||n.onChange==null||n.onChange(a),n.key&&n.debug&&n!=null&&n.debug()){const p=Math.round((Date.now()-o)*100)/100,d=Math.round((Date.now()-u)*100)/100,f=d/16,m=(h,g)=>{for(h=String(h);h.length<g;)h=" "+h;return h};console.info(`%c⏱ ${m(d,5)} /${m(p,5)} ms`,`
58
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return y.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},l8="DialogDescriptionWarning",c8=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${r_(l8).contentName}}.`;return y.useEffect(()=>{const a=e.current?.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},rg=zA,u8=VA,ag=qA,ld=YA,cd=KA,sg=ZA,ig=JA,og=t_;const kt=rg,d8=ag,a_=y.forwardRef(({className:e,...t},n)=>s.jsx(ld,{ref:n,className:Fe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));a_.displayName=ld.displayName;const It=y.forwardRef(({className:e,children:t,...n},r)=>s.jsxs(d8,{children:[s.jsx(a_,{}),s.jsxs(cd,{ref:r,onInteractOutside:a=>a.preventDefault(),className:Fe("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[t,s.jsxs(og,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));It.displayName=cd.displayName;const jt=({className:e,...t})=>s.jsx("div",{className:Fe("flex flex-col space-y-1.5 text-start",e),...t});jt.displayName="DialogHeader";const $t=({className:e,...t})=>s.jsx("div",{className:Fe("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});$t.displayName="DialogFooter";const Mt=y.forwardRef(({className:e,...t},n)=>s.jsx(sg,{ref:n,className:Fe("text-lg font-semibold leading-none tracking-tight",e),...t}));Mt.displayName=sg.displayName;const Kt=y.forwardRef(({className:e,...t},n)=>s.jsx(ig,{ref:n,className:Fe("text-sm text-muted-foreground",e),...t}));Kt.displayName=ig.displayName;function _m(e,[t,n]){return Math.min(n,Math.max(t,e))}function p8(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var lg="ScrollArea",[s_]=Zr(lg),[f8,tr]=s_(lg),i_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...o}=e,[l,c]=y.useState(null),[u,p]=y.useState(null),[d,f]=y.useState(null),[m,h]=y.useState(null),[g,b]=y.useState(null),[x,S]=y.useState(0),[T,N]=y.useState(0),[A,C]=y.useState(!1),[k,O]=y.useState(!1),M=xt(t,j=>c(j)),R=cl(a);return s.jsx(f8,{scope:n,type:r,dir:R,scrollHideDelay:i,scrollArea:l,viewport:u,onViewportChange:p,content:d,onContentChange:f,scrollbarX:m,onScrollbarXChange:h,scrollbarXEnabled:A,onScrollbarXEnabledChange:C,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:k,onScrollbarYEnabledChange:O,onCornerWidthChange:S,onCornerHeightChange:N,children:s.jsx(it.div,{dir:R,...o,ref:M,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});i_.displayName=lg;var o_="ScrollAreaViewport",l_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=e,o=tr(o_,n),l=y.useRef(null),c=xt(t,l,o.onViewportChange);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),s.jsx(it.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...e.style},children:s.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});l_.displayName=o_;var Ir="ScrollAreaScrollbar",cg=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:o}=a,l=e.orientation==="horizontal";return y.useEffect(()=>(l?i(!0):o(!0),()=>{l?i(!1):o(!1)}),[l,i,o]),a.type==="hover"?s.jsx(m8,{...r,ref:t,forceMount:n}):a.type==="scroll"?s.jsx(h8,{...r,ref:t,forceMount:n}):a.type==="auto"?s.jsx(c_,{...r,ref:t,forceMount:n}):a.type==="always"?s.jsx(ug,{...r,ref:t}):null});cg.displayName=Ir;var m8=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),[i,o]=y.useState(!1);return y.useEffect(()=>{const l=a.scrollArea;let c=0;if(l){const u=()=>{window.clearTimeout(c),o(!0)},p=()=>{c=window.setTimeout(()=>o(!1),a.scrollHideDelay)};return l.addEventListener("pointerenter",u),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(c),l.removeEventListener("pointerenter",u),l.removeEventListener("pointerleave",p)}}},[a.scrollArea,a.scrollHideDelay]),s.jsx(er,{present:n||i,children:s.jsx(c_,{"data-state":i?"visible":"hidden",...r,ref:t})})}),h8=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=tr(Ir,e.__scopeScrollArea),i=e.orientation==="horizontal",o=dd(()=>c("SCROLL_END"),100),[l,c]=p8("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return y.useEffect(()=>{if(l==="idle"){const u=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(u)}},[l,a.scrollHideDelay,c]),y.useEffect(()=>{const u=a.viewport,p=i?"scrollLeft":"scrollTop";if(u){let d=u[p];const f=()=>{const m=u[p];d!==m&&(c("SCROLL"),o()),d=m};return u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[a.viewport,i,c,o]),s.jsx(er,{present:n||l!=="hidden",children:s.jsx(ug,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ve(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Ve(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),c_=y.forwardRef((e,t)=>{const n=tr(Ir,e.__scopeScrollArea),{forceMount:r,...a}=e,[i,o]=y.useState(!1),l=e.orientation==="horizontal",c=dd(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,p=n.viewport.offsetHeight<n.viewport.scrollHeight;o(l?u:p)}},10);return fi(n.viewport,c),fi(n.content,c),s.jsx(er,{present:r||i,children:s.jsx(ug,{"data-state":i?"visible":"hidden",...a,ref:t})})}),ug=y.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,a=tr(Ir,e.__scopeScrollArea),i=y.useRef(null),o=y.useRef(0),[l,c]=y.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=m_(l.viewport,l.content),p={...r,sizes:l,onSizesChange:c,hasThumb:u>0&&u<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>o.current=0,onThumbPointerDown:f=>o.current=f};function d(f,m){return v8(f,o.current,l,m)}return n==="horizontal"?s.jsx(g8,{...p,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollLeft,m=d1(f,l,a.dir);i.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollLeft=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollLeft=d(f,a.dir))}}):n==="vertical"?s.jsx(b8,{...p,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollTop,m=d1(f,l);i.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollTop=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollTop=d(f))}}):null}),g8=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...a}=e,i=tr(Ir,e.__scopeScrollArea),[o,l]=y.useState(),c=y.useRef(null),u=xt(t,c,i.onScrollbarXChange);return y.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),s.jsx(d_,{"data-orientation":"horizontal",...a,ref:u,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ud(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,d)=>{if(i.viewport){const f=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(f),g_(f,d)&&p.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:fu(o.paddingLeft),paddingEnd:fu(o.paddingRight)}})}})}),b8=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...a}=e,i=tr(Ir,e.__scopeScrollArea),[o,l]=y.useState(),c=y.useRef(null),u=xt(t,c,i.onScrollbarYChange);return y.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),s.jsx(d_,{"data-orientation":"vertical",...a,ref:u,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ud(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,d)=>{if(i.viewport){const f=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(f),g_(f,d)&&p.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:fu(o.paddingTop),paddingEnd:fu(o.paddingBottom)}})}})}),[x8,u_]=s_(Ir),d_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:o,onThumbPointerDown:l,onThumbPositionChange:c,onDragScroll:u,onWheelScroll:p,onResize:d,...f}=e,m=tr(Ir,n),[h,g]=y.useState(null),b=xt(t,M=>g(M)),x=y.useRef(null),S=y.useRef(""),T=m.viewport,N=r.content-r.viewport,A=nn(p),C=nn(c),k=dd(d,10);function O(M){if(x.current){const R=M.clientX-x.current.left,j=M.clientY-x.current.top;u({x:R,y:j})}}return y.useEffect(()=>{const M=R=>{const j=R.target;h?.contains(j)&&A(R,N)};return document.addEventListener("wheel",M,{passive:!1}),()=>document.removeEventListener("wheel",M,{passive:!1})},[T,h,N,A]),y.useEffect(C,[r,C]),fi(h,k),fi(m.content,k),s.jsx(x8,{scope:n,scrollbar:h,hasThumb:a,onThumbChange:nn(i),onThumbPointerUp:nn(o),onThumbPositionChange:C,onThumbPointerDown:nn(l),children:s.jsx(it.div,{...f,ref:b,style:{position:"absolute",...f.style},onPointerDown:Ve(e.onPointerDown,M=>{M.button===0&&(M.target.setPointerCapture(M.pointerId),x.current=h.getBoundingClientRect(),S.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),O(M))}),onPointerMove:Ve(e.onPointerMove,O),onPointerUp:Ve(e.onPointerUp,M=>{const R=M.target;R.hasPointerCapture(M.pointerId)&&R.releasePointerCapture(M.pointerId),document.body.style.webkitUserSelect=S.current,m.viewport&&(m.viewport.style.scrollBehavior=""),x.current=null})})})}),pu="ScrollAreaThumb",p_=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,a=u_(pu,e.__scopeScrollArea);return s.jsx(er,{present:n||a.hasThumb,children:s.jsx(y8,{ref:t,...r})})}),y8=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...a}=e,i=tr(pu,n),o=u_(pu,n),{onThumbPositionChange:l}=o,c=xt(t,d=>o.onThumbChange(d)),u=y.useRef(void 0),p=dd(()=>{u.current&&(u.current(),u.current=void 0)},100);return y.useEffect(()=>{const d=i.viewport;if(d){const f=()=>{if(p(),!u.current){const m=S8(d,l);u.current=m,l()}};return l(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[i.viewport,p,l]),s.jsx(it.div,{"data-state":o.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ve(e.onPointerDownCapture,d=>{const m=d.target.getBoundingClientRect(),h=d.clientX-m.left,g=d.clientY-m.top;o.onThumbPointerDown({x:h,y:g})}),onPointerUp:Ve(e.onPointerUp,o.onThumbPointerUp)})});p_.displayName=pu;var dg="ScrollAreaCorner",f_=y.forwardRef((e,t)=>{const n=tr(dg,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?s.jsx(E8,{...e,ref:t}):null});f_.displayName=dg;var E8=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,a=tr(dg,n),[i,o]=y.useState(0),[l,c]=y.useState(0),u=!!(i&&l);return fi(a.scrollbarX,()=>{const p=a.scrollbarX?.offsetHeight||0;a.onCornerHeightChange(p),c(p)}),fi(a.scrollbarY,()=>{const p=a.scrollbarY?.offsetWidth||0;a.onCornerWidthChange(p),o(p)}),u?s.jsx(it.div,{...r,ref:t,style:{width:i,height:l,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function fu(e){return e?parseInt(e,10):0}function m_(e,t){const n=e/t;return isNaN(n)?0:n}function ud(e){const t=m_(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function v8(e,t,n,r="ltr"){const a=ud(n),i=a/2,o=t||i,l=a-o,c=n.scrollbar.paddingStart+o,u=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,d=r==="ltr"?[0,p]:[p*-1,0];return h_([c,u],d)(e)}function d1(e,t,n="ltr"){const r=ud(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,o=t.content-t.viewport,l=i-r,c=n==="ltr"?[0,o]:[o*-1,0],u=_m(e,c);return h_([0,o],[0,l])(u)}function h_(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function g_(e,t){return e>0&&e<t}var S8=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function a(){const i={left:e.scrollLeft,top:e.scrollTop},o=n.left!==i.left,l=n.top!==i.top;(o||l)&&t(),n=i,r=window.requestAnimationFrame(a)})(),()=>window.cancelAnimationFrame(r)};function dd(e,t){const n=nn(e),r=y.useRef(0);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),y.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fi(e,t){const n=nn(t);an(()=>{let r=0;if(e){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(e),()=>{window.cancelAnimationFrame(r),a.unobserve(e)}}},[e,n])}var b_=i_,w8=l_,T8=f_;const x_=y.forwardRef(({className:e,children:t,...n},r)=>s.jsxs(b_,{ref:r,className:Fe("relative overflow-hidden",e),...n,children:[s.jsx(w8,{className:"h-full w-full rounded-[inherit]",children:t}),s.jsx(y_,{}),s.jsx(T8,{})]}));x_.displayName=b_.displayName;const y_=y.forwardRef(({className:e,orientation:t="vertical",...n},r)=>s.jsx(cg,{ref:r,orientation:t,className:Fe("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:s.jsx(p_,{className:"relative flex-1 rounded-full bg-border"})}));y_.displayName=cg.displayName;function N8({open:e,onOpenChange:t,assigneeIds:n=[],onAssign:r}){const{isAdmin:a}=ur(),{users:i,loading:o,refetch:l}=Jh(),[c,u]=w.useState(!1),[p,d]=w.useState([]);if(w.useEffect(()=>{e&&(d(n||[]),l().catch(console.error))},[e,n,l]),!a)return null;const f=h=>{d(g=>g.includes(h)?g.filter(b=>b!==h):[...g,h])},m=async()=>{try{u(!0),await r(p),t(!1)}finally{u(!1)}};return s.jsx(kt,{open:e,onOpenChange:t,children:s.jsxs(It,{className:"sm:max-w-[425px]",children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Assign Users"})}),s.jsx("div",{className:"py-4",children:o?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.jsx(x_,{className:"h-[300px] pr-4",children:s.jsxs("div",{className:"space-y-2",children:[i.map(h=>{const g=p.includes(h.id);return s.jsxs("div",{onClick:()=>f(h.id),className:Fe("flex items-center justify-between p-3 rounded-md border cursor-pointer hover:bg-accent transition-colors",g&&"border-primary/50 bg-primary/5"),children:[s.jsxs("div",{className:"flex items-center gap-3 overflow-hidden",children:[s.jsx(_C,{className:"h-5 w-5 text-muted-foreground flex-shrink-0"}),s.jsxs("div",{className:"flex flex-col overflow-hidden",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:h.full_name||h.email}),h.full_name&&s.jsx("span",{className:"text-xs text-muted-foreground truncate",children:h.email})]})]}),s.jsx("div",{className:Fe("h-5 w-5 rounded border flex items-center justify-center flex-shrink-0",g?"bg-primary border-primary text-primary-foreground":"border-input"),children:g&&s.jsx(Yt,{className:"h-3.5 w-3.5"})})]},h.id)}),i.length===0&&s.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No users found."})]})})}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(ie,{variant:"outline",onClick:()=>t(!1),disabled:c,children:"Cancel"}),s.jsxs(ie,{onClick:m,disabled:c||o,children:[c&&s.jsx(Qe,{className:"mr-2 h-4 w-4 animate-spin"}),"Save Assignment"]})]})]})})}function E_({assigneeIds:e=[],className:t}){const{users:n}=Jh();let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{r=[e]}if(Array.isArray(r)||(r=[]),!r||r.length===0)return s.jsxs("div",{className:Fe("text-muted-foreground text-sm flex items-center gap-1.5",t),children:[s.jsx(MC,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Unassigned"})]});const a=r.map(l=>n.find(c=>c.id===l)||{id:l,email:"Loading...",full_name:"Loading..."}),i=a[0],o=a.length-1;return s.jsxs("div",{className:Fe("flex items-center gap-1.5 text-sm",t),children:[s.jsx(_C,{className:"h-3.5 w-3.5 text-primary"}),s.jsx("span",{className:"font-medium truncate max-w-[150px]",title:i?.email||i?.id,children:i?.full_name||i?.email||"Assigned"}),o>0&&s.jsxs("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded-full ml-1",children:["+",o]})]})}function Je({className:e,...t}){return s.jsx("div",{className:Fe("animate-pulse rounded-md bg-primary/10",e),...t})}function p1({count:e,wide:t}){return s.jsx("div",{className:`im-dashboard-stats${t?" im-six-stats":""}`,children:Array.from({length:e}).map((n,r)=>s.jsxs("div",{className:"im-stat",children:[s.jsx(Je,{className:"h-3 w-20"}),s.jsx(Je,{className:"mt-2 h-6 w-12"})]},r))})}function f1({rows:e}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[s.jsx(Je,{className:"h-5 w-9 rounded-full"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(Je,{className:"h-3.5 w-1/2"}),s.jsx(Je,{className:"mt-1.5 h-2.5 w-3/4"})]}),s.jsx(Je,{className:"h-5 w-16 rounded-full"})]},n))})}function m1({rows:e}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"mt-2 h-2.5 w-full rounded-full"})]},n))})}function C8({rows:e=8,cols:t=6}){return s.jsxs("div",{className:"im-table-card",children:[s.jsx("div",{style:{display:"flex",gap:16,padding:"12px 16px",borderBottom:"1px solid var(--im-border)",background:"var(--im-surface-2)"},children:Array.from({length:t}).map((n,r)=>s.jsx(Je,{className:"h-3 flex-1"},r))}),Array.from({length:e}).map((n,r)=>s.jsx("div",{style:{display:"flex",gap:16,padding:"14px 16px",borderBottom:"1px solid var(--im-border)"},children:Array.from({length:t}).map((a,i)=>s.jsx(Je,{className:"h-4 flex-1"},i))},r))]})}function A8({count:e=8}){return s.jsx("div",{className:"grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:Array.from({length:e}).map((t,n)=>s.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:14},children:[s.jsx(Je,{className:"h-9 w-9 rounded-lg"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(Je,{className:"h-3.5 w-3/4"}),s.jsx(Je,{className:"mt-1.5 h-2.5 w-1/2"})]})]}),s.jsx(Je,{className:"h-2.5 w-full"}),s.jsx(Je,{className:"mt-2 h-2.5 w-5/6"}),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:14},children:[s.jsx(Je,{className:"h-5 w-14 rounded-full"}),s.jsx(Je,{className:"h-5 w-16 rounded-full"})]})]},n))})}function h1({titleW:e=32,rows:t=5}){return s.jsxs("div",{className:"im-inc-card",children:[s.jsx(Je,{className:"mb-4 h-4",style:{width:e*4}}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:t}).map((n,r)=>s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"h-3 w-24"})]},r))})]})}function _8(){return s.jsxs("div",{className:"im-inc-detail -m-4",children:[s.jsxs("div",{className:"im-inc-header",children:[s.jsxs("div",{className:"im-inc-header-row1",children:[s.jsx(Je,{className:"h-7 w-7 rounded-md"}),s.jsx(Je,{className:"h-3.5 w-14"}),s.jsx(Je,{className:"h-5 w-48"}),s.jsx(Je,{className:"h-5 w-10 rounded-full"}),s.jsx(Je,{className:"h-5 w-20 rounded-full"})]}),s.jsxs("div",{className:"im-inc-header-row2",style:{marginTop:8},children:[s.jsx(Je,{className:"h-3 w-28"}),s.jsx(Je,{className:"h-3 w-24"}),s.jsx(Je,{className:"h-3 w-16"})]}),s.jsxs("div",{className:"im-inc-actions",children:[s.jsx(Je,{className:"h-8 w-28"}),s.jsx(Je,{className:"h-8 w-24"}),s.jsx(Je,{className:"h-8 w-24"})]})]}),s.jsxs("div",{className:"im-inc-body",children:[s.jsxs("div",{className:"im-inc-main",children:[s.jsx("div",{className:"im-inc-tabs",style:{gap:20},children:Array.from({length:6}).map((e,t)=>s.jsx(Je,{className:"my-2.5 h-4 w-20"},t))}),s.jsx("div",{className:"im-inc-tab-content",children:s.jsxs("div",{className:"im-inc-overview",children:[s.jsx(h1,{titleW:36,rows:6}),s.jsx(h1,{titleW:24,rows:5})]})})]}),s.jsx("aside",{className:"im-inc-sidebar",children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx(Je,{className:"mb-2 h-2.5 w-20"}),s.jsx(Je,{className:"h-4 w-32"})]},t))})]})]})}function R8(){return s.jsxs("div",{className:"flex flex-col h-full overflow-hidden p-4",children:[s.jsxs("div",{className:"shrink-0 mb-6 flex flex-col md:flex-row md:items-start justify-between gap-4",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx(Je,{className:"h-9 w-9 rounded-md"}),s.jsxs("div",{children:[s.jsx(Je,{className:"h-6 w-64"}),s.jsxs("div",{className:"flex items-center gap-4 mt-3",children:[s.jsx(Je,{className:"h-3 w-24"}),s.jsx(Je,{className:"h-3 w-20"}),s.jsx(Je,{className:"h-3 w-28"})]})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[s.jsx(Je,{className:"h-5 w-16 rounded-full"}),s.jsx(Je,{className:"h-5 w-20 rounded-full"})]})]}),s.jsxs("div",{className:"rounded-xl border bg-card p-4 mb-4",children:[s.jsx(Je,{className:"mb-3 h-4 w-32"}),s.jsx(Je,{className:"h-3 w-full"}),s.jsx(Je,{className:"mt-2 h-3 w-11/12"}),s.jsx(Je,{className:"mt-2 h-3 w-4/5"})]}),s.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[s.jsx(Je,{className:"mb-4 h-4 w-28"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{style:{display:"flex",gap:10},children:[s.jsx(Je,{className:"h-5 w-5 rounded-full"}),s.jsx(Je,{className:"h-3 flex-1"})]},t))})]})]})}function qr({variant:e}){return e==="dashboard"?s.jsxs(s.Fragment,{children:[s.jsx(p1,{count:5}),s.jsxs("div",{className:"im-dashboard-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(f1,{rows:4})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-28"}),s.jsx(f1,{rows:5})]})]})]}):e==="analytics"?s.jsxs(s.Fragment,{children:[s.jsx(p1,{count:6,wide:!0}),s.jsxs("div",{className:"im-analytics-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(Je,{className:"h-40 w-full"})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-32"}),s.jsx(m1,{rows:4})]})]}),s.jsxs("section",{className:"im-panel im-resource-panel",children:[s.jsx(Je,{className:"mb-4 h-4 w-40"}),s.jsx(m1,{rows:5})]})]}):e==="cards"?s.jsx(A8,{}):e==="incident-detail"?s.jsx(_8,{}):e==="sop-detail"?s.jsx(R8,{}):s.jsx(C8,{})}const Rm=new Set(["triggered","processing","queued","fetching_ec2","fetching_metrics","fetching_logs","compressing_logs","building_prompt","finding_rca","storing_results","triage_started","infra_analysis","logs_analysis","ai_reasoning","remediation_generated"]);function rf(e){return e?Rm.has(e):!1}function k8(e,t,n="pending"){const[r,a]=w.useState(n),[i,o]=w.useState(0),l=w.useRef(null),c=r==="completed",u=r==="failed",p=w.useCallback(()=>{a("triggered"),o(0)},[]),d=w.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),a("failed"),o(0)},[]);return w.useEffect(()=>{Rm.has(r)||a(n)},[n]),w.useEffect(()=>{if(!(e&&(t||Rm.has(r)))){l.current&&(clearInterval(l.current),l.current=null);return}const m=async()=>{try{const h=await Ie.getIncidentStatus(e),g=h.analysisStatus??"pending";a(g),o(h.progressPercent??0),(h.isComplete||h.isFailed)&&l.current&&(clearInterval(l.current),l.current=null)}catch{}};return m(),l.current=setInterval(m,5e3),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[e,t,r]),{status:r,progressPercent:i,isComplete:c,isFailed:u,optimisticTrigger:p,markFailed:d}}function I8(e,t=globalThis?.document){const n=nn(e);y.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var D8="DismissableLayer",km="dismissableLayer.update",O8="dismissableLayer.pointerDownOutside",L8="dismissableLayer.focusOutside",g1,v_=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),pd=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:o,onDismiss:l,...c}=e,u=y.useContext(v_),[p,d]=y.useState(null),f=p?.ownerDocument??globalThis?.document,[,m]=y.useState({}),h=xt(t,k=>d(k)),g=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(b),S=p?g.indexOf(p):-1,T=u.layersWithOutsidePointerEventsDisabled.size>0,N=S>=x,A=P8(k=>{const O=k.target,M=[...u.branches].some(R=>R.contains(O));!N||M||(a?.(k),o?.(k),k.defaultPrevented||l?.())},f),C=F8(k=>{const O=k.target;[...u.branches].some(R=>R.contains(O))||(i?.(k),o?.(k),k.defaultPrevented||l?.())},f);return I8(k=>{S===u.layers.size-1&&(r?.(k),!k.defaultPrevented&&l&&(k.preventDefault(),l()))},f),y.useEffect(()=>{if(p)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(g1=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),b1(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=g1)}},[p,f,n,u]),y.useEffect(()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),b1())},[p,u]),y.useEffect(()=>{const k=()=>m({});return document.addEventListener(km,k),()=>document.removeEventListener(km,k)},[]),s.jsx(it.div,{...c,ref:h,style:{pointerEvents:T?N?"auto":"none":void 0,...e.style},onFocusCapture:Ve(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Ve(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Ve(e.onPointerDownCapture,A.onPointerDownCapture)})});pd.displayName=D8;var j8="DismissableLayerBranch",M8=y.forwardRef((e,t)=>{const n=y.useContext(v_),r=y.useRef(null),a=xt(t,r);return y.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(it.div,{...e,ref:a})});M8.displayName=j8;function P8(e,t=globalThis?.document){const n=nn(e),r=y.useRef(!1),a=y.useRef(()=>{});return y.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let c=function(){S_(O8,n,u,{discrete:!0})};const u={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},o=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function F8(e,t=globalThis?.document){const n=nn(e),r=y.useRef(!1);return y.useEffect(()=>{const a=i=>{i.target&&!r.current&&S_(L8,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function b1(){const e=new CustomEvent(km);document.dispatchEvent(e)}function S_(e,t,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(e,t,{once:!0}),r?aA(a,i):a.dispatchEvent(i)}var af=0;function pg(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??x1()),document.body.insertAdjacentElement("beforeend",e[1]??x1()),af++,()=>{af===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),af--}},[])}function x1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sf="focusScope.autoFocusOnMount",of="focusScope.autoFocusOnUnmount",y1={bubbles:!1,cancelable:!0},B8="FocusScope",fd=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...o}=e,[l,c]=y.useState(null),u=nn(a),p=nn(i),d=y.useRef(null),f=xt(t,g=>c(g)),m=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let g=function(T){if(m.paused||!l)return;const N=T.target;l.contains(N)?d.current=N:ca(d.current,{select:!0})},b=function(T){if(m.paused||!l)return;const N=T.relatedTarget;N!==null&&(l.contains(N)||ca(d.current,{select:!0}))},x=function(T){if(document.activeElement===document.body)for(const A of T)A.removedNodes.length>0&&ca(l)};document.addEventListener("focusin",g),document.addEventListener("focusout",b);const S=new MutationObserver(x);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",b),S.disconnect()}}},[r,l,m.paused]),y.useEffect(()=>{if(l){v1.add(m);const g=document.activeElement;if(!l.contains(g)){const x=new CustomEvent(sf,y1);l.addEventListener(sf,u),l.dispatchEvent(x),x.defaultPrevented||(U8(V8(w_(l)),{select:!0}),document.activeElement===g&&ca(l))}return()=>{l.removeEventListener(sf,u),setTimeout(()=>{const x=new CustomEvent(of,y1);l.addEventListener(of,p),l.dispatchEvent(x),x.defaultPrevented||ca(g??document.body,{select:!0}),l.removeEventListener(of,p),v1.remove(m)},0)}}},[l,u,p,m]);const h=y.useCallback(g=>{if(!n&&!r||m.paused)return;const b=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(b&&x){const S=g.currentTarget,[T,N]=$8(S);T&&N?!g.shiftKey&&x===N?(g.preventDefault(),n&&ca(T,{select:!0})):g.shiftKey&&x===T&&(g.preventDefault(),n&&ca(N,{select:!0})):x===S&&g.preventDefault()}},[n,r,m.paused]);return s.jsx(it.div,{tabIndex:-1,...o,ref:f,onKeyDown:h})});fd.displayName=B8;function U8(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ca(r,{select:t}),document.activeElement!==n)return}function $8(e){const t=w_(e),n=E1(t,e),r=E1(t.reverse(),e);return[n,r]}function w_(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function E1(e,t){for(const n of e)if(!H8(n,{upTo:t}))return n}function H8(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function z8(e){return e instanceof HTMLInputElement&&"select"in e}function ca(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&z8(e)&&t&&e.select()}}var v1=G8();function G8(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=S1(e,t),e.unshift(t)},remove(t){e=S1(e,t),e[0]?.resume()}}}function S1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function V8(e){return e.filter(t=>t.tagName!=="A")}const W8=["top","right","bottom","left"],Na=Math.min,Mn=Math.max,mu=Math.round,ic=Math.floor,Ar=e=>({x:e,y:e}),q8={left:"right",right:"left",bottom:"top",top:"bottom"};function Im(e,t,n){return Mn(e,Na(t,n))}function Yr(e,t){return typeof e=="function"?e(t):e}function Kr(e){return e.split("-")[0]}function Si(e){return e.split("-")[1]}function fg(e){return e==="x"?"y":"x"}function mg(e){return e==="y"?"height":"width"}function Cr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function hg(e){return fg(Cr(e))}function Y8(e,t,n){n===void 0&&(n=!1);const r=Si(e),a=hg(e),i=mg(a);let o=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(o=hu(o)),[o,hu(o)]}function K8(e){const t=hu(e);return[Dm(e),t,Dm(t)]}function Dm(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const w1=["left","right"],T1=["right","left"],X8=["top","bottom"],Z8=["bottom","top"];function Q8(e,t,n){switch(e){case"top":case"bottom":return n?t?T1:w1:t?w1:T1;case"left":case"right":return t?X8:Z8;default:return[]}}function J8(e,t,n,r){const a=Si(e);let i=Q8(Kr(e),n==="start",r);return a&&(i=i.map(o=>o+"-"+a),t&&(i=i.concat(i.map(Dm)))),i}function hu(e){const t=Kr(e);return q8[t]+e.slice(t.length)}function eU(e){return{top:0,right:0,bottom:0,left:0,...e}}function T_(e){return typeof e!="number"?eU(e):{top:e,right:e,bottom:e,left:e}}function gu(e){const{x:t,y:n,width:r,height:a}=e;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}function N1(e,t,n){let{reference:r,floating:a}=e;const i=Cr(t),o=hg(t),l=mg(o),c=Kr(t),u=i==="y",p=r.x+r.width/2-a.width/2,d=r.y+r.height/2-a.height/2,f=r[l]/2-a[l]/2;let m;switch(c){case"top":m={x:p,y:r.y-a.height};break;case"bottom":m={x:p,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:d};break;case"left":m={x:r.x-a.width,y:d};break;default:m={x:r.x,y:r.y}}switch(Si(t)){case"start":m[o]-=f*(n&&u?-1:1);break;case"end":m[o]+=f*(n&&u?-1:1);break}return m}async function tU(e,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:l,strategy:c}=e,{boundary:u="clippingAncestors",rootBoundary:p="viewport",elementContext:d="floating",altBoundary:f=!1,padding:m=0}=Yr(t,e),h=T_(m),b=l[f?d==="floating"?"reference":"floating":d],x=gu(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:u,rootBoundary:p,strategy:c})),S=d==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),N=await(i.isElement==null?void 0:i.isElement(T))?await(i.getScale==null?void 0:i.getScale(T))||{x:1,y:1}:{x:1,y:1},A=gu(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:S,offsetParent:T,strategy:c}):S);return{top:(x.top-A.top+h.top)/N.y,bottom:(A.bottom-x.bottom+h.bottom)/N.y,left:(x.left-A.left+h.left)/N.x,right:(A.right-x.right+h.right)/N.x}}const nU=50,rU=async(e,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:tU},c=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:p,y:d}=N1(u,r,c),f=r,m=0;const h={};for(let g=0;g<i.length;g++){const b=i[g];if(!b)continue;const{name:x,fn:S}=b,{x:T,y:N,data:A,reset:C}=await S({x:p,y:d,initialPlacement:r,placement:f,strategy:a,middlewareData:h,rects:u,platform:l,elements:{reference:e,floating:t}});p=T??p,d=N??d,h[x]={...h[x],...A},C&&m<nU&&(m++,typeof C=="object"&&(C.placement&&(f=C.placement),C.rects&&(u=C.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):C.rects),{x:p,y:d}=N1(u,f,c)),g=-1)}return{x:p,y:d,placement:f,strategy:a,middlewareData:h}},aU=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:a,rects:i,platform:o,elements:l,middlewareData:c}=t,{element:u,padding:p=0}=Yr(e,t)||{};if(u==null)return{};const d=T_(p),f={x:n,y:r},m=hg(a),h=mg(m),g=await o.getDimensions(u),b=m==="y",x=b?"top":"left",S=b?"bottom":"right",T=b?"clientHeight":"clientWidth",N=i.reference[h]+i.reference[m]-f[m]-i.floating[h],A=f[m]-i.reference[m],C=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let k=C?C[T]:0;(!k||!await(o.isElement==null?void 0:o.isElement(C)))&&(k=l.floating[T]||i.floating[h]);const O=N/2-A/2,M=k/2-g[h]/2-1,R=Na(d[x],M),j=Na(d[S],M),U=R,G=k-g[h]-j,q=k/2-g[h]/2+O,P=Im(U,q,G),z=!c.arrow&&Si(a)!=null&&q!==P&&i.reference[h]/2-(q<U?R:j)-g[h]/2<0,re=z?q<U?q-U:q-G:0;return{[m]:f[m]+re,data:{[m]:P,centerOffset:q-P-re,...z&&{alignmentOffset:re}},reset:z}}}),sU=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:l,platform:c,elements:u}=t,{mainAxis:p=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:g=!0,...b}=Yr(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const x=Kr(a),S=Cr(l),T=Kr(l)===l,N=await(c.isRTL==null?void 0:c.isRTL(u.floating)),A=f||(T||!g?[hu(l)]:K8(l)),C=h!=="none";!f&&C&&A.push(...J8(l,g,h,N));const k=[l,...A],O=await c.detectOverflow(t,b),M=[];let R=((r=i.flip)==null?void 0:r.overflows)||[];if(p&&M.push(O[x]),d){const q=Y8(a,o,N);M.push(O[q[0]],O[q[1]])}if(R=[...R,{placement:a,overflows:M}],!M.every(q=>q<=0)){var j,U;const q=(((j=i.flip)==null?void 0:j.index)||0)+1,P=k[q];if(P&&(!(d==="alignment"?S!==Cr(P):!1)||R.every(B=>Cr(B.placement)===S?B.overflows[0]>0:!0)))return{data:{index:q,overflows:R},reset:{placement:P}};let z=(U=R.filter(re=>re.overflows[0]<=0).sort((re,B)=>re.overflows[1]-B.overflows[1])[0])==null?void 0:U.placement;if(!z)switch(m){case"bestFit":{var G;const re=(G=R.filter(B=>{if(C){const H=Cr(B.placement);return H===S||H==="y"}return!0}).map(B=>[B.placement,B.overflows.filter(H=>H>0).reduce((H,I)=>H+I,0)]).sort((B,H)=>B[1]-H[1])[0])==null?void 0:G[0];re&&(z=re);break}case"initialPlacement":z=l;break}if(a!==z)return{reset:{placement:z}}}return{}}}};function C1(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function A1(e){return W8.some(t=>e[t]>=0)}const iU=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=Yr(e,t);switch(a){case"referenceHidden":{const o=await r.detectOverflow(t,{...i,elementContext:"reference"}),l=C1(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:A1(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...i,altBoundary:!0}),l=C1(o,n.floating);return{data:{escapedOffsets:l,escaped:A1(l)}}}default:return{}}}}},N_=new Set(["left","top"]);async function oU(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=Kr(n),l=Si(n),c=Cr(n)==="y",u=N_.has(o)?-1:1,p=i&&c?-1:1,d=Yr(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:h}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return l&&typeof h=="number"&&(m=l==="end"?h*-1:h),c?{x:m*p,y:f*u}:{x:f*u,y:m*p}}const lU=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:a,y:i,placement:o,middlewareData:l}=t,c=await oU(t,e);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:o}}}}},cU=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:a,platform:i}=t,{mainAxis:o=!0,crossAxis:l=!1,limiter:c={fn:x=>{let{x:S,y:T}=x;return{x:S,y:T}}},...u}=Yr(e,t),p={x:n,y:r},d=await i.detectOverflow(t,u),f=Cr(Kr(a)),m=fg(f);let h=p[m],g=p[f];if(o){const x=m==="y"?"top":"left",S=m==="y"?"bottom":"right",T=h+d[x],N=h-d[S];h=Im(T,h,N)}if(l){const x=f==="y"?"top":"left",S=f==="y"?"bottom":"right",T=g+d[x],N=g-d[S];g=Im(T,g,N)}const b=c.fn({...t,[m]:h,[f]:g});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[m]:o,[f]:l}}}}}},uU=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:a,rects:i,middlewareData:o}=t,{offset:l=0,mainAxis:c=!0,crossAxis:u=!0}=Yr(e,t),p={x:n,y:r},d=Cr(a),f=fg(d);let m=p[f],h=p[d];const g=Yr(l,t),b=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const T=f==="y"?"height":"width",N=i.reference[f]-i.floating[T]+b.mainAxis,A=i.reference[f]+i.reference[T]-b.mainAxis;m<N?m=N:m>A&&(m=A)}if(u){var x,S;const T=f==="y"?"width":"height",N=N_.has(Kr(a)),A=i.reference[d]-i.floating[T]+(N&&((x=o.offset)==null?void 0:x[d])||0)+(N?0:b.crossAxis),C=i.reference[d]+i.reference[T]+(N?0:((S=o.offset)==null?void 0:S[d])||0)-(N?b.crossAxis:0);h<A?h=A:h>C&&(h=C)}return{[f]:m,[d]:h}}}},dU=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:a,rects:i,platform:o,elements:l}=t,{apply:c=()=>{},...u}=Yr(e,t),p=await o.detectOverflow(t,u),d=Kr(a),f=Si(a),m=Cr(a)==="y",{width:h,height:g}=i.floating;let b,x;d==="top"||d==="bottom"?(b=d,x=f===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(x=d,b=f==="end"?"top":"bottom");const S=g-p.top-p.bottom,T=h-p.left-p.right,N=Na(g-p[b],S),A=Na(h-p[x],T),C=!t.middlewareData.shift;let k=N,O=A;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(k=S),C&&!f){const R=Mn(p.left,0),j=Mn(p.right,0),U=Mn(p.top,0),G=Mn(p.bottom,0);m?O=h-2*(R!==0||j!==0?R+j:Mn(p.left,p.right)):k=g-2*(U!==0||G!==0?U+G:Mn(p.top,p.bottom))}await c({...t,availableWidth:O,availableHeight:k});const M=await o.getDimensions(l.floating);return h!==M.width||g!==M.height?{reset:{rects:!0}}:{}}}};function md(){return typeof window<"u"}function wi(e){return C_(e)?(e.nodeName||"").toLowerCase():"#document"}function Fn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dr(e){var t;return(t=(C_(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function C_(e){return md()?e instanceof Node||e instanceof Fn(e).Node:!1}function or(e){return md()?e instanceof Element||e instanceof Fn(e).Element:!1}function Jr(e){return md()?e instanceof HTMLElement||e instanceof Fn(e).HTMLElement:!1}function _1(e){return!md()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Fn(e).ShadowRoot}function pl(e){const{overflow:t,overflowX:n,overflowY:r,display:a}=lr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function pU(e){return/^(table|td|th)$/.test(wi(e))}function hd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const fU=/transform|translate|scale|rotate|perspective|filter/,mU=/paint|layout|strict|content/,$a=e=>!!e&&e!=="none";let lf;function gg(e){const t=or(e)?lr(e):e;return $a(t.transform)||$a(t.translate)||$a(t.scale)||$a(t.rotate)||$a(t.perspective)||!bg()&&($a(t.backdropFilter)||$a(t.filter))||fU.test(t.willChange||"")||mU.test(t.contain||"")}function hU(e){let t=Ca(e);for(;Jr(t)&&!mi(t);){if(gg(t))return t;if(hd(t))return null;t=Ca(t)}return null}function bg(){return lf==null&&(lf=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),lf}function mi(e){return/^(html|body|#document)$/.test(wi(e))}function lr(e){return Fn(e).getComputedStyle(e)}function gd(e){return or(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ca(e){if(wi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_1(e)&&e.host||Dr(e);return _1(t)?t.host:t}function A_(e){const t=Ca(e);return mi(t)?e.ownerDocument?e.ownerDocument.body:e.body:Jr(t)&&pl(t)?t:A_(t)}function Po(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=A_(e),i=a===((r=e.ownerDocument)==null?void 0:r.body),o=Fn(a);if(i){const l=Om(o);return t.concat(o,o.visualViewport||[],pl(a)?a:[],l&&n?Po(l):[])}else return t.concat(a,Po(a,[],n))}function Om(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function __(e){const t=lr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Jr(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,l=mu(n)!==i||mu(r)!==o;return l&&(n=i,r=o),{width:n,height:r,$:l}}function xg(e){return or(e)?e:e.contextElement}function ni(e){const t=xg(e);if(!Jr(t))return Ar(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=__(t);let o=(i?mu(n.width):n.width)/r,l=(i?mu(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const gU=Ar(0);function R_(e){const t=Fn(e);return!bg()||!t.visualViewport?gU:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function bU(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Fn(e)?!1:t}function os(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=xg(e);let o=Ar(1);t&&(r?or(r)&&(o=ni(r)):o=ni(e));const l=bU(i,n,r)?R_(i):Ar(0);let c=(a.left+l.x)/o.x,u=(a.top+l.y)/o.y,p=a.width/o.x,d=a.height/o.y;if(i){const f=Fn(i),m=r&&or(r)?Fn(r):r;let h=f,g=Om(h);for(;g&&r&&m!==h;){const b=ni(g),x=g.getBoundingClientRect(),S=lr(g),T=x.left+(g.clientLeft+parseFloat(S.paddingLeft))*b.x,N=x.top+(g.clientTop+parseFloat(S.paddingTop))*b.y;c*=b.x,u*=b.y,p*=b.x,d*=b.y,c+=T,u+=N,h=Fn(g),g=Om(h)}}return gu({width:p,height:d,x:c,y:u})}function bd(e,t){const n=gd(e).scrollLeft;return t?t.left+n:os(Dr(e)).left+n}function k_(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-bd(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function xU(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=Dr(r),l=t?hd(t.floating):!1;if(r===o||l&&i)return n;let c={scrollLeft:0,scrollTop:0},u=Ar(1);const p=Ar(0),d=Jr(r);if((d||!d&&!i)&&((wi(r)!=="body"||pl(o))&&(c=gd(r)),d)){const m=os(r);u=ni(r),p.x=m.x+r.clientLeft,p.y=m.y+r.clientTop}const f=o&&!d&&!i?k_(o,c):Ar(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-c.scrollLeft*u.x+p.x+f.x,y:n.y*u.y-c.scrollTop*u.y+p.y+f.y}}function yU(e){return Array.from(e.getClientRects())}function EU(e){const t=Dr(e),n=gd(e),r=e.ownerDocument.body,a=Mn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Mn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+bd(e);const l=-n.scrollTop;return lr(r).direction==="rtl"&&(o+=Mn(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:l}}const R1=25;function vU(e,t){const n=Fn(e),r=Dr(e),a=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const p=bg();(!p||p&&t==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const u=bd(r);if(u<=0){const p=r.ownerDocument,d=p.body,f=getComputedStyle(d),m=p.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,h=Math.abs(r.clientWidth-d.clientWidth-m);h<=R1&&(i-=h)}else u<=R1&&(i+=u);return{width:i,height:o,x:l,y:c}}function SU(e,t){const n=os(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=Jr(e)?ni(e):Ar(1),o=e.clientWidth*i.x,l=e.clientHeight*i.y,c=a*i.x,u=r*i.y;return{width:o,height:l,x:c,y:u}}function k1(e,t,n){let r;if(t==="viewport")r=vU(e,n);else if(t==="document")r=EU(Dr(e));else if(or(t))r=SU(t,n);else{const a=R_(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return gu(r)}function I_(e,t){const n=Ca(e);return n===t||!or(n)||mi(n)?!1:lr(n).position==="fixed"||I_(n,t)}function wU(e,t){const n=t.get(e);if(n)return n;let r=Po(e,[],!1).filter(l=>or(l)&&wi(l)!=="body"),a=null;const i=lr(e).position==="fixed";let o=i?Ca(e):e;for(;or(o)&&!mi(o);){const l=lr(o),c=gg(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&(a.position==="absolute"||a.position==="fixed")||pl(o)&&!c&&I_(e,o))?r=r.filter(p=>p!==o):a=l,o=Ca(o)}return t.set(e,r),r}function TU(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?hd(t)?[]:wU(t,this._c):[].concat(n),r],l=k1(t,o[0],a);let c=l.top,u=l.right,p=l.bottom,d=l.left;for(let f=1;f<o.length;f++){const m=k1(t,o[f],a);c=Mn(m.top,c),u=Na(m.right,u),p=Na(m.bottom,p),d=Mn(m.left,d)}return{width:u-d,height:p-c,x:d,y:c}}function NU(e){const{width:t,height:n}=__(e);return{width:t,height:n}}function CU(e,t,n){const r=Jr(t),a=Dr(t),i=n==="fixed",o=os(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=Ar(0);function u(){c.x=bd(a)}if(r||!r&&!i)if((wi(t)!=="body"||pl(a))&&(l=gd(t)),r){const m=os(t,!0,i,t);c.x=m.x+t.clientLeft,c.y=m.y+t.clientTop}else a&&u();i&&!r&&a&&u();const p=a&&!r&&!i?k_(a,l):Ar(0),d=o.left+l.scrollLeft-c.x-p.x,f=o.top+l.scrollTop-c.y-p.y;return{x:d,y:f,width:o.width,height:o.height}}function cf(e){return lr(e).position==="static"}function I1(e,t){if(!Jr(e)||lr(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dr(e)===n&&(n=n.ownerDocument.body),n}function D_(e,t){const n=Fn(e);if(hd(e))return n;if(!Jr(e)){let a=Ca(e);for(;a&&!mi(a);){if(or(a)&&!cf(a))return a;a=Ca(a)}return n}let r=I1(e,t);for(;r&&pU(r)&&cf(r);)r=I1(r,t);return r&&mi(r)&&cf(r)&&!gg(r)?n:r||hU(e)||n}const AU=async function(e){const t=this.getOffsetParent||D_,n=this.getDimensions,r=await n(e.floating);return{reference:CU(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function _U(e){return lr(e).direction==="rtl"}const RU={convertOffsetParentRelativeRectToViewportRelativeRect:xU,getDocumentElement:Dr,getClippingRect:TU,getOffsetParent:D_,getElementRects:AU,getClientRects:yU,getDimensions:NU,getScale:ni,isElement:or,isRTL:_U};function O_(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function kU(e,t){let n=null,r;const a=Dr(e);function i(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function o(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const u=e.getBoundingClientRect(),{left:p,top:d,width:f,height:m}=u;if(l||t(),!f||!m)return;const h=ic(d),g=ic(a.clientWidth-(p+f)),b=ic(a.clientHeight-(d+m)),x=ic(p),T={rootMargin:-h+"px "+-g+"px "+-b+"px "+-x+"px",threshold:Mn(0,Na(1,c))||1};let N=!0;function A(C){const k=C[0].intersectionRatio;if(k!==c){if(!N)return o();k?o(!1,k):r=setTimeout(()=>{o(!1,1e-7)},1e3)}k===1&&!O_(u,e.getBoundingClientRect())&&o(),N=!1}try{n=new IntersectionObserver(A,{...T,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,T)}n.observe(e)}return o(!0),i}function IU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,u=xg(e),p=a||i?[...u?Po(u):[],...t?Po(t):[]]:[];p.forEach(x=>{a&&x.addEventListener("scroll",n,{passive:!0}),i&&x.addEventListener("resize",n)});const d=u&&l?kU(u,n):null;let f=-1,m=null;o&&(m=new ResizeObserver(x=>{let[S]=x;S&&S.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var T;(T=m)==null||T.observe(t)})),n()}),u&&!c&&m.observe(u),t&&m.observe(t));let h,g=c?os(e):null;c&&b();function b(){const x=os(e);g&&!O_(g,x)&&n(),g=x,h=requestAnimationFrame(b)}return n(),()=>{var x;p.forEach(S=>{a&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),d?.(),(x=m)==null||x.disconnect(),m=null,c&&cancelAnimationFrame(h)}}const DU=lU,OU=cU,LU=sU,jU=dU,MU=iU,D1=aU,PU=uU,FU=(e,t,n)=>{const r=new Map,a={platform:RU,...n},i={...a.platform,_c:r};return rU(e,t,{...a,platform:i})};var BU=typeof document<"u",UU=function(){},zc=BU?w.useLayoutEffect:UU;function bu(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,a;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!bu(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!bu(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function L_(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function O1(e,t){const n=L_(e);return Math.round(t*n)/n}function uf(e){const t=y.useRef(e);return zc(()=>{t.current=e}),t}function $U(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:u}=e,[p,d]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=y.useState(r);bu(f,r)||m(r);const[h,g]=y.useState(null),[b,x]=y.useState(null),S=y.useCallback(B=>{B!==C.current&&(C.current=B,g(B))},[]),T=y.useCallback(B=>{B!==k.current&&(k.current=B,x(B))},[]),N=i||h,A=o||b,C=y.useRef(null),k=y.useRef(null),O=y.useRef(p),M=c!=null,R=uf(c),j=uf(a),U=uf(u),G=y.useCallback(()=>{if(!C.current||!k.current)return;const B={placement:t,strategy:n,middleware:f};j.current&&(B.platform=j.current),FU(C.current,k.current,B).then(H=>{const I={...H,isPositioned:U.current!==!1};q.current&&!bu(O.current,I)&&(O.current=I,yi.flushSync(()=>{d(I)}))})},[f,t,n,j,U]);zc(()=>{u===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,d(B=>({...B,isPositioned:!1})))},[u]);const q=y.useRef(!1);zc(()=>(q.current=!0,()=>{q.current=!1}),[]),zc(()=>{if(N&&(C.current=N),A&&(k.current=A),N&&A){if(R.current)return R.current(N,A,G);G()}},[N,A,G,R,M]);const P=y.useMemo(()=>({reference:C,floating:k,setReference:S,setFloating:T}),[S,T]),z=y.useMemo(()=>({reference:N,floating:A}),[N,A]),re=y.useMemo(()=>{const B={position:n,left:0,top:0};if(!z.floating)return B;const H=O1(z.floating,p.x),I=O1(z.floating,p.y);return l?{...B,transform:"translate("+H+"px, "+I+"px)",...L_(z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:I}},[n,l,z.floating,p.x,p.y]);return y.useMemo(()=>({...p,update:G,refs:P,elements:z,floatingStyles:re}),[p,G,P,z,re])}const HU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:a}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?D1({element:r.current,padding:a}).fn(n):{}:r?D1({element:r,padding:a}).fn(n):{}}}},zU=(e,t)=>{const n=DU(e);return{name:n.name,fn:n.fn,options:[e,t]}},GU=(e,t)=>{const n=OU(e);return{name:n.name,fn:n.fn,options:[e,t]}},VU=(e,t)=>({fn:PU(e).fn,options:[e,t]}),WU=(e,t)=>{const n=LU(e);return{name:n.name,fn:n.fn,options:[e,t]}},qU=(e,t)=>{const n=jU(e);return{name:n.name,fn:n.fn,options:[e,t]}},YU=(e,t)=>{const n=MU(e);return{name:n.name,fn:n.fn,options:[e,t]}},KU=(e,t)=>{const n=HU(e);return{name:n.name,fn:n.fn,options:[e,t]}};var XU="Arrow",j_=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:a=5,...i}=e;return s.jsx(it.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});j_.displayName=XU;var ZU=j_;function QU(e){const[t,n]=y.useState(void 0);return an(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;o=u.inlineSize,l=u.blockSize}else o=e.offsetWidth,l=e.offsetHeight;n({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var yg="Popper",[M_,Ti]=Zr(yg),[JU,P_]=M_(yg),F_=e=>{const{__scopePopper:t,children:n}=e,[r,a]=y.useState(null);return s.jsx(JU,{scope:t,anchor:r,onAnchorChange:a,children:n})};F_.displayName=yg;var B_="PopperAnchor",U_=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...a}=e,i=P_(B_,n),o=y.useRef(null),l=xt(t,o),c=y.useRef(null);return y.useEffect(()=>{const u=c.current;c.current=r?.current||o.current,u!==c.current&&i.onAnchorChange(c.current)}),r?null:s.jsx(it.div,{...a,ref:l})});U_.displayName=B_;var Eg="PopperContent",[e7,t7]=M_(Eg),$_=y.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:o=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:h,...g}=e,b=P_(Eg,n),[x,S]=y.useState(null),T=xt(t,K=>S(K)),[N,A]=y.useState(null),C=QU(N),k=C?.width??0,O=C?.height??0,M=r+(i!=="center"?"-"+i:""),R=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},j=Array.isArray(u)?u:[u],U=j.length>0,G={padding:R,boundary:j.filter(r7),altBoundary:U},{refs:q,floatingStyles:P,placement:z,isPositioned:re,middlewareData:B}=$U({strategy:"fixed",placement:M,whileElementsMounted:(...K)=>IU(...K,{animationFrame:m==="always"}),elements:{reference:b.anchor},middleware:[zU({mainAxis:a+O,alignmentAxis:o}),c&&GU({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?VU():void 0,...G}),c&&WU({...G}),qU({...G,apply:({elements:K,rects:Y,availableWidth:J,availableHeight:Ne})=>{const{width:pe,height:te}=Y.reference,Ae=K.floating.style;Ae.setProperty("--radix-popper-available-width",`${J}px`),Ae.setProperty("--radix-popper-available-height",`${Ne}px`),Ae.setProperty("--radix-popper-anchor-width",`${pe}px`),Ae.setProperty("--radix-popper-anchor-height",`${te}px`)}}),N&&KU({element:N,padding:l}),a7({arrowWidth:k,arrowHeight:O}),f&&YU({strategy:"referenceHidden",...G})]}),[H,I]=G_(z),V=nn(h);an(()=>{re&&V?.()},[re,V]);const Z=B.arrow?.x,D=B.arrow?.y,se=B.arrow?.centerOffset!==0,[Q,ne]=y.useState();return an(()=>{x&&ne(window.getComputedStyle(x).zIndex)},[x]),s.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...P,transform:re?P.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[B.transformOrigin?.x,B.transformOrigin?.y].join(" "),...B.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(e7,{scope:n,placedSide:H,onArrowChange:A,arrowX:Z,arrowY:D,shouldHideArrow:se,children:s.jsx(it.div,{"data-side":H,"data-align":I,...g,ref:T,style:{...g.style,animation:re?void 0:"none"}})})})});$_.displayName=Eg;var H_="PopperArrow",n7={top:"bottom",right:"left",bottom:"top",left:"right"},z_=y.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=t7(H_,r),o=n7[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:s.jsx(ZU,{...a,ref:n,style:{...a.style,display:"block"}})})});z_.displayName=H_;function r7(e){return e!==null}var a7=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:a}=t,o=a.arrow?.centerOffset!==0,l=o?0:e.arrowWidth,c=o?0:e.arrowHeight,[u,p]=G_(n),d={start:"0%",center:"50%",end:"100%"}[p],f=(a.arrow?.x??0)+l/2,m=(a.arrow?.y??0)+c/2;let h="",g="";return u==="bottom"?(h=o?d:`${f}px`,g=`${-c}px`):u==="top"?(h=o?d:`${f}px`,g=`${r.floating.height+c}px`):u==="right"?(h=`${-c}px`,g=o?d:`${m}px`):u==="left"&&(h=`${r.floating.width+c}px`,g=o?d:`${m}px`),{data:{x:h,y:g}}}});function G_(e){const[t,n="center"]=e.split("-");return[t,n]}var vg=F_,xd=U_,Sg=$_,wg=z_,s7="Portal",yd=y.forwardRef((e,t)=>{const{container:n,...r}=e,[a,i]=y.useState(!1);an(()=>i(!0),[]);const o=n||a&&globalThis?.document?.body;return o?Fu.createPortal(s.jsx(it.div,{...r,ref:t}),o):null});yd.displayName=s7;function i7(e){const t=o7(e),n=y.forwardRef((r,a)=>{const{children:i,...o}=r,l=y.Children.toArray(i),c=l.find(c7);if(c){const u=c.props.children,p=l.map(d=>d===c?y.Children.count(u)>1?y.Children.only(null):y.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...o,ref:a,children:y.isValidElement(u)?y.cloneElement(u,void 0,p):null})}return s.jsx(t,{...o,ref:a,children:i})});return n.displayName=`${e}.Slot`,n}function o7(e){const t=y.forwardRef((n,r)=>{const{children:a,...i}=n;if(y.isValidElement(a)){const o=d7(a),l=u7(i,a.props);return a.type!==y.Fragment&&(l.ref=r?Rn(r,o):o),y.cloneElement(a,l)}return y.Children.count(a)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var l7=Symbol("radix.slottable");function c7(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===l7}function u7(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function d7(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function p7(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var V_=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),f7="VisuallyHidden",m7=y.forwardRef((e,t)=>s.jsx(it.span,{...e,ref:t,style:{...V_,...e.style}}));m7.displayName=f7;var h7=[" ","Enter","ArrowUp","ArrowDown"],g7=[" ","Enter"],ls="Select",[Ed,vd,b7]=Xh(ls),[Ni]=Zr(ls,[b7,Ti]),Sd=Ti(),[x7,Ia]=Ni(ls),[y7,E7]=Ni(ls),W_=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:o,defaultValue:l,onValueChange:c,dir:u,name:p,autoComplete:d,disabled:f,required:m,form:h}=e,g=Sd(t),[b,x]=y.useState(null),[S,T]=y.useState(null),[N,A]=y.useState(!1),C=cl(u),[k,O]=pi({prop:r,defaultProp:a??!1,onChange:i,caller:ls}),[M,R]=pi({prop:o,defaultProp:l,onChange:c,caller:ls}),j=y.useRef(null),U=b?h||!!b.closest("form"):!0,[G,q]=y.useState(new Set),P=Array.from(G).map(z=>z.props.value).join(";");return s.jsx(vg,{...g,children:s.jsxs(x7,{required:m,scope:t,trigger:b,onTriggerChange:x,valueNode:S,onValueNodeChange:T,valueNodeHasChildren:N,onValueNodeHasChildrenChange:A,contentId:_n(),value:M,onValueChange:R,open:k,onOpenChange:O,dir:C,triggerPointerDownPosRef:j,disabled:f,children:[s.jsx(Ed.Provider,{scope:t,children:s.jsx(y7,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(z=>{q(re=>new Set(re).add(z))},[]),onNativeOptionRemove:y.useCallback(z=>{q(re=>{const B=new Set(re);return B.delete(z),B})},[]),children:n})}),U?s.jsxs(mR,{"aria-hidden":!0,required:m,tabIndex:-1,name:p,autoComplete:d,value:M,onChange:z=>R(z.target.value),disabled:f,form:h,children:[M===void 0?s.jsx("option",{value:""}):null,Array.from(G)]},P):null]})})};W_.displayName=ls;var q_="SelectTrigger",Y_=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=e,i=Sd(n),o=Ia(q_,n),l=o.disabled||r,c=xt(t,o.onTriggerChange),u=vd(n),p=y.useRef("touch"),[d,f,m]=gR(g=>{const b=u().filter(T=>!T.disabled),x=b.find(T=>T.value===o.value),S=bR(b,g,x);S!==void 0&&o.onValueChange(S.value)}),h=g=>{l||(o.onOpenChange(!0),m()),g&&(o.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return s.jsx(xd,{asChild:!0,...i,children:s.jsx(it.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":hR(o.value)?"":void 0,...a,ref:c,onClick:Ve(a.onClick,g=>{g.currentTarget.focus(),p.current!=="mouse"&&h(g)}),onPointerDown:Ve(a.onPointerDown,g=>{p.current=g.pointerType;const b=g.target;b.hasPointerCapture(g.pointerId)&&b.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(h(g),g.preventDefault())}),onKeyDown:Ve(a.onKeyDown,g=>{const b=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&f(g.key),!(b&&g.key===" ")&&h7.includes(g.key)&&(h(),g.preventDefault())})})})});Y_.displayName=q_;var K_="SelectValue",X_=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:o="",...l}=e,c=Ia(K_,n),{onValueNodeHasChildrenChange:u}=c,p=i!==void 0,d=xt(t,c.onValueNodeChange);return an(()=>{u(p)},[u,p]),s.jsx(it.span,{...l,ref:d,style:{pointerEvents:"none"},children:hR(c.value)?s.jsx(s.Fragment,{children:o}):i})});X_.displayName=K_;var v7="SelectIcon",Z_=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...a}=e;return s.jsx(it.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});Z_.displayName=v7;var S7="SelectPortal",Q_=e=>s.jsx(yd,{asChild:!0,...e});Q_.displayName=S7;var cs="SelectContent",J_=y.forwardRef((e,t)=>{const n=Ia(cs,e.__scopeSelect),[r,a]=y.useState();if(an(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?yi.createPortal(s.jsx(eR,{scope:e.__scopeSelect,children:s.jsx(Ed.Slot,{scope:e.__scopeSelect,children:s.jsx("div",{children:e.children})})}),i):null}return s.jsx(tR,{...e,ref:t})});J_.displayName=cs;var rr=10,[eR,Da]=Ni(cs),w7="SelectContentImpl",T7=i7("SelectContent.RemoveScroll"),tR=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:o,side:l,sideOffset:c,align:u,alignOffset:p,arrowPadding:d,collisionBoundary:f,collisionPadding:m,sticky:h,hideWhenDetached:g,avoidCollisions:b,...x}=e,S=Ia(cs,n),[T,N]=y.useState(null),[A,C]=y.useState(null),k=xt(t,K=>N(K)),[O,M]=y.useState(null),[R,j]=y.useState(null),U=vd(n),[G,q]=y.useState(!1),P=y.useRef(!1);y.useEffect(()=>{if(T)return id(T)},[T]),pg();const z=y.useCallback(K=>{const[Y,...J]=U().map(te=>te.ref.current),[Ne]=J.slice(-1),pe=document.activeElement;for(const te of K)if(te===pe||(te?.scrollIntoView({block:"nearest"}),te===Y&&A&&(A.scrollTop=0),te===Ne&&A&&(A.scrollTop=A.scrollHeight),te?.focus(),document.activeElement!==pe))return},[U,A]),re=y.useCallback(()=>z([O,T]),[z,O,T]);y.useEffect(()=>{G&&re()},[G,re]);const{onOpenChange:B,triggerPointerDownPosRef:H}=S;y.useEffect(()=>{if(T){let K={x:0,y:0};const Y=Ne=>{K={x:Math.abs(Math.round(Ne.pageX)-(H.current?.x??0)),y:Math.abs(Math.round(Ne.pageY)-(H.current?.y??0))}},J=Ne=>{K.x<=10&&K.y<=10?Ne.preventDefault():T.contains(Ne.target)||B(!1),document.removeEventListener("pointermove",Y),H.current=null};return H.current!==null&&(document.addEventListener("pointermove",Y),document.addEventListener("pointerup",J,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",J,{capture:!0})}}},[T,B,H]),y.useEffect(()=>{const K=()=>B(!1);return window.addEventListener("blur",K),window.addEventListener("resize",K),()=>{window.removeEventListener("blur",K),window.removeEventListener("resize",K)}},[B]);const[I,V]=gR(K=>{const Y=U().filter(pe=>!pe.disabled),J=Y.find(pe=>pe.ref.current===document.activeElement),Ne=bR(Y,K,J);Ne&&setTimeout(()=>Ne.ref.current.focus())}),Z=y.useCallback((K,Y,J)=>{const Ne=!P.current&&!J;(S.value!==void 0&&S.value===Y||Ne)&&(M(K),Ne&&(P.current=!0))},[S.value]),D=y.useCallback(()=>T?.focus(),[T]),se=y.useCallback((K,Y,J)=>{const Ne=!P.current&&!J;(S.value!==void 0&&S.value===Y||Ne)&&j(K)},[S.value]),Q=r==="popper"?Lm:nR,ne=Q===Lm?{side:l,sideOffset:c,align:u,alignOffset:p,arrowPadding:d,collisionBoundary:f,collisionPadding:m,sticky:h,hideWhenDetached:g,avoidCollisions:b}:{};return s.jsx(eR,{scope:n,content:T,viewport:A,onViewportChange:C,itemRefCallback:Z,selectedItem:O,onItemLeave:D,itemTextRefCallback:se,focusSelectedItem:re,selectedItemText:R,position:r,isPositioned:G,searchRef:I,children:s.jsx(dl,{as:T7,allowPinchZoom:!0,children:s.jsx(fd,{asChild:!0,trapped:S.open,onMountAutoFocus:K=>{K.preventDefault()},onUnmountAutoFocus:Ve(a,K=>{S.trigger?.focus({preventScroll:!0}),K.preventDefault()}),children:s.jsx(pd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:K=>K.preventDefault(),onDismiss:()=>S.onOpenChange(!1),children:s.jsx(Q,{role:"listbox",id:S.contentId,"data-state":S.open?"open":"closed",dir:S.dir,onContextMenu:K=>K.preventDefault(),...x,...ne,onPlaced:()=>q(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:Ve(x.onKeyDown,K=>{const Y=K.ctrlKey||K.altKey||K.metaKey;if(K.key==="Tab"&&K.preventDefault(),!Y&&K.key.length===1&&V(K.key),["ArrowUp","ArrowDown","Home","End"].includes(K.key)){let Ne=U().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);if(["ArrowUp","End"].includes(K.key)&&(Ne=Ne.slice().reverse()),["ArrowUp","ArrowDown"].includes(K.key)){const pe=K.target,te=Ne.indexOf(pe);Ne=Ne.slice(te+1)}setTimeout(()=>z(Ne)),K.preventDefault()}})})})})})})});tR.displayName=w7;var N7="SelectItemAlignedPosition",nR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=e,i=Ia(cs,n),o=Da(cs,n),[l,c]=y.useState(null),[u,p]=y.useState(null),d=xt(t,k=>p(k)),f=vd(n),m=y.useRef(!1),h=y.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:S}=o,T=y.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&u&&g&&b&&x){const k=i.trigger.getBoundingClientRect(),O=u.getBoundingClientRect(),M=i.valueNode.getBoundingClientRect(),R=x.getBoundingClientRect();if(i.dir!=="rtl"){const pe=R.left-O.left,te=M.left-pe,Ae=k.left-te,$e=k.width+Ae,Ee=Math.max($e,O.width),Ze=window.innerWidth-rr,Ye=_m(te,[rr,Math.max(rr,Ze-Ee)]);l.style.minWidth=$e+"px",l.style.left=Ye+"px"}else{const pe=O.right-R.right,te=window.innerWidth-M.right-pe,Ae=window.innerWidth-k.right-te,$e=k.width+Ae,Ee=Math.max($e,O.width),Ze=window.innerWidth-rr,Ye=_m(te,[rr,Math.max(rr,Ze-Ee)]);l.style.minWidth=$e+"px",l.style.right=Ye+"px"}const j=f(),U=window.innerHeight-rr*2,G=g.scrollHeight,q=window.getComputedStyle(u),P=parseInt(q.borderTopWidth,10),z=parseInt(q.paddingTop,10),re=parseInt(q.borderBottomWidth,10),B=parseInt(q.paddingBottom,10),H=P+z+G+B+re,I=Math.min(b.offsetHeight*5,H),V=window.getComputedStyle(g),Z=parseInt(V.paddingTop,10),D=parseInt(V.paddingBottom,10),se=k.top+k.height/2-rr,Q=U-se,ne=b.offsetHeight/2,K=b.offsetTop+ne,Y=P+z+K,J=H-Y;if(Y<=se){const pe=j.length>0&&b===j[j.length-1].ref.current;l.style.bottom="0px";const te=u.clientHeight-g.offsetTop-g.offsetHeight,Ae=Math.max(Q,ne+(pe?D:0)+te+re),$e=Y+Ae;l.style.height=$e+"px"}else{const pe=j.length>0&&b===j[0].ref.current;l.style.top="0px";const Ae=Math.max(se,P+g.offsetTop+(pe?Z:0)+ne)+J;l.style.height=Ae+"px",g.scrollTop=Y-se+g.offsetTop}l.style.margin=`${rr}px 0`,l.style.minHeight=I+"px",l.style.maxHeight=U+"px",r?.(),requestAnimationFrame(()=>m.current=!0)}},[f,i.trigger,i.valueNode,l,u,g,b,x,i.dir,r]);an(()=>T(),[T]);const[N,A]=y.useState();an(()=>{u&&A(window.getComputedStyle(u).zIndex)},[u]);const C=y.useCallback(k=>{k&&h.current===!0&&(T(),S?.(),h.current=!1)},[T,S]);return s.jsx(A7,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:m,onScrollButtonChange:C,children:s.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:s.jsx(it.div,{...a,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});nR.displayName=N7;var C7="SelectPopperPosition",Lm=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=rr,...i}=e,o=Sd(n);return s.jsx(Sg,{...o,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Lm.displayName=C7;var[A7,Tg]=Ni(cs,{}),jm="SelectViewport",rR=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...a}=e,i=Da(jm,n),o=Tg(jm,n),l=xt(t,i.onViewportChange),c=y.useRef(0);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),s.jsx(Ed.Slot,{scope:n,children:s.jsx(it.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Ve(a.onScroll,u=>{const p=u.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:f}=o;if(f?.current&&d){const m=Math.abs(c.current-p.scrollTop);if(m>0){const h=window.innerHeight-rr*2,g=parseFloat(d.style.minHeight),b=parseFloat(d.style.height),x=Math.max(g,b);if(x<h){const S=x+m,T=Math.min(h,S),N=S-T;d.style.height=T+"px",d.style.bottom==="0px"&&(p.scrollTop=N>0?N:0,d.style.justifyContent="flex-end")}}}c.current=p.scrollTop})})})]})});rR.displayName=jm;var aR="SelectGroup",[_7,R7]=Ni(aR),k7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=_n();return s.jsx(_7,{scope:n,id:a,children:s.jsx(it.div,{role:"group","aria-labelledby":a,...r,ref:t})})});k7.displayName=aR;var sR="SelectLabel",I7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=R7(sR,n);return s.jsx(it.div,{id:a.id,...r,ref:t})});I7.displayName=sR;var xu="SelectItem",[D7,iR]=Ni(xu),oR=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...o}=e,l=Ia(xu,n),c=Da(xu,n),u=l.value===r,[p,d]=y.useState(i??""),[f,m]=y.useState(!1),h=xt(t,S=>c.itemRefCallback?.(S,r,a)),g=_n(),b=y.useRef("touch"),x=()=>{a||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return s.jsx(D7,{scope:n,value:r,disabled:a,textId:g,isSelected:u,onItemTextChange:y.useCallback(S=>{d(T=>T||(S?.textContent??"").trim())},[]),children:s.jsx(Ed.ItemSlot,{scope:n,value:r,disabled:a,textValue:p,children:s.jsx(it.div,{role:"option","aria-labelledby":g,"data-highlighted":f?"":void 0,"aria-selected":u&&f,"data-state":u?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...o,ref:h,onFocus:Ve(o.onFocus,()=>m(!0)),onBlur:Ve(o.onBlur,()=>m(!1)),onClick:Ve(o.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:Ve(o.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:Ve(o.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Ve(o.onPointerMove,S=>{b.current=S.pointerType,a?c.onItemLeave?.():b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ve(o.onPointerLeave,S=>{S.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:Ve(o.onKeyDown,S=>{c.searchRef?.current!==""&&S.key===" "||(g7.includes(S.key)&&x(),S.key===" "&&S.preventDefault())})})})})});oR.displayName=xu;var co="SelectItemText",lR=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=e,o=Ia(co,n),l=Da(co,n),c=iR(co,n),u=E7(co,n),[p,d]=y.useState(null),f=xt(t,x=>d(x),c.onItemTextChange,x=>l.itemTextRefCallback?.(x,c.value,c.disabled)),m=p?.textContent,h=y.useMemo(()=>s.jsx("option",{value:c.value,disabled:c.disabled,children:m},c.value),[c.disabled,c.value,m]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return an(()=>(g(h),()=>b(h)),[g,b,h]),s.jsxs(s.Fragment,{children:[s.jsx(it.span,{id:c.textId,...i,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?yi.createPortal(i.children,o.valueNode):null]})});lR.displayName=co;var cR="SelectItemIndicator",uR=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return iR(cR,n).isSelected?s.jsx(it.span,{"aria-hidden":!0,...r,ref:t}):null});uR.displayName=cR;var Mm="SelectScrollUpButton",dR=y.forwardRef((e,t)=>{const n=Da(Mm,e.__scopeSelect),r=Tg(Mm,e.__scopeSelect),[a,i]=y.useState(!1),o=xt(t,r.onScrollButtonChange);return an(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollTop>0;i(u)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),a?s.jsx(fR,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});dR.displayName=Mm;var Pm="SelectScrollDownButton",pR=y.forwardRef((e,t)=>{const n=Da(Pm,e.__scopeSelect),r=Tg(Pm,e.__scopeSelect),[a,i]=y.useState(!1),o=xt(t,r.onScrollButtonChange);return an(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,p=Math.ceil(c.scrollTop)<u;i(p)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),a?s.jsx(fR,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});pR.displayName=Pm;var fR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=e,i=Da("SelectScrollButton",n),o=y.useRef(null),l=vd(n),c=y.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return y.useEffect(()=>()=>c(),[c]),an(()=>{l().find(p=>p.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[l]),s.jsx(it.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Ve(a.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Ve(a.onPointerMove,()=>{i.onItemLeave?.(),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Ve(a.onPointerLeave,()=>{c()})})}),O7="SelectSeparator",L7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return s.jsx(it.div,{"aria-hidden":!0,...r,ref:t})});L7.displayName=O7;var Fm="SelectArrow",j7=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,a=Sd(n),i=Ia(Fm,n),o=Da(Fm,n);return i.open&&o.position==="popper"?s.jsx(wg,{...a,...r,ref:t}):null});j7.displayName=Fm;var M7="SelectBubbleInput",mR=y.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const a=y.useRef(null),i=xt(r,a),o=p7(t);return y.useEffect(()=>{const l=a.current;if(!l)return;const c=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==t&&p){const d=new Event("change",{bubbles:!0});p.call(l,t),l.dispatchEvent(d)}},[o,t]),s.jsx(it.select,{...n,style:{...V_,...n.style},ref:i,defaultValue:t})});mR.displayName=M7;function hR(e){return e===""||e===void 0}function gR(e){const t=nn(e),n=y.useRef(""),r=y.useRef(0),a=y.useCallback(o=>{const l=n.current+o;t(l),(function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))})(l)},[t]),i=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function bR(e,t,n){const a=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=P7(e,Math.max(i,0));a.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function P7(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var F7=W_,B7=Y_,U7=X_,$7=Z_,H7=Q_,z7=J_,G7=rR,V7=oR,W7=lR,q7=uR,Y7=dR,K7=pR;function Fo({...e}){return s.jsx(F7,{"data-slot":"select",...e})}function Bo({...e}){return s.jsx(U7,{"data-slot":"select-value",...e})}function Uo({className:e,size:t="default",children:n,...r}){return s.jsxs(B7,{"data-slot":"select-trigger","data-size":t,className:Fe("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[n,s.jsx($7,{asChild:!0,children:s.jsx(Ku,{className:"size-4 opacity-50"})})]})}function $o({className:e,children:t,position:n="popper",...r}){return s.jsx(H7,{children:s.jsxs(z7,{"data-slot":"select-content",className:Fe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[s.jsx(X7,{}),s.jsx(G7,{className:Fe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),s.jsx(Z7,{})]})})}function ba({className:e,children:t,...n}){return s.jsxs(V7,{"data-slot":"select-item",className:Fe("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[s.jsx("span",{className:"absolute end-2 flex size-3.5 items-center justify-center",children:s.jsx(q7,{children:s.jsx(Yt,{className:"size-4"})})}),s.jsx(W7,{children:t})]})}function X7({className:e,...t}){return s.jsx(Y7,{"data-slot":"select-scroll-up-button",className:Fe("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(rF,{className:"size-4"})})}function Z7({className:e,...t}){return s.jsx(K7,{"data-slot":"select-scroll-down-button",className:Fe("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(Ku,{className:"size-4"})})}const Ho=y.forwardRef(({className:e,...t},n)=>s.jsx("textarea",{className:Fe("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Ho.displayName="Textarea";function Bm({status:e}){const t="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-semibold border uppercase tracking-wider whitespace-nowrap";switch(e){case"open":return s.jsx("span",{className:Fe(t,"bg-red-500/15 text-red-600 border-red-500/30"),children:"Open"});case"in_progress":return s.jsx("span",{className:Fe(t,"bg-blue-500/15 text-blue-600 border-blue-500/30"),children:"In Progress"});case"resolved":return s.jsx("span",{className:Fe(t,"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"),children:"Resolved"});case"closed":return s.jsx("span",{className:Fe(t,"bg-gray-500/15 text-gray-600 border-gray-500/30"),children:"Closed"});default:return s.jsx("span",{className:Fe(t,"bg-secondary text-secondary-foreground"),children:e})}}function xR(e){if(!e)return"—";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function yR(e){if(!e)return"—";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);return n<60?`${n}m`:`${Math.floor(n/60)}h ${n%60}m`}function Va(e){const t=String(e.tags?.priority||e.tags?.severity||"").toUpperCase();return t==="P1"||t==="CRITICAL"||e.status==="in_progress"?"P1":t==="P2"?"P2":t==="P3"||t==="LOW"||e.status==="resolved"||e.status==="closed"?"P3":"P2"}function ER(e){const t=String(e||"").toLowerCase();return t==="critical"||t==="p1"?{ack:10,resolve:60}:t==="high"||t==="p2"?{ack:30,resolve:120}:{ack:30,resolve:120}}function L1(e,t){return!e||!t?null:Math.max(0,Math.floor((new Date(t).getTime()-new Date(e).getTime())/6e4))}function j1(e,t){const{ack:n,resolve:r}=ER(e.tags?.severity||e.tags?.priority),a=t==="ack"?n:r,i=e.status!=="open",o=e.status==="resolved"||e.status==="closed";if(t==="ack"?i:o){const p=t==="ack"?e.analysisTriggeredAt||e.updatedAt:e.resolvedAt,d=L1(e.createdAt,p);return d==null?{label:"✓ met",cls:"ok"}:d<=a?{label:`✓ ${d}m`,cls:"ok"}:{label:`⚠ ${d}m`,cls:"breach"}}const c=L1(e.createdAt,new Date().toISOString())??0,u=a-c;return u>=0?{label:`⏱ ${u}m left`,cls:"pending"}:{label:`⚠ ${Math.abs(u)}m over`,cls:"breach"}}function Um(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`}function Q7(e){if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return"—";const n=r=>r.toString().padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const yu={open:"Open",in_progress:"Investigating",resolved:"Resolved",closed:"Closed"};function J7(e){if(e.events&&e.events.length){const n=e.events.map(r=>{const a=r.type==="status_change"&&r.afterValue==="in_progress",i=r.type==="created"?"created":r.type==="analysis"?"ai":r.type==="assigned"?"state":r.type==="status_change"?r.afterValue==="resolved"||r.afterValue==="closed"?"resolved":a?"ack":"state":"comment";let o,l;if(r.type==="status_change")if(a)o="Acknowledged",l=r.actor?`by ${r.actor}`:null;else if(r.afterValue==="resolved"){o="Incident resolved";const c=r.actor?`by ${r.actor}`:"",u=r.message&&r.message!=="State changed"?r.message:null;l=u?`${u}${c?` · ${c}`:""}`:c||null}else r.afterValue==="closed"?(o="Incident closed",l=r.actor?`by ${r.actor}`:null):(o="State changed",l=`${yu[r.beforeValue??""]??r.beforeValue} → ${yu[r.afterValue??""]??r.afterValue}${r.actor?` · by ${r.actor}`:""}`);else r.type==="assigned"?(o=r.message||"Assignment changed",l=r.actor?`by ${r.actor}`:null):r.type==="analysis"?(o="AI Insight ran",l=r.message||"RCA analysis requested"):r.type==="created"?(o="Incident created",l=r.message?`${r.message}${r.actor?` · ${r.actor}`:""}`:e.source?`Source ${e.source}`:null):(o=r.message||r.type,l=r.actor?`by ${r.actor}`:null);return{t:r.createdAt,title:o,detail:l,kind:i}});e.events.some(r=>r.type==="created")||n.push({t:e.createdAt,title:"Incident created",detail:e.source?`Source ${e.source}`:null,kind:"created"});for(const r of e.comments||[])n.push({t:r.createdAt,title:"Note added",detail:r.message,kind:"comment"});return n.filter(r=>r.t).sort((r,a)=>new Date(r.t).getTime()-new Date(a.t).getTime())}const t=[];t.push({t:e.createdAt,title:"Incident created",detail:e.source?`Source ${e.source}${e.alertId?" · alert linked":""}`:null,kind:"created"}),e.analysisTriggeredAt&&t.push({t:e.analysisTriggeredAt,title:"AI Insight triggered",detail:"RCA analysis requested",kind:"ai"}),e.analysisCompletedAt&&t.push({t:e.analysisCompletedAt,title:"AI Insight completed",detail:e.aiModelUsed?`Model ${e.aiModelUsed}`:null,kind:"ai"}),e.analysisStatus==="failed"&&t.push({t:e.updatedAt,title:"AI Insight failed",detail:"Analysis did not complete",kind:"failed"});for(const n of e.comments||[])t.push({t:n.createdAt,title:"Note added",detail:n.message,kind:"comment"});return e.resolvedAt&&t.push({t:e.resolvedAt,title:"Incident resolved",detail:null,kind:"resolved"}),t.filter(n=>n.t).sort((n,r)=>new Date(n.t).getTime()-new Date(r.t).getTime())}const e9={created:"#922B21",ack:"#1A5276",ai:"#7048C4",state:"#E67E22",comment:"#5a6b7b",resolved:"#1E8449",failed:"#C0392B"};function t9(e){if(e.events&&e.events.length){const n=e.events.map(r=>({ts:r.createdAt,actor:r.actor||"—",action:r.message||r.type,before:r.beforeValue?(yu[r.beforeValue]??r.beforeValue).toUpperCase():"—",after:r.afterValue?(yu[r.afterValue]??r.afterValue).toUpperCase():"—"}));return e.events.some(r=>r.type==="created")||n.push({ts:e.createdAt,actor:"System",action:"Incident created",before:"—",after:"OPEN"}),n.sort((r,a)=>new Date(r.ts).getTime()-new Date(a.ts).getTime())}const t=[];return t.push({ts:e.createdAt,actor:"System",action:e.alertId?"Incident created from alert":"Incident created",before:"—",after:"OPEN"}),e.analysisTriggeredAt&&t.push({ts:e.analysisTriggeredAt,actor:"AI Insight",action:"Analysis triggered",before:"pending",after:"processing"}),e.analysisCompletedAt&&t.push({ts:e.analysisCompletedAt,actor:"AI Insight",action:"Analysis generated",before:"—",after:"completed"}),e.status==="in_progress"&&t.push({ts:e.analysisTriggeredAt||e.updatedAt,actor:"—",action:"State changed",before:"OPEN",after:"INVESTIGATING"}),e.resolvedAt&&t.push({ts:e.resolvedAt,actor:"—",action:"State changed",before:"INVESTIGATING",after:"RESOLVED"}),t.filter(n=>n.ts).sort((n,r)=>new Date(n.ts).getTime()-new Date(r.ts).getTime())}const n9=[{id:"overview",label:"Overview"},{id:"alerts",label:"Alerts group"},{id:"ai",label:"AI Insight"},{id:"timeline",label:"Timeline"},{id:"notifications",label:"Notifications"},{id:"audit",label:"Audit"}];function r9({incident:e}){const t=Va(e),n=e.analysisTriggeredAt&&e.createdAt?Math.max(0,Math.floor((new Date(e.analysisTriggeredAt).getTime()-new Date(e.createdAt).getTime())/6e4)):null;return s.jsxs("div",{className:"im-inc-overview",children:[s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Incident summary"}),e.description&&s.jsxs("div",{className:"mt-4 p-4 border rounded bg-secondary/20",children:[s.jsx("h4",{className:"font-semibold text-sm mb-2 text-primary flex items-center",children:"Short Description"}),s.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed text-muted-foreground",children:e.description})]}),s.jsxs("div",{className:"im-inc-meta-rows",children:[s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Affected resource"}),s.jsxs("span",{className:"im-mono",children:[e.resourceType," · ",e.resourceName]})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Priority"}),s.jsx("span",{children:s.jsx("span",{className:`im-priority-pill im-priority-${t.toLowerCase()}`,children:t})})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Source"}),s.jsx("span",{className:"im-mono",children:e.source||"—"})]}),(e.accountName||e.account_name)&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Account Name"}),s.jsx("span",{className:"im-mono font-medium",children:e.accountName||e.account_name})]}),(e.accountId||e.account_id)&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Account ID"}),s.jsx("span",{className:"im-mono",children:e.accountId||e.account_id})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Created"}),s.jsx("span",{children:e.createdAt?new Date(e.createdAt).toLocaleString():"—"})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Tags"}),s.jsx("div",{className:"flex flex-wrap gap-1 justify-end",children:e.tags&&Object.keys(e.tags).length>0?Object.entries(e.tags).map(([r,a])=>s.jsxs("span",{className:"im-inc-label-chip font-mono text-[11px]",children:[r,":",a]},r)):s.jsx("span",{children:"—"})})]}),e.alertId&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Source alert"}),s.jsxs("span",{className:"im-mono",children:[e.alertId.slice(0,8),"…"]})]})]})]}),s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Quick stats"}),s.jsxs("div",{className:"im-inc-quick-stats",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Time open"}),s.jsx("strong",{children:yR(e.createdAt)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Time to acknowledge"}),s.jsx("strong",{children:n!=null?`${n}m`:"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Analysis status"}),s.jsx("strong",{style:{textTransform:"capitalize"},children:e.analysisStatus})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Alert group size"}),s.jsx("strong",{children:(()=>{const r=e.name.match(/^(\d+) alerts? on/);return r?parseInt(r[1]):e.alertId?1:0})()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Comments"}),s.jsx("strong",{children:e.comments?.length??0})]}),e.resolvedAt&&s.jsxs("div",{children:[s.jsx("span",{children:"Resolved"}),s.jsx("strong",{children:xR(e.resolvedAt)})]})]})]})]})}function a9({incident:e,onViewAlert:t}){const[n,r]=w.useState([]),[a,i]=w.useState(!1);w.useEffect(()=>{e.id&&(i(!0),Ie.listAlerts({incidentId:e.id,limit:100}).then(c=>r(c.alerts)).catch(()=>{}).finally(()=>i(!1)))},[e.id]);const o=n[0]?.sourceType??e.source??"—",l=n.length?`${n.length} alert${n.length>1?"s":""} across 1 resource · Source: ${o} · First alert ${Um(n[n.length-1]?.createdAt)}`:"No alerts are linked to this incident yet.";return s.jsxs("div",{className:"im-inc-alarm-group",children:[s.jsxs("div",{className:"im-inc-group-banner",children:[s.jsx("span",{children:l}),n.length>0&&t&&s.jsx("button",{type:"button",onClick:()=>t(n[0].id),children:"View group timeline"})]}),s.jsxs("div",{className:"im-inc-alarm-table",children:[s.jsxs("div",{className:"im-inc-alarm-thead",children:[s.jsx("span",{style:{flex:"0 0 80px"},children:"Time"}),s.jsx("span",{style:{flex:"0 0 90px"},children:"Severity"}),s.jsx("span",{style:{flex:"0 0 90px"},children:"State"}),s.jsx("span",{style:{flex:"0 0 120px"},children:"Source"}),s.jsx("span",{style:{flex:1},children:"Metric / Alert"}),s.jsx("span",{style:{flex:"0 0 80px"},children:"Value"}),s.jsx("span",{style:{flex:"0 0 60px",textAlign:"right"},children:"Raw"})]}),a?s.jsx("div",{className:"im-inc-alarm-empty",children:s.jsx(Qe,{className:"h-5 w-5 animate-spin"})}):n.length===0?s.jsx("div",{className:"im-inc-alarm-empty",children:"No alerts in this group."}):n.map(c=>{const u=c.metricName||c.alertName,p=c.metricValue??c.value??"—";return s.jsxs("div",{className:"im-inc-alarm-trow",children:[s.jsx("span",{style:{flex:"0 0 80px"},className:"im-mono im-muted",children:Um(c.createdAt)}),s.jsx("span",{style:{flex:"0 0 90px"},children:s.jsx("span",{className:`im-sev-badge im-sev-${c.severity}`,children:c.severity})}),s.jsx("span",{style:{flex:"0 0 90px"},children:s.jsxs("span",{className:`im-alarm-state im-alarm-state-${String(c.status).toLowerCase()}`,children:[s.jsx("i",{}),c.status]})}),s.jsx("span",{style:{flex:"0 0 120px"},className:"im-muted",children:c.sourceType??"—"}),s.jsx("span",{style:{flex:1},className:"im-mono",children:u}),s.jsx("span",{style:{flex:"0 0 80px",fontWeight:700},children:p}),s.jsx("span",{style:{flex:"0 0 60px",textAlign:"right"},children:t&&s.jsx("button",{type:"button",className:"im-link-button",onClick:()=>t(c.id),children:"View"})})]},c.id)})]})]})}function s9({incident:e,readOnly:t,submitting:n,onSubmit:r}){const[a,i]=w.useState(""),o=J7(e),l=()=>{a.trim()&&(r(a.trim()),i(""))};return s.jsxs("div",{className:"im-inc-timeline-tab",children:[s.jsx("div",{className:"im-inc-card",children:s.jsx("div",{className:"im-inc-timeline",children:o.map((c,u)=>s.jsxs("div",{className:"im-inc-tl-row",children:[s.jsxs("div",{className:"im-inc-tl-rail",children:[s.jsx("span",{className:"im-inc-tl-dot",style:{borderColor:e9[c.kind]}}),u<o.length-1&&s.jsx("span",{className:"im-inc-tl-line"})]}),s.jsxs("div",{className:"im-inc-tl-body",children:[s.jsxs("div",{className:"im-inc-tl-head",children:[s.jsx("strong",{children:c.title}),s.jsx("span",{className:"im-mono im-inc-tl-time",children:Um(c.t)})]}),c.detail&&s.jsx("div",{className:"im-inc-tl-detail",children:c.detail})]})]},u))})}),!t&&s.jsxs("div",{className:"im-inc-note-box",children:[s.jsx("textarea",{placeholder:"Add a note… (Markdown, @mention supported)",value:a,onChange:c=>i(c.target.value)}),s.jsx(ie,{onClick:l,disabled:n||!a.trim(),children:n?"Posting…":"Post note"})]})]})}function i9({incident:e,isActive:t,isCompleted:n,isFailed:r,isPending:a,polled:i,validAnalysisResult:o,analysisError:l,backendError:c,sopId:u,isReadOnly:p,onRunAnalysis:d,getStatusLabel:f}){return s.jsxs("div",{className:"im-ai-tab",children:[a&&s.jsxs("div",{className:"im-ai-idle-card",children:[s.jsx("div",{className:"im-ai-idle-icon",children:"✦"}),s.jsx("div",{className:"im-ai-idle-title",children:"AI Insight"}),s.jsx("p",{children:"Run AI Insight to get root cause hints, SOP steps, and recommendations for this incident."}),!p&&s.jsxs(ie,{onClick:d,children:[s.jsx(ho,{className:"mr-2 h-4 w-4"})," Run AI Insight"]}),s.jsxs("div",{className:"im-ai-context-list",children:[s.jsx("span",{children:"✓ Incident data"}),s.jsxs("span",{children:["✓ Resource metadata (",e.resourceType," · ",e.resourceName,")"]}),e.alertId&&s.jsx("span",{children:"✓ Source alert linked"})]})]}),t&&!o&&s.jsxs("div",{className:"im-ai-running-card",children:[s.jsx(Qe,{className:"h-8 w-8 animate-spin",style:{color:"var(--im-primary)"}}),s.jsx("div",{className:"im-ai-running-title",children:"Generating analysis…"}),s.jsx("div",{className:"im-ai-running-sub",children:f(i?.status)}),i?.progressPercent>0&&s.jsx("div",{className:"im-ai-progress-bar",children:s.jsx("div",{style:{width:`${i.progressPercent}%`}})})]}),r&&s.jsxs("div",{className:"im-ai-failed-card",children:[s.jsx(bs,{size:24,style:{color:"var(--im-danger)"}}),s.jsx("div",{children:"Analysis failed"}),s.jsx("p",{children:l||c||"Something went wrong with the AI pipeline."}),!p&&s.jsxs(ie,{variant:"outline",onClick:d,children:[s.jsx(Ra,{className:"mr-2 h-4 w-4"})," Retry"]})]}),(n||t&&o)&&o&&s.jsxs("div",{className:"im-ai-results",children:[typeof o=="string"?s.jsxs("div",{className:"im-inc-card",children:[s.jsxs("div",{className:"im-inc-card-title",children:["🔍 Root cause analysis",s.jsx("span",{className:"im-ai-badge",children:"✦ AI-generated"})]}),e.confidenceScore!=null&&s.jsxs("div",{className:"im-ai-confidence",children:["Confidence: ",e.confidenceScore,"%"]}),s.jsx("pre",{className:"im-ai-text-result",children:o})]}):s.jsx(C5,{result:o,remediationSteps:e.remediationSteps,confidenceScore:e.confidenceScore,aiModelUsed:e.aiModelUsed,isCompleted:n}),u&&s.jsxs("div",{className:"im-inc-card",children:[s.jsxs("div",{className:"im-inc-card-title",children:["📋 Related SOP",s.jsx("span",{className:"im-ai-badge",children:"✦ AI-matched"})]}),s.jsxs(Ei,{to:`/sops/${u}`,className:"im-ai-sop-link",children:["View SOP ",s.jsx(ui,{size:13,style:{display:"inline-block",marginLeft:4}})]})]})]})]})}function o9({incident:e}){const[t,n]=w.useState([]),[r,a]=w.useState([]),[i,o]=w.useState(`${Va(e)} ${e.aliasId?`INC-${String(e.aliasId).padStart(3,"0")}`:e.id.slice(0,7)} — ${e.name}.`);w.useEffect(()=>{Ie.getNotificationProviders().then(c=>{const u=(c.providers||[]).map(p=>p.type||p.name).filter(Boolean);n(u),u[0]&&a([u[0]])}).catch(()=>{})},[]);const l=c=>a(u=>u.includes(c)?u.filter(p=>p!==c):[...u,c]);return s.jsxs("div",{className:"im-inc-notifs",children:[s.jsxs("div",{className:"im-inc-card im-inc-notifs-sent",children:[s.jsx("div",{className:"im-inc-card-title",children:"Sent notifications"}),s.jsx("div",{className:"im-inc-empty-inline",children:s.jsx("p",{children:"No notifications have been sent for this incident yet."})})]}),s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Send manual notification"}),s.jsxs("div",{className:"im-inc-notif-field",children:[s.jsx("label",{children:"Channels"}),s.jsx("div",{className:"im-chip-row",children:t.length===0?s.jsx("span",{className:"im-muted",style:{fontSize:12},children:"No notification providers configured."}):t.map(c=>s.jsx("button",{type:"button",className:`im-notif-chip ${r.includes(c)?"is-on":""}`,onClick:()=>l(c),children:c},c))})]}),s.jsx("textarea",{className:"im-inc-notif-textarea",value:i,onChange:c=>o(c.target.value)}),s.jsx(ie,{disabled:r.length===0||!i.trim(),onClick:()=>ae.info("Manual notification sending is not yet wired to a backend endpoint."),children:"Send now"})]})]})}function l9({incident:e}){const t=t9(e);return s.jsxs("div",{className:"im-inc-card im-inc-audit-card",children:[s.jsx("div",{className:"im-inc-audit-head",children:s.jsx("span",{children:"Audit trail · derived from incident events"})}),s.jsxs("div",{className:"im-inc-audit-thead",children:[s.jsx("span",{style:{flex:"0 0 170px"},children:"Timestamp"}),s.jsx("span",{style:{flex:"0 0 130px"},children:"Actor"}),s.jsx("span",{style:{flex:1},children:"Action"}),s.jsx("span",{style:{flex:"0 0 180px"},children:"Before → After"})]}),t.map((n,r)=>s.jsxs("div",{className:"im-inc-audit-trow",children:[s.jsx("span",{style:{flex:"0 0 170px"},className:"im-mono im-muted",children:Q7(n.ts)}),s.jsx("span",{style:{flex:"0 0 130px"},children:n.actor}),s.jsx("span",{style:{flex:1},className:"im-muted",children:n.action}),s.jsxs("span",{style:{flex:"0 0 180px"},className:"im-mono im-muted",children:[n.before," → ",n.after]})]},r))]})}function c9({incidentId:e,onBack:t,onViewAlert:n}){const{isReadOnly:r}=ur(),a=St(),[i,o]=w.useState(null),[l,c]=w.useState(null),[u,p]=w.useState(!0),[d,f]=w.useState("overview"),[m,h]=w.useState(null),[g,b]=w.useState(!1),[x,S]=w.useState(!1),[T,N]=w.useState(!1),[A,C]=w.useState(""),[k,O]=w.useState(null),[M,R]=w.useState([]),j=w.useCallback(async()=>{try{const Y=await Ie.getIncident(e);o(Y.incident)}catch{ae.error("Failed to load incident")}finally{p(!1)}},[e]);w.useEffect(()=>{j()},[j]),w.useEffect(()=>{i?.name&&Tr.lookupByAlertName(i.name).then(Y=>{Y&&c(Y)}).catch(()=>{})},[i?.name]),w.useEffect(()=>{i?.resourceName&&Ie.listIncidents({page:1,limit:6,search:i.resourceName}).then(Y=>R((Y.incidents??[]).filter(J=>J.id!==i.id).slice(0,4))).catch(()=>{})},[i?.resourceName,i?.id]);const U=rf(i?.analysisStatus),G=k8(e,!!U,i?.analysisStatus??"pending");w.useEffect(()=>{(G.isComplete||G.isFailed)&&j()},[G.isComplete,G.isFailed,j]);const q=async Y=>{h(null),G.optimisticTrigger();try{await Ie.triggerAnalysis(Y),ae.success("Analysis triggered"),j()}catch(J){const Ne=J?.response?.data?.error??"Failed to trigger analysis";h(Ne),G.markFailed(),j(),ae.error(Ne)}},P=async Y=>{if(i){b(!0);try{const J=await Ie.addIncidentComment(i.id,{message:Y});o({...i,comments:[...i.comments||[],J.comment]}),ae.success("Comment added")}catch(J){ae.error(J?.response?.data?.error??"Failed to add comment")}finally{b(!1)}}},z=async Y=>{if(!i)return;const J=i.assigneeIds;o({...i,assigneeIds:Y});try{await Ie.assignIncident(i.id,Y),ae.success("Assignees updated"),j()}catch(Ne){o({...i,assigneeIds:J}),ae.error(Ne?.response?.data?.error??"Failed to assign users")}},re=async(Y,J)=>{if(!i)return;const Ne=i.status;o({...i,status:Y});try{await Ie.updateIncident(i.id,{status:Y,statusMessage:J}),ae.success("Status updated"),j()}catch(pe){o({...i,status:Ne}),ae.error(pe?.response?.data?.error??"Failed to update status")}},B=async()=>{if(i)try{await re("resolved",A.trim()||void 0),N(!1),C("")}catch(Y){ae.error(Y?.response?.data?.error??"Failed to resolve incident")}},H=Y=>({queued:"Queued for analysis...",triage_started:"Triaging incident...",infra_analysis:"Analysing infrastructure...",logs_analysis:"Analysing logs...",ai_reasoning:"AI reasoning in progress...",remediation_generated:"Generating remediation steps...",fetching_ec2:"Fetching EC2 details...",fetching_metrics:"Fetching metrics...",fetching_logs:"Fetching logs...",finding_rca:"Finding Root Cause..."})[Y??""]??"Analysis in progress...";if(u)return s.jsx(qr,{variant:"incident-detail"});if(!i)return s.jsx("div",{className:"im-page",children:s.jsxs("div",{className:"im-inc-empty",children:[s.jsx("h2",{children:"Incident Not Found"}),s.jsxs(ie,{variant:"outline",onClick:t,children:[s.jsx(Vr,{className:"mr-2 h-4 w-4"})," Back"]})]})});const I=U||rf(G.status)?G.status??i.analysisStatus:i.analysisStatus,V=typeof i.analysisResult=="object"&&i.analysisResult?.error?i.analysisResult.error:null,Z=V?null:i.analysisResult,D=!m&&rf(I),se=I==="completed",Q=!D&&(I==="failed"||!!m||!!V),ne=I==="pending",K=i.aliasId?`INC-${String(i.aliasId).padStart(3,"0")}`:i.id.slice(0,8);return s.jsxs("div",{className:"im-inc-detail -m-4",children:[s.jsxs("div",{className:"im-inc-header",children:[s.jsxs("div",{className:"im-inc-header-row1",children:[s.jsx("button",{className:"im-back-button",type:"button",onClick:t,"aria-label":"Back",children:s.jsx(Vr,{size:16})}),s.jsx("span",{className:"im-inc-id im-mono",children:K}),s.jsx("h1",{className:"im-inc-title",children:i.name}),s.jsx("span",{className:`im-priority-pill im-priority-${Va(i).toLowerCase()}`,children:Va(i)}),s.jsx(Bm,{status:i.status})]}),s.jsxs("div",{className:"im-inc-header-row2",children:[s.jsxs("span",{className:"im-inc-time",children:[s.jsx(rs,{size:13})," opened ",xR(i.createdAt)]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsxs("span",{className:"im-inc-resource im-mono",children:[i.resourceType," · ",i.resourceName]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsx("span",{children:i.alertId?"1 alert":"0 alerts"}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsxs("span",{className:"im-inc-dur",children:["⏱ ",yR(i.createdAt)]})]}),s.jsxs("div",{className:"im-inc-actions",children:[!r&&s.jsxs(s.Fragment,{children:[s.jsx(ie,{size:"sm",onClick:()=>re("in_progress"),disabled:i.status==="in_progress"||i.status==="resolved",children:"Acknowledge"}),s.jsx(ie,{size:"sm",variant:"outline",style:{borderColor:"var(--im-success)",color:"var(--im-success)"},onClick:()=>N(!0),disabled:i.status==="resolved"||i.status==="closed",children:"Resolve"}),s.jsxs(ie,{size:"sm",variant:"outline",onClick:()=>S(!0),children:[s.jsx(MC,{size:13,className:"mr-1"})," Assign"]})]}),r&&s.jsxs(Fo,{value:i.status,onValueChange:re,children:[s.jsx(Uo,{className:"h-7 text-xs w-36 px-2.5",children:s.jsx(Bo,{placeholder:"Status"})}),s.jsxs($o,{children:[s.jsx(ba,{value:"open",children:"Open"}),s.jsx(ba,{value:"in_progress",children:"In Progress"}),s.jsx(ba,{value:"resolved",children:"Resolved"}),s.jsx(ba,{value:"closed",children:"Closed"})]})]})]})]}),s.jsxs("div",{className:"im-inc-body",children:[s.jsxs("div",{className:"im-inc-main",children:[s.jsx("div",{className:"im-inc-tabs",children:n9.map(({id:Y,label:J})=>s.jsxs("button",{type:"button",className:d===Y?"is-active":"",onClick:()=>f(Y),children:[J,Y==="ai"&&se&&s.jsx("span",{className:"im-ai-done-dot"})]},Y))}),s.jsxs("div",{className:"im-inc-tab-content",children:[d==="overview"&&s.jsx(r9,{incident:i}),d==="alerts"&&s.jsx(a9,{incident:i,onViewAlert:O}),d==="ai"&&s.jsx(i9,{incident:i,isActive:D,isCompleted:se,isFailed:Q,isPending:ne,polled:G,validAnalysisResult:Z,analysisError:m,backendError:V,sopId:l,isReadOnly:r,onRunAnalysis:()=>q(i.id),getStatusLabel:H}),d==="timeline"&&s.jsx(s9,{incident:i,readOnly:r,submitting:g,onSubmit:P}),d==="notifications"&&s.jsx(o9,{incident:i}),d==="audit"&&s.jsx(l9,{incident:i})]})]}),s.jsxs("aside",{className:"im-inc-sidebar",children:[s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Incident ID"}),s.jsx("div",{className:"im-mono",style:{fontSize:12},children:K})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Status"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(Bm,{status:i.status}),s.jsx("span",{className:`im-priority-pill im-priority-${Va(i).toLowerCase()}`,children:Va(i)})]})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Assignees"}),s.jsx("div",{className:r?"":"im-inc-assignee-click",onClick:()=>!r&&S(!0),children:s.jsx(E_,{assigneeIds:i.assigneeIds})}),!r&&s.jsx("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>S(!0),children:"Reassign"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Resource"}),s.jsxs("div",{className:"im-mono",style:{fontSize:11},children:[i.resourceType," · ",i.resourceName]})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Source"}),s.jsx("div",{style:{fontSize:12},children:i.source||"—"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"SLA"}),(()=>{const{ack:Y,resolve:J}=ER(i.tags?.severity||i.tags?.priority),Ne=j1(i,"ack"),pe=j1(i,"resolve");return s.jsxs("div",{className:"im-inc-sla",children:[s.jsxs("div",{className:"im-inc-sla-row",children:[s.jsxs("span",{children:["Ack in ",Y,"m"]}),s.jsx("span",{className:`im-inc-sla-val im-inc-sla-${Ne.cls}`,children:Ne.label})]}),s.jsxs("div",{className:"im-inc-sla-row",children:[s.jsxs("span",{children:["Resolve in ",J,"m"]}),s.jsx("span",{className:`im-inc-sla-val im-inc-sla-${pe.cls}`,children:pe.label})]})]})})()]}),M.length>0&&s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Related incidents"}),s.jsx("div",{className:"im-inc-related",children:M.map(Y=>s.jsxs("button",{type:"button",className:"im-inc-related-row",onClick:()=>a({to:`/incidents/${Y.id}`}),children:[s.jsxs("span",{className:"im-mono im-inc-related-id",children:["#",Y.aliasId?`INC-${String(Y.aliasId).padStart(3,"0")}`:Y.id.slice(0,7)]}),s.jsxs("span",{className:"im-muted",children:[Y.resourceName," · ",Va(Y)]})]},Y.id))})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Tags"}),i.tags&&Object.keys(i.tags).length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(i.tags).map(([Y,J])=>s.jsxs("span",{className:"im-inc-label-chip font-mono text-[11px]",children:[Y,":",J]},Y))}):s.jsx("div",{style:{fontSize:12,color:"var(--im-fg-subtle)"},children:"None"})]}),s.jsxs("div",{className:"im-inc-sidebar-section",children:[s.jsx("div",{className:"im-inc-sidebar-label",children:"Quick actions"}),s.jsxs("div",{className:"im-inc-sidebar-actions",children:[i.alertId&&s.jsxs("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>O(i.alertId),children:[s.jsx(ui,{size:12})," View source alert"]}),l&&s.jsxs(Ei,{to:`/sops/${l}`,className:"im-inc-sidebar-action",children:[s.jsx(ed,{size:12})," View SOP"]}),!r&&!D&&s.jsxs("button",{type:"button",className:"im-inc-sidebar-action",onClick:()=>q(i.id),children:[s.jsx(ho,{size:12})," ",se?"Re-run AI":"Run AI Insight"]})]})]})]})]}),x&&s.jsx(N8,{open:x,onOpenChange:S,assigneeIds:i.assigneeIds,onAssign:z}),s.jsx(kt,{open:T,onOpenChange:N,children:s.jsxs(It,{children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Resolve Incident"})}),s.jsxs("div",{className:"py-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"You are about to mark this incident as resolved. You can optionally leave a comment explaining the resolution."}),s.jsx(Ho,{placeholder:"Optional resolution comment...",value:A,onChange:Y=>C(Y.target.value),className:"min-h-[100px]"})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),s.jsx(ie,{onClick:B,children:"Resolve Incident"})]})]})}),s.jsx(kt,{open:!!k,onOpenChange:Y=>!Y&&O(null),children:s.jsx(It,{className:"max-w-[600px] w-full max-h-[90vh] overflow-y-auto",children:k&&s.jsx(u9,{alertId:k,onClose:()=>O(null)})})})]})}function u9({alertId:e,onClose:t}){const n=St(),[r,a]=w.useState(null),[i,o]=w.useState(!0);if(w.useEffect(()=>{Ie.getAlert(e).then(c=>a(c.alert)).catch(()=>ae.error("Failed to load alert details")).finally(()=>o(!1))},[e]),i)return s.jsx("div",{className:"p-8 text-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin mx-auto text-muted-foreground"})});if(!r)return s.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Alert not found"});const l=r.severity==="critical"?"var(--im-priority-p1)":r.severity==="high"?"var(--im-priority-p2)":r.severity==="medium"?"var(--im-priority-p3)":"var(--im-priority-p4)";return s.jsxs("div",{className:"flex flex-col gap-4 py-2",children:[s.jsx(jt,{children:s.jsxs(Mt,{className:"flex items-center gap-2 text-lg",children:[s.jsx(bs,{className:"h-5 w-5",style:{color:l}}),r.alertName]})}),(()=>{if(!r.description)return s.jsx("div",{className:"text-sm text-muted-foreground",children:"No description provided."});const c=r.description.match(/^(.+?)\s+by\s+(arn:aws:[^\s]+)(?:\s+from\s+([0-9.]+))?/);if(c){const[,u,p,d]=c;return s.jsxs("div",{className:"bg-muted/30 border rounded-md p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Action"}),s.jsx("div",{className:"text-sm font-medium",children:u})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Identity"}),s.jsx("div",{className:"text-xs font-mono text-muted-foreground break-all bg-muted/50 px-2 py-1.5 rounded border border-muted/50",children:p})]}),d&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Source IP"}),s.jsx("div",{className:"text-xs font-mono text-muted-foreground",children:d})]})]})}return s.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.description})})(),s.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Source"}),s.jsx("div",{className:"text-sm im-mono bg-muted px-2 py-1 rounded inline-block",children:r.sourceType})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Status"}),s.jsx("div",{className:"text-sm bg-muted px-2 py-1 rounded inline-block capitalize",children:r.status})]}),s.jsxs("div",{className:"col-span-2",children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Resource"}),s.jsxs("div",{className:"text-sm im-mono bg-muted px-2 py-1 rounded",children:[r.resourceType," · ",r.resourceName]})]})]}),s.jsxs($t,{className:"mt-6 border-t pt-4",children:[s.jsx(ie,{variant:"outline",onClick:t,children:"Close"}),s.jsxs(ie,{onClick:()=>{t(),n({to:`/alerts/${r.id}`})},children:[s.jsx(ui,{className:"w-4 h-4 mr-2"}),"View Full Alert"]})]})]})}const Xe=y.forwardRef(({className:e,type:t,...n},r)=>s.jsx("input",{type:t,className:Fe("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));Xe.displayName="Input";var d9=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],p9=d9.reduce((e,t)=>{const n=Yh(`Primitive.${t}`),r=y.forwardRef((a,i)=>{const{asChild:o,...l}=a,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),f9="Label",vR=y.forwardRef((e,t)=>s.jsx(p9.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));vR.displayName=f9;var SR=vR;const Pe=y.forwardRef(({className:e,...t},n)=>s.jsx(SR,{ref:n,className:Fe("block text-sm font-medium leading-snug peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),...t}));Pe.displayName=SR.displayName;function m9(e){const t=h9(e),n=y.forwardRef((r,a)=>{const{children:i,...o}=r,l=y.Children.toArray(i),c=l.find(b9);if(c){const u=c.props.children,p=l.map(d=>d===c?y.Children.count(u)>1?y.Children.only(null):y.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...o,ref:a,children:y.isValidElement(u)?y.cloneElement(u,void 0,p):null})}return s.jsx(t,{...o,ref:a,children:i})});return n.displayName=`${e}.Slot`,n}function h9(e){const t=y.forwardRef((n,r)=>{const{children:a,...i}=n;if(y.isValidElement(a)){const o=y9(a),l=x9(i,a.props);return a.type!==y.Fragment&&(l.ref=r?Rn(r,o):o),y.cloneElement(a,l)}return y.Children.count(a)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var g9=Symbol("radix.slottable");function b9(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===g9}function x9(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function y9(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var $m=["Enter"," "],E9=["ArrowDown","PageUp","Home"],wR=["ArrowUp","PageDown","End"],v9=[...E9,...wR],S9={ltr:[...$m,"ArrowRight"],rtl:[...$m,"ArrowLeft"]},w9={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fl="Menu",[zo,T9,N9]=Xh(fl),[Es,TR]=Zr(fl,[N9,Ti,td]),wd=Ti(),NR=td(),[C9,vs]=Es(fl),[A9,ml]=Es(fl),CR=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:o=!0}=e,l=wd(t),[c,u]=y.useState(null),p=y.useRef(!1),d=nn(i),f=cl(a);return y.useEffect(()=>{const m=()=>{p.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>p.current=!1;return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),s.jsx(vg,{...l,children:s.jsx(C9,{scope:t,open:n,onOpenChange:d,content:c,onContentChange:u,children:s.jsx(A9,{scope:t,onClose:y.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:p,dir:f,modal:o,children:r})})})};CR.displayName=fl;var _9="MenuAnchor",Ng=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=wd(n);return s.jsx(xd,{...a,...r,ref:t})});Ng.displayName=_9;var Cg="MenuPortal",[R9,AR]=Es(Cg,{forceMount:void 0}),_R=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,i=vs(Cg,t);return s.jsx(R9,{scope:t,forceMount:n,children:s.jsx(er,{present:n||i.open,children:s.jsx(yd,{asChild:!0,container:a,children:r})})})};_R.displayName=Cg;var Jn="MenuContent",[k9,Ag]=Es(Jn),RR=y.forwardRef((e,t)=>{const n=AR(Jn,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,i=vs(Jn,e.__scopeMenu),o=ml(Jn,e.__scopeMenu);return s.jsx(zo.Provider,{scope:e.__scopeMenu,children:s.jsx(er,{present:r||i.open,children:s.jsx(zo.Slot,{scope:e.__scopeMenu,children:o.modal?s.jsx(I9,{...a,ref:t}):s.jsx(D9,{...a,ref:t})})})})}),I9=y.forwardRef((e,t)=>{const n=vs(Jn,e.__scopeMenu),r=y.useRef(null),a=xt(t,r);return y.useEffect(()=>{const i=r.current;if(i)return id(i)},[]),s.jsx(_g,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ve(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),D9=y.forwardRef((e,t)=>{const n=vs(Jn,e.__scopeMenu);return s.jsx(_g,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),O9=m9("MenuContent.ScrollLock"),_g=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:d,onInteractOutside:f,onDismiss:m,disableOutsideScroll:h,...g}=e,b=vs(Jn,n),x=ml(Jn,n),S=wd(n),T=NR(n),N=T9(n),[A,C]=y.useState(null),k=y.useRef(null),O=xt(t,k,b.onContentChange),M=y.useRef(0),R=y.useRef(""),j=y.useRef(0),U=y.useRef(null),G=y.useRef("right"),q=y.useRef(0),P=h?dl:y.Fragment,z=h?{as:O9,allowPinchZoom:!0}:void 0,re=H=>{const I=R.current+H,V=N().filter(K=>!K.disabled),Z=document.activeElement,D=V.find(K=>K.ref.current===Z)?.textValue,se=V.map(K=>K.textValue),Q=V9(se,I,D),ne=V.find(K=>K.textValue===Q)?.ref.current;(function K(Y){R.current=Y,window.clearTimeout(M.current),Y!==""&&(M.current=window.setTimeout(()=>K(""),1e3))})(I),ne&&setTimeout(()=>ne.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),pg();const B=y.useCallback(H=>G.current===U.current?.side&&q9(H,U.current?.area),[]);return s.jsx(k9,{scope:n,searchRef:R,onItemEnter:y.useCallback(H=>{B(H)&&H.preventDefault()},[B]),onItemLeave:y.useCallback(H=>{B(H)||(k.current?.focus(),C(null))},[B]),onTriggerLeave:y.useCallback(H=>{B(H)&&H.preventDefault()},[B]),pointerGraceTimerRef:j,onPointerGraceIntentChange:y.useCallback(H=>{U.current=H},[]),children:s.jsx(P,{...z,children:s.jsx(fd,{asChild:!0,trapped:a,onMountAutoFocus:Ve(i,H=>{H.preventDefault(),k.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:s.jsx(pd,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:d,onInteractOutside:f,onDismiss:m,children:s.jsx(uA,{asChild:!0,...T,dir:x.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:C,onEntryFocus:Ve(c,H=>{x.isUsingKeyboardRef.current||H.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(Sg,{role:"menu","aria-orientation":"vertical","data-state":VR(b.open),"data-radix-menu-content":"",dir:x.dir,...S,...g,ref:O,style:{outline:"none",...g.style},onKeyDown:Ve(g.onKeyDown,H=>{const V=H.target.closest("[data-radix-menu-content]")===H.currentTarget,Z=H.ctrlKey||H.altKey||H.metaKey,D=H.key.length===1;V&&(H.key==="Tab"&&H.preventDefault(),!Z&&D&&re(H.key));const se=k.current;if(H.target!==se||!v9.includes(H.key))return;H.preventDefault();const ne=N().filter(K=>!K.disabled).map(K=>K.ref.current);wR.includes(H.key)&&ne.reverse(),z9(ne)}),onBlur:Ve(e.onBlur,H=>{H.currentTarget.contains(H.target)||(window.clearTimeout(M.current),R.current="")}),onPointerMove:Ve(e.onPointerMove,Go(H=>{const I=H.target,V=q.current!==H.clientX;if(H.currentTarget.contains(I)&&V){const Z=H.clientX>q.current?"right":"left";G.current=Z,q.current=H.clientX}}))})})})})})})});RR.displayName=Jn;var L9="MenuGroup",Rg=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{role:"group",...r,ref:t})});Rg.displayName=L9;var j9="MenuLabel",kR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{...r,ref:t})});kR.displayName=j9;var Eu="MenuItem",M1="menu.itemSelect",Td=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,i=y.useRef(null),o=ml(Eu,e.__scopeMenu),l=Ag(Eu,e.__scopeMenu),c=xt(t,i),u=y.useRef(!1),p=()=>{const d=i.current;if(!n&&d){const f=new CustomEvent(M1,{bubbles:!0,cancelable:!0});d.addEventListener(M1,m=>r?.(m),{once:!0}),aA(d,f),f.defaultPrevented?u.current=!1:o.onClose()}};return s.jsx(IR,{...a,ref:c,disabled:n,onClick:Ve(e.onClick,p),onPointerDown:d=>{e.onPointerDown?.(d),u.current=!0},onPointerUp:Ve(e.onPointerUp,d=>{u.current||d.currentTarget?.click()}),onKeyDown:Ve(e.onKeyDown,d=>{const f=l.searchRef.current!=="";n||f&&d.key===" "||$m.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});Td.displayName=Eu;var IR=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=e,o=Ag(Eu,n),l=NR(n),c=y.useRef(null),u=xt(t,c),[p,d]=y.useState(!1),[f,m]=y.useState("");return y.useEffect(()=>{const h=c.current;h&&m((h.textContent??"").trim())},[i.children]),s.jsx(zo.ItemSlot,{scope:n,disabled:r,textValue:a??f,children:s.jsx(dA,{asChild:!0,...l,focusable:!r,children:s.jsx(it.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:u,onPointerMove:Ve(e.onPointerMove,Go(h=>{r?o.onItemLeave(h):(o.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ve(e.onPointerLeave,Go(h=>o.onItemLeave(h))),onFocus:Ve(e.onFocus,()=>d(!0)),onBlur:Ve(e.onBlur,()=>d(!1))})})})}),M9="MenuCheckboxItem",DR=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return s.jsx(PR,{scope:e.__scopeMenu,checked:n,children:s.jsx(Td,{role:"menuitemcheckbox","aria-checked":vu(n)?"mixed":n,...a,ref:t,"data-state":Ig(n),onSelect:Ve(a.onSelect,()=>r?.(vu(n)?!0:!n),{checkForDefaultPrevented:!1})})})});DR.displayName=M9;var OR="MenuRadioGroup",[P9,F9]=Es(OR,{value:void 0,onValueChange:()=>{}}),LR=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,i=nn(r);return s.jsx(P9,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(Rg,{...a,ref:t})})});LR.displayName=OR;var jR="MenuRadioItem",MR=y.forwardRef((e,t)=>{const{value:n,...r}=e,a=F9(jR,e.__scopeMenu),i=n===a.value;return s.jsx(PR,{scope:e.__scopeMenu,checked:i,children:s.jsx(Td,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":Ig(i),onSelect:Ve(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});MR.displayName=jR;var kg="MenuItemIndicator",[PR,B9]=Es(kg,{checked:!1}),FR=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,i=B9(kg,n);return s.jsx(er,{present:r||vu(i.checked)||i.checked===!0,children:s.jsx(it.span,{...a,ref:t,"data-state":Ig(i.checked)})})});FR.displayName=kg;var U9="MenuSeparator",BR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(it.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});BR.displayName=U9;var $9="MenuArrow",UR=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=wd(n);return s.jsx(wg,{...a,...r,ref:t})});UR.displayName=$9;var H9="MenuSub",[ude,$R]=Es(H9),uo="MenuSubTrigger",HR=y.forwardRef((e,t)=>{const n=vs(uo,e.__scopeMenu),r=ml(uo,e.__scopeMenu),a=$R(uo,e.__scopeMenu),i=Ag(uo,e.__scopeMenu),o=y.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,u={__scopeMenu:e.__scopeMenu},p=y.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return y.useEffect(()=>p,[p]),y.useEffect(()=>{const d=l.current;return()=>{window.clearTimeout(d),c(null)}},[l,c]),s.jsx(Ng,{asChild:!0,...u,children:s.jsx(IR,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":VR(n.open),...e,ref:Rn(t,a.onTriggerChange),onClick:d=>{e.onClick?.(d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ve(e.onPointerMove,Go(d=>{i.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(i.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:Ve(e.onPointerLeave,Go(d=>{p();const f=n.content?.getBoundingClientRect();if(f){const m=n.content?.dataset.side,h=m==="right",g=h?-5:5,b=f[h?"left":"right"],x=f[h?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+g,y:d.clientY},{x:b,y:f.top},{x,y:f.top},{x,y:f.bottom},{x:b,y:f.bottom}],side:m}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ve(e.onKeyDown,d=>{const f=i.searchRef.current!=="";e.disabled||f&&d.key===" "||S9[r.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});HR.displayName=uo;var zR="MenuSubContent",GR=y.forwardRef((e,t)=>{const n=AR(Jn,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,i=vs(Jn,e.__scopeMenu),o=ml(Jn,e.__scopeMenu),l=$R(zR,e.__scopeMenu),c=y.useRef(null),u=xt(t,c);return s.jsx(zo.Provider,{scope:e.__scopeMenu,children:s.jsx(er,{present:r||i.open,children:s.jsx(zo.Slot,{scope:e.__scopeMenu,children:s.jsx(_g,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:u,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{o.isUsingKeyboardRef.current&&c.current?.focus(),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:Ve(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ve(e.onEscapeKeyDown,p=>{o.onClose(),p.preventDefault()}),onKeyDown:Ve(e.onKeyDown,p=>{const d=p.currentTarget.contains(p.target),f=w9[o.dir].includes(p.key);d&&f&&(i.onOpenChange(!1),l.trigger?.focus(),p.preventDefault())})})})})})});GR.displayName=zR;function VR(e){return e?"open":"closed"}function vu(e){return e==="indeterminate"}function Ig(e){return vu(e)?"indeterminate":e?"checked":"unchecked"}function z9(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function G9(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function V9(e,t,n){const a=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=G9(e,Math.max(i,0));a.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function W9(e,t){const{x:n,y:r}=e;let a=!1;for(let i=0,o=t.length-1;i<t.length;o=i++){const l=t[i],c=t[o],u=l.x,p=l.y,d=c.x,f=c.y;p>r!=f>r&&n<(d-u)*(r-p)/(f-p)+u&&(a=!a)}return a}function q9(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return W9(n,t)}function Go(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Y9=CR,K9=Ng,X9=_R,Z9=RR,Q9=Rg,J9=kR,e$=Td,t$=DR,n$=LR,r$=MR,a$=FR,s$=BR,i$=UR,o$=HR,l$=GR,Nd="DropdownMenu",[c$]=Zr(Nd,[TR]),vn=TR(),[u$,WR]=c$(Nd),qR=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:o,modal:l=!0}=e,c=vn(t),u=y.useRef(null),[p,d]=pi({prop:a,defaultProp:i??!1,onChange:o,caller:Nd});return s.jsx(u$,{scope:t,triggerId:_n(),triggerRef:u,contentId:_n(),open:p,onOpenChange:d,onOpenToggle:y.useCallback(()=>d(f=>!f),[d]),modal:l,children:s.jsx(Y9,{...c,open:p,onOpenChange:d,dir:r,modal:l,children:n})})};qR.displayName=Nd;var YR="DropdownMenuTrigger",Dg=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,i=WR(YR,n),o=vn(n);return s.jsx(K9,{asChild:!0,...o,children:s.jsx(it.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Rn(t,i.triggerRef),onPointerDown:Ve(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:Ve(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});Dg.displayName=YR;var d$="DropdownMenuPortal",KR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=vn(t);return s.jsx(X9,{...r,...n})};KR.displayName=d$;var XR="DropdownMenuContent",ZR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=WR(XR,n),i=vn(n),o=y.useRef(!1);return s.jsx(Z9,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:Ve(e.onCloseAutoFocus,l=>{o.current||a.triggerRef.current?.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:Ve(e.onInteractOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,p=c.button===2||u;(!a.modal||p)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ZR.displayName=XR;var p$="DropdownMenuGroup",f$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(Q9,{...a,...r,ref:t})});f$.displayName=p$;var m$="DropdownMenuLabel",QR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(J9,{...a,...r,ref:t})});QR.displayName=m$;var h$="DropdownMenuItem",JR=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(e$,{...a,...r,ref:t})});JR.displayName=h$;var g$="DropdownMenuCheckboxItem",ek=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(t$,{...a,...r,ref:t})});ek.displayName=g$;var b$="DropdownMenuRadioGroup",x$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(n$,{...a,...r,ref:t})});x$.displayName=b$;var y$="DropdownMenuRadioItem",E$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(r$,{...a,...r,ref:t})});E$.displayName=y$;var v$="DropdownMenuItemIndicator",tk=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(a$,{...a,...r,ref:t})});tk.displayName=v$;var S$="DropdownMenuSeparator",nk=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(s$,{...a,...r,ref:t})});nk.displayName=S$;var w$="DropdownMenuArrow",T$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(i$,{...a,...r,ref:t})});T$.displayName=w$;var N$="DropdownMenuSubTrigger",C$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(o$,{...a,...r,ref:t})});C$.displayName=N$;var A$="DropdownMenuSubContent",_$=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=vn(n);return s.jsx(l$,{...a,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_$.displayName=A$;var R$=qR,k$=Dg,I$=KR,D$=ZR,O$=QR,L$=JR,j$=ek,M$=tk,P$=nk;function Or({...e}){return s.jsx(R$,{"data-slot":"dropdown-menu",...e})}function ea({...e}){return s.jsx(k$,{"data-slot":"dropdown-menu-trigger",...e})}function Lr({className:e,sideOffset:t=4,...n}){return s.jsx(I$,{children:s.jsx(D$,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Fe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...n})})}function Lt({className:e,inset:t,variant:n="default",...r}){return s.jsx(L$,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:Fe("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:ps-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r})}function rk({className:e,children:t,checked:n,...r}){return s.jsxs(j$,{"data-slot":"dropdown-menu-checkbox-item",className:Fe("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:n,...r,children:[s.jsx("span",{className:"pointer-events-none absolute start-2 flex size-3.5 items-center justify-center",children:s.jsx(M$,{children:s.jsx(Yt,{className:"size-4"})})}),t]})}function ak({className:e,inset:t,...n}){return s.jsx(O$,{"data-slot":"dropdown-menu-label","data-inset":t,className:Fe("px-2 py-1.5 text-sm font-medium data-[inset]:ps-8",e),...n})}function Ci({className:e,...t}){return s.jsx(P$,{"data-slot":"dropdown-menu-separator",className:Fe("bg-border -mx-1 my-1 h-px",e),...t})}function Bn({label:e,value:t,options:n,onValueChange:r,disabled:a,className:i,minWidth:o=132}){const c=(n.find(u=>u.value===t)??n[0])?.label??"";return s.jsxs(Or,{modal:!1,children:[s.jsx(ea,{asChild:!0,disabled:a,children:s.jsxs(ie,{type:"button",variant:"outline",size:"sm",className:Fe("h-9 justify-between gap-2 px-3 font-normal",i),style:{minWidth:o},disabled:a,children:[s.jsx("span",{children:c}),s.jsx(Ku,{className:"size-4 opacity-60","aria-hidden":"true"})]})}),s.jsxs(Lr,{align:"start",className:"w-[150px]",style:{minWidth:o},children:[e&&s.jsxs(s.Fragment,{children:[s.jsx(ak,{children:e}),s.jsx(Ci,{})]}),n.map(u=>s.jsx(rk,{className:"capitalize",checked:u.value===t,onSelect:()=>r(u.value),children:s.jsx("span",{children:u.label})},u.value||"all"))]})]})}function F$({open:e,incident:t,submitting:n,onClose:r,onSubmit:a}){const[i,o]=w.useState(""),[l,c]=w.useState(""),[u,p]=w.useState("Manual"),[d,f]=w.useState("P1"),[m,h]=w.useState(""),[g,b]=w.useState("open");w.useEffect(()=>{if(e){if(t){o(t.name||""),c(t.downMessage||""),p(t.source||"Manual"),f(t.tags?.priority||t.priority||"P2"),h(t.resourceName||""),b(t.status||"open");return}o(""),c(""),p("Manual"),f("P1"),h(""),b("open")}},[e,t]);const x=S=>{if(S.preventDefault(),!i.trim()){ae.error("Title is required");return}if(!t&&!m.trim()){ae.error("Affected resource is required");return}const T=t?.tags||{};a({name:i.trim(),downMessage:l.trim()||void 0,tags:{...T,priority:d},source:u.trim()||"Manual",resourceName:m.trim()||t?.resourceName,resourceType:"service",status:g})};return s.jsx(kt,{open:e,onOpenChange:S=>!S&&!n&&r(),children:s.jsxs(It,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:t?"Edit Incident":"Create Incident"}),s.jsx(Kt,{children:t?"Update incident details":"Manual incident raised outside the alarm pipeline"})]}),s.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4 mt-2",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Title ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{value:i,onChange:S=>o(S.target.value),placeholder:"Short description of the incident",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx("textarea",{value:l,onChange:S=>c(S.target.value),placeholder:"Markdown supported",rows:4,disabled:n,className:"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50 resize-none"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Priority ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Bn,{label:"Select priority",className:"im-single-select-full w-full",value:d,onValueChange:f,disabled:n,options:[{label:"P1",value:"P1"},{label:"P2",value:"P2"},{label:"P3",value:"P3"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source"}),s.jsx(Bn,{label:"Select source",className:"im-single-select-full w-full",value:u,onValueChange:p,disabled:n,options:[{label:"Manual",value:"Manual"},{label:"CloudWatch",value:"CloudWatch"},{label:"Prometheus",value:"Prometheus"},{label:"Datadog",value:"Datadog"},{label:"Grafana",value:"Grafana"}]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Affected Resource"}),s.jsx(Xe,{value:m,onChange:S=>h(S.target.value),placeholder:"Resource name or ID",disabled:n,className:"font-mono"})]}),t&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"State"}),s.jsx(Bn,{label:"Select state",className:"im-single-select-full w-full",value:g,onValueChange:S=>b(S),disabled:n,options:[{label:"Open",value:"open"},{label:"Investigating",value:"in_progress"},{label:"Resolved",value:"resolved"},{label:"Closed",value:"closed"}]})]})]}),s.jsxs($t,{children:[s.jsx(ie,{type:"button",variant:"outline",onClick:r,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",disabled:n,children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):t?"Save Changes":"Create Incident"})]})]})]})})}function xa(e,t){return typeof e=="function"?e(t):e}function zn(e,t){return n=>{t.setState(r=>({...r,[e]:xa(n,r[e])}))}}function Cd(e){return e instanceof Function}function B$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function U$(e,t){const n=[],r=a=>{a.forEach(i=>{n.push(i);const o=t(i);o!=null&&o.length&&r(o)})};return r(e),n}function rt(e,t,n){let r=[],a;return i=>{let o;n.key&&n.debug&&(o=Date.now());const l=e(i);if(!(l.length!==r.length||l.some((p,d)=>r[d]!==p)))return a;r=l;let u;if(n.key&&n.debug&&(u=Date.now()),a=t(...l),n==null||n.onChange==null||n.onChange(a),n.key&&n.debug&&n!=null&&n.debug()){const p=Math.round((Date.now()-o)*100)/100,d=Math.round((Date.now()-u)*100)/100,f=d/16,m=(h,g)=>{for(h=String(h);h.length<g;)h=" "+h;return h};console.info(`%c⏱ ${m(d,5)} /${m(p,5)} ms`,`
59
59
  font-size: .6rem;
60
60
  font-weight: bold;
61
61
  color: hsl(${Math.max(0,Math.min(120-120*f,120))}deg 100% 31%);`,n?.key)}return a}}function at(e,t,n,r){return{debug:()=>{var a;return(a=e?.debugAll)!=null?a:e[t]},key:process.env.NODE_ENV==="development"&&n,onChange:r}}function $$(e,t,n,r){const a=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:a,getContext:rt(()=>[e,n,t,i],(o,l,c,u)=>({table:o,column:l,row:c,cell:u,getValue:u.getValue,renderValue:u.renderValue}),at(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,n,t,e)},{}),i}function H$(e,t,n,r){var a,i;const l={...e._getDefaultColumnDef(),...t},c=l.accessorKey;let u=(a=(i=l.id)!=null?i:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?a:typeof l.header=="string"?l.header:void 0,p;if(l.accessorFn?p=l.accessorFn:c&&(c.includes(".")?p=f=>{let m=f;for(const g of c.split(".")){var h;m=(h=m)==null?void 0:h[g],process.env.NODE_ENV!=="production"&&m===void 0&&console.warn(`"${g}" in deeply nested key "${c}" returned undefined.`)}return m}:p=f=>f[l.accessorKey]),!u)throw process.env.NODE_ENV!=="production"?new Error(l.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let d={id:`${String(u)}`,accessorFn:p,parent:r,depth:n,columnDef:l,columns:[],getFlatColumns:rt(()=>[!0],()=>{var f;return[d,...(f=d.columns)==null?void 0:f.flatMap(m=>m.getFlatColumns())]},at(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:rt(()=>[e._getOrderColumnsFn()],f=>{var m;if((m=d.columns)!=null&&m.length){let h=d.columns.flatMap(g=>g.getLeafColumns());return f(h)}return[d]},at(e.options,"debugColumns","column.getLeafColumns"))};for(const f of e._features)f.createColumn==null||f.createColumn(d,e);return d}const un="debugHeaders";function P1(e,t,n){var r;let i={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const o=[],l=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(l),o.push(c)};return l(i),o},getContext:()=>({table:e,header:i,column:t})};return e._features.forEach(o=>{o.createHeader==null||o.createHeader(i,e)}),i}const z$={createTable:e=>{e.getHeaderGroups=rt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,a)=>{var i,o;const l=(i=r?.map(d=>n.find(f=>f.id===d)).filter(Boolean))!=null?i:[],c=(o=a?.map(d=>n.find(f=>f.id===d)).filter(Boolean))!=null?o:[],u=n.filter(d=>!(r!=null&&r.includes(d.id))&&!(a!=null&&a.includes(d.id)));return oc(t,[...l,...u,...c],e)},at(e.options,un,"getHeaderGroups")),e.getCenterHeaderGroups=rt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,a)=>(n=n.filter(i=>!(r!=null&&r.includes(i.id))&&!(a!=null&&a.includes(i.id))),oc(t,n,e,"center")),at(e.options,un,"getCenterHeaderGroups")),e.getLeftHeaderGroups=rt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var a;const i=(a=r?.map(o=>n.find(l=>l.id===o)).filter(Boolean))!=null?a:[];return oc(t,i,e,"left")},at(e.options,un,"getLeftHeaderGroups")),e.getRightHeaderGroups=rt(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var a;const i=(a=r?.map(o=>n.find(l=>l.id===o)).filter(Boolean))!=null?a:[];return oc(t,i,e,"right")},at(e.options,un,"getRightHeaderGroups")),e.getFooterGroups=rt(()=>[e.getHeaderGroups()],t=>[...t].reverse(),at(e.options,un,"getFooterGroups")),e.getLeftFooterGroups=rt(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),at(e.options,un,"getLeftFooterGroups")),e.getCenterFooterGroups=rt(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),at(e.options,un,"getCenterFooterGroups")),e.getRightFooterGroups=rt(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),at(e.options,un,"getRightFooterGroups")),e.getFlatHeaders=rt(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,un,"getFlatHeaders")),e.getLeftFlatHeaders=rt(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,un,"getLeftFlatHeaders")),e.getCenterFlatHeaders=rt(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,un,"getCenterFlatHeaders")),e.getRightFlatHeaders=rt(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,un,"getRightFlatHeaders")),e.getCenterLeafHeaders=rt(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,un,"getCenterLeafHeaders")),e.getLeftLeafHeaders=rt(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,un,"getLeftLeafHeaders")),e.getRightLeafHeaders=rt(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,un,"getRightLeafHeaders")),e.getLeafHeaders=rt(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var a,i,o,l,c,u;return[...(a=(i=t[0])==null?void 0:i.headers)!=null?a:[],...(o=(l=n[0])==null?void 0:l.headers)!=null?o:[],...(c=(u=r[0])==null?void 0:u.headers)!=null?c:[]].map(p=>p.getLeafHeaders()).flat()},at(e.options,un,"getLeafHeaders"))}};function oc(e,t,n,r){var a,i;let o=0;const l=function(f,m){m===void 0&&(m=1),o=Math.max(o,m),f.filter(h=>h.getIsVisible()).forEach(h=>{var g;(g=h.columns)!=null&&g.length&&l(h.columns,m+1)},0)};l(e);let c=[];const u=(f,m)=>{const h={depth:m,id:[r,`${m}`].filter(Boolean).join("_"),headers:[]},g=[];f.forEach(b=>{const x=[...g].reverse()[0],S=b.column.depth===h.depth;let T,N=!1;if(S&&b.column.parent?T=b.column.parent:(T=b.column,N=!0),x&&x?.column===T)x.subHeaders.push(b);else{const A=P1(n,T,{id:[r,m,T.id,b?.id].filter(Boolean).join("_"),isPlaceholder:N,placeholderId:N?`${g.filter(C=>C.column===T).length}`:void 0,depth:m,index:g.length});A.subHeaders.push(b),g.push(A)}h.headers.push(b),b.headerGroup=h}),c.push(h),m>0&&u(g,m-1)},p=t.map((f,m)=>P1(n,f,{depth:o,index:m}));u(p,o-1),c.reverse();const d=f=>f.filter(h=>h.column.getIsVisible()).map(h=>{let g=0,b=0,x=[0];h.subHeaders&&h.subHeaders.length?(x=[],d(h.subHeaders).forEach(T=>{let{colSpan:N,rowSpan:A}=T;g+=N,x.push(A)})):g=1;const S=Math.min(...x);return b=b+S,h.colSpan=g,h.rowSpan=b,{colSpan:g,rowSpan:b}});return d((a=(i=c[0])==null?void 0:i.headers)!=null?a:[]),c}const G$=(e,t,n,r,a,i,o)=>{let l={id:t,index:r,original:n,depth:a,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(l._valuesCache.hasOwnProperty(c))return l._valuesCache[c];const u=e.getColumn(c);if(u!=null&&u.accessorFn)return l._valuesCache[c]=u.accessorFn(l.original,r),l._valuesCache[c]},getUniqueValues:c=>{if(l._uniqueValuesCache.hasOwnProperty(c))return l._uniqueValuesCache[c];const u=e.getColumn(c);if(u!=null&&u.accessorFn)return u.columnDef.getUniqueValues?(l._uniqueValuesCache[c]=u.columnDef.getUniqueValues(l.original,r),l._uniqueValuesCache[c]):(l._uniqueValuesCache[c]=[l.getValue(c)],l._uniqueValuesCache[c])},renderValue:c=>{var u;return(u=l.getValue(c))!=null?u:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>U$(l.subRows,c=>c.subRows),getParentRow:()=>l.parentId?e.getRow(l.parentId,!0):void 0,getParentRows:()=>{let c=[],u=l;for(;;){const p=u.getParentRow();if(!p)break;c.push(p),u=p}return c.reverse()},getAllCells:rt(()=>[e.getAllLeafColumns()],c=>c.map(u=>$$(e,l,u,u.id)),at(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:rt(()=>[l.getAllCells()],c=>c.reduce((u,p)=>(u[p.column.id]=p,u),{}),at(e.options,"debugRows","getAllCellsByColumnId"))};for(let c=0;c<e._features.length;c++){const u=e._features[c];u==null||u.createRow==null||u.createRow(l,e)}return l},V$={createColumn:(e,t)=>{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},sk=(e,t,n)=>{var r,a;const i=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((a=e.getValue(t))==null||(a=a.toString())==null||(a=a.toLowerCase())==null)&&a.includes(i))};sk.autoRemove=e=>sr(e);const ik=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};ik.autoRemove=e=>sr(e);const ok=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};ok.autoRemove=e=>sr(e);const lk=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};lk.autoRemove=e=>sr(e);const ck=(e,t,n)=>!n.some(r=>{var a;return!((a=e.getValue(t))!=null&&a.includes(r))});ck.autoRemove=e=>sr(e)||!(e!=null&&e.length);const uk=(e,t,n)=>n.some(r=>{var a;return(a=e.getValue(t))==null?void 0:a.includes(r)});uk.autoRemove=e=>sr(e)||!(e!=null&&e.length);const dk=(e,t,n)=>e.getValue(t)===n;dk.autoRemove=e=>sr(e);const pk=(e,t,n)=>e.getValue(t)==n;pk.autoRemove=e=>sr(e);const Og=(e,t,n)=>{let[r,a]=n;const i=e.getValue(t);return i>=r&&i<=a};Og.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,a=typeof n!="number"?parseFloat(n):n,i=t===null||Number.isNaN(r)?-1/0:r,o=n===null||Number.isNaN(a)?1/0:a;if(i>o){const l=i;i=o,o=l}return[i,o]};Og.autoRemove=e=>sr(e)||sr(e[0])&&sr(e[1]);const Ur={includesString:sk,includesStringSensitive:ik,equalsString:ok,arrIncludes:lk,arrIncludesAll:ck,arrIncludesSome:uk,equals:dk,weakEquals:pk,inNumberRange:Og};function sr(e){return e==null||e===""}const W$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:zn("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?Ur.includesString:typeof r=="number"?Ur.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Ur.equals:Array.isArray(r)?Ur.arrIncludes:Ur.weakEquals},e.getFilterFn=()=>{var n,r;return Cd(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:Ur[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,a;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((a=t.options.enableFilters)!=null?a:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(a=>a.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const a=e.getFilterFn(),i=r?.find(p=>p.id===e.id),o=xa(n,i?i.value:void 0);if(F1(a,o,e)){var l;return(l=r?.filter(p=>p.id!==e.id))!=null?l:[]}const c={id:e.id,value:o};if(i){var u;return(u=r?.map(p=>p.id===e.id?c:p))!=null?u:[]}return r!=null&&r.length?[...r,c]:[c]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=a=>{var i;return(i=xa(t,a))==null?void 0:i.filter(o=>{const l=n.find(c=>c.id===o.id);if(l){const c=l.getFilterFn();if(F1(c,o.value,l))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function F1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const q$=(e,t,n)=>n.reduce((r,a)=>{const i=a.getValue(e);return r+(typeof i=="number"?i:0)},0),Y$=(e,t,n)=>{let r;return n.forEach(a=>{const i=a.getValue(e);i!=null&&(r>i||r===void 0&&i>=i)&&(r=i)}),r},K$=(e,t,n)=>{let r;return n.forEach(a=>{const i=a.getValue(e);i!=null&&(r<i||r===void 0&&i>=i)&&(r=i)}),r},X$=(e,t,n)=>{let r,a;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(r===void 0?o>=o&&(r=a=o):(r>o&&(r=o),a<o&&(a=o)))}),[r,a]},Z$=(e,t)=>{let n=0,r=0;if(t.forEach(a=>{let i=a.getValue(e);i!=null&&(i=+i)>=i&&(++n,r+=i)}),n)return r/n},Q$=(e,t)=>{if(!t.length)return;const n=t.map(i=>i.getValue(e));if(!B$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),a=n.sort((i,o)=>i-o);return n.length%2!==0?a[r]:(a[r-1]+a[r])/2},J$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),eH=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,tH=(e,t)=>t.length,df={sum:q$,min:Y$,max:K$,extent:X$,mean:Z$,median:Q$,unique:J$,uniqueCount:eH,count:tH},nH={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:zn("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return df.sum;if(Object.prototype.toString.call(r)==="[object Date]")return df.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Cd(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:df[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var a;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((a=n.subRows)!=null&&a.length)}}};function rH(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(i=>!t.includes(i.id));return n==="remove"?r:[...t.map(i=>e.find(o=>o.id===i)).filter(Boolean),...r]}const aH={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:zn("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=rt(n=>[go(t,n)],n=>n.findIndex(r=>r.id===e.id),at(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=n=>{var r;return((r=go(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const a=go(t,n);return((r=a[a.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=rt(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>a=>{let i=[];if(!(t!=null&&t.length))i=a;else{const o=[...t],l=[...a];for(;l.length&&o.length;){const c=o.shift(),u=l.findIndex(p=>p.id===c);u>-1&&i.push(l.splice(u,1)[0])}i=[...i,...l]}return rH(i,n,r)},at(e.options,"debugTable","_getOrderColumnsFn"))}},pf=()=>({left:[],right:[]}),sH={getInitialState:e=>({columnPinning:pf(),...e}),getDefaultOptions:e=>({onColumnPinningChange:zn("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(a=>a.id).filter(Boolean);t.setColumnPinning(a=>{var i,o;if(n==="right"){var l,c;return{left:((l=a?.left)!=null?l:[]).filter(d=>!(r!=null&&r.includes(d))),right:[...((c=a?.right)!=null?c:[]).filter(d=>!(r!=null&&r.includes(d))),...r]}}if(n==="left"){var u,p;return{left:[...((u=a?.left)!=null?u:[]).filter(d=>!(r!=null&&r.includes(d))),...r],right:((p=a?.right)!=null?p:[]).filter(d=>!(r!=null&&r.includes(d)))}}return{left:((i=a?.left)!=null?i:[]).filter(d=>!(r!=null&&r.includes(d))),right:((o=a?.right)!=null?o:[]).filter(d=>!(r!=null&&r.includes(d)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var a,i,o;return((a=r.columnDef.enablePinning)!=null?a:!0)&&((i=(o=t.options.enableColumnPinning)!=null?o:t.options.enablePinning)!=null?i:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(l=>l.id),{left:r,right:a}=t.getState().columnPinning,i=n.some(l=>r?.includes(l)),o=n.some(l=>a?.includes(l));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var n,r;const a=e.getIsPinned();return a?(n=(r=t.getState().columnPinning)==null||(r=r[a])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=rt(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,a)=>{const i=[...r??[],...a??[]];return n.filter(o=>!i.includes(o.column.id))},at(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=rt(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(i=>n.find(o=>o.column.id===i)).filter(Boolean).map(i=>({...i,position:"left"})),at(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=rt(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(i=>n.find(o=>o.column.id===i)).filter(Boolean).map(i=>({...i,position:"right"})),at(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?pf():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:pf())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var a,i;return!!((a=r.left)!=null&&a.length||(i=r.right)!=null&&i.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=rt(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(a=>a.id===r)).filter(Boolean),at(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=rt(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(a=>a.id===r)).filter(Boolean),at(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=rt(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const a=[...n??[],...r??[]];return t.filter(i=>!a.includes(i.id))},at(e.options,"debugColumns","getCenterLeafColumns"))}};function iH(e){return e||(typeof document<"u"?document:null)}const lc={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ff=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),oH={getDefaultColumnDef:()=>lc,getInitialState:e=>({columnSizing:{},columnSizingInfo:ff(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:zn("columnSizing",e),onColumnSizingInfoChange:zn("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,a;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:lc.minSize,(r=i??e.columnDef.size)!=null?r:lc.size),(a=e.columnDef.maxSize)!=null?a:lc.maxSize)},e.getStart=rt(n=>[n,go(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((a,i)=>a+i.getSize(),0),at(t.options,"debugColumns","getStart")),e.getAfter=rt(n=>[n,go(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((a,i)=>a+i.getSize(),0),at(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...a}=n;return a})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=a=>{if(a.subHeaders.length)a.subHeaders.forEach(r);else{var i;n+=(i=a.column.getSize())!=null?i:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),a=r?.getCanResize();return i=>{if(!r||!a||(i.persist==null||i.persist(),mf(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),l=e?e.getLeafHeaders().map(x=>[x.column.id,x.column.getSize()]):[[r.id,r.getSize()]],c=mf(i)?Math.round(i.touches[0].clientX):i.clientX,u={},p=(x,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(T=>{var N,A;const C=t.options.columnResizeDirection==="rtl"?-1:1,k=(S-((N=T?.startOffset)!=null?N:0))*C,O=Math.max(k/((A=T?.startSize)!=null?A:0),-.999999);return T.columnSizingStart.forEach(M=>{let[R,j]=M;u[R]=Math.round(Math.max(j+j*O,0)*100)/100}),{...T,deltaOffset:k,deltaPercentage:O}}),(t.options.columnResizeMode==="onChange"||x==="end")&&t.setColumnSizing(T=>({...T,...u})))},d=x=>p("move",x),f=x=>{p("end",x),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},m=iH(n),h={moveHandler:x=>d(x.clientX),upHandler:x=>{m?.removeEventListener("mousemove",h.moveHandler),m?.removeEventListener("mouseup",h.upHandler),f(x.clientX)}},g={moveHandler:x=>(x.cancelable&&(x.preventDefault(),x.stopPropagation()),d(x.touches[0].clientX),!1),upHandler:x=>{var S;m?.removeEventListener("touchmove",g.moveHandler),m?.removeEventListener("touchend",g.upHandler),x.cancelable&&(x.preventDefault(),x.stopPropagation()),f((S=x.touches[0])==null?void 0:S.clientX)}},b=lH()?{passive:!1}:!1;mf(i)?(m?.addEventListener("touchmove",g.moveHandler,b),m?.addEventListener("touchend",g.upHandler,b)):(m?.addEventListener("mousemove",h.moveHandler,b),m?.addEventListener("mouseup",h.upHandler,b)),t.setColumnSizingInfo(x=>({...x,startOffset:c,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ff():(n=e.initialState.columnSizingInfo)!=null?n:ff())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,a)=>r+a.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,a)=>r+a.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,a)=>r+a.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,a)=>r+a.getSize(),0))!=null?t:0}}};let cc=null;function lH(){if(typeof cc=="boolean")return cc;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return cc=e,cc}function mf(e){return e.type==="touchstart"}const cH={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:zn("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const a=e.columns;return(n=a.length?a.some(i=>i.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=rt(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),at(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=rt(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,a)=>[...n,...r,...a],at(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(n,r)=>rt(()=>[r(),r().filter(a=>a.getIsVisible()).map(a=>a.id).join("_")],a=>a.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),at(e.options,"debugColumns",n));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((a,i)=>({...a,[i.id]:n||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function go(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const uH={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},dH={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:zn("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,a,i;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((a=t.options.enableFilters)!=null?a:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>Ur.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Cd(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:Ur[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},pH={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:zn("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,a;if(!t){e._queue(()=>{t=!0});return}if((r=(a=e.options.autoResetAll)!=null?a:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var a,i;e.setExpanded(r?{}:(a=(i=e.initialState)==null?void 0:i.expanded)!=null?a:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(a=>!a.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(i=>{const o=i.split(".");r=Math.max(r,o.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var a;const i=r===!0?!0:!!(r!=null&&r[e.id]);let o={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(l=>{o[l]=!0}):o=r,n=(a=n)!=null?a:!i,!i&&n)return{...o,[e.id]:!0};if(i&&!n){const{[e.id]:l,...c}=o;return c}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,a;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((a=e.subRows)!=null&&a.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Hm=0,zm=10,hf=()=>({pageIndex:Hm,pageSize:zm}),fH={getInitialState:e=>({...e,pagination:{...hf(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:zn("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,a;if(!t){e._queue(()=>{t=!0});return}if((r=(a=e.options.autoResetAll)!=null?a:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const a=i=>xa(r,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(a)},e.resetPagination=r=>{var a;e.setPagination(r?hf():(a=e.initialState.pagination)!=null?a:hf())},e.setPageIndex=r=>{e.setPagination(a=>{let i=xa(r,a.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...a,pageIndex:i}})},e.resetPageIndex=r=>{var a,i;e.setPageIndex(r?Hm:(a=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?a:Hm)},e.resetPageSize=r=>{var a,i;e.setPageSize(r?zm:(a=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?a:zm)},e.setPageSize=r=>{e.setPagination(a=>{const i=Math.max(1,xa(r,a.pageSize)),o=a.pageSize*a.pageIndex,l=Math.floor(o/i);return{...a,pageIndex:l,pageSize:i}})},e.setPageCount=r=>e.setPagination(a=>{var i;let o=xa(r,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...a,pageCount:o}}),e.getPageOptions=rt(()=>[e.getPageCount()],r=>{let a=[];return r&&r>0&&(a=[...new Array(r)].fill(null).map((i,o)=>o)),a},at(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,a=e.getPageCount();return a===-1?!0:a===0?!1:r<a-1},e.previousPage=()=>e.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},gf=()=>({top:[],bottom:[]}),mH={getInitialState:e=>({rowPinning:gf(),...e}),getDefaultOptions:e=>({onRowPinningChange:zn("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,a)=>{const i=r?e.getLeafRows().map(c=>{let{id:u}=c;return u}):[],o=a?e.getParentRows().map(c=>{let{id:u}=c;return u}):[],l=new Set([...o,e.id,...i]);t.setRowPinning(c=>{var u,p;if(n==="bottom"){var d,f;return{top:((d=c?.top)!=null?d:[]).filter(g=>!(l!=null&&l.has(g))),bottom:[...((f=c?.bottom)!=null?f:[]).filter(g=>!(l!=null&&l.has(g))),...Array.from(l)]}}if(n==="top"){var m,h;return{top:[...((m=c?.top)!=null?m:[]).filter(g=>!(l!=null&&l.has(g))),...Array.from(l)],bottom:((h=c?.bottom)!=null?h:[]).filter(g=>!(l!=null&&l.has(g)))}}return{top:((u=c?.top)!=null?u:[]).filter(g=>!(l!=null&&l.has(g))),bottom:((p=c?.bottom)!=null?p:[]).filter(g=>!(l!=null&&l.has(g)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:a}=t.options;return typeof r=="function"?r(e):(n=r??a)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:a}=t.getState().rowPinning,i=n.some(l=>r?.includes(l)),o=n.some(l=>a?.includes(l));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const a=e.getIsPinned();if(!a)return-1;const i=(n=a==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(o=>{let{id:l}=o;return l});return(r=i?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?gf():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:gf())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var a,i;return!!((a=r.top)!=null&&a.length||(i=r.bottom)!=null&&i.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var a;return((a=e.options.keepPinnedRows)==null||a?(n??[]).map(o=>{const l=e.getRow(o,!0);return l.getIsAllParentsExpanded()?l:null}):(n??[]).map(o=>t.find(l=>l.id===o))).filter(Boolean).map(o=>({...o,position:r}))},e.getTopRows=rt(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),at(e.options,"debugRows","getTopRows")),e.getBottomRows=rt(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),at(e.options,"debugRows","getBottomRows")),e.getCenterRows=rt(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const a=new Set([...n??[],...r??[]]);return t.filter(i=>!a.has(i.id))},at(e.options,"debugRows","getCenterRows"))}},hH={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:zn("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},a=e.getPreGroupedRowModel().flatRows;return t?a.forEach(i=>{i.getCanSelect()&&(r[i.id]=!0)}):a.forEach(i=>{delete r[i.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),a={...n};return e.getRowModel().rows.forEach(i=>{Gm(a,i.id,r,!0,e)}),a}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=rt(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?bf(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=rt(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?bf(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=rt(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?bf(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(a=>a.getCanSelect()&&!n[a.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(a=>a.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(a=>!n[a.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const a=e.getIsSelected();t.setRowSelection(i=>{var o;if(n=typeof n<"u"?n:!a,e.getCanSelect()&&a===n)return i;const l={...i};return Gm(l,e.id,n,(o=r?.selectChildren)!=null?o:!0,t),l})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Lg(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Vm(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Vm(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var a;n&&e.toggleSelected((a=r.target)==null?void 0:a.checked)}}}},Gm=(e,t,n,r,a)=>{var i;const o=a.getRow(t,!0);n?(o.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),o.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(l=>Gm(e,l.id,n,r,a))};function bf(e,t){const n=e.getState().rowSelection,r=[],a={},i=function(o,l){return o.map(c=>{var u;const p=Lg(c,n);if(p&&(r.push(c),a[c.id]=c),(u=c.subRows)!=null&&u.length&&(c={...c,subRows:i(c.subRows)}),p)return c}).filter(Boolean)};return{rows:i(t.rows),flatRows:r,rowsById:a}}function Lg(e,t){var n;return(n=t[e.id])!=null?n:!1}function Vm(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let a=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!a)&&(o.getCanSelect()&&(Lg(o,t)?i=!0:a=!1),o.subRows&&o.subRows.length)){const l=Vm(o,t);l==="all"?i=!0:(l==="some"&&(i=!0),a=!1)}}),a?"all":i?"some":!1}const Wm=/([0-9]+)/gm,gH=(e,t,n)=>fk(Aa(e.getValue(n)).toLowerCase(),Aa(t.getValue(n)).toLowerCase()),bH=(e,t,n)=>fk(Aa(e.getValue(n)),Aa(t.getValue(n))),xH=(e,t,n)=>jg(Aa(e.getValue(n)).toLowerCase(),Aa(t.getValue(n)).toLowerCase()),yH=(e,t,n)=>jg(Aa(e.getValue(n)),Aa(t.getValue(n))),EH=(e,t,n)=>{const r=e.getValue(n),a=t.getValue(n);return r>a?1:r<a?-1:0},vH=(e,t,n)=>jg(e.getValue(n),t.getValue(n));function jg(e,t){return e===t?0:e>t?1:-1}function Aa(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function fk(e,t){const n=e.split(Wm).filter(Boolean),r=t.split(Wm).filter(Boolean);for(;n.length&&r.length;){const a=n.shift(),i=r.shift(),o=parseInt(a,10),l=parseInt(i,10),c=[o,l].sort();if(isNaN(c[0])){if(a>i)return 1;if(i>a)return-1;continue}if(isNaN(c[1]))return isNaN(o)?-1:1;if(o>l)return 1;if(l>o)return-1}return n.length-r.length}const Yi={alphanumeric:gH,alphanumericCaseSensitive:bH,text:xH,textCaseSensitive:yH,datetime:EH,basic:vH},SH={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:zn("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const a of n){const i=a?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return Yi.datetime;if(typeof i=="string"&&(r=!0,i.split(Wm).length>1))return Yi.alphanumeric}return r?Yi.text:Yi.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Cd(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Yi[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const a=e.getNextSortingOrder(),i=typeof n<"u"&&n!==null;t.setSorting(o=>{const l=o?.find(m=>m.id===e.id),c=o?.findIndex(m=>m.id===e.id);let u=[],p,d=i?n:a==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&r?l?p="toggle":p="add":o!=null&&o.length&&c!==o.length-1?p="replace":l?p="toggle":p="replace",p==="toggle"&&(i||a||(p="remove")),p==="add"){var f;u=[...o,{id:e.id,desc:d}],u.splice(0,u.length-((f=t.options.maxMultiSortColCount)!=null?f:Number.MAX_SAFE_INTEGER))}else p==="toggle"?u=o.map(m=>m.id===e.id?{...m,desc:d}:m):p==="remove"?u=o.filter(m=>m.id!==e.id):u=[{id:e.id,desc:d}];return u})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,a;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(a=t.options.enableMultiRemove)!=null)||a)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(a=>a.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(a=>a.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},wH=[z$,cH,aH,sH,V$,W$,uH,dH,SH,nH,pH,fH,mH,hH,oH];function TH(e){var t,n;process.env.NODE_ENV!=="production"&&(e.debugAll||e.debugTable)&&console.info("Creating Table Instance...");const r=[...wH,...(t=e._features)!=null?t:[]];let a={_features:r};const i=a._features.reduce((f,m)=>Object.assign(f,m.getDefaultOptions==null?void 0:m.getDefaultOptions(a)),{}),o=f=>a.options.mergeOptions?a.options.mergeOptions(i,f):{...i,...f};let c={...{},...(n=e.initialState)!=null?n:{}};a._features.forEach(f=>{var m;c=(m=f.getInitialState==null?void 0:f.getInitialState(c))!=null?m:c});const u=[];let p=!1;const d={_features:r,options:{...i,...e},initialState:c,_queue:f=>{u.push(f),p||(p=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();p=!1}).catch(m=>setTimeout(()=>{throw m})))},reset:()=>{a.setState(a.initialState)},setOptions:f=>{const m=xa(f,a.options);a.options=o(m)},getState:()=>a.options.state,setState:f=>{a.options.onStateChange==null||a.options.onStateChange(f)},_getRowId:(f,m,h)=>{var g;return(g=a.options.getRowId==null?void 0:a.options.getRowId(f,m,h))!=null?g:`${h?[h.id,m].join("."):m}`},getCoreRowModel:()=>(a._getCoreRowModel||(a._getCoreRowModel=a.options.getCoreRowModel(a)),a._getCoreRowModel()),getRowModel:()=>a.getPaginationRowModel(),getRow:(f,m)=>{let h=(m?a.getPrePaginationRowModel():a.getRowModel()).rowsById[f];if(!h&&(h=a.getCoreRowModel().rowsById[f],!h))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${f}`):new Error;return h},_getDefaultColumnDef:rt(()=>[a.options.defaultColumn],f=>{var m;return f=(m=f)!=null?m:{},{header:h=>{const g=h.header.column.columnDef;return g.accessorKey?g.accessorKey:g.accessorFn?g.id:null},cell:h=>{var g,b;return(g=(b=h.renderValue())==null||b.toString==null?void 0:b.toString())!=null?g:null},...a._features.reduce((h,g)=>Object.assign(h,g.getDefaultColumnDef==null?void 0:g.getDefaultColumnDef()),{}),...f}},at(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>a.options.columns,getAllColumns:rt(()=>[a._getColumnDefs()],f=>{const m=function(h,g,b){return b===void 0&&(b=0),h.map(x=>{const S=H$(a,x,b,g),T=x;return S.columns=T.columns?m(T.columns,S,b+1):[],S})};return m(f)},at(e,"debugColumns","getAllColumns")),getAllFlatColumns:rt(()=>[a.getAllColumns()],f=>f.flatMap(m=>m.getFlatColumns()),at(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:rt(()=>[a.getAllFlatColumns()],f=>f.reduce((m,h)=>(m[h.id]=h,m),{}),at(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:rt(()=>[a.getAllColumns(),a._getOrderColumnsFn()],(f,m)=>{let h=f.flatMap(g=>g.getLeafColumns());return m(h)},at(e,"debugColumns","getAllLeafColumns")),getColumn:f=>{const m=a._getAllFlatColumnsById()[f];return process.env.NODE_ENV!=="production"&&!m&&console.error(`[Table] Column with id '${f}' does not exist.`),m}};Object.assign(a,d);for(let f=0;f<a._features.length;f++){const m=a._features[f];m==null||m.createTable==null||m.createTable(a)}return a}function hl(){return e=>rt(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(a,i,o){i===void 0&&(i=0);const l=[];for(let u=0;u<a.length;u++){const p=G$(e,e._getRowId(a[u],u,o),a[u],u,i,void 0,o?.id);if(n.flatRows.push(p),n.rowsById[p.id]=p,l.push(p),e.options.getSubRows){var c;p.originalSubRows=e.options.getSubRows(a[u],u),(c=p.originalSubRows)!=null&&c.length&&(p.subRows=r(p.originalSubRows,i+1,p))}}return l};return n.rows=r(t),n},at(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function NH(e){const t=[],n=r=>{var a;t.push(r),(a=r.subRows)!=null&&a.length&&r.getIsExpanded()&&r.subRows.forEach(n)};return e.rows.forEach(n),{rows:t,flatRows:e.flatRows,rowsById:e.rowsById}}function mk(e){return t=>rt(()=>[t.getState().pagination,t.getPrePaginationRowModel(),t.options.paginateExpandedRows?void 0:t.getState().expanded],(n,r)=>{if(!r.rows.length)return r;const{pageSize:a,pageIndex:i}=n;let{rows:o,flatRows:l,rowsById:c}=r;const u=a*i,p=u+a;o=o.slice(u,p);let d;t.options.paginateExpandedRows?d={rows:o,flatRows:l,rowsById:c}:d=NH({rows:o,flatRows:l,rowsById:c}),d.flatRows=[];const f=m=>{d.flatRows.push(m),m.subRows.length&&m.subRows.forEach(f)};return d.rows.forEach(f),d},at(t.options,"debugTable","getPaginationRowModel"))}function Ad(){return e=>rt(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,a=[],i=r.filter(c=>{var u;return(u=e.getColumn(c.id))==null?void 0:u.getCanSort()}),o={};i.forEach(c=>{const u=e.getColumn(c.id);u&&(o[c.id]={sortUndefined:u.columnDef.sortUndefined,invertSorting:u.columnDef.invertSorting,sortingFn:u.getSortingFn()})});const l=c=>{const u=c.map(p=>({...p}));return u.sort((p,d)=>{for(let m=0;m<i.length;m+=1){var f;const h=i[m],g=o[h.id],b=g.sortUndefined,x=(f=h?.desc)!=null?f:!1;let S=0;if(b){const T=p.getValue(h.id),N=d.getValue(h.id),A=T===void 0,C=N===void 0;if(A||C){if(b==="first")return A?-1:1;if(b==="last")return A?1:-1;S=A&&C?0:A?b:-b}}if(S===0&&(S=g.sortingFn(p,d,h.id)),S!==0)return x&&(S*=-1),g.invertSorting&&(S*=-1),S}return p.index-d.index}),u.forEach(p=>{var d;a.push(p),(d=p.subRows)!=null&&d.length&&(p.subRows=l(p.subRows))}),u};return{rows:l(n.rows),flatRows:a,rowsById:n.rowsById}},at(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function Rr(e,t){return e?CH(e)?y.createElement(e,t):e:null}function CH(e){return AH(e)||typeof e=="function"||_H(e)}function AH(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function _H(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function gl(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=y.useState(()=>({current:TH(t)})),[r,a]=y.useState(()=>n.current.initialState);return n.current.setOptions(i=>({...i,...e,state:{...r,...e.state},onStateChange:o=>{a(o),e.onStateChange==null||e.onStateChange(o)}})),n.current}const Oa=y.forwardRef(({className:e,...t},n)=>s.jsx("div",{className:"relative w-full overflow-auto",children:s.jsx("table",{ref:n,className:Fe("w-full caption-bottom text-sm",e),...t})}));Oa.displayName="Table";const La=y.forwardRef(({className:e,...t},n)=>s.jsx("thead",{ref:n,className:Fe("[&_tr]:border-b",e),...t}));La.displayName="TableHeader";const ja=y.forwardRef(({className:e,...t},n)=>s.jsx("tbody",{ref:n,className:Fe("[&_tr:last-child]:border-0",e),...t}));ja.displayName="TableBody";const RH=y.forwardRef(({className:e,...t},n)=>s.jsx("tfoot",{ref:n,className:Fe("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));RH.displayName="TableFooter";const Ft=y.forwardRef(({className:e,...t},n)=>s.jsx("tr",{ref:n,className:Fe("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));Ft.displayName="TableRow";const gn=y.forwardRef(({className:e,...t},n)=>s.jsx("th",{ref:n,className:Fe("h-10 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));gn.displayName="TableHead";const Pt=y.forwardRef(({className:e,...t},n)=>s.jsx("td",{ref:n,className:Fe("p-4 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));Pt.displayName="TableCell";const kH=y.forwardRef(({className:e,...t},n)=>s.jsx("caption",{ref:n,className:Fe("mt-4 text-sm text-muted-foreground",e),...t}));kH.displayName="TableCaption";function bl({table:e,className:t}){const n=e.getState().pagination.pageIndex+1,r=e.getPageCount(),a=tA(n,r),i=e.getRowModel().rows.length>0,o=e.getState().pagination.pageSize,l=Array.from(new Set([5,10,20,30,40,50,o])).sort((c,u)=>c-u);return s.jsxs("div",{className:Fe("flex items-center justify-between overflow-clip px-2","@max-2xl/content:flex-col-reverse @max-2xl/content:gap-4",t),style:{overflowClipMargin:1},children:[s.jsxs("div",{className:"flex w-full items-center justify-between",children:[i&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",n," of ",r]}),s.jsxs("div",{className:"flex items-center gap-2 @max-2xl/content:flex-row-reverse",children:[s.jsxs(Fo,{value:`${o}`,onValueChange:c=>{e.setPageSize(Number(c))},children:[s.jsx(Uo,{className:"h-8 w-[70px]",children:s.jsx(Bo,{placeholder:`${o}`})}),s.jsx($o,{side:"top",children:l.map(c=>s.jsx(ba,{value:`${c}`,children:c},c))})]}),s.jsx("p",{className:"hidden text-sm font-medium sm:block",children:"Rows per page"})]})]}),s.jsxs("div",{className:"flex items-center sm:space-x-6 lg:space-x-8",children:[i&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",n," of ",r]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>e.setPageIndex(0),disabled:!e.getCanPreviousPage(),children:[s.jsx("span",{className:"sr-only",children:"Go to first page"}),s.jsx(NC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>e.previousPage(),disabled:!e.getCanPreviousPage(),children:[s.jsx("span",{className:"sr-only",children:"Go to previous page"}),s.jsx(wC,{className:"h-4 w-4"})]}),i&&a.map((c,u)=>s.jsx("div",{className:"flex items-center",children:c==="..."?s.jsx("span",{className:"text-muted-foreground px-1 text-sm",children:"..."}):s.jsxs(ie,{variant:n===c?"default":"outline",className:"h-8 min-w-8 px-2",onClick:()=>e.setPageIndex(c-1),children:[s.jsxs("span",{className:"sr-only",children:["Go to page ",c]}),c]})},`${c}-${u}`)),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>e.nextPage(),disabled:!e.getCanNextPage(),children:[s.jsx("span",{className:"sr-only",children:"Go to next page"}),s.jsx(TC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>e.setPageIndex(e.getPageCount()-1),disabled:!e.getCanNextPage(),children:[s.jsx("span",{className:"sr-only",children:"Go to last page"}),s.jsx(CC,{className:"h-4 w-4"})]})]})]})]})}function dt({column:e,title:t,className:n}){return e.getCanSort()?s.jsx("div",{className:Fe("flex items-center space-x-2",n),children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsxs(ie,{variant:"ghost",size:"sm",className:"data-[state=open]:bg-accent h-8",children:[s.jsx("span",{children:t}),e.getIsSorted()==="desc"?s.jsx(DS,{className:"ms-2 h-4 w-4"}):e.getIsSorted()==="asc"?s.jsx(OS,{className:"ms-2 h-4 w-4"}):s.jsx(AC,{className:"ms-2 h-4 w-4"})]})}),s.jsxs(Lr,{align:"start",children:[s.jsxs(Lt,{onClick:()=>e.toggleSorting(!1),children:[s.jsx(OS,{className:"text-muted-foreground/70 size-3.5"}),"Asc"]}),s.jsxs(Lt,{onClick:()=>e.toggleSorting(!0),children:[s.jsx(DS,{className:"text-muted-foreground/70 size-3.5"}),"Desc"]}),e.getCanHide()&&s.jsxs(s.Fragment,{children:[s.jsx(Ci,{}),s.jsxs(Lt,{onClick:()=>e.toggleVisibility(!1),children:[s.jsx(DF,{className:"text-muted-foreground/70 size-3.5"}),"Hide"]})]})]})]})}):s.jsx("div",{className:Fe(n),children:t})}const IH=rA("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function zt({className:e,variant:t,...n}){return s.jsx("div",{className:Fe(IH({variant:t}),e),...n})}function B1(e){if(!e)return"-";const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0"),a=t.getSeconds().toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),o=(t.getMonth()+1).toString().padStart(2,"0"),l=t.getFullYear();return`${i}/${o}/${l} ${n}:${r}:${a}`}const DH=e=>[{accessorKey:"aliasId",header:({column:t})=>s.jsx(dt,{column:t,title:"ID"}),cell:({row:t})=>{const n=t.original.aliasId||t.original.alias_id;return s.jsx(zt,{variant:"outline",className:"text-[10px] font-medium",children:n?`INC-${String(n).padStart(3,"0")}`:"-"})}},{accessorKey:"name",header:({column:t})=>s.jsx(dt,{column:t,title:"Name"}),cell:({row:t})=>{const n=t.getValue("name");return s.jsx("div",{className:"max-w-[200px] truncate font-medium text-sm",title:n,children:n})}},{accessorKey:"source",header:({column:t})=>s.jsx(dt,{column:t,title:"Source"}),cell:({row:t})=>s.jsx(zt,{variant:"outline",className:"text-[10px] font-medium uppercase",children:t.getValue("source")})},{accessorKey:"resourceName",header:({column:t})=>s.jsx(dt,{column:t,title:"Resource"}),cell:({row:t})=>{const n=t.original.resourceName||"—";return s.jsx("div",{className:"max-w-[180px] truncate text-sm",title:n,children:n})}},{accessorKey:"accountName",header:({column:t})=>s.jsx(dt,{column:t,title:"Account Name"}),cell:({row:t})=>{const n=t.original.accountName||t.original.account_name;return s.jsx("div",{className:"max-w-[160px] truncate text-sm font-medium",title:n||"—",children:n||"—"})}},{accessorKey:"accountId",header:({column:t})=>s.jsx(dt,{column:t,title:"Account ID"}),cell:({row:t})=>{const n=t.getValue("accountId")||t.original.account_id;return s.jsx("div",{className:"max-w-[140px] truncate font-mono text-xs text-muted-foreground",title:n||"—",children:n||"—"})}},{id:"tags",header:({column:t})=>s.jsx(dt,{column:t,title:"Tags"}),cell:({row:t})=>{const n=t.original.tags||{},r=Object.entries(n);return r.length===0?s.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):s.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[200px]",children:[r.slice(0,2).map(([a,i])=>s.jsxs(zt,{variant:"secondary",className:"text-[10px] px-1.5 py-0 font-mono max-w-[120px] truncate",title:`${a}:${i}`,children:[a,":",i]},a)),r.length>2&&s.jsxs("span",{className:"text-[10px] text-muted-foreground self-center",title:r.slice(2).map(([a,i])=>`${a}:${i}`).join(", "),children:["+",r.length-2]})]})}},{id:"assignee",header:({column:t})=>s.jsx(dt,{column:t,title:"Assigned"}),cell:({row:t})=>{const n=t.original;return s.jsx("div",{className:"p-1 -m-1 rounded-md",children:s.jsx(E_,{assigneeIds:n.assigneeIds,className:"text-xs"})})}},{accessorKey:"status",header:({column:t})=>s.jsx(dt,{column:t,title:"Status"}),cell:({row:t})=>s.jsx(Bm,{status:t.original.status||"open"})},{accessorKey:"createdAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Created At"}),cell:({row:t})=>s.jsx("div",{className:"text-sm text-muted-foreground whitespace-nowrap tabular-nums",children:B1(t.getValue("createdAt"))})},{accessorKey:"analysisCompletedAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Completed At"}),cell:({row:t})=>s.jsx("div",{className:"text-sm text-muted-foreground whitespace-nowrap tabular-nums",children:B1(t.getValue("analysisCompletedAt")||t.original.resolvedAt)})},{id:"ai",header:()=>s.jsx("span",{title:"AI analysis",style:{display:"flex",justifyContent:"center"},children:s.jsx(ho,{size:13,style:{opacity:.5}})}),cell:({row:t})=>{const n=t.original.analysisStatus;return n==="completed"?s.jsx("div",{title:"AI analysis complete",style:{display:"flex",justifyContent:"center"},children:s.jsx(ho,{size:15,style:{color:"var(--im-primary, #2563eb)"}})}):n==="triggered"||n==="processing"?s.jsx("div",{title:"Analysis running",style:{display:"flex",justifyContent:"center"},children:s.jsx(Qe,{size:13,className:"animate-spin",style:{color:"var(--im-primary, #2563eb)"}})}):s.jsx("div",{title:"No analysis",style:{display:"flex",justifyContent:"center"},children:s.jsx(ho,{size:15,style:{opacity:.2}})})},size:40,enableSorting:!1},{id:"actions",cell:({row:t})=>{const n=t.original;return s.jsx("div",{onClick:r=>r.stopPropagation(),children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx(ie,{variant:"ghost",size:"icon",className:"h-7 w-7",children:s.jsx(hs,{className:"h-4 w-4"})})}),s.jsx(Lr,{align:"end",children:s.jsxs(Lt,{onClick:()=>e.onEdit(n),children:[s.jsx(Ju,{className:"h-4 w-4 mr-2"})," Edit"]})})]})})}}];function OH({data:e,total:t,page:n,limit:r,loading:a,onPageChange:i,onLimitChange:o,onViewResult:l,onEdit:c,renderFilters:u}){const[p,d]=w.useState({}),[f,m]=w.useState([]),h=w.useMemo(()=>DH({onEdit:c}),[c]),g=Math.max(1,Math.ceil(t/r)),b=gl({data:e,columns:h,state:{pagination:{pageIndex:n-1,pageSize:r},columnVisibility:p,sorting:f},pageCount:g,manualPagination:!0,manualFiltering:!0,onSortingChange:m,getSortedRowModel:Ad(),onPaginationChange:x=>{const S=typeof x=="function"?x({pageIndex:n-1,pageSize:r}):x;S.pageIndex+1!==n&&i(S.pageIndex+1),S.pageSize!==r&&o(S.pageSize)},onColumnVisibilityChange:d,getCoreRowModel:hl()});return s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[u?.(b),a&&e.length===0?s.jsx(qr,{variant:"table"}):s.jsx("div",{className:"rounded-md border overflow-hidden bg-card text-card-foreground",children:s.jsxs(Oa,{children:[s.jsx(La,{children:b.getHeaderGroups().map(x=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:x.headers.map(S=>s.jsx(gn,{children:S.isPlaceholder?null:Rr(S.column.columnDef.header,S.getContext())},S.id))},x.id))}),s.jsx(ja,{children:b.getRowModel().rows?.length?b.getRowModel().rows.map(x=>s.jsx(Ft,{"data-state":x.getIsSelected()&&"selected",className:"cursor-pointer group/row hover:bg-muted/30",onClick:()=>l(x.original.id),children:x.getVisibleCells().map(S=>s.jsx(Pt,{children:Rr(S.column.columnDef.cell,S.getContext())},S.id))},x.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:h.length,className:"h-24 text-center",children:"No incidents found."})})})]})}),s.jsx(bl,{table:b,className:"mt-auto"})]})}function Mg({table:e}){return s.jsxs(Or,{modal:!1,children:[s.jsx(Dg,{asChild:!0,children:s.jsxs(ie,{variant:"outline",size:"sm",className:"ms-auto hidden h-8 lg:flex",children:[s.jsx(Gh,{className:"size-4"}),"Column Visibility"]})}),s.jsxs(Lr,{align:"end",className:"w-[150px]",children:[s.jsx(ak,{children:"Toggle columns"}),s.jsx(Ci,{}),e.getAllColumns().filter(t=>typeof t.accessorFn<"u"&&t.getCanHide()).map(t=>s.jsx(rk,{className:"capitalize",checked:t.getIsVisible(),onCheckedChange:n=>t.toggleVisibility(!!n),children:(()=>{const n=t.columnDef.header;return typeof n=="string"?n:t.id==="is_confirmed"?"Status":typeof n=="function"?t.id.charAt(0).toUpperCase()+t.id.slice(1).replace(/_/g," "):t.id})()},t.id))]})]})}var U1=1,LH=.9,jH=.8,MH=.17,xf=.1,yf=.999,PH=.9999,FH=.99,BH=/[\\\/_+.#"@\[\(\{&]/,UH=/[\\\/_+.#"@\[\(\{&]/g,$H=/[\s-]/,hk=/[\s-]/g;function qm(e,t,n,r,a,i,o){if(i===t.length)return a===e.length?U1:FH;var l=`${a},${i}`;if(o[l]!==void 0)return o[l];for(var c=r.charAt(i),u=n.indexOf(c,a),p=0,d,f,m,h;u>=0;)d=qm(e,t,n,r,u+1,i+1,o),d>p&&(u===a?d*=U1:BH.test(e.charAt(u-1))?(d*=jH,m=e.slice(a,u-1).match(UH),m&&a>0&&(d*=Math.pow(yf,m.length))):$H.test(e.charAt(u-1))?(d*=LH,h=e.slice(a,u-1).match(hk),h&&a>0&&(d*=Math.pow(yf,h.length))):(d*=MH,a>0&&(d*=Math.pow(yf,u-a))),e.charAt(u)!==t.charAt(i)&&(d*=PH)),(d<xf&&n.charAt(u-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&n.charAt(u-1)!==r.charAt(i))&&(f=qm(e,t,n,r,u+1,i+2,o),f*xf>d&&(d=f*xf)),d>p&&(p=d),u=n.indexOf(c,u+1);return o[l]=p,p}function $1(e){return e.toLowerCase().replace(hk," ")}function HH(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,qm(e,t,$1(e),$1(t),0,0,{})}var Ki='[cmdk-group=""]',Ef='[cmdk-group-items=""]',zH='[cmdk-group-heading=""]',gk='[cmdk-item=""]',H1=`${gk}:not([aria-disabled="true"])`,Ym="cmdk-item-select",Ws="data-value",GH=(e,t,n)=>HH(e,t,n),bk=y.createContext(void 0),xl=()=>y.useContext(bk),xk=y.createContext(void 0),Pg=()=>y.useContext(xk),yk=y.createContext(void 0),Ek=y.forwardRef((e,t)=>{let n=qs(()=>{var Z,D;return{search:"",value:(D=(Z=e.value)!=null?Z:e.defaultValue)!=null?D:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=qs(()=>new Set),a=qs(()=>new Map),i=qs(()=>new Map),o=qs(()=>new Set),l=vk(e),{label:c,children:u,value:p,onValueChange:d,filter:f,shouldFilter:m,loop:h,disablePointerSelection:g=!1,vimBindings:b=!0,...x}=e,S=_n(),T=_n(),N=_n(),A=y.useRef(null),C=tz();us(()=>{if(p!==void 0){let Z=p.trim();n.current.value=Z,k.emit()}},[p]),us(()=>{C(6,G)},[]);let k=y.useMemo(()=>({subscribe:Z=>(o.current.add(Z),()=>o.current.delete(Z)),snapshot:()=>n.current,setState:(Z,D,se)=>{var Q,ne,K,Y;if(!Object.is(n.current[Z],D)){if(n.current[Z]=D,Z==="search")U(),R(),C(1,j);else if(Z==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let J=document.getElementById(N);J?J.focus():(Q=document.getElementById(S))==null||Q.focus()}if(C(7,()=>{var J;n.current.selectedItemId=(J=q())==null?void 0:J.id,k.emit()}),se||C(5,G),((ne=l.current)==null?void 0:ne.value)!==void 0){let J=D??"";(Y=(K=l.current).onValueChange)==null||Y.call(K,J);return}}k.emit()}},emit:()=>{o.current.forEach(Z=>Z())}}),[]),O=y.useMemo(()=>({value:(Z,D,se)=>{var Q;D!==((Q=i.current.get(Z))==null?void 0:Q.value)&&(i.current.set(Z,{value:D,keywords:se}),n.current.filtered.items.set(Z,M(D,se)),C(2,()=>{R(),k.emit()}))},item:(Z,D)=>(r.current.add(Z),D&&(a.current.has(D)?a.current.get(D).add(Z):a.current.set(D,new Set([Z]))),C(3,()=>{U(),R(),n.current.value||j(),k.emit()}),()=>{i.current.delete(Z),r.current.delete(Z),n.current.filtered.items.delete(Z);let se=q();C(4,()=>{U(),se?.getAttribute("id")===Z&&j(),k.emit()})}),group:Z=>(a.current.has(Z)||a.current.set(Z,new Set),()=>{i.current.delete(Z),a.current.delete(Z)}),filter:()=>l.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:S,inputId:N,labelId:T,listInnerRef:A}),[]);function M(Z,D){var se,Q;let ne=(Q=(se=l.current)==null?void 0:se.filter)!=null?Q:GH;return Z?ne(Z,n.current.search,D):0}function R(){if(!n.current.search||l.current.shouldFilter===!1)return;let Z=n.current.filtered.items,D=[];n.current.filtered.groups.forEach(Q=>{let ne=a.current.get(Q),K=0;ne.forEach(Y=>{let J=Z.get(Y);K=Math.max(J,K)}),D.push([Q,K])});let se=A.current;P().sort((Q,ne)=>{var K,Y;let J=Q.getAttribute("id"),Ne=ne.getAttribute("id");return((K=Z.get(Ne))!=null?K:0)-((Y=Z.get(J))!=null?Y:0)}).forEach(Q=>{let ne=Q.closest(Ef);ne?ne.appendChild(Q.parentElement===ne?Q:Q.closest(`${Ef} > *`)):se.appendChild(Q.parentElement===se?Q:Q.closest(`${Ef} > *`))}),D.sort((Q,ne)=>ne[1]-Q[1]).forEach(Q=>{var ne;let K=(ne=A.current)==null?void 0:ne.querySelector(`${Ki}[${Ws}="${encodeURIComponent(Q[0])}"]`);K?.parentElement.appendChild(K)})}function j(){let Z=P().find(se=>se.getAttribute("aria-disabled")!=="true"),D=Z?.getAttribute(Ws);k.setState("value",D||void 0)}function U(){var Z,D,se,Q;if(!n.current.search||l.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ne=0;for(let K of r.current){let Y=(D=(Z=i.current.get(K))==null?void 0:Z.value)!=null?D:"",J=(Q=(se=i.current.get(K))==null?void 0:se.keywords)!=null?Q:[],Ne=M(Y,J);n.current.filtered.items.set(K,Ne),Ne>0&&ne++}for(let[K,Y]of a.current)for(let J of Y)if(n.current.filtered.items.get(J)>0){n.current.filtered.groups.add(K);break}n.current.filtered.count=ne}function G(){var Z,D,se;let Q=q();Q&&(((Z=Q.parentElement)==null?void 0:Z.firstChild)===Q&&((se=(D=Q.closest(Ki))==null?void 0:D.querySelector(zH))==null||se.scrollIntoView({block:"nearest"})),Q.scrollIntoView({block:"nearest"}))}function q(){var Z;return(Z=A.current)==null?void 0:Z.querySelector(`${gk}[aria-selected="true"]`)}function P(){var Z;return Array.from(((Z=A.current)==null?void 0:Z.querySelectorAll(H1))||[])}function z(Z){let D=P()[Z];D&&k.setState("value",D.getAttribute(Ws))}function re(Z){var D;let se=q(),Q=P(),ne=Q.findIndex(Y=>Y===se),K=Q[ne+Z];(D=l.current)!=null&&D.loop&&(K=ne+Z<0?Q[Q.length-1]:ne+Z===Q.length?Q[0]:Q[ne+Z]),K&&k.setState("value",K.getAttribute(Ws))}function B(Z){let D=q(),se=D?.closest(Ki),Q;for(;se&&!Q;)se=Z>0?JH(se,Ki):ez(se,Ki),Q=se?.querySelector(H1);Q?k.setState("value",Q.getAttribute(Ws)):re(Z)}let H=()=>z(P().length-1),I=Z=>{Z.preventDefault(),Z.metaKey?H():Z.altKey?B(1):re(1)},V=Z=>{Z.preventDefault(),Z.metaKey?z(0):Z.altKey?B(-1):re(-1)};return y.createElement(it.div,{ref:t,tabIndex:-1,...x,"cmdk-root":"",onKeyDown:Z=>{var D;(D=x.onKeyDown)==null||D.call(x,Z);let se=Z.nativeEvent.isComposing||Z.keyCode===229;if(!(Z.defaultPrevented||se))switch(Z.key){case"n":case"j":{b&&Z.ctrlKey&&I(Z);break}case"ArrowDown":{I(Z);break}case"p":case"k":{b&&Z.ctrlKey&&V(Z);break}case"ArrowUp":{V(Z);break}case"Home":{Z.preventDefault(),z(0);break}case"End":{Z.preventDefault(),H();break}case"Enter":{Z.preventDefault();let Q=q();if(Q){let ne=new Event(Ym);Q.dispatchEvent(ne)}}}}},y.createElement("label",{"cmdk-label":"",htmlFor:O.inputId,id:O.labelId,style:rz},c),_d(e,Z=>y.createElement(xk.Provider,{value:k},y.createElement(bk.Provider,{value:O},Z))))}),VH=y.forwardRef((e,t)=>{var n,r;let a=_n(),i=y.useRef(null),o=y.useContext(yk),l=xl(),c=vk(e),u=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:o?.forceMount;us(()=>{if(!u)return l.item(a,o?.id)},[u]);let p=Sk(a,i,[e.value,e.children,i],e.keywords),d=Pg(),f=_a(C=>C.value&&C.value===p.current),m=_a(C=>u||l.filter()===!1?!0:C.search?C.filtered.items.get(a)>0:!0);y.useEffect(()=>{let C=i.current;if(!(!C||e.disabled))return C.addEventListener(Ym,h),()=>C.removeEventListener(Ym,h)},[m,e.onSelect,e.disabled]);function h(){var C,k;g(),(k=(C=c.current).onSelect)==null||k.call(C,p.current)}function g(){d.setState("value",p.current,!0)}if(!m)return null;let{disabled:b,value:x,onSelect:S,forceMount:T,keywords:N,...A}=e;return y.createElement(it.div,{ref:Rn(i,t),...A,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!f,"data-disabled":!!b,"data-selected":!!f,onPointerMove:b||l.getDisablePointerSelection()?void 0:g,onClick:b?void 0:h},e.children)}),WH=y.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:a,...i}=e,o=_n(),l=y.useRef(null),c=y.useRef(null),u=_n(),p=xl(),d=_a(m=>a||p.filter()===!1?!0:m.search?m.filtered.groups.has(o):!0);us(()=>p.group(o),[]),Sk(o,l,[e.value,e.heading,c]);let f=y.useMemo(()=>({id:o,forceMount:a}),[a]);return y.createElement(it.div,{ref:Rn(l,t),...i,"cmdk-group":"",role:"presentation",hidden:d?void 0:!0},n&&y.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),_d(e,m=>y.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},y.createElement(yk.Provider,{value:f},m))))}),qH=y.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,a=y.useRef(null),i=_a(o=>!o.search);return!n&&!i?null:y.createElement(it.div,{ref:Rn(a,t),...r,"cmdk-separator":"",role:"separator"})}),YH=y.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,a=e.value!=null,i=Pg(),o=_a(u=>u.search),l=_a(u=>u.selectedItemId),c=xl();return y.useEffect(()=>{e.value!=null&&i.setState("search",e.value)},[e.value]),y.createElement(it.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":l,id:c.inputId,type:"text",value:a?e.value:o,onChange:u=>{a||i.setState("search",u.target.value),n?.(u.target.value)}})}),KH=y.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...a}=e,i=y.useRef(null),o=y.useRef(null),l=_a(u=>u.selectedItemId),c=xl();return y.useEffect(()=>{if(o.current&&i.current){let u=o.current,p=i.current,d,f=new ResizeObserver(()=>{d=requestAnimationFrame(()=>{let m=u.offsetHeight;p.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return f.observe(u),()=>{cancelAnimationFrame(d),f.unobserve(u)}}},[]),y.createElement(it.div,{ref:Rn(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":r,id:c.listId},_d(e,u=>y.createElement("div",{ref:Rn(o,c.listInnerRef),"cmdk-list-sizer":""},u)))}),XH=y.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:o,...l}=e;return y.createElement(rg,{open:n,onOpenChange:r},y.createElement(ag,{container:o},y.createElement(ld,{"cmdk-overlay":"",className:a}),y.createElement(cd,{"aria-label":e.label,"cmdk-dialog":"",className:i},y.createElement(Ek,{ref:t,...l}))))}),ZH=y.forwardRef((e,t)=>_a(n=>n.filtered.count===0)?y.createElement(it.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),QH=y.forwardRef((e,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=e;return y.createElement(it.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},_d(e,o=>y.createElement("div",{"aria-hidden":!0},o)))}),Ss=Object.assign(Ek,{List:KH,Item:VH,Input:YH,Group:WH,Separator:qH,Dialog:XH,Empty:ZH,Loading:QH});function JH(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function ez(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function vk(e){let t=y.useRef(e);return us(()=>{t.current=e}),t}var us=typeof window>"u"?y.useEffect:y.useLayoutEffect;function qs(e){let t=y.useRef();return t.current===void 0&&(t.current=e()),t}function _a(e){let t=Pg(),n=()=>e(t.snapshot());return y.useSyncExternalStore(t.subscribe,n,n)}function Sk(e,t,n,r=[]){let a=y.useRef(),i=xl();return us(()=>{var o;let l=(()=>{var u;for(let p of n){if(typeof p=="string")return p.trim();if(typeof p=="object"&&"current"in p)return p.current?(u=p.current.textContent)==null?void 0:u.trim():a.current}})(),c=r.map(u=>u.trim());i.value(e,l,c),(o=t.current)==null||o.setAttribute(Ws,l),a.current=l}),a}var tz=()=>{let[e,t]=y.useState(),n=qs(()=>new Map);return us(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,a)=>{n.current.set(r,a),t({})}};function nz(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function _d({asChild:e,children:t},n){return e&&y.isValidElement(t)?y.cloneElement(nz(t),{ref:t.ref},n(t.props.children)):n(t)}var rz={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function wk({className:e,...t}){return s.jsx(Ss,{"data-slot":"command",className:Fe("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...t})}function Tk({className:e,...t}){return s.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[s.jsx(gs,{className:"size-4 shrink-0 opacity-50"}),s.jsx(Ss.Input,{"data-slot":"command-input",className:Fe("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function Nk({className:e,...t}){return s.jsx(Ss.List,{"data-slot":"command-list",className:Fe("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function Ck({...e}){return s.jsx(Ss.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function Km({className:e,...t}){return s.jsx(Ss.Group,{"data-slot":"command-group",className:Fe("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function az({className:e,...t}){return s.jsx(Ss.Separator,{"data-slot":"command-separator",className:Fe("bg-border -mx-1 h-px",e),...t})}function Xm({className:e,...t}){return s.jsx(Ss.Item,{"data-slot":"command-item",className:Fe("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function sz(e){const t=iz(e),n=y.forwardRef((r,a)=>{const{children:i,...o}=r,l=y.Children.toArray(i),c=l.find(lz);if(c){const u=c.props.children,p=l.map(d=>d===c?y.Children.count(u)>1?y.Children.only(null):y.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...o,ref:a,children:y.isValidElement(u)?y.cloneElement(u,void 0,p):null})}return s.jsx(t,{...o,ref:a,children:i})});return n.displayName=`${e}.Slot`,n}function iz(e){const t=y.forwardRef((n,r)=>{const{children:a,...i}=n;if(y.isValidElement(a)){const o=uz(a),l=cz(i,a.props);return a.type!==y.Fragment&&(l.ref=r?Rn(r,o):o),y.cloneElement(a,l)}return y.Children.count(a)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var oz=Symbol("radix.slottable");function lz(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===oz}function cz(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function uz(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Rd="Popover",[Ak]=Zr(Rd,[Ti]),yl=Ti(),[dz,Ma]=Ak(Rd),_k=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:o=!1}=e,l=yl(t),c=y.useRef(null),[u,p]=y.useState(!1),[d,f]=pi({prop:r,defaultProp:a??!1,onChange:i,caller:Rd});return s.jsx(vg,{...l,children:s.jsx(dz,{scope:t,contentId:_n(),triggerRef:c,open:d,onOpenChange:f,onOpenToggle:y.useCallback(()=>f(m=>!m),[f]),hasCustomAnchor:u,onCustomAnchorAdd:y.useCallback(()=>p(!0),[]),onCustomAnchorRemove:y.useCallback(()=>p(!1),[]),modal:o,children:n})})};_k.displayName=Rd;var Rk="PopoverAnchor",pz=y.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,a=Ma(Rk,n),i=yl(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=a;return y.useEffect(()=>(o(),()=>l()),[o,l]),s.jsx(xd,{...i,...r,ref:t})});pz.displayName=Rk;var kk="PopoverTrigger",Ik=y.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,a=Ma(kk,n),i=yl(n),o=xt(t,a.triggerRef),l=s.jsx(it.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Mk(a.open),...r,ref:o,onClick:Ve(e.onClick,a.onOpenToggle)});return a.hasCustomAnchor?l:s.jsx(xd,{asChild:!0,...i,children:l})});Ik.displayName=kk;var Fg="PopoverPortal",[fz,mz]=Ak(Fg,{forceMount:void 0}),Dk=e=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=e,i=Ma(Fg,t);return s.jsx(fz,{scope:t,forceMount:n,children:s.jsx(er,{present:n||i.open,children:s.jsx(yd,{asChild:!0,container:a,children:r})})})};Dk.displayName=Fg;var hi="PopoverContent",Ok=y.forwardRef((e,t)=>{const n=mz(hi,e.__scopePopover),{forceMount:r=n.forceMount,...a}=e,i=Ma(hi,e.__scopePopover);return s.jsx(er,{present:r||i.open,children:i.modal?s.jsx(gz,{...a,ref:t}):s.jsx(bz,{...a,ref:t})})});Ok.displayName=hi;var hz=sz("PopoverContent.RemoveScroll"),gz=y.forwardRef((e,t)=>{const n=Ma(hi,e.__scopePopover),r=y.useRef(null),a=xt(t,r),i=y.useRef(!1);return y.useEffect(()=>{const o=r.current;if(o)return id(o)},[]),s.jsx(dl,{as:hz,allowPinchZoom:!0,children:s.jsx(Lk,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(e.onCloseAutoFocus,o=>{o.preventDefault(),i.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Ve(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Ve(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),bz=y.forwardRef((e,t)=>{const n=Ma(hi,e.__scopePopover),r=y.useRef(!1),a=y.useRef(!1);return s.jsx(Lk,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(r.current||n.triggerRef.current?.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const o=i.target;n.triggerRef.current?.contains(o)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Lk=y.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:p,...d}=e,f=Ma(hi,n),m=yl(n);return pg(),s.jsx(fd,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:s.jsx(pd,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:s.jsx(Sg,{"data-state":Mk(f.open),role:"dialog",id:f.contentId,...m,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),jk="PopoverClose",xz=y.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,a=Ma(jk,n);return s.jsx(it.button,{type:"button",...r,ref:t,onClick:Ve(e.onClick,()=>a.onOpenChange(!1))})});xz.displayName=jk;var yz="PopoverArrow",Ez=y.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,a=yl(n);return s.jsx(wg,{...a,...r,ref:t})});Ez.displayName=yz;function Mk(e){return e?"open":"closed"}var vz=_k,Sz=Ik,wz=Dk,Tz=Ok;function Bg({...e}){return s.jsx(vz,{"data-slot":"popover",...e})}function Ug({...e}){return s.jsx(Sz,{"data-slot":"popover-trigger",...e})}function $g({className:e,align:t="center",sideOffset:n=4,...r}){return s.jsx(wz,{children:s.jsx(Tz,{"data-slot":"popover-content",align:t,sideOffset:n,className:Fe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...r})})}var Nz=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Cz=Nz.reduce((e,t)=>{const n=Yh(`Primitive.${t}`),r=y.forwardRef((a,i)=>{const{asChild:o,...l}=a,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Az="Separator",z1="horizontal",_z=["horizontal","vertical"],Pk=y.forwardRef((e,t)=>{const{decorative:n,orientation:r=z1,...a}=e,i=Rz(r)?r:z1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return s.jsx(Cz.div,{"data-orientation":i,...l,...a,ref:t})});Pk.displayName=Az;function Rz(e){return _z.includes(e)}var Fk=Pk;const Bk=y.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},a)=>s.jsx(Fk,{ref:a,decorative:n,orientation:t,className:Fe("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Bk.displayName=Fk.displayName;function Qn({title:e,options:t,selected:n,onChange:r}){const a=new Set(n),i=o=>{const l=new Set(a);l.has(o)?l.delete(o):l.add(o),r(Array.from(l))};return s.jsxs(Bg,{children:[s.jsx(Ug,{asChild:!0,children:s.jsxs(ie,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[s.jsx(Gh,{className:"h-4 w-4 mr-2"}),e,a.size>0&&s.jsxs(s.Fragment,{children:[s.jsx(Bk,{orientation:"vertical",className:"mx-2 h-4"}),s.jsx(zt,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:a.size}),s.jsx("div",{className:"hidden space-x-1 lg:flex",children:a.size>2?s.jsxs(zt,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[a.size," selected"]}):t.filter(o=>a.has(o.value)).map(o=>s.jsx(zt,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:o.label},o.value))})]})]})}),s.jsx($g,{className:"w-[220px] p-0",align:"start",children:s.jsxs(wk,{children:[s.jsx(Tk,{placeholder:e}),s.jsxs(Nk,{children:[s.jsx(Ck,{children:"No results found."}),s.jsx(Km,{children:t.map(o=>{const l=a.has(o.value);return s.jsxs(Xm,{onSelect:()=>i(o.value),children:[s.jsx("div",{className:Fe("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",l?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:s.jsx(Yt,{className:"h-4 w-4"})}),o.icon&&s.jsx(o.icon,{className:"mr-2 h-4 w-4 text-muted-foreground"}),s.jsx("span",{children:o.label})]},o.value)})}),a.size>0&&s.jsxs(s.Fragment,{children:[s.jsx(az,{}),s.jsx(Km,{children:s.jsx(Xm,{onSelect:()=>r([]),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}function kz(e,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(e?.(a),n===!1||!a.defaultPrevented)return t?.(a)}}function G1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Iz(...e){return t=>{let n=!1;const r=e.map(a=>{const i=G1(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():G1(e[a],null)}}}}function Hg(...e){return y.useCallback(Iz(...e),e)}function Dz(e,t=[]){let n=[];function r(i,o){const l=y.createContext(o);l.displayName=i+"Context";const c=n.length;n=[...n,o];const u=d=>{const{scope:f,children:m,...h}=d,g=f?.[e]?.[c]||l,b=y.useMemo(()=>h,Object.values(h));return s.jsx(g.Provider,{value:b,children:m})};u.displayName=i+"Provider";function p(d,f){const m=f?.[e]?.[c]||l,h=y.useContext(m);if(h)return h;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,p]}const a=()=>{const i=n.map(o=>y.createContext(o));return function(l){const c=l?.[e]||i;return y.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return a.scopeName=e,[r,Oz(a,...t)]}function Oz(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((l,{useScope:c,scopeName:u})=>{const d=c(i)[`__scope${u}`];return{...l,...d}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}var Uk=globalThis?.document?y.useLayoutEffect:()=>{},Lz=y[" useInsertionEffect ".trim().toString()]||Uk;function jz({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,o]=Mz({defaultProp:t,onChange:n}),l=e!==void 0,c=l?e:a;{const p=y.useRef(e!==void 0);y.useEffect(()=>{const d=p.current;d!==l&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),p.current=l},[l,r])}const u=y.useCallback(p=>{if(l){const d=Pz(p)?p(e):p;d!==e&&o.current?.(d)}else i(p)},[l,e,i,o]);return[c,u]}function Mz({defaultProp:e,onChange:t}){const[n,r]=y.useState(e),a=y.useRef(n),i=y.useRef(t);return Lz(()=>{i.current=t},[t]),y.useEffect(()=>{a.current!==n&&(i.current?.(n),a.current=n)},[n,a]),[n,r,i]}function Pz(e){return typeof e=="function"}function Fz(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Bz(e){const[t,n]=y.useState(void 0);return Uk(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;o=u.inlineSize,l=u.blockSize}else o=e.offsetWidth,l=e.offsetHeight;n({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}function Uz(e){const t=y.forwardRef((n,r)=>{let{children:a,...i}=n,o=null,l=!1;const c=[];V1(a)&&typeof uc=="function"&&(a=uc(a._payload)),y.Children.forEach(a,f=>{if(Vz(f)){l=!0;const m=f;let h="child"in m.props?m.props.child:m.props.children;V1(h)&&typeof uc=="function"&&(h=uc(h._payload)),o=Hz(m,h),c.push(o?.props?.children)}else c.push(f)}),o?o=y.cloneElement(o,void 0,c):!l&&y.Children.count(a)===1&&y.isValidElement(a)&&(o=a);const u=o?Gz(o):void 0,p=Hg(r,u);if(!o){if(a||a===0)throw new Error(l?Kz(e):Yz(e));return a}const d=zz(i,o.props??{});return o.type!==y.Fragment&&(d.ref=r?p:u),y.cloneElement(o,d)});return t.displayName=`${e}.Slot`,t}var $z=Symbol.for("radix.slottable"),Hz=(e,t)=>{if("child"in e.props){const n=e.props.child;return y.isValidElement(n)?y.cloneElement(n,void 0,e.props.children(n.props.children)):null}return y.isValidElement(t)?t:null};function zz(e,t){const n={...t};for(const r in t){const a=e[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...l)=>{const c=i(...l);return a(...l),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...e,...n}}function Gz(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Vz(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$z}var Wz=Symbol.for("react.lazy");function V1(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Wz&&"_payload"in e&&qz(e._payload)}function qz(e){return typeof e=="object"&&e!==null&&"then"in e}var Yz=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Kz=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,uc=y[" use ".trim().toString()],Xz=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],zg=Xz.reduce((e,t)=>{const n=Uz(`Primitive.${t}`),r=y.forwardRef((a,i)=>{const{asChild:o,...l}=a,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),kd="Switch",[Zz]=Dz(kd),[Qz,Gg]=Zz(kd);function Jz(e){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:a,disabled:i,form:o,name:l,onCheckedChange:c,required:u,value:p="on",internal_do_not_use_render:d}=e,[f,m]=jz({prop:n,defaultProp:a??!1,onChange:c,caller:kd}),[h,g]=y.useState(null),[b,x]=y.useState(null),S=y.useRef(!1),T=h?!!o||!!h.closest("form"):!0,N={checked:f,setChecked:m,disabled:i,control:h,setControl:g,name:l,form:o,value:p,hasConsumerStoppedPropagationRef:S,required:u,defaultChecked:a,isFormControl:T,bubbleInput:b,setBubbleInput:x};return s.jsx(Qz,{scope:t,...N,children:eG(d)?d(N):r})}var $k="SwitchTrigger",Hk=y.forwardRef(({__scopeSwitch:e,onClick:t,...n},r)=>{const{value:a,disabled:i,checked:o,required:l,setControl:c,setChecked:u,hasConsumerStoppedPropagationRef:p,isFormControl:d,bubbleInput:f}=Gg($k,e),m=Hg(r,c);return s.jsx(zg.button,{type:"button",role:"switch","aria-checked":o,"aria-required":l,"data-state":qk(o),"data-disabled":i?"":void 0,disabled:i,value:a,...n,ref:m,onClick:kz(t,h=>{u(g=>!g),f&&d&&(p.current=h.isPropagationStopped(),p.current||h.stopPropagation())})})});Hk.displayName=$k;var Vg=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:o,disabled:l,value:c,onCheckedChange:u,form:p,...d}=e;return s.jsx(Jz,{__scopeSwitch:n,checked:a,defaultChecked:i,disabled:l,required:o,onCheckedChange:u,name:r,form:p,value:c,internal_do_not_use_render:({isFormControl:f})=>s.jsxs(s.Fragment,{children:[s.jsx(Hk,{...d,ref:t,__scopeSwitch:n}),f&&s.jsx(Wk,{__scopeSwitch:n})]})})});Vg.displayName=kd;var zk="SwitchThumb",Gk=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,a=Gg(zk,n);return s.jsx(zg.span,{"data-state":qk(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});Gk.displayName=zk;var Vk="SwitchBubbleInput",Wk=y.forwardRef(({__scopeSwitch:e,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:o,required:l,disabled:c,name:u,value:p,form:d,bubbleInput:f,setBubbleInput:m}=Gg(Vk,e),h=Hg(n,m),g=Fz(i),b=Bz(r);y.useEffect(()=>{const S=f;if(!S)return;const T=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(T,"checked").set,C=!a.current;if(g!==i&&A){const k=new Event("click",{bubbles:C});A.call(S,i),S.dispatchEvent(k)}},[f,g,i,a]);const x=y.useRef(i);return s.jsx(zg.input,{type:"checkbox","aria-hidden":!0,defaultChecked:o??x.current,required:l,disabled:c,name:u,value:p,form:d,...t,tabIndex:-1,ref:h,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Wk.displayName=Vk;function eG(e){return typeof e=="function"}function qk(e){return e?"checked":"unchecked"}const Wg=y.forwardRef(({className:e,...t},n)=>s.jsx(Vg,{className:Fe("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:s.jsx(Gk,{className:Fe("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Wg.displayName=Vg.displayName;const dc={statuses:[],assigneeIds:[],priorities:[],assignedToMe:!1};function tG(){return{statuses:[...dc.statuses],assigneeIds:[...dc.assigneeIds],priorities:[...dc.priorities],assignedToMe:dc.assignedToMe}}function nG({search:e,filters:t,loading:n,onSearchChange:r,onFiltersChange:a,onRefresh:i,children:o}){const{users:l}=Jh(),c=[{label:"P1",value:"P1"},{label:"P2",value:"P2"},{label:"P3",value:"P3"}],u=[{label:"Open",value:"open"},{label:"Investigating",value:"in_progress"},{label:"Resolved",value:"resolved"},{label:"Closed",value:"closed"}],p=[{label:"Unassigned",value:"unassigned"},...l.map(d=>({label:d.full_name||d.email||d.id,value:d.id}))];return s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{placeholder:"Search incidents...",value:e,onChange:d=>r(d.target.value),className:"h-9 w-[150px] lg:w-[250px] pl-8"}),e&&s.jsxs(ie,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground",onClick:()=>r(""),children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Clear"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Priority",options:c,selected:t.priorities,onChange:d=>a({...t,priorities:d})}),s.jsx(Qn,{title:"State",options:u,selected:t.statuses,onChange:d=>a({...t,statuses:d})}),s.jsx(Qn,{title:"Assignee",options:p,selected:t.assigneeIds,onChange:d=>a({...t,assigneeIds:d,assignedToMe:!1})}),s.jsxs("div",{className:"flex items-center space-x-2 ml-2",children:[s.jsx(Wg,{id:"assigned-to-me",checked:t.assignedToMe,onCheckedChange:d=>a({...t,assignedToMe:d,assigneeIds:[]})}),s.jsx(Pe,{htmlFor:"assigned-to-me",className:"text-sm cursor-pointer whitespace-nowrap text-muted-foreground",children:"Assigned to me"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ie,{variant:"outline",size:"sm",onClick:i,disabled:n,className:"h-8 hidden lg:flex",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",n&&"animate-spin")}),"Refresh"]}),o]})]})}function rG(e){const t=String(e.tags?.priority||e.tags?.severity||"").toUpperCase();return t==="P1"||t==="CRITICAL"||e.status==="in_progress"?"P1":t==="P3"||t==="LOW"||e.status==="resolved"?"P3":"P2"}function aG({onViewResult:e,incidentType:t,sourceTypes:n}){const[r,a]=w.useState([]),[i,o]=w.useState(0),[l,c]=w.useState(!0),[u,p]=w.useState(1),[d,f]=w.useState(""),[m,h]=w.useState(""),[g,b]=w.useState(()=>tG()),[x,S]=w.useState(null),[T,N]=w.useState(!1),[A,C]=w.useState(!1),{userId:k}=ur(),[O,M]=w.useState(10);w.useEffect(()=>{const z=setTimeout(()=>{h(d),p(1)},350);return()=>clearTimeout(z)},[d]);const R=z=>{b(z),p(1)},j=(n??[]).join(",");w.useEffect(()=>{p(1)},[t,j]);const U=w.useCallback(async(z=!1)=>{z||c(!0);try{const re={page:u,limit:O};m&&(re.search=m),g.statuses.length>0&&(re.status=g.statuses.join(",")),g.assignedToMe&&k?re.assigneeId=k:g.assigneeIds.length>0&&(re.assigneeId=g.assigneeIds.join(",")),t&&(re.incidentType=t),n&&n.length>0&&(re.sourceTypes=n);const B=await Ie.listIncidents(re),H=g.priorities.length?(B.incidents??[]).filter(I=>g.priorities.includes(rG(I))):B.incidents??[];a(H),o(g.priorities.length?H.length:B.total??0)}catch{ae.error("Failed to load incidents")}finally{z||c(!1)}},[u,O,m,g,t,j]);w.useEffect(()=>{U(!!m)},[U,m]);const G=()=>{S(null),N(!0)},q=z=>{S(z),N(!0)},P=async z=>{C(!0);try{x?(await Ie.updateIncident(x.id,z),ae.success("Incident updated")):(await Ie.createIncident({name:z.name,source:z.source||"Manual",resourceName:z.resourceName,resourceType:z.resourceType||"service",downMessage:z.downMessage,tags:z.tags||{}}),ae.success("Incident created")),N(!1),S(null),U()}catch(re){ae.error(re?.response?.data?.error||"Failed to save incident")}finally{C(!1)}};return s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{children:s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Incidents"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"All incidents for this workspace"})]}),s.jsxs(ie,{onClick:G,children:[s.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Create incident"]})]})}),s.jsx(OH,{data:r,total:i,page:u,limit:O,loading:l,onPageChange:p,onLimitChange:z=>{M(z),p(1)},onViewResult:e,onEdit:q,renderFilters:z=>s.jsx(nG,{search:d,filters:g,loading:l,onSearchChange:f,onFiltersChange:R,onRefresh:()=>U(),children:s.jsx(Mg,{table:z})})}),s.jsx(F$,{open:T,incident:x,submitting:A,onClose:()=>{N(!1),S(null)},onSubmit:P})]})}function sG(e){if(!e)return"";const t=Date.now()-new Date(e).getTime(),n=Math.max(1,Math.floor(t/6e4));return n<60?`${n}m`:`${Math.floor(n/60)}h ${n%60}m`}function vf(e){return!e||e<1?"—":e<60?`${e}m`:`${Math.floor(e/60)}h ${e%60}m`}function iG(e){if(!e)return"";const t=new Date(e);return`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`}function oG(e){return e==="in_progress"?"Investigating":e==="resolved"?"Resolved":"Open"}function lG(e,t){return t?`INC-${String(t).padStart(3,"0")}`:e.slice(0,7)}const cG={created:{color:"#922B21",title:"Incident created"},ai_completed:{color:"#7048C4",title:"AI Insight completed"},investigating:{color:"#E67E22",title:"Moved to Investigating"},resolved:{color:"#1E8449",title:"Incident resolved"}},uG={cloudwatch:"#E67E22",prometheus:"#8E44AD",datadog:"#7048C4",grafana:"#C0392B",meyi_pulse:"#1A5276",custom:"#5a6b7b"},dG=["S","M","T","W","T","F","S"],W1={stats:{p1:0,p2:0,unacked:0,mttrMinutes:0,resolvedToday:0},openIncidents:[],activity:[]},q1={range:"7d",totals:{total:0,mttaMinutes:0,mttrMinutes:0,repeat:0,sla:0,aiPct:0},timeline:[],bySource:[],topResources:[]};function pG({initialView:e="overview",onViewIncident:t,onViewList:n,incidentType:r,sourceTypes:a}){const[i,o]=w.useState(e),[l,c]=w.useState(W1),[u,p]=w.useState(!0),[d,f]=w.useState(q1),[m,h]=w.useState("7d"),[g,b]=w.useState(!0);w.useEffect(()=>{if(i!=="overview")return;let j=!1;const U=()=>{Ie.getIncidentDashboard({incidentType:r,sourceTypes:a}).then(q=>{j||c({stats:q.stats,openIncidents:q.openIncidents,activity:q.activity})}).catch(()=>{j||c(W1)}).finally(()=>{j||p(!1)})};U();const G=setInterval(U,3e4);return()=>{j=!0,clearInterval(G)}},[i,r,a]),w.useEffect(()=>{if(i!=="analytics")return;let j=!1;return b(!0),Ie.getIncidentAnalytics(m,{incidentType:r,sourceTypes:a}).then(U=>{j||f(U)}).catch(()=>{j||f(q1)}).finally(()=>{j||b(!1)}),()=>{j=!0}},[i,m,r,a]);const{stats:x,openIncidents:S,activity:T}=l,{totals:N,timeline:A,bySource:C,topResources:k}=d,O=m==="30d"?(()=>{const j=[];for(let U=0;U<A.length;U+=3){const G=A.slice(U,U+3);j.push({label:"",count:G.reduce((q,P)=>q+P.count,0)})}return j})():A.map(j=>({label:dG[new Date(j.date).getDay()],count:j.count})),M=Math.max(1,...O.map(j=>j.count)),R=Math.max(1,...k.map(j=>j.value));return s.jsxs("div",{className:"im-page im-wide-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:i==="analytics"?"Incident analytics":"Incident dashboard"}),s.jsx("p",{children:i==="analytics"?"MTTR, sources, and trends":"Real-time overview - auto-refreshing every 30s"})]}),s.jsxs("div",{className:"im-filters-actions flex items-center gap-2",children:[i==="analytics"&&s.jsx(Bn,{label:"Select range",value:m,onValueChange:h,options:[{label:"Last 7 days",value:"7d"},{label:"Last 30 days",value:"30d"}]}),s.jsx(ie,{variant:i==="analytics"?"default":"outline",size:"sm",className:"h-8 gap-1.5",onClick:()=>o(j=>j==="analytics"?"overview":"analytics"),children:i==="analytics"?s.jsxs(s.Fragment,{children:[s.jsx(Ta,{className:"h-4 w-4"})," Live Dashboard"]}):s.jsxs(s.Fragment,{children:[s.jsx(XP,{className:"h-4 w-4"})," Analytics"]})}),n&&s.jsxs(ie,{variant:"outline",size:"sm",className:"h-8 gap-1.5",onClick:n,children:[s.jsx(LC,{className:"h-4 w-4"})," Incident list"]})]})]}),i==="overview"?u?s.jsx(qr,{variant:"dashboard"}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-dashboard-stats",children:[s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Active P1"}),s.jsx("strong",{className:"im-danger-text",children:x.p1})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Active P2"}),s.jsx("strong",{className:"im-accent-text",children:x.p2})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Unacked > 15m"}),s.jsx("strong",{className:"im-danger-text",children:x.unacked})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Avg MTTR today"}),s.jsx("strong",{children:vf(x.mttrMinutes)})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Resolved today"}),s.jsx("strong",{className:"im-success-text",children:x.resolvedToday})]})]}),s.jsxs("div",{className:"im-dashboard-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsxs("div",{className:"im-panel-header",children:[s.jsxs("h3",{children:["Open incidents ",s.jsx("span",{children:S.length})]}),s.jsx("b",{children:"Live"})]}),s.jsx("div",{className:"im-incident-feed",children:S.length===0?s.jsx("div",{className:"im-empty-panel",children:s.jsx("p",{children:"No open incidents."})}):S.map(j=>s.jsxs("button",{type:"button",onClick:()=>t?.(j.id),className:"im-feed-row",children:[s.jsx("span",{className:`im-priority-pill im-priority-${j.priority.toLowerCase()}`,children:j.priority}),s.jsxs("span",{className:"im-feed-main",children:[s.jsx("strong",{children:j.name}),s.jsxs("small",{children:[lG(j.id,j.aliasId)," - ",j.resourceName," -"," ",sG(j.createdAt)]})]}),s.jsx("span",{className:`im-incident-state im-incident-state-${j.status}`,children:oG(j.status)}),s.jsx("i",{className:"im-avatar-dot",children:j.assigneeIds?.[0]?.slice(0,2).toUpperCase()||""})]},j.id))})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx("div",{className:"im-panel-header",children:s.jsx("h3",{children:"Recent activity"})}),s.jsx("div",{className:"im-activity-feed",children:T.length===0?s.jsx("div",{className:"im-empty-panel",children:s.jsx("p",{children:"No recent activity."})}):T.map((j,U)=>{const G=cG[j.kind]??{color:"#5a6b7b",title:j.kind};return s.jsxs("div",{className:"im-activity-row",children:[s.jsx("i",{style:{backgroundColor:G.color}}),s.jsxs("div",{children:[s.jsx("strong",{children:G.title}),s.jsxs("span",{children:[iG(j.t)," - ",j.label," - ",j.resourceName]})]})]},`${j.kind}-${j.t}-${U}`)})})]})]})]}):g?s.jsx(qr,{variant:"analytics"}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-dashboard-stats im-six-stats",children:[s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Total incidents"}),s.jsx("strong",{children:N.total})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"MTTA"}),s.jsx("strong",{children:vf(N.mttaMinutes)})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"MTTR"}),s.jsx("strong",{children:vf(N.mttrMinutes)})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Repeat incidents"}),s.jsx("strong",{children:N.repeat})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"SLA breaches"}),s.jsx("strong",{children:N.sla})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"AI insight usage"}),s.jsxs("strong",{children:[N.aiPct,"%"]})]})]}),s.jsxs("div",{className:"im-analytics-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx("h3",{children:"Incidents over time"}),s.jsx("div",{className:"im-analytics-bars",children:O.length===0?s.jsx("div",{className:"im-empty-panel",children:s.jsx("p",{children:"No data for this range."})}):O.map((j,U)=>s.jsxs("div",{children:[s.jsx("span",{style:{height:Math.round(j.count/M*160)||2},title:`${j.count} incidents`}),s.jsx("small",{children:j.label})]},U))})]}),s.jsxs("section",{className:"im-panel",children:[s.jsx("h3",{children:"Incidents by source"}),C.length===0?s.jsx("div",{className:"im-empty-panel",children:s.jsx("p",{children:"No data for this range."})}):C.map(({label:j,pct:U})=>s.jsxs("div",{className:"im-source-bar",children:[s.jsxs("div",{children:[s.jsx("span",{style:{textTransform:"capitalize"},children:j}),s.jsxs("b",{children:[U,"%"]})]}),s.jsx("i",{children:s.jsx("em",{style:{width:`${U}%`,backgroundColor:uG[j]||"#5a6b7b"}})})]},j))]})]}),s.jsxs("section",{className:"im-panel im-resource-panel",children:[s.jsx("h3",{children:"Top affected resources"}),k.length===0?s.jsx("div",{className:"im-empty-panel",children:s.jsx("p",{children:"No data for this range."})}):k.map(j=>s.jsxs("div",{className:"im-resource-row",children:[s.jsx("span",{children:j.name}),s.jsx("i",{children:s.jsx("em",{style:{width:`${Math.max(8,Math.round(j.value/R*100))}%`}})}),s.jsx("b",{children:j.value})]},j.name))]})]})]})}const fG={security:{title:"Security Incidents Coming Soon",description:"Security incident sources like GuardDuty and Security Hub will be integrated here.",icon:s.jsx(il,{className:"h-12 w-12 text-slate-400 mb-4"})},cost:{title:"Cost Incidents Coming Soon",description:"Cost anomalies and budget alerts will be integrated here.",icon:s.jsx(NF,{className:"h-12 w-12 text-slate-400 mb-4"})}};function Sf({category:e,onViewResult:t}){const n=Dh({strict:!1}),r=St(),a=n.tab||"list",i=o=>{r({search:{tab:o}})};if(e!=="operations"){const o=fG[e];return s.jsxs("div",{className:"flex flex-col items-center justify-center h-full pt-32 text-center",children:[o?.icon||s.jsx(lF,{className:"h-12 w-12 text-slate-400 mb-4"}),s.jsx("h2",{className:"text-xl font-semibold mb-2",children:o?.title||"Coming Soon"}),s.jsx("p",{className:"text-slate-500 max-w-md",children:o?.description||"This category is not yet available."})]})}return s.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[s.jsx("div",{className:"px-6 py-4 border-b",children:s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold capitalize tracking-tight",children:e}),s.jsxs("p",{className:"text-muted-foreground text-sm mt-0.5",children:["Manage and resolve ",e," incidents"]})]}),s.jsxs("div",{className:"flex bg-muted/50 p-1 rounded-md border",children:[s.jsxs(ie,{size:"sm",variant:a==="list"?"secondary":"ghost",onClick:()=>i("list"),children:[s.jsx(LC,{className:"h-4 w-4 mr-2"})," Incidents"]}),s.jsxs(ie,{size:"sm",variant:a==="dashboard"?"secondary":"ghost",onClick:()=>i("dashboard"),children:[s.jsx(qF,{className:"h-4 w-4 mr-2"})," Dashboard"]})]})]})}),s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-6",children:[a==="list"&&s.jsx(aG,{onViewResult:t,incidentType:e}),a==="dashboard"&&s.jsx(pG,{onViewIncident:t,onViewList:()=>i("list"),incidentType:e})]})]})}const kr=Object.create(null);kr.open="0";kr.close="1";kr.ping="2";kr.pong="3";kr.message="4";kr.upgrade="5";kr.noop="6";const Gc=Object.create(null);Object.keys(kr).forEach(e=>{Gc[kr[e]]=e});const Zm={type:"error",data:"parser error"},Yk=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Kk=typeof ArrayBuffer=="function",Xk=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,qg=({type:e,data:t},n,r)=>Yk&&t instanceof Blob?n?r(t):Y1(t,r):Kk&&(t instanceof ArrayBuffer||Xk(t))?n?r(t):Y1(new Blob([t]),r):r(kr[e]+(t||"")),Y1=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function K1(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let wf;function mG(e,t){if(Yk&&e.data instanceof Blob)return e.data.arrayBuffer().then(K1).then(t);if(Kk&&(e.data instanceof ArrayBuffer||Xk(e.data)))return t(K1(e.data));qg(e,!1,n=>{wf||(wf=new TextEncoder),t(wf.encode(n))})}const X1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",po=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<X1.length;e++)po[X1.charCodeAt(e)]=e;const hG=e=>{let t=e.length*.75,n=e.length,r,a=0,i,o,l,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),p=new Uint8Array(u);for(r=0;r<n;r+=4)i=po[e.charCodeAt(r)],o=po[e.charCodeAt(r+1)],l=po[e.charCodeAt(r+2)],c=po[e.charCodeAt(r+3)],p[a++]=i<<2|o>>4,p[a++]=(o&15)<<4|l>>2,p[a++]=(l&3)<<6|c&63;return u},gG=typeof ArrayBuffer=="function",Yg=(e,t)=>{if(typeof e!="string")return{type:"message",data:Zk(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:bG(e.substring(1),t)}:Gc[n]?e.length>1?{type:Gc[n],data:e.substring(1)}:{type:Gc[n]}:Zm},bG=(e,t)=>{if(gG){const n=hG(e);return Zk(n,t)}else return{base64:!0,data:e}},Zk=(e,t)=>t==="blob"?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Qk="",xG=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{qg(i,!1,l=>{r[o]=l,++a===n&&t(r.join(Qk))})})},yG=(e,t)=>{const n=e.split(Qk),r=[];for(let a=0;a<n.length;a++){const i=Yg(n[a],t);if(r.push(i),i.type==="error")break}return r};function EG(){return new TransformStream({transform(e,t){mG(e,n=>{const r=n.length;let a;if(r<126)a=new Uint8Array(1),new DataView(a.buffer).setUint8(0,r);else if(r<65536){a=new Uint8Array(3);const i=new DataView(a.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{a=new Uint8Array(9);const i=new DataView(a.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(a[0]|=128),t.enqueue(a),t.enqueue(n)})}})}let Tf;function pc(e){return e.reduce((t,n)=>t+n.length,0)}function fc(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let a=0;a<t;a++)n[a]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function vG(e,t){Tf||(Tf=new TextDecoder);const n=[];let r=0,a=-1,i=!1;return new TransformStream({transform(o,l){for(n.push(o);;){if(r===0){if(pc(n)<1)break;const c=fc(n,1);i=(c[0]&128)===128,a=c[0]&127,a<126?r=3:a===126?r=1:r=2}else if(r===1){if(pc(n)<2)break;const c=fc(n,2);a=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(pc(n)<8)break;const c=fc(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),p=u.getUint32(0);if(p>Math.pow(2,21)-1){l.enqueue(Zm);break}a=p*Math.pow(2,32)+u.getUint32(4),r=3}else{if(pc(n)<a)break;const c=fc(n,a);l.enqueue(Yg(i?c:Tf.decode(c),t)),r=0}if(a===0||a>e){l.enqueue(Zm);break}}}})}const Jk=4;function Gt(e){if(e)return SG(e)}function SG(e){for(var t in Gt.prototype)e[t]=Gt.prototype[t];return e}Gt.prototype.on=Gt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Gt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Gt.prototype.off=Gt.prototype.removeListener=Gt.prototype.removeAllListeners=Gt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,a=0;a<n.length;a++)if(r=n[a],r===t||r.fn===t){n.splice(a,1);break}return n.length===0&&delete this._callbacks["$"+e],this};Gt.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,a=n.length;r<a;++r)n[r].apply(this,t)}return this};Gt.prototype.emitReserved=Gt.prototype.emit;Gt.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Gt.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Id=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Kn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),wG="arraybuffer";function eI(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const TG=Kn.setTimeout,NG=Kn.clearTimeout;function Dd(e,t){t.useNativeTimers?(e.setTimeoutFn=TG.bind(Kn),e.clearTimeoutFn=NG.bind(Kn)):(e.setTimeoutFn=Kn.setTimeout.bind(Kn),e.clearTimeoutFn=Kn.clearTimeout.bind(Kn))}const CG=1.33;function AG(e){return typeof e=="string"?_G(e):Math.ceil((e.byteLength||e.size)*CG)}function _G(e){let t=0,n=0;for(let r=0,a=e.length;r<a;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function tI(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function RG(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function kG(e){let t={},n=e.split("&");for(let r=0,a=n.length;r<a;r++){let i=n[r].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class IG extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class Kg extends Gt{constructor(t){super(),this.writable=!1,Dd(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,r){return super.emitReserved("error",new IG(t,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=Yg(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=RG(t);return n.length?"?"+n:""}}class DG extends Kg{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};yG(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,xG(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=tI()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let nI=!1;try{nI=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const OG=nI;function LG(){}class jG extends DG{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(a,i)=>{this.onError("xhr post error",a,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class _r extends Gt{constructor(t,n,r){super(),this.createRequest=t,Dd(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=eI(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let a in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(a)&&r.setRequestHeader(a,this._opts.extraHeaders[a])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var a;r.readyState===3&&((a=this._opts.cookieJar)===null||a===void 0||a.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(a){this.setTimeoutFn(()=>{this._onError(a)},0);return}typeof document<"u"&&(this._index=_r.requestsCount++,_r.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=LG,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete _r.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}_r.requestsCount=0;_r.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Z1);else if(typeof addEventListener=="function"){const e="onpagehide"in Kn?"pagehide":"unload";addEventListener(e,Z1,!1)}}function Z1(){for(let e in _r.requests)_r.requests.hasOwnProperty(e)&&_r.requests[e].abort()}const MG=(function(){const e=rI({xdomain:!1});return e&&e.responseType!==null})();class PG extends jG{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=MG&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new _r(rI,this.uri(),t)}}function rI(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||OG))return new XMLHttpRequest}catch{}if(!t)try{return new Kn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const aI=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class FG extends Kg{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=aI?{}:eI(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(a){return this.emitReserved("error",a)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;qg(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&Id(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=tI()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Nf=Kn.WebSocket||Kn.MozWebSocket;class BG extends FG{createSocket(t,n,r){return aI?new Nf(t,n,r):n?new Nf(t,n):new Nf(t)}doWrite(t,n){this.ws.send(n)}}class UG extends Kg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=vG(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=EG();a.readable.pipeTo(t.writable),this._writer=a.writable.getWriter();const i=()=>{r.read().then(({done:l,value:c})=>{l||(this.onPacket(c),i())}).catch(l=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;this._writer.write(r).then(()=>{a&&Id(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const $G={websocket:BG,webtransport:UG,polling:PG},HG=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,zG=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Qm(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let a=HG.exec(e||""),i={},o=14;for(;o--;)i[zG[o]]=a[o]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=GG(i,i.path),i.queryKey=VG(i,i.query),i}function GG(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function VG(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const Jm=typeof addEventListener=="function"&&typeof removeEventListener=="function",Vc=[];Jm&&addEventListener("offline",()=>{Vc.forEach(e=>e())},!1);class Sa extends Gt{constructor(t,n){if(super(),this.binaryType=wG,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=Qm(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=Qm(n.host).host);Dd(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const a=r.prototype.name;this.transports.push(a),this._transportsByName[a]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=kG(this.opts.query)),Jm&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Vc.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=Jk,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Sa.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",Sa.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const a=this.writeBuffer[r].data;if(a&&(n+=AG(a)),r>0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Id(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,a){if(typeof n=="function"&&(a=n,n=void 0),typeof r=="function"&&(a=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),a&&this.once("flush",a),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(Sa.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Jm&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=Vc.indexOf(this._offlineEventListener);r!==-1&&Vc.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Sa.protocol=Jk;class WG extends Sa{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),r=!1;Sa.priorWebsocketSuccess=!1;const a=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",d=>{if(!r)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Sa.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const f=new Error("probe error");f.transport=n.name,this.emitReserved("upgradeError",f)}}))};function i(){r||(r=!0,p(),n.close(),n=null)}const o=d=>{const f=new Error("probe error: "+d);f.transport=n.name,i(),this.emitReserved("upgradeError",f)};function l(){o("transport closed")}function c(){o("socket closed")}function u(d){n&&d.name!==n.name&&i()}const p=()=>{n.removeListener("open",a),n.removeListener("error",o),n.removeListener("close",l),this.off("close",c),this.off("upgrading",u)};n.once("open",a),n.once("error",o),n.once("close",l),this.once("close",c),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;r<t.length;r++)~this.transports.indexOf(t[r])&&n.push(t[r]);return n}}let qG=class extends WG{constructor(t,n={}){const r=typeof t=="object"?t:n;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(a=>$G[a]).filter(a=>!!a)),super(t,r)}};function YG(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=Qm(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const KG=typeof ArrayBuffer=="function",XG=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,sI=Object.prototype.toString,ZG=typeof Blob=="function"||typeof Blob<"u"&&sI.call(Blob)==="[object BlobConstructor]",QG=typeof File=="function"||typeof File<"u"&&sI.call(File)==="[object FileConstructor]";function Xg(e){return KG&&(e instanceof ArrayBuffer||XG(e))||ZG&&e instanceof Blob||QG&&e instanceof File}function Wc(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(Wc(e[n]))return!0;return!1}if(Xg(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Wc(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Wc(e[n]))return!0;return!1}function JG(e){const t=[],n=e.data,r=e;return r.data=eh(n,t),r.attachments=t.length,{packet:r,buffers:t}}function eh(e,t){if(!e)return e;if(Xg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=eh(e[r],t);return n}else if(typeof e=="object"&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=eh(e[r],t));return n}return e}function eV(e,t){return e.data=th(e.data,t),delete e.attachments,e}function th(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=th(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=th(e[n],t));return e}const tV=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var gt;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(gt||(gt={}));class nV{constructor(t){this.replacer=t}encode(t){return(t.type===gt.EVENT||t.type===gt.ACK)&&Wc(t)?this.encodeAsBinary({type:t.type===gt.EVENT?gt.BINARY_EVENT:gt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===gt.BINARY_EVENT||t.type===gt.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=JG(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}class Zg extends Gt{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const r=n.type===gt.BINARY_EVENT;r||n.type===gt.BINARY_ACK?(n.type=r?gt.EVENT:gt.ACK,this.reconstructor=new rV(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(Xg(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const r={type:Number(t.charAt(0))};if(gt[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===gt.BINARY_EVENT||r.type===gt.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const o=t.substring(i,n);if(o!=Number(o)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const l=Number(o);if(!aV(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");r.attachments=l}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););r.nsp=t.substring(i,n)}else r.nsp="/";const a=t.charAt(n+1);if(a!==""&&Number(a)==a){const i=n+1;for(;++n;){const o=t.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===t.length)break}r.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(Zg.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return r}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case gt.CONNECT:return Q1(n);case gt.DISCONNECT:return n===void 0;case gt.CONNECT_ERROR:return typeof n=="string"||Q1(n);case gt.EVENT:case gt.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&tV.indexOf(n[0])===-1);case gt.ACK:case gt.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class rV{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=eV(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const aV=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Q1(e){return Object.prototype.toString.call(e)==="[object Object]"}const sV=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Zg,Encoder:nV,get PacketType(){return gt}},Symbol.toStringTag,{value:"Module"}));function ar(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const iV=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class iI extends Gt{constructor(t,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[ar(t,"open",this.onopen.bind(this)),ar(t,"packet",this.onpacket.bind(this)),ar(t,"error",this.onerror.bind(this)),ar(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var r,a,i;if(iV.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:gt.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const p=this.ids++,d=n.pop();this._registerAckCallback(p,d),o.id=p}const l=(a=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||a===void 0?void 0:a.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!l||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,n){var r;const a=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(a===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},a),o=(...l)=>{this.io.clearTimeoutFn(i),n.apply(this,l)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((r,a)=>{const i=(o,l)=>o?a(o):r(l);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((a,...i)=>(this._queue[0],a!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(a)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:gt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case gt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case gt.EVENT:case gt.BINARY_EVENT:this.onevent(t);break;case gt.ACK:case gt.BINARY_ACK:this.onack(t);break;case gt.DISCONNECT:this.ondisconnect();break;case gt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...a){r||(r=!0,n.packet({type:gt.ACK,id:t,data:a}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:gt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,t.data)}}}function Ai(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ai.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(Math.floor(t*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};Ai.prototype.reset=function(){this.attempts=0};Ai.prototype.setMin=function(e){this.ms=e};Ai.prototype.setMax=function(e){this.max=e};Ai.prototype.setJitter=function(e){this.jitter=e};class nh extends Gt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Dd(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ai({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const a=n.parser||sV;this.encoder=new a.Encoder,this.decoder=new a.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new qG(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=ar(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},o=ar(n,"error",i);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{a(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(a),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(ar(t,"ping",this.onping.bind(this)),ar(t,"data",this.ondata.bind(this)),ar(t,"error",this.onerror.bind(this)),ar(t,"close",this.onclose.bind(this)),ar(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){Id(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new iI(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;r<n.length;r++)this.engine.write(n[r],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(a=>{a?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",a)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Xi={};function bo(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=YG(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=Xi[a]&&i in Xi[a].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let c;return l?c=new nh(r,t):(Xi[a]||(Xi[a]=new nh(r,t)),c=Xi[a]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(bo,{Manager:nh,Socket:iI,io:bo,connect:bo});function oV({webhookUrl:e,sourceType:t,onClose:n}){const[r,a]=w.useState(!1),i=typeof window>"u"||e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/api/v1/")?`${window.location.origin}${e}`:e.startsWith("/")?`${window.location.origin}/api/v1${e}`:`${window.location.origin}/api/v1/${e}`,o=()=>{Vn(i),a(!0),setTimeout(()=>a(!1),2e3)};return s.jsx(kt,{open:!0,onOpenChange:l=>!l&&n(),children:s.jsxs(It,{children:[s.jsx(jt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full",children:s.jsx(Yt,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx(Mt,{children:"Source Created!"}),s.jsx(Kt,{children:"Your webhook URL is ready."})]})]})}),s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsx(Pe,{className:"uppercase tracking-wide text-xs text-muted-foreground",children:"Webhook URL"}),s.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-muted border p-3",children:[s.jsx("code",{className:"text-xs font-mono flex-1 break-all text-foreground",children:i}),s.jsx(ie,{variant:"ghost",size:"icon",onClick:o,className:"h-7 w-7",children:r?s.jsx(Yt,{className:"h-3.5 w-3.5 text-emerald-500"}):s.jsx(yn,{className:"h-3.5 w-3.5"})})]})]}),s.jsx($t,{className:"mt-4",children:s.jsx(ie,{onClick:n,className:"w-full",children:"Got it, close"})})]})})}const lV=["grafana","prometheus","cloudwatch","cloudtrail","custom"],cV={meyi_pulse:{label:"Meyi Pulse",Icon:Ta,color:"text-violet-500"},grafana:{label:"Grafana",Icon:Uh,color:"text-orange-500"},datadog:{label:"Datadog",Icon:OC,color:"text-purple-500"},prometheus:{label:"Prometheus",Icon:IC,color:"text-red-500"},cloudwatch:{label:"AWS CloudWatch",Icon:lu,color:"text-amber-500"},cloudtrail:{label:"Level 1 Security",Icon:il,color:"text-orange-600"},pagerduty:{label:"PagerDuty",Icon:zP,color:"text-green-500"},custom:{label:"Custom Webhook",Icon:L4,color:"text-blue-500"}};function uV({open:e,source:t,submitting:n,onClose:r,onSubmit:a,createdWebhookUrl:i,onWebhookModalClose:o,initialType:l}){const c=!!t,[u,p]=w.useState(""),[d,f]=w.useState("meyi_pulse"),[m,h]=w.useState("");w.useEffect(()=>{e&&(t?(p(t.name),f(t.type),h(t.description??"")):(p(""),f(l||"meyi_pulse"),h("")))},[e,t,l]);const g=b=>{if(b.preventDefault(),!u.trim()){ae.error("Source name is required");return}a(u.trim(),d,m.trim()||void 0)};return i?s.jsx(oV,{webhookUrl:i,sourceType:d,onClose:o??r}):s.jsx(kt,{open:e,onOpenChange:b=>!b&&!n&&r(),children:s.jsx(It,{children:s.jsxs("form",{onSubmit:g,children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:c?"Configure Source":"Add Webhook Source"}),s.jsx(Kt,{children:c?"Update the source details below.":"Create a webhook endpoint to receive alerts from your monitoring tool."})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Source Name ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{value:u,onChange:b=>p(b.target.value),placeholder:"e.g. Production Pulse",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Source Type ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Bn,{label:"Select source type",className:"im-single-select-full",value:d,onValueChange:b=>!c&&f(b),disabled:c||n,options:lV.map(b=>({label:cV[b].label,value:b}))}),c&&s.jsx("p",{className:"text-xs text-muted-foreground",children:"Source type cannot be changed after creation."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Description ",s.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),s.jsx("textarea",{rows:2,value:m,onChange:b=>h(b.target.value),placeholder:"Brief description of what this source monitors…",disabled:n,className:"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 resize-none"})]}),!c&&s.jsxs("div",{className:"rounded-lg bg-muted/50 border p-3 text-xs text-muted-foreground space-y-1",children:[s.jsx("p",{className:"font-medium text-foreground",children:"After saving:"}),s.jsx("p",{children:"A unique webhook URL will be generated. Configure your monitoring tool to POST alerts to that URL when a resource goes down."})]})]}),s.jsxs($t,{children:[s.jsx(ie,{type:"button",variant:"outline",onClick:r,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",disabled:n,children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Creating…"]}):c?"Save Changes":"Create & Get URL"})]})]})})})}function Zi(e){return String(e||"").toLowerCase().trim()}function mc(e){return String(e||"unknown").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function dV(e){if(!e)return[];const t=Zi(e.type),n=[];if(t==="cloudwatch"){const r=Zi(e.awsDeploymentStatus);["pending","deployed","failed"].includes(r)&&n.push(`AWS CloudWatch setup status is ${mc(e.awsDeploymentStatus)}. Local AWS setup data will be removed before deleting this source. If an AWS stack or Lambda still exists, remove it from AWS as well.`)}if(t==="cloudtrail"){const r=Zi(e.awsDeploymentStatus);["pending","deployed","failed"].includes(r)&&n.push(`AWS CloudTrail setup status is ${mc(e.awsDeploymentStatus)}. Local AWS setup data will be removed before deleting this source. If an AWS CloudFormation stack (CloudTrail, S3, SNS, Lambda) still exists, remove it from AWS as well.`)}if(t==="grafana"){const r=Zi(e.grafanaSetupStatus);["manual_ready","configured","failed"].includes(r)&&n.push(`Grafana setup status is ${mc(e.grafanaSetupStatus)}. Meyi Connect will try to remove the Grafana policy route/contact point first when a saved token is available, then remove the local setup data and source.`)}if(t==="prometheus"){const r=Zi(e.prometheusSetupStatus);["generated","downloaded","configured","failed"].includes(r)&&n.push(`Prometheus setup status is ${mc(e.prometheusSetupStatus)}. Local Prometheus setup data will be removed before deleting this source. Remove any downloaded Alertmanager/Prometheus config from your environment if it was applied.`)}return n}function pV({open:e,onOpenChange:t,source:n,onConfirm:r}){const[a,i]=w.useState(!1),o=dV(n),l=async()=>{i(!0);try{await r()}catch(c){console.error("Error deleting source:",c)}finally{i(!1)}};return s.jsx(kt,{open:e,onOpenChange:c=>!a&&t(c),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Are you absolutely sure?"}),s.jsxs(Kt,{children:["This will permanently delete the source"," ",s.jsx("strong",{className:"text-foreground font-semibold",children:n?.name||"this source"}),". This action cannot be undone and will remove all connection configurations."]})]}),o.length>0?s.jsxs("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900",children:[s.jsxs("div",{className:"mb-2 flex items-center gap-2 font-semibold",children:[s.jsx(bs,{className:"h-4 w-4"}),"Configured source cleanup"]}),s.jsx("div",{className:"space-y-2",children:o.map(c=>s.jsx("p",{children:c},c))})]}):null,s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:()=>t(!1),disabled:a,children:"Cancel"}),s.jsx(ie,{variant:"destructive",onClick:l,disabled:a,children:a?"Deleting...":o.length>0?"Delete Source and Setup":"Delete"})]})]})})}function fV({open:e,source:t,loading:n,submitting:r,onOpenChange:a,onSubmit:i}){const[o,l]=w.useState("expires"),[c,u]=w.useState("30");w.useEffect(()=>{if(!e||!t)return;const f=t.tokenPolicy?.mode==="unlimited"?"unlimited":"expires";l(f),u(String(t.tokenPolicy?.defaultTtlDays??30))},[e,t]);const p=async()=>{if(o==="unlimited"){await i("unlimited");return}const f=Number.parseInt(c,10);!Number.isFinite(f)||f<=0||await i("expires",f)},d=!!(n||r);return s.jsx(kt,{open:e,onOpenChange:f=>!d&&a(f),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Webhook Token Policy"}),s.jsx(Kt,{children:"Configure token expiry per source. Default is 30 days, or set unlimited."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Mode"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(ie,{type:"button",variant:o==="expires"?"default":"outline",onClick:()=>l("expires"),disabled:d,children:"Expires"}),s.jsx(ie,{type:"button",variant:o==="unlimited"?"default":"outline",onClick:()=>l("unlimited"),disabled:d,children:"Unlimited"})]})]}),o==="expires"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ttlDays",children:"TTL Days"}),s.jsx(Xe,{id:"ttlDays",type:"number",min:1,value:c,onChange:f=>u(f.target.value),disabled:d})]})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:()=>a(!1),disabled:d,children:"Cancel"}),s.jsxs(ie,{onClick:p,disabled:d,children:[r?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Save Policy"]})]})]})})}function hc(e,t){for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function mV(e){const t={},n=e.split(/\r?\n/);for(const l of n){const c=l.trim();if(!c||c.startsWith("#"))continue;const u=c.replace(/^export\s+/i,""),p=u.indexOf("=");if(p<=0)continue;const d=u.slice(0,p).trim();let f=u.slice(p+1).trim();f=f.replace(/^['"]|['"]$/g,""),d&&(t[d]=f)}const r=t.AWS_ACCESS_KEY_ID||t.AWS_ACCESS_KEY||t.ACCESS_KEY_ID||"",a=t.AWS_SECRET_ACCESS_KEY||t.SECRET_ACCESS_KEY||"",i=t.AWS_SESSION_TOKEN||t.SESSION_TOKEN||"",o=t.AWS_REGION||t.AWS_DEFAULT_REGION||t.REGION||"";return{accessKeyId:r,secretAccessKey:a,sessionToken:i,region:o}}function hV({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function gV({open:e,loadingDiscover:t,deploying:n,discoveringReady:r,credentials:a,naming:i,alarmDefaults:o,selectedAlarmNames:l,selectedMetricKeys:c,discoverData:u,deployData:p,templateDownloadUrl:d,onChangeCredentials:f,onChangeNaming:m,onChangeAlarmDefaults:h,onToggleAlarm:g,onToggleMetric:b,onDiscover:x,onDeploy:S,onOpenChange:T}){const N=w.useMemo(()=>new Set(l),[l]),A=w.useMemo(()=>new Set(c),[c]),[C,k]=w.useState(!1),[O,M]=w.useState(!1),[R,j]=w.useState(""),[U,G]=w.useState(null),q=()=>{let P="",z="",re="",B="";try{const H=JSON.parse(R);P=hc(H,["accessKeyId","aws_access_key_id","AccessKeyId"]),z=hc(H,["secretAccessKey","aws_secret_access_key","SecretAccessKey"]),re=hc(H,["sessionToken","aws_session_token","SessionToken"]),B=hc(H,["region","aws_region","Region"])}catch{const H=mV(R);P=H.accessKeyId,z=H.secretAccessKey,re=H.sessionToken,B=H.region}if(!P||!z){G("Provide valid JSON or export format with AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.");return}f({accessKeyId:P,secretAccessKey:z,sessionToken:re,region:B||a.region||"ap-south-1"}),j(""),G(null),k(!1)};return s.jsx(kt,{open:e,onOpenChange:P=>!(t||n)&&T(P),children:s.jsxs(It,{className:"w-[96vw] max-w-5xl max-h-[88vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"AWS CloudWatch Setup"}),s.jsx(Kt,{children:"Save AWS credentials, discover alarms/metrics, select alarm mapping, then deploy automatically."})]}),s.jsxs("div",{className:"space-y-5",children:[s.jsxs(Qh,{defaultValue:"connection",className:"w-full",children:[s.jsxs(rd,{className:"grid w-full grid-cols-2",children:[s.jsx(as,{value:"connection",children:"Connection"}),s.jsx(as,{value:"naming",children:"Naming"})]}),s.jsxs(ss,{value:"connection",className:"space-y-3",children:[s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:"Credentials Input"}),s.jsx(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{k(P=>!P),G(null)},children:C?"Hide Paste":"Paste Credentials"})]}),C?s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx("textarea",{value:R,onChange:P=>j(P.target.value),rows:6,className:"w-full rounded-md border bg-background p-2 text-xs font-mono focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",placeholder:`{"accessKeyId":"AKIA...","secretAccessKey":"...","sessionToken":"...","region":"ap-south-1"}
@@ -65,7 +65,7 @@ or
65
65
  export AWS_ACCESS_KEY_ID=...
66
66
  export AWS_SECRET_ACCESS_KEY=...
67
67
  export AWS_SESSION_TOKEN=...
68
- export AWS_DEFAULT_REGION=ap-south-1`}),U?s.jsx("div",{className:"text-xs text-destructive",children:U}):null,s.jsx("div",{className:"flex justify-end",children:s.jsx(ie,{type:"button",size:"sm",onClick:q,children:"Apply JSON"})})]}):null]}),s.jsxs("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"AWS Access Key ID"}),s.jsx(Xe,{type:"password",value:a.accessKeyId,onChange:P=>f({accessKeyId:P.target.value}),placeholder:"AKIA...",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"AWS Secret Access Key"}),s.jsx(Xe,{type:"password",value:a.secretAccessKey,onChange:P=>f({secretAccessKey:P.target.value}),placeholder:"Secret key",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Session Token (Optional for STS/SSO)"}),s.jsx(Xe,{type:"password",value:a.sessionToken,onChange:P=>f({sessionToken:P.target.value}),placeholder:"Required when access key starts with ASIA...",autoComplete:"off"})]})]}),s.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Region"}),s.jsx(Xe,{value:a.region,onChange:P=>f({region:P.target.value}),placeholder:"ap-south-1"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Stack Name"}),s.jsx(Xe,{value:a.stackName,onChange:P=>f({stackName:P.target.value}),placeholder:"meyi-cloudwatch-xxxx"})]})]}),s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:"Alarm Defaults"}),s.jsx(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>M(P=>!P),children:O?"Hide Alarm Defaults":"Edit Alarm Defaults"})]}),O?s.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Threshold"}),s.jsx(Xe,{type:"number",step:"any",value:o.threshold,onChange:P=>h({threshold:P.target.value}),placeholder:"50"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Period (sec)"}),s.jsx(Xe,{type:"number",value:o.period,onChange:P=>h({period:P.target.value}),placeholder:"60"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Evaluation Periods"}),s.jsx(Xe,{type:"number",value:o.evaluationPeriods,onChange:P=>h({evaluationPeriods:P.target.value}),placeholder:"1"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Statistic"}),s.jsx(Bn,{label:"Select statistic",className:"im-single-select-full",value:o.statistic,onValueChange:P=>h({statistic:P}),options:[{label:"Average",value:"Average"},{label:"Sum",value:"Sum"},{label:"Minimum",value:"Minimum"},{label:"Maximum",value:"Maximum"},{label:"SampleCount",value:"SampleCount"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Comparison"}),s.jsx(Bn,{label:"Select comparison",className:"im-single-select-full",value:o.comparisonOperator,onValueChange:P=>h({comparisonOperator:P}),options:[{label:"GreaterThanOrEqualToThreshold",value:"GreaterThanOrEqualToThreshold"},{label:"GreaterThanThreshold",value:"GreaterThanThreshold"},{label:"LessThanThreshold",value:"LessThanThreshold"},{label:"LessThanOrEqualToThreshold",value:"LessThanOrEqualToThreshold"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Treat Missing Data"}),s.jsx(Bn,{label:"Select missing-data mode",className:"im-single-select-full",value:o.treatMissingData,onValueChange:P=>h({treatMissingData:P}),options:[{label:"breaching",value:"breaching"},{label:"notBreaching",value:"notBreaching"},{label:"ignore",value:"ignore"},{label:"missing",value:"missing"}]})]})]}):s.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Threshold ",o.threshold,", period ",o.period,"s, eval ",o.evaluationPeriods,", statistic ",o.statistic,"."]})]})]}),s.jsx(ss,{value:"naming",className:"space-y-3",children:s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Lambda Name"}),s.jsx(Xe,{value:i.lambdaName,onChange:P=>m({lambdaName:P.target.value}),placeholder:"meyi-cloudwatch-forwarder-xxxx",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Alarm Name Prefix"}),s.jsx(Xe,{value:i.alarmNamePrefix,onChange:P=>m({alarmNamePrefix:P.target.value}),placeholder:"meyi-alerts-xxxx",autoComplete:"off"})]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Suggested names are auto-filled. You can override them, and deploy will use these names in CloudFormation and AWS resources."})]})})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{onClick:x,disabled:!r||!!t||!!n,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):s.jsx(Ra,{className:"h-4 w-4"}),"Fetch Metrics & Alarms"]}),u?.aws?.accessKeyIdMasked?s.jsxs("span",{className:"text-xs text-muted-foreground",children:["Saved Credentials: ",u.aws.accessKeyIdMasked]}):null]}),u?s.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsx("div",{className:"mb-2 text-sm font-medium",children:"CloudWatch Alarms"}),s.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto pr-1",children:u.alarms.length===0?s.jsx("p",{className:"text-xs text-muted-foreground",children:"No alarms found in this region."}):u.alarms.map(P=>s.jsxs("label",{className:"flex items-start gap-2 rounded px-1 py-1 hover:bg-muted/40",children:[s.jsx("input",{type:"checkbox",checked:N.has(P.alarmName),onChange:z=>g(P.alarmName,z.target.checked),className:"mt-0.5"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-xs font-medium break-all",children:P.alarmName}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[P.namespace||"-"," / ",P.metricName||"-"," / ",P.stateValue||"-"]})]})]},P.alarmName))})]}),s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsx("div",{className:"mb-2 text-sm font-medium",children:"CloudWatch Metrics"}),s.jsx("div",{className:"max-h-72 overflow-y-auto pr-1",children:u.metrics.length===0?s.jsx("p",{className:"text-xs text-muted-foreground",children:"No metrics found."}):s.jsx("ul",{className:"space-y-1",children:u.metrics.map(P=>s.jsx("li",{children:s.jsxs("label",{className:"flex items-start gap-2 rounded px-1 py-1 hover:bg-muted/40",children:[s.jsx("input",{type:"checkbox",checked:A.has(`${P.namespace}::${P.metricName}`),onChange:z=>b(`${P.namespace}::${P.metricName}`,z.target.checked),className:"mt-0.5"}),s.jsxs("span",{className:"text-xs",children:[s.jsx("span",{className:"text-muted-foreground",children:P.namespace})," / ",P.metricName]})]})},`${P.namespace}:${P.metricName}`))})})]})]}):null,s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{onClick:S,disabled:!u||!!n||!!t,children:[n?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Deploy AWS Automation"]}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"Creates/updates CloudWatch alarms from selected metrics and wires AlarmActions to Lambda."})]}),p?s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment Result"}),s.jsxs("div",{className:"text-xs",children:["Action: ",s.jsx("span",{className:"font-medium",children:p.deployment.action})," | Status:"," ",s.jsx("span",{className:"font-medium",children:p.deployment.stackStatus||"-"})]}),s.jsxs("div",{className:"text-xs",children:["Lambda Name: ",p.deployment.lambdaName||"-"]}),s.jsxs("div",{className:"text-xs",children:["Alarm Prefix: ",p.deployment.alarmNamePrefix||"-"]}),s.jsxs("div",{className:"text-xs break-all",children:["Stack ID: ",p.deployment.stackId||"-"]}),s.jsxs("div",{className:"text-xs",children:["Created/Updated Alarms: ",p.deployment.createdAlarmNames?.length||0]}),s.jsxs("div",{className:"text-xs break-all",children:["Webhook URL: ",p.webhook.url]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[s.jsx(hV,{value:p.webhook.url}),d?s.jsx(ie,{asChild:!0,variant:"outline",size:"sm",children:s.jsx("a",{href:d,target:"_blank",rel:"noreferrer",children:"Download CloudFormation Template"})}):null]})]}):null]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>T(!1),disabled:!!t||!!n,children:"Close"})})]})})}function Cf({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function bV({href:e,label:t}){return s.jsx(ie,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-3.5 w-3.5"}),t]})})}function xV({open:e,loading:t,data:n,prometheusBaseUrl:r,alertmanagerBaseUrl:a,checkingStatus:i,statusResult:o,onPrometheusBaseUrlChange:l,onAlertmanagerBaseUrlChange:c,onCheckStatus:u,onRefresh:p,onOpenChange:d}){const f=!!(t||i),[m,h]=w.useState("docker"),g=m==="linux"?n?.defaults.linuxCommand:m==="kubernetes"?n?.defaults.kubernetesCommand:n?.defaults.dockerCommand,b=m==="linux"?n?.downloads?.linuxScript:m==="kubernetes"?n?.downloads?.kubernetesYaml:n?.downloads?.dockerScript,x=m==="kubernetes"?"Download YAML":"Download Script",S={docker:kC,linux:jC,kubernetes:SC},T=o?.status==="configured"?"border-emerald-200 bg-emerald-50 text-emerald-800":o?.status==="failed"?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800";return s.jsx(kt,{open:e,onOpenChange:N=>!f&&d(N),children:s.jsxs(It,{className:"w-[96vw] max-w-4xl max-h-[88vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Prometheus Setup"}),s.jsx(Kt,{children:"Generate a setup script or Kubernetes YAML to connect Alertmanager to Meyi Connect."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(ie,{variant:"outline",size:"sm",onClick:p,disabled:f,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):s.jsx(Ra,{className:"h-4 w-4"}),"Refresh"]}),n?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:n.webhook.url})]}),s.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment status check"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Run this after applying the setup script/YAML. It checks readiness and whether Alertmanager has the Meyi receiver."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Prometheus URL"}),s.jsx(Xe,{value:r,onChange:N=>l(N.target.value),placeholder:"http://65.2.144.245:9090"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Alertmanager URL"}),s.jsx(Xe,{value:a,onChange:N=>c(N.target.value),placeholder:"http://65.2.144.245:9093"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:f,children:[i?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Check Status"]}),o?s.jsxs("div",{className:`rounded-md border px-3 py-1.5 text-xs ${T}`,children:[s.jsx("span",{className:"font-semibold",children:o.status.replace(/_/g," ")}),o.reason?s.jsxs("span",{children:[" - ",o.reason]}):null]}):null]})]}),s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:(n.environments||[]).map(N=>{const A=S[N.id],C=m===N.id;return s.jsxs("button",{type:"button",onClick:()=>h(N.id),className:`rounded-lg border p-3 text-left transition ${C?"border-primary bg-primary/5 shadow-sm":"bg-background hover:bg-muted/30"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(A,{className:"h-4 w-4 text-primary"}),N.label]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:N.description})]},N.id)})}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Automated setup"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Download and run this on the Prometheus host or cluster."})]}),b?s.jsx(bV,{href:b,label:x}):null]}),g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"rounded-md border bg-background p-2 text-xs break-all font-mono",children:g}),s.jsx(Cf,{value:g})]}):null]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"How it works"}),s.jsx("ol",{className:"list-decimal list-inside space-y-1 text-xs text-muted-foreground",children:n.manual.steps.map((N,A)=>s.jsx("li",{children:N},A))})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Manual alertmanager.yml snippet"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono whitespace-pre-wrap",children:n.snippets.alertmanagerConfig}),s.jsx(Cf,{value:n.snippets.alertmanagerConfig})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Reload Command"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono",children:n.snippets.reloadCommand}),s.jsx(Cf,{value:n.snippets.reloadCommand})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:n.snippets.note})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Load setup details to continue."})]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>d(!1),disabled:f,children:"Close"})})]})})}function yV({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function EV({open:e,loading:t,configuring:n,data:r,result:a,site:i,webhookName:o,datadogApiKey:l,datadogAppKey:c,onSiteChange:u,onWebhookNameChange:p,onDatadogApiKeyChange:d,onDatadogAppKeyChange:f,onRefresh:m,onConfigure:h,onOpenChange:g}){const b=!!(t||n);return s.jsx(kt,{open:e,onOpenChange:x=>!b&&g(x),children:s.jsxs(It,{className:"w-[96vw] max-w-4xl max-h-[88vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Datadog Setup"}),s.jsx(Kt,{children:"Configure this Datadog source manually or automatically via Datadog API."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(ie,{variant:"outline",onClick:m,disabled:b,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh"]}),r?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:r.webhook.url})]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Manual Setup"}),s.jsx("ol",{className:"list-decimal list-inside space-y-1 text-xs text-muted-foreground",children:r.manual.steps.map((x,S)=>s.jsx("li",{children:x},S))}),s.jsx("div",{className:"rounded-md border bg-background/70 p-2 text-xs font-mono",children:r.defaults.notifyHandle})]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Automatic Setup"}),s.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddSite",children:"Datadog Site"}),s.jsx(Xe,{id:"ddSite",value:i,onChange:x=>u(x.target.value),placeholder:"datadoghq.com",disabled:b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddWebhookName",children:"Webhook Name"}),s.jsx(Xe,{id:"ddWebhookName",value:o,onChange:x=>p(x.target.value),disabled:b})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddApiKey",children:"Datadog API Key"}),s.jsx(Xe,{id:"ddApiKey",type:"password",value:l,onChange:x=>d(x.target.value),disabled:b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddAppKey",children:"Datadog Application Key"}),s.jsx(Xe,{id:"ddAppKey",type:"password",value:c,onChange:x=>f(x.target.value),disabled:b})]}),s.jsxs(ie,{onClick:h,disabled:b,children:[n?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Configure Automatically"]})]}),a?s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3 text-xs",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Action:"})," ",a.action]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Site:"})," ",a.site]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Webhook Name:"})," ",a.webhookName]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Notify Handle:"}),s.jsx("span",{className:"font-mono",children:a.notifyHandle}),s.jsx(yV,{value:a.notifyHandle})]})]}):null]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Load setup details to continue."})]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>g(!1),disabled:b,children:"Close"})})]})})}const J1={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus / Alertmanager",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom / SDK",mono:"CU",color:"#5A6B7B"}};function oI(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function vV(e){const t=typeof window<"u"?window.location.origin:"";return e.webhookUrl?.startsWith("http://")||e.webhookUrl?.startsWith("https://")?e.webhookUrl:e.webhookUrl?.startsWith("/api/v1/")?`${t}${e.webhookUrl}`:e.webhookUrl?.startsWith("/")?`${t}/api/v1${e.webhookUrl}`:`${t}/api/v1/insight/webhook/${e.webhookToken}`}function SV(e){const t=e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt;if(!t)return"Never";const n=Date.now()-new Date(t).getTime();if(!Number.isFinite(n)||n<0)return"just now";const r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r} minute${r===1?"":"s"} ago`;const a=Math.floor(r/60);if(a<24)return`${a} hour${a===1?"":"s"} ago`;const i=Math.floor(a/24);return`${i} day${i===1?"":"s"} ago`}function wV(e){const t=oI(e.type);return t==="cloudwatch"?`aws ****${e.id.slice(-4)} - ${e.awsStackName||"sns:prod-alarms"} - ${e.awsRegion||"us-east-1"} - production`:t==="cloudtrail"?`aws ****${e.id.slice(-4)} - ${e.awsStackName||"cloudtrail:security"} - ${e.awsRegion||"us-east-1"} - security`:t==="grafana"?`${e.grafanaBaseUrl||"https://grafana.meyi.io"} - production`:t==="prometheus"?`${e.prometheusEnvironment||"k8s-prod"} - alertmanager.yml`:e.description||e.webhookUrl||"production"}function ew(e){return e.isActive?e.deliveryStatus==="failed"?"Error":"Active":"Disabled"}function TV(e){const t=e.webhookToken||"";return t?`${t.slice(0,7)}************${t.slice(-3)}`:"whk_cl_************cw1"}function NV(e){const t=Math.max(1,Number(e||47));return[.74,.58,.88,.65,.83,.88,.56].map((n,r)=>Math.max(44,Math.round(130*Math.min(1,n+(t+r)%11/100))))}function CV({open:e,source:t,onOpenChange:n}){const[r,a]=w.useState(!1),i=w.useMemo(()=>t?vV(t):"",[t]);if(!t)return s.jsx(kt,{open:e,onOpenChange:n});const o=oI(t.type),l=J1[o]||J1.custom,c=Number(t.alertCount||0),u=Number(t.webhookFailureCount||0);return s.jsx(kt,{open:e,onOpenChange:n,children:s.jsx(It,{className:"im-source-detail-dialog p-0",children:s.jsxs("div",{className:"im-source-detail-page",children:[s.jsxs("div",{className:"im-detail-header",children:[s.jsxs("div",{className:"im-detail-title-wrap",children:[s.jsx("span",{className:"im-provider-badge im-detail-provider",style:{backgroundColor:l.color},children:l.mono}),s.jsxs("div",{children:[s.jsxs("div",{className:"im-detail-title-line",children:[s.jsx("h2",{children:t.name||`${l.label} source`}),s.jsx("span",{className:`im-state-chip ${t.isActive?"is-active":"is-disabled"}`,children:ew(t)})]}),s.jsx("p",{children:wV(t)})]})]}),s.jsxs("div",{className:"im-detail-actions",children:[s.jsx(ie,{variant:"outline",type:"button",children:t.isActive?"Disable":"Enable"}),s.jsx(ie,{variant:"outline",type:"button",children:"Test connection"}),s.jsx(ie,{variant:"outline",size:"icon",type:"button","aria-label":"More source actions",children:s.jsx(hs,{size:18})})]})]}),s.jsxs("div",{className:"im-detail-tabs",role:"tablist","aria-label":"Source details",children:[s.jsx("button",{className:"is-active",type:"button",children:"Overview"}),s.jsx("button",{type:"button",children:"Alarms"}),s.jsx("button",{type:"button",children:"Configuration"}),s.jsx("button",{type:"button",children:"Logs"}),s.jsx("button",{type:"button",children:"Test"})]}),s.jsxs("div",{className:"im-detail-stats",children:[s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Status"}),s.jsxs("strong",{children:[s.jsx("i",{className:`im-status-dot im-status-${t.isActive?"active":"disabled"}`}),ew(t)]})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Last alarm"}),s.jsx("strong",{children:SV(t)})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Alarms today"}),s.jsx("strong",{children:c})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Errors (1h)"}),s.jsx("strong",{className:u>0?"is-danger":"",children:u})]})]}),s.jsxs("div",{className:"im-detail-grid",children:[s.jsxs("section",{className:"im-detail-card im-rate-card",children:[s.jsx("h3",{children:"7-day alarm rate"}),s.jsx("div",{className:"im-bar-chart","aria-label":"7-day alarm rate",children:NV(c).map((p,d)=>s.jsxs("div",{className:"im-bar-col",children:[s.jsx("span",{style:{height:p}}),s.jsx("small",{children:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][d]})]},d))})]}),s.jsxs("section",{className:"im-detail-card im-webhook-card",children:[s.jsx("h3",{children:"Webhook endpoint"}),s.jsxs("div",{className:"im-code-row",children:[s.jsx("code",{children:i}),s.jsx("button",{type:"button","aria-label":"Copy webhook endpoint",onClick:()=>{Vn(i),a(!0),window.setTimeout(()=>a(!1),1500)},children:r?s.jsx(Yt,{size:15}):s.jsx(yn,{size:15})})]}),s.jsx("label",{children:"Auth token"}),s.jsx("div",{className:"im-token-row",children:TV(t)})]})]})]})})})}const rh=[{type:"cloudwatch",label:"CloudWatch",description:"Receive CloudWatch alarms via an SNS topic subscription",mono:"CW",color:"#E67E22"},{type:"cloudtrail",label:"Level 1 Security",description:"Stream CloudTrail security events via EventBridge into Meyi",mono:"L1",color:"#D35400"},{type:"grafana",label:"Grafana",description:"Forward Grafana alerts through a webhook contact point",mono:"GF",color:"#C0392B"},{type:"prometheus",label:"Prometheus / Alertmanager",description:"Ingest Alertmanager alerts via authenticated webhook",mono:"PR",color:"#8E44AD"},{type:"cost",label:"AWS Cost",description:"Connect an AWS account for Cost Explorer and CUR data",mono:"$",color:"#167A6A"},{type:"custom",label:"Custom / SDK",description:"Push any source using the ingest API and SDK",mono:"</>",color:"#5A6B7B"}];function Qg(e){return rh.find(t=>t.type===e)??rh[0]}const tw={cloudwatch:["Creates an authenticated webhook for CloudWatch.","Prepares a CloudFormation template with Lambda, EventBridge, and IAM permissions.","Events are forwarded to Meyi automatically upon stack creation."],cloudtrail:["Creates an authenticated webhook for CloudTrail security monitoring.","Generates a CloudFormation central-stack with S3, SNS, and EventBridge security rules.","Security events flow into Meyi in real-time across selected AWS accounts."],grafana:["Creates an authenticated webhook endpoint for Grafana alert delivery.","Provides contact point configuration details for Grafana alert rules."],prometheus:["Creates an authenticated Alertmanager webhook receiver.","Provides setup configurations for Docker, Linux, and Kubernetes."],datadog:["Creates an authenticated webhook endpoint for Datadog monitor events.","Provides Datadog webhook integration settings."],custom:["Creates an authenticated webhook for custom collectors and SDKs.","Send normalized event payloads directly to the ingestion endpoint."],meyi_pulse:["Creates an authenticated source for native pulse events."],pagerduty:["Creates an authenticated webhook endpoint for PagerDuty incident payloads."]};function AV({selected:e,onSelect:t}){return s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsx("h3",{children:"Choose a source type"}),s.jsx("p",{children:"Each instance connects one account or endpoint. Add more instances later for additional accounts."}),s.jsx("div",{className:"im-source-grid",children:rh.map(n=>{const r=e===n.type;return s.jsxs("button",{type:"button",onClick:()=>t(n.type),className:`im-source-card ${r?"is-selected":""}`,children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:n.color},children:n.mono==="</>"?s.jsx(EF,{size:18}):n.mono}),s.jsxs("span",{children:[s.jsx("strong",{children:n.label}),s.jsx("small",{children:n.description})]})]},n.type)})})]})}const _V={async list(){return(await Rt.get("/api/v1/connectors",{withCredentials:!0})).data},async getById(e){try{return(await Rt.get(`/api/v1/connectors/${e}`,{withCredentials:!0})).data?.connector??null}catch{return null}}},Af={deploymentMode:"Organizations",targetAccounts:"",managementAccountId:void 0,createTrail:!0};function RV({config:e,onChange:t,onConnectorsLoaded:n}){const r=e.deploymentMode==="Organizations",[a,i]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(null),[p,d]=w.useState(null);function f(g,b){const x={...e,[g]:b};g==="deploymentMode"&&(x.targetAccounts=""),t(x)}w.useEffect(()=>{l(!0),u(null),_V.list().then(({connectors:g})=>{i(g);const b=g.filter(S=>!!(S.managementAccountId&&S.accountId&&S.managementAccountId===S.accountId));let x=null;e.managementAccountId&&(x=b.find(S=>S.accountId===e.managementAccountId)||null),x||(x=b[0]??g.find(S=>S.connectionStatus==="CONNECTED")??g[0]??null),d(x),x&&!e.managementAccountId&&b.length>1&&f("managementAccountId",x.accountId),n?.(x,g),g.length===0&&u("No AWS account connectors found. Complete onboarding in the Connectors section first.")}).catch(()=>{u("Failed to load connectors. Please refresh and try again.")}).finally(()=>l(!1))},[]);const m=a.filter(g=>g.connectionStatus==="CONNECTED"),h=a.filter(g=>!!(g.managementAccountId&&g.accountId&&g.managementAccountId===g.accountId));return s.jsxs("div",{className:"im-cloudtrail-deploy-form",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Deployment Type"}),s.jsxs("div",{className:"im-radio-group",children:[s.jsxs("label",{className:`im-radio-option ${r?"is-selected":""}`,children:[s.jsx("input",{type:"radio",name:"deploymentMode",value:"Organizations",checked:r,onChange:()=>f("deploymentMode","Organizations")}),s.jsxs("span",{className:"im-radio-label",children:[s.jsx("strong",{children:"Organizations"}),s.jsx("small",{children:"Deploy across your entire AWS Organization automatically"})]})]}),s.jsxs("label",{className:`im-radio-option ${r?"":"is-selected"}`,children:[s.jsx("input",{type:"radio",name:"deploymentMode",value:"Standalone",checked:!r,onChange:()=>f("deploymentMode","Standalone")}),s.jsxs("span",{className:"im-radio-label",children:[s.jsx("strong",{children:"Standalone"}),s.jsx("small",{children:"Deploy to a single specific AWS account"})]})]})]})]}),r&&s.jsx("div",{className:"im-form-row",children:o?s.jsx("div",{className:"im-connector-loading",children:"Loading connector information…"}):c?s.jsxs("div",{className:"im-connector-error-banner",children:[s.jsx("span",{className:"im-connector-error-icon",children:"⚠"}),c]}):h.length>1?s.jsxs("div",{children:[s.jsxs(Pe,{className:"mb-1.5 block",children:["Target AWS Organization ",s.jsx("span",{className:"im-required-badge",children:"Required"})]}),s.jsxs(Fo,{value:e.managementAccountId||p?.accountId||"",onValueChange:g=>{const b=h.find(x=>x.accountId===g)||null;d(b),f("managementAccountId",g),n?.(b,a)},children:[s.jsx(Uo,{className:"w-full",children:s.jsx(Bo,{placeholder:"Select an organization management account…"})}),s.jsx($o,{children:h.map(g=>s.jsxs(ba,{value:g.accountId,children:[g.accountName," (",g.accountId,")"]},g.accountId))})]})]}):p?s.jsxs("div",{children:[s.jsx(Pe,{className:"mb-1.5 block",children:"Management Account"}),s.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-lg border border-border bg-muted/20 text-sm",children:[s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-semibold text-foreground truncate",children:p.accountName}),s.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:p.accountId})]}),s.jsx("span",{className:"text-xs px-2.5 py-0.5 rounded border border-border/80 text-muted-foreground bg-card shrink-0",children:"Management"})]})]}):s.jsxs("div",{className:"p-4 rounded-lg border border-dashed border-border/80 bg-muted/10 text-center space-y-1",children:[s.jsx("p",{className:"text-sm font-medium text-foreground",children:"No AWS Organization found"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Complete AWS onboarding in the Connectors section to enable Organization deployment."})]})}),!r&&s.jsx("div",{className:"im-form-row",children:o?s.jsx("div",{className:"im-connector-loading",children:"Loading connectors…"}):c?s.jsxs("div",{className:"im-connector-error-banner",children:[s.jsx("span",{className:"im-connector-error-icon",children:"⚠"}),c]}):m.length===0?s.jsxs("div",{className:"p-4 rounded-lg border border-dashed border-border/80 bg-muted/10 text-center space-y-1",children:[s.jsx("p",{className:"text-sm font-medium text-foreground",children:"No connected accounts found"}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Only accounts with status ",s.jsx("strong",{children:"CONNECTED"})," can be used for Standalone deployment."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Pe,{className:"mb-1.5 block",children:["Target Account ",s.jsx("span",{className:"im-required-badge",children:"Required"})]}),s.jsxs(Fo,{value:e.targetAccounts,onValueChange:g=>f("targetAccounts",g),children:[s.jsx(Uo,{className:"w-full",children:s.jsx(Bo,{placeholder:"Select an account…"})}),s.jsx($o,{children:m.map(g=>s.jsxs(ba,{value:g.accountId,children:[g.accountName," (",g.accountId,")"]},g.accountId))})]})]})}),s.jsxs("div",{className:"im-form-row im-switch-row",style:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("div",{className:"im-switch-label",children:[s.jsx(Pe,{style:{marginBottom:"4px",display:"block"},children:"Create CloudTrail"}),s.jsx("span",{className:"im-field-hint",children:"Create a new multi-region trail. Turn off if you already have an active CloudTrail."})]}),s.jsx(Wg,{checked:e.createTrail,onCheckedChange:g=>f("createTrail",g)})]})]})}function kV({type:e,name:t,onNameChange:n,deploymentConfig:r,onDeploymentConfigChange:a,onConnectorsLoaded:i}){const o=e==="cloudtrail",l=Qg(e),c=tw[e]??tw.custom,u=s.jsxs(Bg,{children:[s.jsx(Ug,{asChild:!0,children:s.jsx("button",{type:"button",className:"h-7 w-7 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors border border-border/40 focus:outline-none",title:"View deployment info","aria-label":"View deployment info",children:s.jsx(Xu,{className:"h-3.5 w-3.5"})})}),s.jsxs($g,{align:"end",className:"w-80 p-4 text-xs space-y-3 bg-card border-border shadow-xl",children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2.5",children:[s.jsx("span",{className:"im-provider-badge shrink-0",style:{backgroundColor:l.color,width:22,height:22,fontSize:10},children:l.mono}),s.jsxs("div",{className:"font-semibold text-foreground text-sm leading-tight",children:[l.label," Deployment Info"]})]}),s.jsx("ul",{className:"space-y-1.5 list-disc pl-4 text-muted-foreground leading-relaxed",children:c.map((p,d)=>s.jsx("li",{children:p},d))})]})]});return o&&r&&a?s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{children:"Configure deployment"}),s.jsx("p",{children:"Choose your deployment type and CloudTrail settings."})]}),u]}),s.jsx("div",{className:"im-add-config-form mt-2",children:s.jsx(RV,{config:r,onChange:a,onConnectorsLoaded:i})})]}):s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{children:"Configure source"}),s.jsx("p",{children:"Set a name for this source instance."})]}),u]}),s.jsx("div",{className:"im-add-config-form mt-2",children:s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Source name"}),s.jsx(Xe,{value:t,onChange:p=>n(p.target.value),placeholder:"Source name"})]})})]})}const IV="****************";function Ha({value:e,label:t="Copy"}){const[n,r]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),r(!0),window.setTimeout(()=>r(!1),1200)},children:[n?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),n?"Copied":t]})}function _f({steps:e}){return e?.length?s.jsx("ol",{className:"im-add-manual-steps",children:e.map(t=>s.jsx("li",{children:t},t))}):null}function lI({type:e,webhookUrl:t,loading:n,cloudWatch:r,cloudTrail:a,grafana:i,prometheus:o,datadog:l}){const c=Qg(e);return s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"im-add-overview-heading",children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:c.color},children:c.mono}),s.jsxs("div",{children:[s.jsxs("h3",{children:[c.label," deployment"]}),s.jsx("p",{children:"Finish setup in the source system."})]})]}),n?s.jsxs("div",{className:"im-add-loading",children:[s.jsx(Qe,{className:"h-5 w-5 animate-spin"})," Preparing setup details..."]}):e==="cloudwatch"&&r?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-form-grid-3",children:[s.jsxs("div",{children:[s.jsx("span",{children:"AWS Region"}),s.jsx("strong",{children:r.deployment.region})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Stack Name"}),s.jsx("strong",{children:r.deployment.stackName})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Lambda Name"}),s.jsx("strong",{children:r.deployment.lambdaName})]})]}),s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Webhook URL"}),s.jsx("code",{children:r.webhook.url||t})]}),s.jsx(Ha,{value:r.webhook.url||t})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"CloudFormation Template"}),s.jsx("p",{children:"Creates Lambda, EventBridge, IAM role, and invoke permission."})]}),s.jsxs("div",{className:"im-dialog-footer-actions",children:[s.jsx(ie,{type:"button",variant:"outline",asChild:!0,children:s.jsxs("a",{href:r.deployment.templateDownloadUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-4 w-4"})," Download"]})}),s.jsx(ie,{type:"button",className:"im-primary-button",asChild:!0,children:s.jsxs("a",{href:r.deployment.quickCreateUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(ui,{className:"h-4 w-4"})," Connect AWS"]})})]})]})]}):e==="cloudtrail"&&a?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-form-grid-3",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Mode"}),s.jsx("strong",{className:`im-mode-badge ${a.deployment.deploymentMode==="Organizations"?"is-org":"is-standalone"}`,children:a.deployment.deploymentMode})]}),s.jsxs("div",{children:[s.jsx("span",{children:"AWS Region"}),s.jsx("strong",{children:a.deployment.region})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Stack Name"}),s.jsx("strong",{children:a.deployment.stackName})]})]}),s.jsxs("div",{className:"im-deploy-targets-grid",children:[s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"Target Accounts"}),s.jsx("span",{className:"im-target-value",children:a.deployment.deploymentMode==="Organizations"?s.jsxs(s.Fragment,{children:["All accounts in organization",a.deployment.managementAccountName&&s.jsxs(s.Fragment,{children:[" ",s.jsx("code",{className:"im-region-chip",children:a.deployment.managementAccountName}),a.deployment.managementAccountId&&s.jsx("code",{className:"im-region-chip",style:{marginLeft:4},children:a.deployment.managementAccountId})]})]}):a.deployment.targetAccounts?s.jsx("code",{className:"im-region-chip",children:a.deployment.targetAccounts}):"—"})]}),s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"Target Regions"}),s.jsx("span",{className:"im-target-value",children:"All active regions"})]}),s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"CloudTrail"}),s.jsx("span",{className:"im-target-value",children:a.deployment.createNewTrail?"Create new multi-region trail":"Use existing trail"})]})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"Deploy CloudFormation Stack"}),s.jsx("p",{children:a.deployment.deploymentMode==="Organizations"?"Deploys security monitoring across all AWS Organization accounts and active regions in a single automated template.":"Deploys CloudTrail, SNS, EventBridge rules, and notification Lambda to your account."})]}),s.jsxs("div",{className:"im-dialog-footer-actions",children:[s.jsx(ie,{type:"button",variant:"outline",asChild:!0,children:s.jsxs("a",{href:a.deployment.templateDownloadUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-4 w-4"})," Download"]})}),s.jsx(ie,{type:"button",className:"im-primary-button",asChild:!0,children:s.jsxs("a",{href:a.deployment.quickCreateUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(ui,{className:"h-4 w-4"})," Connect AWS"]})})]})]})]}):e==="grafana"&&i?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Grafana webhook URL"}),s.jsx("code",{children:i.webhook.url||t})]}),s.jsx(Ha,{value:i.webhook.url||t})]}),s.jsxs("div",{className:"im-grafana-review-grid",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Grafana URL"}),s.jsx(Xe,{value:i.defaults.grafanaBaseUrl||i.setup?.grafanaBaseUrl||"",readOnly:!0,placeholder:"https://grafana.example.com"})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Contact Point Name"}),s.jsx(Xe,{value:i.defaults.contactPointName||i.setup?.contactPointName||"",readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Account Token"}),s.jsx(Xe,{type:"password",value:i.defaults.hasAccountToken?i.defaults.accountTokenMasked||IV:"",readOnly:!0,placeholder:"glsa_..."})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Notification Route"}),s.jsx(Xe,{value:i.setup?.matcher?`${i.setup.matcher.label}=${i.setup.matcher.value}`:`${i.defaults.matcherLabel}=${i.defaults.matcherValue}`,readOnly:!0})]})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"Grafana automatic setup"}),s.jsx("p",{children:"Paste a service account token in the source setup tab to create or update the contact point automatically."})]}),s.jsx(Ha,{value:`Name: ${i.defaults.contactPointName}
68
+ export AWS_DEFAULT_REGION=ap-south-1`}),U?s.jsx("div",{className:"text-xs text-destructive",children:U}):null,s.jsx("div",{className:"flex justify-end",children:s.jsx(ie,{type:"button",size:"sm",onClick:q,children:"Apply JSON"})})]}):null]}),s.jsxs("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"AWS Access Key ID"}),s.jsx(Xe,{type:"password",value:a.accessKeyId,onChange:P=>f({accessKeyId:P.target.value}),placeholder:"AKIA...",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"AWS Secret Access Key"}),s.jsx(Xe,{type:"password",value:a.secretAccessKey,onChange:P=>f({secretAccessKey:P.target.value}),placeholder:"Secret key",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Session Token (Optional for STS/SSO)"}),s.jsx(Xe,{type:"password",value:a.sessionToken,onChange:P=>f({sessionToken:P.target.value}),placeholder:"Required when access key starts with ASIA...",autoComplete:"off"})]})]}),s.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Region"}),s.jsx(Xe,{value:a.region,onChange:P=>f({region:P.target.value}),placeholder:"ap-south-1"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Stack Name"}),s.jsx(Xe,{value:a.stackName,onChange:P=>f({stackName:P.target.value}),placeholder:"meyi-cloudwatch-xxxx"})]})]}),s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:"Alarm Defaults"}),s.jsx(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>M(P=>!P),children:O?"Hide Alarm Defaults":"Edit Alarm Defaults"})]}),O?s.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Threshold"}),s.jsx(Xe,{type:"number",step:"any",value:o.threshold,onChange:P=>h({threshold:P.target.value}),placeholder:"50"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Period (sec)"}),s.jsx(Xe,{type:"number",value:o.period,onChange:P=>h({period:P.target.value}),placeholder:"60"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Evaluation Periods"}),s.jsx(Xe,{type:"number",value:o.evaluationPeriods,onChange:P=>h({evaluationPeriods:P.target.value}),placeholder:"1"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Statistic"}),s.jsx(Bn,{label:"Select statistic",className:"im-single-select-full",value:o.statistic,onValueChange:P=>h({statistic:P}),options:[{label:"Average",value:"Average"},{label:"Sum",value:"Sum"},{label:"Minimum",value:"Minimum"},{label:"Maximum",value:"Maximum"},{label:"SampleCount",value:"SampleCount"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Comparison"}),s.jsx(Bn,{label:"Select comparison",className:"im-single-select-full",value:o.comparisonOperator,onValueChange:P=>h({comparisonOperator:P}),options:[{label:"GreaterThanOrEqualToThreshold",value:"GreaterThanOrEqualToThreshold"},{label:"GreaterThanThreshold",value:"GreaterThanThreshold"},{label:"LessThanThreshold",value:"LessThanThreshold"},{label:"LessThanOrEqualToThreshold",value:"LessThanOrEqualToThreshold"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Treat Missing Data"}),s.jsx(Bn,{label:"Select missing-data mode",className:"im-single-select-full",value:o.treatMissingData,onValueChange:P=>h({treatMissingData:P}),options:[{label:"breaching",value:"breaching"},{label:"notBreaching",value:"notBreaching"},{label:"ignore",value:"ignore"},{label:"missing",value:"missing"}]})]})]}):s.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Threshold ",o.threshold,", period ",o.period,"s, eval ",o.evaluationPeriods,", statistic ",o.statistic,"."]})]})]}),s.jsx(ss,{value:"naming",className:"space-y-3",children:s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Lambda Name"}),s.jsx(Xe,{value:i.lambdaName,onChange:P=>m({lambdaName:P.target.value}),placeholder:"meyi-cloudwatch-forwarder-xxxx",autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Alarm Name Prefix"}),s.jsx(Xe,{value:i.alarmNamePrefix,onChange:P=>m({alarmNamePrefix:P.target.value}),placeholder:"meyi-alerts-xxxx",autoComplete:"off"})]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Suggested names are auto-filled. You can override them, and deploy will use these names in CloudFormation and AWS resources."})]})})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{onClick:x,disabled:!r||!!t||!!n,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):s.jsx(Ra,{className:"h-4 w-4"}),"Fetch Metrics & Alarms"]}),u?.aws?.accessKeyIdMasked?s.jsxs("span",{className:"text-xs text-muted-foreground",children:["Saved Credentials: ",u.aws.accessKeyIdMasked]}):null]}),u?s.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsx("div",{className:"mb-2 text-sm font-medium",children:"CloudWatch Alarms"}),s.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto pr-1",children:u.alarms.length===0?s.jsx("p",{className:"text-xs text-muted-foreground",children:"No alarms found in this region."}):u.alarms.map(P=>s.jsxs("label",{className:"flex items-start gap-2 rounded px-1 py-1 hover:bg-muted/40",children:[s.jsx("input",{type:"checkbox",checked:N.has(P.alarmName),onChange:z=>g(P.alarmName,z.target.checked),className:"mt-0.5"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-xs font-medium break-all",children:P.alarmName}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[P.namespace||"-"," / ",P.metricName||"-"," / ",P.stateValue||"-"]})]})]},P.alarmName))})]}),s.jsxs("div",{className:"rounded-md border p-3",children:[s.jsx("div",{className:"mb-2 text-sm font-medium",children:"CloudWatch Metrics"}),s.jsx("div",{className:"max-h-72 overflow-y-auto pr-1",children:u.metrics.length===0?s.jsx("p",{className:"text-xs text-muted-foreground",children:"No metrics found."}):s.jsx("ul",{className:"space-y-1",children:u.metrics.map(P=>s.jsx("li",{children:s.jsxs("label",{className:"flex items-start gap-2 rounded px-1 py-1 hover:bg-muted/40",children:[s.jsx("input",{type:"checkbox",checked:A.has(`${P.namespace}::${P.metricName}`),onChange:z=>b(`${P.namespace}::${P.metricName}`,z.target.checked),className:"mt-0.5"}),s.jsxs("span",{className:"text-xs",children:[s.jsx("span",{className:"text-muted-foreground",children:P.namespace})," / ",P.metricName]})]})},`${P.namespace}:${P.metricName}`))})})]})]}):null,s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{onClick:S,disabled:!u||!!n||!!t,children:[n?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Deploy AWS Automation"]}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"Creates/updates CloudWatch alarms from selected metrics and wires AlarmActions to Lambda."})]}),p?s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment Result"}),s.jsxs("div",{className:"text-xs",children:["Action: ",s.jsx("span",{className:"font-medium",children:p.deployment.action})," | Status:"," ",s.jsx("span",{className:"font-medium",children:p.deployment.stackStatus||"-"})]}),s.jsxs("div",{className:"text-xs",children:["Lambda Name: ",p.deployment.lambdaName||"-"]}),s.jsxs("div",{className:"text-xs",children:["Alarm Prefix: ",p.deployment.alarmNamePrefix||"-"]}),s.jsxs("div",{className:"text-xs break-all",children:["Stack ID: ",p.deployment.stackId||"-"]}),s.jsxs("div",{className:"text-xs",children:["Created/Updated Alarms: ",p.deployment.createdAlarmNames?.length||0]}),s.jsxs("div",{className:"text-xs break-all",children:["Webhook URL: ",p.webhook.url]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[s.jsx(hV,{value:p.webhook.url}),d?s.jsx(ie,{asChild:!0,variant:"outline",size:"sm",children:s.jsx("a",{href:d,target:"_blank",rel:"noreferrer",children:"Download CloudFormation Template"})}):null]})]}):null]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>T(!1),disabled:!!t||!!n,children:"Close"})})]})})}function Cf({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function bV({href:e,label:t}){return s.jsx(ie,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-3.5 w-3.5"}),t]})})}function xV({open:e,loading:t,data:n,prometheusBaseUrl:r,alertmanagerBaseUrl:a,checkingStatus:i,statusResult:o,onPrometheusBaseUrlChange:l,onAlertmanagerBaseUrlChange:c,onCheckStatus:u,onRefresh:p,onOpenChange:d}){const f=!!(t||i),[m,h]=w.useState("docker"),g=m==="linux"?n?.defaults.linuxCommand:m==="kubernetes"?n?.defaults.kubernetesCommand:n?.defaults.dockerCommand,b=m==="linux"?n?.downloads?.linuxScript:m==="kubernetes"?n?.downloads?.kubernetesYaml:n?.downloads?.dockerScript,x=m==="kubernetes"?"Download YAML":"Download Script",S={docker:kC,linux:jC,kubernetes:SC},T=o?.status==="configured"?"border-emerald-200 bg-emerald-50 text-emerald-800":o?.status==="failed"?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800";return s.jsx(kt,{open:e,onOpenChange:N=>!f&&d(N),children:s.jsxs(It,{className:"w-[96vw] max-w-4xl max-h-[88vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Prometheus Setup"}),s.jsx(Kt,{children:"Generate a setup script or Kubernetes YAML to connect Alertmanager to Meyi Connect."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(ie,{variant:"outline",size:"sm",onClick:p,disabled:f,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):s.jsx(Ra,{className:"h-4 w-4"}),"Refresh"]}),n?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:n.webhook.url})]}),s.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment status check"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Run this after applying the setup script/YAML. It checks readiness and whether Alertmanager has the Meyi receiver."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Prometheus URL"}),s.jsx(Xe,{value:r,onChange:N=>l(N.target.value),placeholder:"http://65.2.144.245:9090"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Alertmanager URL"}),s.jsx(Xe,{value:a,onChange:N=>c(N.target.value),placeholder:"http://65.2.144.245:9093"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:f,children:[i?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Check Status"]}),o?s.jsxs("div",{className:`rounded-md border px-3 py-1.5 text-xs ${T}`,children:[s.jsx("span",{className:"font-semibold",children:o.status.replace(/_/g," ")}),o.reason?s.jsxs("span",{children:[" - ",o.reason]}):null]}):null]})]}),s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:(n.environments||[]).map(N=>{const A=S[N.id],C=m===N.id;return s.jsxs("button",{type:"button",onClick:()=>h(N.id),className:`rounded-lg border p-3 text-left transition ${C?"border-primary bg-primary/5 shadow-sm":"bg-background hover:bg-muted/30"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(A,{className:"h-4 w-4 text-primary"}),N.label]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:N.description})]},N.id)})}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Automated setup"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Download and run this on the Prometheus host or cluster."})]}),b?s.jsx(bV,{href:b,label:x}):null]}),g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"rounded-md border bg-background p-2 text-xs break-all font-mono",children:g}),s.jsx(Cf,{value:g})]}):null]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"How it works"}),s.jsx("ol",{className:"list-decimal list-inside space-y-1 text-xs text-muted-foreground",children:n.manual.steps.map((N,A)=>s.jsx("li",{children:N},A))})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Manual alertmanager.yml snippet"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono whitespace-pre-wrap",children:n.snippets.alertmanagerConfig}),s.jsx(Cf,{value:n.snippets.alertmanagerConfig})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Reload Command"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono",children:n.snippets.reloadCommand}),s.jsx(Cf,{value:n.snippets.reloadCommand})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:n.snippets.note})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Load setup details to continue."})]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>d(!1),disabled:f,children:"Close"})})]})})}function yV({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function EV({open:e,loading:t,configuring:n,data:r,result:a,site:i,webhookName:o,datadogApiKey:l,datadogAppKey:c,onSiteChange:u,onWebhookNameChange:p,onDatadogApiKeyChange:d,onDatadogAppKeyChange:f,onRefresh:m,onConfigure:h,onOpenChange:g}){const b=!!(t||n);return s.jsx(kt,{open:e,onOpenChange:x=>!b&&g(x),children:s.jsxs(It,{className:"w-[96vw] max-w-4xl max-h-[88vh] overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Datadog Setup"}),s.jsx(Kt,{children:"Configure this Datadog source manually or automatically via Datadog API."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(ie,{variant:"outline",onClick:m,disabled:b,children:[t?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh"]}),r?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:r.webhook.url})]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Manual Setup"}),s.jsx("ol",{className:"list-decimal list-inside space-y-1 text-xs text-muted-foreground",children:r.manual.steps.map((x,S)=>s.jsx("li",{children:x},S))}),s.jsx("div",{className:"rounded-md border bg-background/70 p-2 text-xs font-mono",children:r.defaults.notifyHandle})]}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsx("div",{className:"text-sm font-medium",children:"Automatic Setup"}),s.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddSite",children:"Datadog Site"}),s.jsx(Xe,{id:"ddSite",value:i,onChange:x=>u(x.target.value),placeholder:"datadoghq.com",disabled:b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddWebhookName",children:"Webhook Name"}),s.jsx(Xe,{id:"ddWebhookName",value:o,onChange:x=>p(x.target.value),disabled:b})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddApiKey",children:"Datadog API Key"}),s.jsx(Xe,{id:"ddApiKey",type:"password",value:l,onChange:x=>d(x.target.value),disabled:b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ddAppKey",children:"Datadog Application Key"}),s.jsx(Xe,{id:"ddAppKey",type:"password",value:c,onChange:x=>f(x.target.value),disabled:b})]}),s.jsxs(ie,{onClick:h,disabled:b,children:[n?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Configure Automatically"]})]}),a?s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3 text-xs",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Action:"})," ",a.action]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Site:"})," ",a.site]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Webhook Name:"})," ",a.webhookName]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Notify Handle:"}),s.jsx("span",{className:"font-mono",children:a.notifyHandle}),s.jsx(yV,{value:a.notifyHandle})]})]}):null]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Load setup details to continue."})]}),s.jsx($t,{children:s.jsx(ie,{variant:"outline",onClick:()=>g(!1),disabled:b,children:"Close"})})]})})}const J1={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus / Alertmanager",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom / SDK",mono:"CU",color:"#5A6B7B"}};function oI(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function vV(e){const t=typeof window<"u"?window.location.origin:"";return e.webhookUrl?.startsWith("http://")||e.webhookUrl?.startsWith("https://")?e.webhookUrl:e.webhookUrl?.startsWith("/api/v1/")?`${t}${e.webhookUrl}`:e.webhookUrl?.startsWith("/")?`${t}/api/v1${e.webhookUrl}`:`${t}/api/v1/insight/webhook/${e.webhookToken}`}function SV(e){const t=e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt;if(!t)return"Never";const n=Date.now()-new Date(t).getTime();if(!Number.isFinite(n)||n<0)return"just now";const r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r} minute${r===1?"":"s"} ago`;const a=Math.floor(r/60);if(a<24)return`${a} hour${a===1?"":"s"} ago`;const i=Math.floor(a/24);return`${i} day${i===1?"":"s"} ago`}function wV(e){const t=oI(e.type);return t==="cloudwatch"?`aws ****${e.id.slice(-4)} - ${e.awsStackName||"sns:prod-alarms"} - ${e.awsRegion||"us-east-1"} - production`:t==="cloudtrail"?`aws ****${e.id.slice(-4)} - ${e.awsStackName||"cloudtrail:security"} - ${e.awsRegion||"us-east-1"} - security`:t==="grafana"?`${e.grafanaBaseUrl||"https://grafana.meyi.io"} - production`:t==="prometheus"?`${e.prometheusEnvironment||"k8s-prod"} - alertmanager.yml`:e.description||e.webhookUrl||"production"}function ew(e){return e.isActive?e.deliveryStatus==="failed"?"Error":"Active":"Disabled"}function TV(e){const t=e.webhookToken||"";return t?`${t.slice(0,7)}************${t.slice(-3)}`:"whk_cl_************cw1"}function NV(e){const t=Math.max(1,Number(e||47));return[.74,.58,.88,.65,.83,.88,.56].map((n,r)=>Math.max(44,Math.round(130*Math.min(1,n+(t+r)%11/100))))}function CV({open:e,source:t,onOpenChange:n}){const[r,a]=w.useState(!1),i=w.useMemo(()=>t?vV(t):"",[t]);if(!t)return s.jsx(kt,{open:e,onOpenChange:n});const o=oI(t.type),l=J1[o]||J1.custom,c=Number(t.alertCount||0),u=Number(t.webhookFailureCount||0);return s.jsx(kt,{open:e,onOpenChange:n,children:s.jsx(It,{className:"im-source-detail-dialog p-0",children:s.jsxs("div",{className:"im-source-detail-page",children:[s.jsxs("div",{className:"im-detail-header",children:[s.jsxs("div",{className:"im-detail-title-wrap",children:[s.jsx("span",{className:"im-provider-badge im-detail-provider",style:{backgroundColor:l.color},children:l.mono}),s.jsxs("div",{children:[s.jsxs("div",{className:"im-detail-title-line",children:[s.jsx("h2",{children:t.name||`${l.label} source`}),s.jsx("span",{className:`im-state-chip ${t.isActive?"is-active":"is-disabled"}`,children:ew(t)})]}),s.jsx("p",{children:wV(t)})]})]}),s.jsxs("div",{className:"im-detail-actions",children:[s.jsx(ie,{variant:"outline",type:"button",children:t.isActive?"Disable":"Enable"}),s.jsx(ie,{variant:"outline",type:"button",children:"Test connection"}),s.jsx(ie,{variant:"outline",size:"icon",type:"button","aria-label":"More source actions",children:s.jsx(hs,{size:18})})]})]}),s.jsxs("div",{className:"im-detail-tabs",role:"tablist","aria-label":"Source details",children:[s.jsx("button",{className:"is-active",type:"button",children:"Overview"}),s.jsx("button",{type:"button",children:"Alerts"}),s.jsx("button",{type:"button",children:"Configuration"}),s.jsx("button",{type:"button",children:"Logs"}),s.jsx("button",{type:"button",children:"Test"})]}),s.jsxs("div",{className:"im-detail-stats",children:[s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Status"}),s.jsxs("strong",{children:[s.jsx("i",{className:`im-status-dot im-status-${t.isActive?"active":"disabled"}`}),ew(t)]})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Last alert"}),s.jsx("strong",{children:SV(t)})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Alerts today"}),s.jsx("strong",{children:c})]}),s.jsxs("div",{className:"im-detail-stat",children:[s.jsx("span",{children:"Errors (1h)"}),s.jsx("strong",{className:u>0?"is-danger":"",children:u})]})]}),s.jsxs("div",{className:"im-detail-grid",children:[s.jsxs("section",{className:"im-detail-card im-rate-card",children:[s.jsx("h3",{children:"7-day alert rate"}),s.jsx("div",{className:"im-bar-chart","aria-label":"7-day alert rate",children:NV(c).map((p,d)=>s.jsxs("div",{className:"im-bar-col",children:[s.jsx("span",{style:{height:p}}),s.jsx("small",{children:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][d]})]},d))})]}),s.jsxs("section",{className:"im-detail-card im-webhook-card",children:[s.jsx("h3",{children:"Webhook endpoint"}),s.jsxs("div",{className:"im-code-row",children:[s.jsx("code",{children:i}),s.jsx("button",{type:"button","aria-label":"Copy webhook endpoint",onClick:()=>{Vn(i),a(!0),window.setTimeout(()=>a(!1),1500)},children:r?s.jsx(Yt,{size:15}):s.jsx(yn,{size:15})})]}),s.jsx("label",{children:"Auth token"}),s.jsx("div",{className:"im-token-row",children:TV(t)})]})]})]})})})}const rh=[{type:"cloudwatch",label:"CloudWatch",description:"Receive CloudWatch alarms via an SNS topic subscription",mono:"CW",color:"#E67E22"},{type:"cloudtrail",label:"Level 1 Security",description:"Stream CloudTrail security events via EventBridge into Meyi",mono:"L1",color:"#D35400"},{type:"grafana",label:"Grafana",description:"Forward Grafana alerts through a webhook contact point",mono:"GF",color:"#C0392B"},{type:"prometheus",label:"Prometheus / Alertmanager",description:"Ingest Alertmanager alerts via authenticated webhook",mono:"PR",color:"#8E44AD"},{type:"cost",label:"AWS Cost",description:"Connect an AWS account for Cost Explorer and CUR data",mono:"$",color:"#167A6A"},{type:"custom",label:"Custom / SDK",description:"Push any source using the ingest API and SDK",mono:"</>",color:"#5A6B7B"}];function Qg(e){return rh.find(t=>t.type===e)??rh[0]}const tw={cloudwatch:["Creates an authenticated webhook for CloudWatch.","Prepares a CloudFormation template with Lambda, EventBridge, and IAM permissions.","Events are forwarded to Meyi automatically upon stack creation."],cloudtrail:["Creates an authenticated webhook for CloudTrail security monitoring.","Generates a CloudFormation central-stack with S3, SNS, and EventBridge security rules.","Security events flow into Meyi in real-time across selected AWS accounts."],grafana:["Creates an authenticated webhook endpoint for Grafana alert delivery.","Provides contact point configuration details for Grafana alert rules."],prometheus:["Creates an authenticated Alertmanager webhook receiver.","Provides setup configurations for Docker, Linux, and Kubernetes."],datadog:["Creates an authenticated webhook endpoint for Datadog monitor events.","Provides Datadog webhook integration settings."],custom:["Creates an authenticated webhook for custom collectors and SDKs.","Send normalized event payloads directly to the ingestion endpoint."],meyi_pulse:["Creates an authenticated source for native pulse events."],pagerduty:["Creates an authenticated webhook endpoint for PagerDuty incident payloads."]};function AV({selected:e,onSelect:t}){return s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsx("h3",{children:"Choose a source type"}),s.jsx("p",{children:"Each instance connects one account or endpoint. Add more instances later for additional accounts."}),s.jsx("div",{className:"im-source-grid",children:rh.map(n=>{const r=e===n.type;return s.jsxs("button",{type:"button",onClick:()=>t(n.type),className:`im-source-card ${r?"is-selected":""}`,children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:n.color},children:n.mono==="</>"?s.jsx(EF,{size:18}):n.mono}),s.jsxs("span",{children:[s.jsx("strong",{children:n.label}),s.jsx("small",{children:n.description})]})]},n.type)})})]})}const _V={async list(){return(await Rt.get("/api/v1/connectors",{withCredentials:!0})).data},async getById(e){try{return(await Rt.get(`/api/v1/connectors/${e}`,{withCredentials:!0})).data?.connector??null}catch{return null}}},Af={deploymentMode:"Organizations",targetAccounts:"",managementAccountId:void 0,createTrail:!0};function RV({config:e,onChange:t,onConnectorsLoaded:n}){const r=e.deploymentMode==="Organizations",[a,i]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(null),[p,d]=w.useState(null);function f(g,b){const x={...e,[g]:b};g==="deploymentMode"&&(x.targetAccounts=""),t(x)}w.useEffect(()=>{l(!0),u(null),_V.list().then(({connectors:g})=>{i(g);const b=g.filter(S=>!!(S.managementAccountId&&S.accountId&&S.managementAccountId===S.accountId));let x=null;e.managementAccountId&&(x=b.find(S=>S.accountId===e.managementAccountId)||null),x||(x=b[0]??g.find(S=>S.connectionStatus==="CONNECTED")??g[0]??null),d(x),x&&!e.managementAccountId&&b.length>1&&f("managementAccountId",x.accountId),n?.(x,g),g.length===0&&u("No AWS account connectors found. Complete onboarding in the Connectors section first.")}).catch(()=>{u("Failed to load connectors. Please refresh and try again.")}).finally(()=>l(!1))},[]);const m=a.filter(g=>g.connectionStatus==="CONNECTED"),h=a.filter(g=>!!(g.managementAccountId&&g.accountId&&g.managementAccountId===g.accountId));return s.jsxs("div",{className:"im-cloudtrail-deploy-form",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Deployment Type"}),s.jsxs("div",{className:"im-radio-group",children:[s.jsxs("label",{className:`im-radio-option ${r?"is-selected":""}`,children:[s.jsx("input",{type:"radio",name:"deploymentMode",value:"Organizations",checked:r,onChange:()=>f("deploymentMode","Organizations")}),s.jsxs("span",{className:"im-radio-label",children:[s.jsx("strong",{children:"Organizations"}),s.jsx("small",{children:"Deploy across your entire AWS Organization automatically"})]})]}),s.jsxs("label",{className:`im-radio-option ${r?"":"is-selected"}`,children:[s.jsx("input",{type:"radio",name:"deploymentMode",value:"Standalone",checked:!r,onChange:()=>f("deploymentMode","Standalone")}),s.jsxs("span",{className:"im-radio-label",children:[s.jsx("strong",{children:"Standalone"}),s.jsx("small",{children:"Deploy to a single specific AWS account"})]})]})]})]}),r&&s.jsx("div",{className:"im-form-row",children:o?s.jsx("div",{className:"im-connector-loading",children:"Loading connector information…"}):c?s.jsxs("div",{className:"im-connector-error-banner",children:[s.jsx("span",{className:"im-connector-error-icon",children:"⚠"}),c]}):h.length>1?s.jsxs("div",{children:[s.jsxs(Pe,{className:"mb-1.5 block",children:["Target AWS Organization ",s.jsx("span",{className:"im-required-badge",children:"Required"})]}),s.jsxs(Fo,{value:e.managementAccountId||p?.accountId||"",onValueChange:g=>{const b=h.find(x=>x.accountId===g)||null;d(b),f("managementAccountId",g),n?.(b,a)},children:[s.jsx(Uo,{className:"w-full",children:s.jsx(Bo,{placeholder:"Select an organization management account…"})}),s.jsx($o,{children:h.map(g=>s.jsxs(ba,{value:g.accountId,children:[g.accountName," (",g.accountId,")"]},g.accountId))})]})]}):p?s.jsxs("div",{children:[s.jsx(Pe,{className:"mb-1.5 block",children:"Management Account"}),s.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-lg border border-border bg-muted/20 text-sm",children:[s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-semibold text-foreground truncate",children:p.accountName}),s.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:p.accountId})]}),s.jsx("span",{className:"text-xs px-2.5 py-0.5 rounded border border-border/80 text-muted-foreground bg-card shrink-0",children:"Management"})]})]}):s.jsxs("div",{className:"p-4 rounded-lg border border-dashed border-border/80 bg-muted/10 text-center space-y-1",children:[s.jsx("p",{className:"text-sm font-medium text-foreground",children:"No AWS Organization found"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Complete AWS onboarding in the Connectors section to enable Organization deployment."})]})}),!r&&s.jsx("div",{className:"im-form-row",children:o?s.jsx("div",{className:"im-connector-loading",children:"Loading connectors…"}):c?s.jsxs("div",{className:"im-connector-error-banner",children:[s.jsx("span",{className:"im-connector-error-icon",children:"⚠"}),c]}):m.length===0?s.jsxs("div",{className:"p-4 rounded-lg border border-dashed border-border/80 bg-muted/10 text-center space-y-1",children:[s.jsx("p",{className:"text-sm font-medium text-foreground",children:"No connected accounts found"}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Only accounts with status ",s.jsx("strong",{children:"CONNECTED"})," can be used for Standalone deployment."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Pe,{className:"mb-1.5 block",children:["Target Account ",s.jsx("span",{className:"im-required-badge",children:"Required"})]}),s.jsxs(Fo,{value:e.targetAccounts,onValueChange:g=>f("targetAccounts",g),children:[s.jsx(Uo,{className:"w-full",children:s.jsx(Bo,{placeholder:"Select an account…"})}),s.jsx($o,{children:m.map(g=>s.jsxs(ba,{value:g.accountId,children:[g.accountName," (",g.accountId,")"]},g.accountId))})]})]})}),s.jsxs("div",{className:"im-form-row im-switch-row",style:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("div",{className:"im-switch-label",children:[s.jsx(Pe,{style:{marginBottom:"4px",display:"block"},children:"Create CloudTrail"}),s.jsx("span",{className:"im-field-hint",children:"Create a new multi-region trail. Turn off if you already have an active CloudTrail."})]}),s.jsx(Wg,{checked:e.createTrail,onCheckedChange:g=>f("createTrail",g)})]})]})}function kV({type:e,name:t,onNameChange:n,deploymentConfig:r,onDeploymentConfigChange:a,onConnectorsLoaded:i}){const o=e==="cloudtrail",l=Qg(e),c=tw[e]??tw.custom,u=s.jsxs(Bg,{children:[s.jsx(Ug,{asChild:!0,children:s.jsx("button",{type:"button",className:"h-7 w-7 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors border border-border/40 focus:outline-none",title:"View deployment info","aria-label":"View deployment info",children:s.jsx(Xu,{className:"h-3.5 w-3.5"})})}),s.jsxs($g,{align:"end",className:"w-80 p-4 text-xs space-y-3 bg-card border-border shadow-xl",children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2.5",children:[s.jsx("span",{className:"im-provider-badge shrink-0",style:{backgroundColor:l.color,width:22,height:22,fontSize:10},children:l.mono}),s.jsxs("div",{className:"font-semibold text-foreground text-sm leading-tight",children:[l.label," Deployment Info"]})]}),s.jsx("ul",{className:"space-y-1.5 list-disc pl-4 text-muted-foreground leading-relaxed",children:c.map((p,d)=>s.jsx("li",{children:p},d))})]})]});return o&&r&&a?s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{children:"Configure deployment"}),s.jsx("p",{children:"Choose your deployment type and CloudTrail settings."})]}),u]}),s.jsx("div",{className:"im-add-config-form mt-2",children:s.jsx(RV,{config:r,onChange:a,onConnectorsLoaded:i})})]}):s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{children:"Configure source"}),s.jsx("p",{children:"Set a name for this source instance."})]}),u]}),s.jsx("div",{className:"im-add-config-form mt-2",children:s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Source name"}),s.jsx(Xe,{value:t,onChange:p=>n(p.target.value),placeholder:"Source name"})]})})]})}const IV="****************";function Ha({value:e,label:t="Copy"}){const[n,r]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),r(!0),window.setTimeout(()=>r(!1),1200)},children:[n?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),n?"Copied":t]})}function _f({steps:e}){return e?.length?s.jsx("ol",{className:"im-add-manual-steps",children:e.map(t=>s.jsx("li",{children:t},t))}):null}function lI({type:e,webhookUrl:t,loading:n,cloudWatch:r,cloudTrail:a,grafana:i,prometheus:o,datadog:l}){const c=Qg(e);return s.jsxs("div",{className:"im-add-dialog-body",children:[s.jsxs("div",{className:"im-add-overview-heading",children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:c.color},children:c.mono}),s.jsxs("div",{children:[s.jsxs("h3",{children:[c.label," deployment"]}),s.jsx("p",{children:"Finish setup in the source system."})]})]}),n?s.jsxs("div",{className:"im-add-loading",children:[s.jsx(Qe,{className:"h-5 w-5 animate-spin"})," Preparing setup details..."]}):e==="cloudwatch"&&r?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-form-grid-3",children:[s.jsxs("div",{children:[s.jsx("span",{children:"AWS Region"}),s.jsx("strong",{children:r.deployment.region})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Stack Name"}),s.jsx("strong",{children:r.deployment.stackName})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Lambda Name"}),s.jsx("strong",{children:r.deployment.lambdaName})]})]}),s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Webhook URL"}),s.jsx("code",{children:r.webhook.url||t})]}),s.jsx(Ha,{value:r.webhook.url||t})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"CloudFormation Template"}),s.jsx("p",{children:"Creates Lambda, EventBridge, IAM role, and invoke permission."})]}),s.jsxs("div",{className:"im-dialog-footer-actions",children:[s.jsx(ie,{type:"button",variant:"outline",asChild:!0,children:s.jsxs("a",{href:r.deployment.templateDownloadUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-4 w-4"})," Download"]})}),s.jsx(ie,{type:"button",className:"im-primary-button",asChild:!0,children:s.jsxs("a",{href:r.deployment.quickCreateUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(ui,{className:"h-4 w-4"})," Connect AWS"]})})]})]})]}):e==="cloudtrail"&&a?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-form-grid-3",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Mode"}),s.jsx("strong",{className:`im-mode-badge ${a.deployment.deploymentMode==="Organizations"?"is-org":"is-standalone"}`,children:a.deployment.deploymentMode})]}),s.jsxs("div",{children:[s.jsx("span",{children:"AWS Region"}),s.jsx("strong",{children:a.deployment.region})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Stack Name"}),s.jsx("strong",{children:a.deployment.stackName})]})]}),s.jsxs("div",{className:"im-deploy-targets-grid",children:[s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"Target Accounts"}),s.jsx("span",{className:"im-target-value",children:a.deployment.deploymentMode==="Organizations"?s.jsxs(s.Fragment,{children:["All accounts in organization",a.deployment.managementAccountName&&s.jsxs(s.Fragment,{children:[" ",s.jsx("code",{className:"im-region-chip",children:a.deployment.managementAccountName}),a.deployment.managementAccountId&&s.jsx("code",{className:"im-region-chip",style:{marginLeft:4},children:a.deployment.managementAccountId})]})]}):a.deployment.targetAccounts?s.jsx("code",{className:"im-region-chip",children:a.deployment.targetAccounts}):"—"})]}),s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"Target Regions"}),s.jsx("span",{className:"im-target-value",children:"All active regions"})]}),s.jsxs("div",{className:"im-deploy-target-row",children:[s.jsx("span",{className:"im-target-label",children:"CloudTrail"}),s.jsx("span",{className:"im-target-value",children:a.deployment.createNewTrail?"Create new multi-region trail":"Use existing trail"})]})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"Deploy CloudFormation Stack"}),s.jsx("p",{children:a.deployment.deploymentMode==="Organizations"?"Deploys security monitoring across all AWS Organization accounts and active regions in a single automated template.":"Deploys CloudTrail, SNS, EventBridge rules, and notification Lambda to your account."})]}),s.jsxs("div",{className:"im-dialog-footer-actions",children:[s.jsx(ie,{type:"button",variant:"outline",asChild:!0,children:s.jsxs("a",{href:a.deployment.templateDownloadUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-4 w-4"})," Download"]})}),s.jsx(ie,{type:"button",className:"im-primary-button",asChild:!0,children:s.jsxs("a",{href:a.deployment.quickCreateUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(ui,{className:"h-4 w-4"})," Connect AWS"]})})]})]})]}):e==="grafana"&&i?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Grafana webhook URL"}),s.jsx("code",{children:i.webhook.url||t})]}),s.jsx(Ha,{value:i.webhook.url||t})]}),s.jsxs("div",{className:"im-grafana-review-grid",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Grafana URL"}),s.jsx(Xe,{value:i.defaults.grafanaBaseUrl||i.setup?.grafanaBaseUrl||"",readOnly:!0,placeholder:"https://grafana.example.com"})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Contact Point Name"}),s.jsx(Xe,{value:i.defaults.contactPointName||i.setup?.contactPointName||"",readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Account Token"}),s.jsx(Xe,{type:"password",value:i.defaults.hasAccountToken?i.defaults.accountTokenMasked||IV:"",readOnly:!0,placeholder:"glsa_..."})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Notification Route"}),s.jsx(Xe,{value:i.setup?.matcher?`${i.setup.matcher.label}=${i.setup.matcher.value}`:`${i.defaults.matcherLabel}=${i.defaults.matcherValue}`,readOnly:!0})]})]}),s.jsxs("div",{className:"im-add-template-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"Grafana automatic setup"}),s.jsx("p",{children:"Paste a service account token in the source setup tab to create or update the contact point automatically."})]}),s.jsx(Ha,{value:`Name: ${i.defaults.contactPointName}
69
69
  Integration: Webhook
70
70
  Webhook URL: ${i.webhook.url||t}`,label:"Copy details"})]}),s.jsx(_f,{steps:i.manual.steps})]}):e==="prometheus"&&o?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Alertmanager webhook URL"}),s.jsx("code",{children:o.webhook.url||t})]}),s.jsx(Ha,{value:o.webhook.url||t})]}),s.jsxs("div",{className:"im-add-template-card im-add-command-card",children:[s.jsxs("div",{children:[s.jsx("h4",{children:"Generated setup command"}),s.jsx("p",{children:"Run this on the Prometheus or Alertmanager host."})]}),s.jsx(Ha,{value:o.defaults.dockerCommand||o.snippets.alertmanagerConfig,label:"Copy command"})]}),s.jsx("pre",{className:"im-add-code-block",children:o.defaults.dockerCommand||o.snippets.alertmanagerConfig}),s.jsx(_f,{steps:o.manual.steps})]}):e==="datadog"&&l?s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Datadog webhook URL"}),s.jsx("code",{children:l.webhook.url||t})]}),s.jsx(Ha,{value:l.webhook.url||t})]}),s.jsxs("p",{children:["Webhook name: ",s.jsx("strong",{children:l.defaults.webhookName})]}),s.jsx(_f,{steps:l.manual.steps})]}):s.jsxs("section",{className:"im-add-deploy-card",children:[s.jsxs("div",{className:"im-add-webhook-card",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Webhook URL"}),s.jsx("code",{children:t})]}),s.jsx(Ha,{value:t})]}),s.jsx("pre",{className:"im-add-code-block",children:`POST ${t}
71
71
  Content-Type: application/json
@@ -107,7 +107,7 @@ aws cloudwatch describe-alarms \\
107
107
  --query 'MetricAlarms[0].StateValue' \\
108
108
  --output text`},[d,g]),J=async Ee=>{const Ze=await Ie.getSource(Ee),Ye=Ze.source.awsDeploymentStatus||"not_started",st=Ze.source.awsDeploymentStatusReason||null;B(Ye),I(st);const lt=String(Ye).toLowerCase();["deployed","failed","deleted"].includes(lt)&&(Z(!1),n(),lt==="deployed"&&ae.success("AWS CloudWatch stack deployed"),lt==="failed"&&ae.error(st||"AWS CloudWatch stack deployment failed"))};w.useEffect(()=>{if(!e||!x||!V)return;let Ee=!1;const Ze=async()=>{try{Ee||await J(x)}catch{}},Ye=window.setInterval(Ze,5e3);return Ze(),()=>{Ee=!0,window.clearInterval(Ye)}},[e,x,V]);const Ne=async(Ee,Ze)=>{z(!0);try{const Ye=await Ie.getCloudWatchConsoleDeploy(Ee,{region:Ze?.region||d,stackName:Ze?.stackName||m||void 0,lambdaName:Ze?.lambdaName||g||void 0});return C(Ye),f(Ye.deployment.region),h(Ye.deployment.stackName),b(Ye.deployment.lambdaName),N(Ye.webhook.url),Ye}catch(Ye){return ae.error(Ye?.response?.data?.error||"Failed to prepare AWS deployment"),null}finally{z(!1)}},pe=async Ee=>{U(!0);try{const Ze=new URL(Ee,window.location.origin),Ye=await fetch(`${Ze.pathname}${Ze.search}`,{headers:{"ngrok-skip-browser-warning":"true"}}),st=await Ye.text();if(!Ye.ok)throw new Error(st||`Template request failed (${Ye.status})`);O(st)}catch(Ze){O(Ze?.message||"Failed to load template preview")}finally{U(!1)}},te=async()=>{if(!D){ae.error("Source name is required");return}q(!0);try{const Ee=await Ie.createSource({name:l.trim(),type:"cloudwatch",description:u.trim()||void 0});S(Ee.sourceId),N(Ee.webhookUrl),B("not_started"),I(null);const Ze=Ee.sourceId.slice(0,8),Ye=m||`meyi-cloudwatch-${Ze}`,st=g||`meyi-cloudwatch-forwarder-${Ze}`;h(Ye),b(st),await Ne(Ee.sourceId,{region:d,stackName:Ye,lambdaName:st}),o(3),n(),ae.success("CloudWatch source created")}catch(Ee){ae.error(Ee?.response?.data?.error||"Failed to create source")}finally{q(!1)}},Ae=async()=>{if(!x)return;const Ee=await Ne(x,{region:d,stackName:m,lambdaName:g});Ee?.deployment?.templateDownloadUrl&&(M?await pe(Ee.deployment.templateDownloadUrl):O(""))},$e=async()=>{if(A?.deployment.quickCreateUrl){if(m&&Vn(m),x)try{const Ee=await Ie.startCloudWatchConsoleDeploy(x,{stackName:m});B(Ee.source.awsDeploymentStatus||"pending"),I(Ee.source.awsDeploymentStatusReason||null),Z(!0),n()}catch{}m&&!A.deployment.canPrefillTemplateUrl&&ae.info("Stack name copied. Paste it in AWS if it is not prefilled."),window.open(A.deployment.quickCreateUrl,"_blank","noopener,noreferrer")}};return s.jsx(kt,{open:e,onOpenChange:Ee=>!G&&!P&&t(Ee),children:s.jsxs(It,{className:"max-h-[92vh] w-[min(96vw,900px)] max-w-none overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx(lu,{className:"h-5 w-5 text-amber-500"}),"AWS CloudWatch Wizard"]}),s.jsx(Kt,{children:"Create a CloudWatch source and deploy the AWS forwarding stack from your AWS Console session."})]}),s.jsx("div",{className:"border-b pb-4",children:s.jsx("div",{className:"mx-auto flex max-w-2xl items-center justify-center",children:nw.map(({step:Ee,label:Ze,Icon:Ye},st)=>s.jsxs("div",{className:"flex flex-1 items-center",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-2",children:[s.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-full border shadow-sm transition ${i>=Ee?"border-primary bg-primary text-primary-foreground":"border-border bg-muted text-muted-foreground"}`,children:i>Ee?s.jsx(Yt,{className:"h-5 w-5"}):s.jsx(Ye,{className:"h-5 w-5"})}),s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:`text-sm font-semibold ${i>=Ee?"text-foreground":"text-muted-foreground"}`,children:Ze}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Step ",Ee]})]})]}),st<nw.length-1&&s.jsx("div",{className:`mt-[-26px] h-px flex-1 ${i>Ee?"bg-primary":"bg-border"}`})]},Ee))})}),i===1&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"rounded-md border bg-muted/30 p-4",children:[s.jsx("h3",{className:"font-semibold",children:"How deployment works"}),s.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:"Meyi Connect creates a source webhook, then generates a CloudFormation template. The template creates a Lambda function, IAM role, EventBridge rule, and Lambda invoke permission in your AWS account."})]}),s.jsxs("div",{className:"rounded-md border bg-muted/30 p-4",children:[s.jsx("h3",{className:"font-semibold",children:"AWS Console deploy option"}),s.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:"This path does not ask for AWS access keys. It opens CloudFormation in the browser, so the customer reviews and deploys using their current AWS Console login session."})]})]}),i===2&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Source Name ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{value:l,onChange:Ee=>c(Ee.target.value),disabled:G})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Description ",s.jsx("span",{className:"font-normal text-muted-foreground",children:"(optional)"})]}),s.jsx("textarea",{rows:3,value:u,onChange:Ee=>p(Ee.target.value),disabled:G,className:"flex w-full resize-none rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",placeholder:"Example: Production AWS CloudWatch alarms"})]})]}),i===3&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"AWS Region"}),s.jsx(Xe,{value:d,onChange:Ee=>f(Ee.target.value),disabled:P})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Stack Name"}),s.jsx(Xe,{value:m,onChange:Ee=>h(Ee.target.value),disabled:P})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Lambda Name"}),s.jsx(Xe,{value:g,onChange:Ee=>b(Ee.target.value),disabled:P})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Webhook URL"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Xe,{value:T,readOnly:!0}),s.jsx(ie,{type:"button",variant:"outline",size:"icon",onClick:()=>rw(T,"Webhook URL"),children:s.jsx(yn,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"rounded-md border p-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"font-semibold",children:"CloudFormation Template"}),s.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Creates Lambda, EventBridge, IAM role, and invoke permission."})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:Ae,disabled:P||!x,children:[P?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Update"]}),A?.deployment.templateDownloadUrl&&s.jsx(ie,{type:"button",variant:"outline",asChild:!0,children:s.jsxs("a",{href:A.deployment.templateDownloadUrl,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-4 w-4"}),"Download"]})})]})]}),A&&!A.deployment.canPrefillTemplateUrl&&s.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:"AWS CloudFormation only accepts supported template URLs, normally Amazon S3 URLs. This backend template can be previewed/downloaded here, but AWS Console will require manual upload unless the template is hosted in S3."}),s.jsxs("div",{className:"mt-4 space-y-2",children:[s.jsx(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{const Ee=!M;R(Ee),Ee&&A?.deployment.templateDownloadUrl&&!k&&pe(A.deployment.templateDownloadUrl)},disabled:!A?.deployment.templateDownloadUrl,children:M?"Hide Template":"View Template"}),M?s.jsxs("div",{className:"space-y-2 overflow-hidden min-w-0 w-full",children:[s.jsx(Pe,{children:"Template Preview"}),s.jsx("pre",{className:"max-h-80 w-full max-w-full overflow-auto whitespace-pre rounded-md border bg-muted/30 p-3 text-xs leading-5",children:j?"Loading template...":k||"Template not loaded."})]}):null]})]}),(Q||ne||K)&&s.jsxs("div",{className:`rounded-md border p-3 text-sm ${ne?"border-emerald-200 bg-emerald-50 text-emerald-800":K?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[Q?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,ne?"Deployment successful":K?"Deployment failed":"Deployment in progress"]}),H?s.jsx("p",{className:"mt-1 text-xs opacity-80",children:H}):null]}),ne?s.jsxs("div",{className:"rounded-md border p-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"font-semibold",children:"Test Alarm Commands"}),s.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Run these AWS CLI commands to create and trigger a dummy CloudWatch alarm."})]}),s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>rw(Y,"Test commands"),children:[s.jsx(yn,{className:"h-4 w-4"}),"Copy"]})]}),s.jsx("pre",{className:"mt-3 max-h-64 w-full overflow-auto whitespace-pre rounded-md border bg-muted/30 p-3 text-xs leading-5",children:Y}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"CloudWatch sends notifications on state changes. If the alarm is already ALARM, send value 10, wait for OK, then send 100 again."})]}):null]}),s.jsxs($t,{children:[i>1&&i<3&&s.jsx(ie,{type:"button",variant:"outline",onClick:()=>o(i-1),disabled:G||P,children:"Back"}),i===1&&s.jsx(ie,{type:"button",onClick:()=>o(2),children:"Next"}),i===2&&s.jsxs(ie,{type:"button",onClick:te,disabled:G||!D,children:[G?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Create Webhook"]}),i===3&&s.jsxs(ie,{type:"button",onClick:$e,disabled:!A?.deployment.quickCreateUrl||P||V||ne,children:[V?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):s.jsx(ui,{className:"h-4 w-4"}),ne?"Deployment Complete":V?"Waiting for Deployment":"Connect AWS"]})]})]})})}const aw=[{step:1,label:"Overview",Icon:Xu},{step:2,label:"Source",Icon:Qu},{step:3,label:"Setup",Icon:Gh}],xc="****************";function LV({value:e,label:t="Copy"}){const[n,r]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),r(!0),setTimeout(()=>r(!1),1200)},children:[n?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),n?"Copied":t]})}function jV(e){const t=e.trim().replace(/\/+$/,"");return t?/^https?:\/\//i.test(t)?t:`https://${t}`:""}function MV({open:e,source:t,onOpenChange:n,onCreated:r}){const[a,i]=w.useState(1),[o,l]=w.useState("Grafana"),[c,u]=w.useState(""),[p,d]=w.useState(!1),[f,m]=w.useState(!1),[h,g]=w.useState(!1),[b,x]=w.useState(!1),[S,T]=w.useState(null),[N,A]=w.useState(null),[C,k]=w.useState(null),[O,M]=w.useState(!1),[R,j]=w.useState(""),[U,G]=w.useState(""),[q,P]=w.useState(""),[z,re]=w.useState(!1),[B,H]=w.useState("service"),[I,V]=w.useState(""),Z=w.useMemo(()=>!!o.trim(),[o]),D=w.useMemo(()=>!!(S&&R.trim()&&U.trim()&&q.trim()),[S,R,U,q]),se=w.useMemo(()=>!!(S&&R.trim()&&q.trim()),[S,R,q]),Q=p||f||h||b;async function ne(pe){m(!0);try{const te=await Ie.getGrafanaOnboarding(pe),Ae=te.defaults.contactPointName;A(te),j(te.defaults.grafanaBaseUrl||""),G(te.defaults.hasAccountToken?te.defaults.accountTokenMasked||xc:""),P(Ae),re(!!te.setup?.autoRoute),H(te.defaults.matcherLabel),V(te.defaults.matcherValue)}catch(te){ae.error(te?.response?.data?.error||"Failed to load Grafana setup")}finally{m(!1)}}w.useEffect(()=>{if(!e){i(1),l("Grafana"),u(""),d(!1),m(!1),g(!1),x(!1),T(null),A(null),k(null),M(!1),j(""),G(""),P(""),re(!1),H("service"),V("");return}t&&(i(3),l(t.name),u(t.description||""),T(t.id),k(null),M(!1),G(""),re(!1),ne(t.id))},[e,t?.id]);const K=async()=>{if(!Z){ae.error("Source name is required");return}d(!0);try{const pe=await Ie.createSource({name:o.trim(),type:"grafana",description:c.trim()||void 0});T(pe.sourceId),i(3),r(),ae.success("Grafana source created"),await ne(pe.sourceId)}catch(pe){ae.error(pe?.response?.data?.error||"Failed to create Grafana source")}finally{d(!1)}},Y=async()=>{if(S){if(!D){ae.error("Grafana URL, service token, and contact point name are required");return}g(!0),k(null);try{const pe=await Ie.setupGrafana(S,{grafanaBaseUrl:R,grafanaToken:U===xc?void 0:U,contactPointName:q,autoRoute:z,matcherLabel:z?B:void 0,matcherValue:z?I:void 0});k(pe),r(),ae.success("Grafana contact point configured")}catch(pe){ae.error(pe?.response?.data?.error||"Failed to configure Grafana")}finally{g(!1)}}},J=async()=>{if(S){if(!se){ae.error("Grafana URL and contact point name are required");return}x(!0),M(!1);try{await Ie.saveGrafanaSetup(S,{grafanaBaseUrl:R,grafanaToken:U===xc?void 0:U||void 0,contactPointName:q,autoRoute:z,matcherLabel:z?B:void 0,matcherValue:z?I:void 0}),M(!0),r(),ae.success("Grafana details saved")}catch(pe){ae.error(pe?.response?.data?.error||"Failed to save Grafana details")}finally{x(!1)}}},Ne=()=>{const pe=jV(R);if(!pe){ae.error("Enter Grafana URL first");return}q&&N?.webhook.url&&(Vn(`Name: ${q}
109
109
  Integration: Webhook
110
- Webhook URL: ${N.webhook.url}`),ae.success("Contact point details copied")),window.open(`${pe}/alerting/notifications/receivers/new`,"_blank","noopener,noreferrer")};return s.jsx(kt,{open:e,onOpenChange:pe=>!Q&&n(pe),children:s.jsxs(It,{className:"max-h-[92vh] w-[min(96vw,920px)] max-w-none overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx(Uh,{className:"h-5 w-5 text-orange-500"}),"Grafana Source Wizard"]}),s.jsx(Kt,{children:"Create a Grafana source and configure Grafana alerts to send webhooks to Meyi Connect."})]}),s.jsx("div",{className:"border-b pb-4",children:s.jsx("div",{className:"mx-auto flex max-w-2xl items-center justify-center",children:aw.map(({step:pe,label:te,Icon:Ae},$e)=>s.jsxs("div",{className:"flex flex-1 items-center",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-2",children:[s.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-full border shadow-sm transition ${a>=pe?"border-primary bg-primary text-primary-foreground":"border-border bg-muted text-muted-foreground"}`,children:a>pe?s.jsx(Yt,{className:"h-5 w-5"}):s.jsx(Ae,{className:"h-5 w-5"})}),s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:`text-sm font-semibold ${a>=pe?"text-foreground":"text-muted-foreground"}`,children:te}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Step ",pe]})]})]}),$e<aw.length-1&&s.jsx("div",{className:`mt-[-26px] h-px flex-1 ${a>pe?"bg-primary":"bg-border"}`})]},pe))})}),a===1?s.jsxs("div",{className:"grid gap-4 md:grid-cols-[1.1fr_0.9fr]",children:[s.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[s.jsx("div",{className:"mb-2 text-sm font-semibold",children:"How Grafana setup works"}),s.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[s.jsx("p",{children:"Meyi Connect creates a webhook source and generates a Grafana contact point target."}),s.jsx("p",{children:"If you provide a Grafana service account token, Meyi Connect can create the Grafana webhook contact point through Grafana APIs."})]})]}),s.jsxs("div",{className:"rounded-xl border p-4",children:[s.jsx("div",{className:"text-sm font-semibold",children:"Setup options"}),s.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[s.jsx("li",{children:"Automatic: Grafana URL + service account token."}),s.jsx("li",{children:"Optional routing: add a notification policy matcher route."}),s.jsx("li",{children:"Manual: copy webhook URL and configure contact point in Grafana UI."})]})]})]}):null,a===2?s.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source Name"}),s.jsx(Xe,{value:o,onChange:pe=>l(pe.target.value),disabled:p})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:c,onChange:pe=>u(pe.target.value),disabled:p,placeholder:"Optional"})]})]}):null,a===3?s.jsx("div",{className:"space-y-4",children:f&&!N?s.jsx("div",{className:"flex min-h-[180px] items-center justify-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("div",{className:"min-w-0 flex-1 rounded-md border bg-muted/20 p-2 text-xs break-all",children:N.webhook.url}),s.jsx(LV,{value:N.webhook.url})]})]}),s.jsx("div",{className:"rounded-xl border bg-muted/20 p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Hh,{className:"mt-0.5 h-4 w-4 text-orange-500"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Manual setup"}),s.jsx("ol",{className:"mt-2 list-inside list-decimal space-y-1 text-xs text-muted-foreground",children:N.manual.steps.map((pe,te)=>s.jsx("li",{children:pe},te))})]})]})}),s.jsxs("div",{className:"space-y-4 rounded-xl border p-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Grafana connection details"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"These values are used for manual setup, service-account navigation, and automatic API setup."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Grafana URL"}),s.jsx(Xe,{value:R,onChange:pe=>j(pe.target.value),placeholder:"http://65.2.144.245:3001",disabled:h||b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Contact Point Name"}),s.jsx(Xe,{value:q,onChange:pe=>P(pe.target.value),disabled:h||b})]})]}),s.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Manual Grafana contact point"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Opens Grafana contact-point creation and copies name, Webhook integration, and webhook URL."})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:J,disabled:!se||b,children:[b?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Save Details"]}),s.jsx(ie,{type:"button",variant:"outline",onClick:Ne,disabled:h||b,children:"Open Grafana Contact Point"})]})]}),O?s.jsx("div",{className:"mt-3 rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-800",children:"Grafana URL and contact point details are saved for this source."}):null]})]}),s.jsxs("div",{className:"space-y-4 rounded-xl border p-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Automatic API setup"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paste a Grafana service account token. Saved tokens are encrypted and shown masked when reopened."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Account Token"}),s.jsx(Xe,{type:"password",value:U,onChange:pe=>G(pe.target.value),placeholder:N.defaults.hasAccountToken?xc:"glsa_...",disabled:h}),N.defaults.hasAccountToken?s.jsx("p",{className:"text-xs text-muted-foreground",children:"A token is already saved. Keep the masked value to reuse it, or paste a new token to replace it."}):null]}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:z,onChange:pe=>re(pe.target.checked),disabled:h||b}),"Add notification policy route for matching Grafana alerts"]}),z?s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Matcher Label"}),s.jsx(Xe,{value:B,onChange:pe=>H(pe.target.value),disabled:h||b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Matcher Value"}),s.jsx(Xe,{value:I,onChange:pe=>V(pe.target.value),disabled:h||b})]})]}):null,s.jsxs(ie,{type:"button",onClick:Y,disabled:!D||h,children:[h?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Configure Grafana"]})]}),C?s.jsxs("div",{className:"space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup completed"}),s.jsxs("div",{children:["Contact point: ",C.contactPointName]}),s.jsxs("div",{children:["Policy updated: ",C.policyUpdated?"Yes":"No"]}),C.matcher?s.jsxs("div",{children:["Matcher: ",C.matcher.label,"=",C.matcher.value]}):null]}):null,!C&&N.setup?.status==="configured"?s.jsxs("div",{className:"space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup completed"}),s.jsxs("div",{children:["Contact point: ",N.setup.contactPointName]}),s.jsxs("div",{children:["Policy updated: ",N.setup.policyUpdated?"Yes":"No"]}),N.setup.matcher?s.jsxs("div",{children:["Matcher: ",N.setup.matcher.label,"=",N.setup.matcher.value]}):null]}):null,!C&&N.setup?.status==="failed"?s.jsxs("div",{className:"space-y-2 rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup failed"}),s.jsx("div",{children:N.setup.statusReason||"Retry automatic setup with a valid Grafana URL and token."})]}):null]}):s.jsx("div",{className:"rounded-md border bg-muted/20 p-4 text-sm text-muted-foreground",children:"Setup details are not loaded yet."})}):null,s.jsxs($t,{className:"gap-2",children:[a>1&&a<3?s.jsx(ie,{type:"button",variant:"outline",onClick:()=>i(pe=>pe-1),disabled:Q,children:"Back"}):null,a===1?s.jsx(ie,{type:"button",onClick:()=>i(2),children:"Continue"}):null,a===2?s.jsxs(ie,{type:"button",onClick:K,disabled:!Z||p,children:[p?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Create Source"]}):null,a===3?s.jsxs(s.Fragment,{children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:()=>S&&ne(S),disabled:f||!S,children:[f?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh Setup"]}),s.jsx(ie,{type:"button",onClick:()=>n(!1),disabled:f||h,children:"Close"})]}):null]})]})})}const sw=[{step:1,label:"Overview",Icon:Xu},{step:2,label:"Source",Icon:Qu},{step:3,label:"Setup",Icon:Hh}],PV={docker:kC,linux:jC,kubernetes:SC};function iw({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function FV({href:e,label:t}){return s.jsx(ie,{type:"button",variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-3.5 w-3.5"}),t]})})}function BV({open:e,onOpenChange:t,onCreated:n}){const[r,a]=w.useState(1),[i,o]=w.useState("Prometheus"),[l,c]=w.useState(""),[u,p]=w.useState(!1),[d,f]=w.useState(!1),[m,h]=w.useState(null),[g,b]=w.useState(null),[x,S]=w.useState("docker"),[T,N]=w.useState(""),[A,C]=w.useState(""),[k,O]=w.useState(!1),[M,R]=w.useState(null);w.useEffect(()=>{e||(a(1),o("Prometheus"),c(""),p(!1),f(!1),h(null),b(null),S("docker"),N(""),C(""),O(!1),R(null))},[e]);const j=w.useMemo(()=>!!i.trim(),[i]),U=u||d,G=x==="linux"?g?.defaults.linuxCommand:x==="kubernetes"?g?.defaults.kubernetesCommand:g?.defaults.dockerCommand,q=x==="linux"?g?.downloads?.linuxScript:x==="kubernetes"?g?.downloads?.kubernetesYaml:g?.downloads?.dockerScript,P=async()=>{if(!j){ae.error("Source name is required");return}p(!0);try{const H=await Ie.createSource({name:i.trim(),type:"prometheus",description:l.trim()||void 0});h(H.sourceId),a(3),n(),ae.success("Prometheus source created"),f(!0);const I=await Ie.getPrometheusOnboarding(H.sourceId);b(I),N(I.defaults.prometheusBaseUrl||""),C(I.defaults.alertmanagerBaseUrl||""),R(I.defaults.setupStatus?{status:I.defaults.setupStatus,reason:I.defaults.setupStatusReason||""}:null)}catch(H){ae.error(H?.response?.data?.error||"Failed to create Prometheus source")}finally{p(!1),f(!1)}},z=async()=>{if(m){f(!0);try{const H=await Ie.getPrometheusOnboarding(m);b(H),N(H.defaults.prometheusBaseUrl||""),C(H.defaults.alertmanagerBaseUrl||""),R(H.defaults.setupStatus?{status:H.defaults.setupStatus,reason:H.defaults.setupStatusReason||""}:null)}catch(H){ae.error(H?.response?.data?.error||"Failed to load Prometheus setup")}finally{f(!1)}}},re=async()=>{if(m){if(!T.trim()||!A.trim()){ae.error("Prometheus URL and Alertmanager URL are required");return}O(!0),R(null);try{const H=await Ie.checkPrometheusStatus(m,{prometheusBaseUrl:T.trim(),alertmanagerBaseUrl:A.trim(),timeoutSeconds:20});R({status:H.status,reason:H.reason}),H.status==="configured"?ae.success("Prometheus setup verified"):H.status==="not_yet"?ae.info("Prometheus changes are not visible yet"):ae.error(H.reason||"Prometheus setup verification failed"),n()}catch(H){ae.error(H?.response?.data?.error||"Failed to check Prometheus setup")}finally{O(!1)}}},B=M?.status==="configured"?"border-emerald-200 bg-emerald-50 text-emerald-800":M?.status==="failed"?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800";return s.jsx(kt,{open:e,onOpenChange:H=>!U&&t(H),children:s.jsxs(It,{className:"max-h-[92vh] w-[min(96vw,900px)] max-w-none overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx(Qu,{className:"h-5 w-5 text-red-500"}),"Prometheus Source Wizard"]}),s.jsx(Kt,{children:"Create a Prometheus source and generate setup automation for Alertmanager."})]}),s.jsx("div",{className:"border-b pb-4",children:s.jsx("div",{className:"mx-auto flex max-w-2xl items-center justify-center",children:sw.map(({step:H,label:I,Icon:V},Z)=>s.jsxs("div",{className:"flex flex-1 items-center",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-2",children:[s.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-full border shadow-sm transition ${r>=H?"border-primary bg-primary text-primary-foreground":"border-border bg-muted text-muted-foreground"}`,children:r>H?s.jsx(Yt,{className:"h-5 w-5"}):s.jsx(V,{className:"h-5 w-5"})}),s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:`text-sm font-semibold ${r>=H?"text-foreground":"text-muted-foreground"}`,children:I}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Step ",H]})]})]}),Z<sw.length-1&&s.jsx("div",{className:`mt-[-26px] h-px flex-1 ${r>H?"bg-primary":"bg-border"}`})]},H))})}),r===1?s.jsxs("div",{className:"grid gap-4 md:grid-cols-[1.1fr_0.9fr]",children:[s.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[s.jsx("div",{className:"mb-2 text-sm font-semibold",children:"How Prometheus automation works"}),s.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[s.jsx("p",{children:"Meyi Connect creates a webhook source, then generates setup artifacts for your Prometheus environment."}),s.jsx("p",{children:"For self-hosted Prometheus, full automation is script-based because Prometheus and Alertmanager APIs do not persistently edit YAML config."})]})]}),s.jsxs("div",{className:"rounded-xl border p-4",children:[s.jsx("div",{className:"text-sm font-semibold",children:"Supported setup methods"}),s.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[s.jsx("li",{children:"Docker: download and run a container setup script."}),s.jsx("li",{children:"Linux service: download and run a local config script."}),s.jsx("li",{children:"Kubernetes: download and apply Prometheus Operator YAML."})]})]})]}):null,r===2?s.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source Name"}),s.jsx(Xe,{value:i,onChange:H=>o(H.target.value),disabled:u})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:l,onChange:H=>c(H.target.value),disabled:u,placeholder:"Optional"})]})]}):null,r===3?s.jsx("div",{className:"space-y-4",children:d&&!g?s.jsx("div",{className:"flex min-h-[180px] items-center justify-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:g.webhook.url})]}),s.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment status check"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"After running the setup artifact, click Check Status. Meyi Connect will verify readiness and Alertmanager config once."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Prometheus URL"}),s.jsx(Xe,{value:T,onChange:H=>N(H.target.value),placeholder:"http://65.2.144.245:9090"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Alertmanager URL"}),s.jsx(Xe,{value:A,onChange:H=>C(H.target.value),placeholder:"http://65.2.144.245:9093"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:re,disabled:k,children:[k?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Check Status"]}),M?s.jsxs("div",{className:`rounded-md border px-3 py-1.5 text-xs ${B}`,children:[s.jsx("span",{className:"font-semibold",children:M.status.replace(/_/g," ")}),M.reason?s.jsxs("span",{children:[" - ",M.reason]}):null]}):null]})]}),s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:(g.environments||[]).map(H=>{const I=PV[H.id],V=x===H.id;return s.jsxs("button",{type:"button",onClick:()=>S(H.id),className:`rounded-lg border p-3 text-left transition ${V?"border-primary bg-primary/5 shadow-sm":"bg-background hover:bg-muted/30"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(I,{className:"h-4 w-4 text-primary"}),H.label]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:H.description})]},H.id)})}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Automated setup"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Download and run this on the Prometheus host or cluster."})]}),q?s.jsx(FV,{href:q,label:x==="kubernetes"?"Download YAML":"Download Script"}):null]}),G?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"rounded-md border bg-background p-2 text-xs break-all font-mono",children:G}),s.jsx(iw,{value:G})]}):null]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Manual alertmanager.yml snippet"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono whitespace-pre-wrap",children:g.snippets.alertmanagerConfig}),s.jsx(iw,{value:g.snippets.alertmanagerConfig})]})]}):s.jsx("div",{className:"rounded-md border bg-muted/20 p-4 text-sm text-muted-foreground",children:"Setup details are not loaded yet."})}):null,s.jsxs($t,{className:"gap-2",children:[r>1&&r<3?s.jsx(ie,{type:"button",variant:"outline",onClick:()=>a(H=>H-1),disabled:U,children:"Back"}):null,r===1?s.jsx(ie,{type:"button",onClick:()=>a(2),children:"Continue"}):null,r===2?s.jsxs(ie,{type:"button",onClick:P,disabled:!j||u,children:[u?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Create Source"]}):null,r===3?s.jsxs(s.Fragment,{children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:z,disabled:d||!m,children:[d?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh Setup"]}),s.jsx(ie,{type:"button",onClick:()=>t(!1),disabled:d,children:"Close"})]}):null]})]})})}function cI({currentPage:e,pageSize:t,totalPages:n,total:r,onPageChange:a,onPageSizeChange:i,className:o}){const l=tA(e,n),c=r>0;return s.jsxs("div",{className:Fe("flex flex-col sm:flex-row items-center justify-between overflow-clip px-2 gap-4 py-4 border-t mt-4","@max-2xl/content:flex-col-reverse @max-2xl/content:gap-4",o),style:{overflowClipMargin:1},children:[s.jsxs("div",{className:"flex w-full items-center justify-between",children:[c&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",e," of ",n]}),i&&s.jsxs("div",{className:"flex items-center gap-2 @max-2xl/content:flex-row-reverse",children:[s.jsxs(Fo,{value:`${t}`,onValueChange:u=>i(Number(u)),children:[s.jsx(Uo,{className:"h-8 w-[70px]",children:s.jsx(Bo,{placeholder:t})}),s.jsx($o,{side:"top",children:[10,20,30,40,50].map(u=>s.jsx(ba,{value:`${u}`,children:u},u))})]}),s.jsx("p",{className:"hidden text-sm font-medium sm:block",children:"Rows per page"})]})]}),s.jsxs("div",{className:"flex items-center sm:space-x-6 lg:space-x-8",children:[c&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",e," of ",n]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>a(1),disabled:e<=1,title:"First page",children:[s.jsx("span",{className:"sr-only",children:"Go to first page"}),s.jsx(NC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>a(e-1),disabled:e<=1,title:"Previous page",children:[s.jsx("span",{className:"sr-only",children:"Go to previous page"}),s.jsx(wC,{className:"h-4 w-4"})]}),c&&l.map((u,p)=>s.jsx("div",{className:"flex items-center",children:u==="..."?s.jsx("span",{className:"text-muted-foreground px-1 text-sm",children:"..."}):s.jsx(ie,{variant:e===u?"default":"outline",className:"h-8 min-w-8 px-2",onClick:()=>a(u),children:u})},`${u}-${p}`)),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>a(e+1),disabled:e>=n,title:"Next page",children:[s.jsx("span",{className:"sr-only",children:"Go to next page"}),s.jsx(TC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>a(n),disabled:e>=n,title:"Last page",children:[s.jsx("span",{className:"sr-only",children:"Go to last page"}),s.jsx(CC,{className:"h-4 w-4"})]})]})]})]})}const kf={sourceTypes:[],status:"",region:""},UV=[{label:"CloudWatch",value:"cloudwatch"},{label:"Level 1 Security",value:"cloudtrail"},{label:"Grafana",value:"grafana"},{label:"Prometheus",value:"prometheus"},{label:"Datadog",value:"datadog"},{label:"Custom",value:"custom"}];function $V(){return{sourceTypes:[...kf.sourceTypes],status:kf.status,region:kf.region}}function HV({search:e,filters:t,loading:n,onSearchChange:r,onFiltersChange:a,onRefresh:i}){const o=[{label:"Active",value:"active"},{label:"Degraded",value:"degraded"},{label:"Error",value:"error"},{label:"Disabled",value:"disabled"}],l=[{label:"Global",value:"global"},{label:"AWS",value:"aws"},{label:"K8s",value:"k8s"},{label:"Datadog",value:"datadog"},{label:"Multi",value:"multi"}];return s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{type:"text",value:e,onChange:c=>r(c.target.value),placeholder:"Search sources...",className:"h-9 w-[150px] lg:w-[250px] pl-8",disabled:n}),e&&s.jsxs(ie,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground",onClick:()=>r(""),children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Clear"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Type",options:UV,selected:t.sourceTypes,onChange:c=>a({...t,sourceTypes:c})}),s.jsx(Qn,{title:"Status",options:o,selected:t.status?[t.status]:[],onChange:c=>a({...t,status:c[0]||""})}),s.jsx(Qn,{title:"Region",options:l,selected:t.region?[t.region]:[],onChange:c=>a({...t,region:c[0]||""})})]})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs(ie,{variant:"outline",size:"sm",onClick:i,disabled:n,className:"h-8 hidden lg:flex",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",n&&"animate-spin")}),"Refresh"]})})]})}const ow={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus / Alertmanager",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom / SDK",mono:"CU",color:"#5A6B7B"}};function Vo(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function zV(e){const t=Vo(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsDeploymentStatus||"not_started":t==="grafana"?e.grafanaSetupStatus||"not_started":t==="prometheus"?e.prometheusSetupStatus||"not_started":e.deliveryStatus||"unknown"}function uI(e){if(!e.isActive)return"disabled";const t=String(zV(e)).toLowerCase();return t==="failed"?"error":t==="pending"||t==="not_yet"||t==="checking"||t==="not_started"?"degraded":"active"}function GV(e){return e==="error"?"Error":e==="degraded"?"Degraded":e==="disabled"?"Disabled":"Active"}function dI(e){const t=Vo(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsRegion||"aws":t==="prometheus"?e.prometheusEnvironment||"k8s":t==="datadog"?"datadog":t==="grafana"?"multi":"global"}function VV(e){return dI(e)}function WV(e){const t=Vo(e.type);return t==="grafana"?e.grafanaBaseUrl||e.webhookUrl:t==="prometheus"?e.alertmanagerBaseUrl||e.prometheusReceiverName||"alertmanager.yml":t==="cloudwatch"?`${e.awsStackName||"aws"} - ${e.webhookUrl}`:t==="cloudtrail"?`${e.awsStackName||"aws"} - cloudtrail:security`:t==="datadog"?e.webhookUrl:e.description||e.webhookUrl}function qV(e){const t=e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt;if(!t)return"Never";const n=Date.now()-new Date(t).getTime();if(!Number.isFinite(n)||n<0)return"just now";const r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r} minute${r===1?"":"s"} ago`;const a=Math.floor(r/60);if(a<24)return`${a} hour${a===1?"":"s"} ago`;const i=Math.floor(a/24);return`${i} day${i===1?"":"s"} ago`}function YV(e){const t=Math.max(0,Number(e||0));return t===0?[3,3,3,3,3,3,3,3]:[.32,.56,.42,.8,.62,.48,.92,.72].map(n=>Math.max(3,Math.round(16*Math.min(1,n+Math.min(t,100)/300))))}function KV(e){return uI(e)}function Br({title:e,onClick:t,children:n}){return s.jsx("button",{className:"im-icon-button",type:"button",title:e,"aria-label":e,onClick:t,children:n})}function XV({sources:e,...t}){const[n,r]=w.useState({}),a=5,o=["cloudwatch","cloudtrail","grafana","prometheus","datadog","meyi_pulse","pagerduty","custom"].map(l=>({type:l,meta:ow[l]||ow.custom,instances:e.filter(c=>Vo(c.type)===l)})).filter(l=>l.instances.length>0);return s.jsx("div",{className:"im-source-groups",children:o.map(l=>s.jsxs("section",{className:"im-source-group",children:[s.jsxs("div",{className:"im-source-group-header",children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:l.meta.color},children:l.meta.mono}),s.jsx("span",{className:"im-group-title",children:l.meta.label}),s.jsxs("span",{className:"im-count-pill",children:[l.instances.length," ",l.instances.length===1?"instance":"instances"]}),s.jsx(Ku,{className:"im-header-chevron",size:14,"aria-hidden":"true"})]}),s.jsxs("div",{children:[l.instances.slice(((n[l.type]||1)-1)*a,(n[l.type]||1)*a).map(c=>{const u=Vo(c.type),p=uI(c),d=Number(c.alertCount??0);return s.jsxs("div",{className:"im-source-row",onClick:()=>t.onView(c),children:[s.jsx("span",{className:`im-status-dot im-status-${p}`}),s.jsxs("div",{className:"im-source-name",children:[s.jsxs("div",{className:"im-source-title-line",children:[s.jsx("strong",{children:c.name}),s.jsx("span",{className:`im-status-pill im-status-pill-${p}`,children:GV(p)})]}),s.jsx("span",{children:WV(c)})]}),s.jsxs("div",{className:"im-row-metric",children:[s.jsx("span",{children:"Region / env"}),s.jsxs("strong",{children:[dI(c),"/production"]})]}),s.jsxs("div",{className:"im-row-metric",children:[s.jsx("span",{children:"Last alarm"}),s.jsx("strong",{children:qV(c)})]}),s.jsxs("div",{className:"im-alarms-metric",children:[s.jsx("span",{children:"Alarms today"}),s.jsxs("div",{children:[s.jsx("strong",{children:d}),d>0?s.jsx("span",{className:"im-sparkline","aria-hidden":"true",children:YV(d).map((f,m)=>s.jsx("span",{style:{height:f}},`${c.id}-${m}`))}):s.jsx("span",{className:"im-zero-sparkline",children:"No alarms"})]})]}),Number(c.webhookFailureCount||0)>0?s.jsxs("div",{className:"im-alarms-metric",children:[s.jsx("span",{className:"text-red-500",children:"Failed deliveries"}),s.jsx("div",{children:s.jsx("strong",{className:"text-red-500",children:c.webhookFailureCount||0})})]}):s.jsx("div",{}),s.jsxs("div",{className:"im-row-actions",children:[s.jsx(Br,{title:"Copy webhook URL",onClick:f=>{f.stopPropagation(),Vn(c.webhookUrl).then(m=>{m?ae.success("Webhook URL copied"):ae.error("Failed to copy webhook URL")})},children:s.jsx(yn,{size:15})}),s.jsx(Br,{title:"Token policy",onClick:f=>{f.stopPropagation(),t.onManageTokenPolicy(c)},children:s.jsx(VF,{size:15})}),u==="cloudwatch"&&s.jsx(Br,{title:"CloudWatch setup",onClick:f=>{f.stopPropagation(),t.onAwsSetup(c)},children:s.jsx(lu,{size:15})}),u==="cloudtrail"&&s.jsx(Br,{title:"Level 1 Security setup",onClick:f=>{f.stopPropagation(),t.onAwsSetup(c)},children:s.jsx(lu,{size:15})}),u==="grafana"&&s.jsx(Br,{title:"Grafana setup",onClick:f=>{f.stopPropagation(),t.onGrafanaSetup(c)},children:s.jsx(Uh,{size:15})}),u==="prometheus"&&s.jsx(Br,{title:"Prometheus setup",onClick:f=>{f.stopPropagation(),t.onPrometheusSetup(c)},children:s.jsx(IC,{size:15})}),u==="datadog"&&s.jsx(Br,{title:"Datadog setup",onClick:f=>{f.stopPropagation(),t.onDatadogSetup(c)},children:s.jsx(OC,{size:15})}),s.jsx(Br,{title:"Edit source",onClick:f=>{f.stopPropagation(),t.onEdit(c)},children:s.jsx(Zu,{size:15})}),s.jsx(Br,{title:"Delete source",onClick:f=>{f.stopPropagation(),t.onDelete(c.id)},children:s.jsx(ll,{size:15})})]})]},c.id)}),l.instances.length>a&&s.jsxs("div",{className:"im-group-pagination",children:[s.jsxs("span",{children:[Math.min(((n[l.type]||1)-1)*a+1,l.instances.length),"-",Math.min((n[l.type]||1)*a,l.instances.length)," of ",l.instances.length]}),s.jsxs("div",{className:"im-pager",children:[s.jsx("button",{type:"button",disabled:(n[l.type]||1)<=1,onClick:()=>r(c=>({...c,[l.type]:Math.max(1,(c[l.type]||1)-1)})),children:"‹"}),Array.from({length:Math.ceil(l.instances.length/a)},(c,u)=>u+1).map(c=>s.jsx("button",{type:"button",className:(n[l.type]||1)===c?"is-active":"",onClick:()=>r(u=>({...u,[l.type]:c})),children:c},c)),s.jsx("button",{type:"button",disabled:(n[l.type]||1)>=Math.ceil(l.instances.length/a),onClick:()=>r(c=>({...c,[l.type]:Math.min(Math.ceil(l.instances.length/a),(c[l.type]||1)+1)})),children:"›"})]})]})]})]},l.type))})}const ZV={};function QV(){const{isReadOnly:e,openCostSources:t}=ur(),n=St(),[r,a]=w.useState([]),[i,o]=w.useState(0),[l,c]=w.useState(!0),[u,p]=w.useState(1),[d,f]=w.useState(10),[m,h]=w.useState(""),[g,b]=w.useState(""),[x,S]=w.useState(()=>$V()),[T,N]=w.useState(!1),[A,C]=w.useState(!1),[k,O]=w.useState(!1),[M,R]=w.useState(!1),[j,U]=w.useState(!1),[G,q]=w.useState(null),[P,z]=w.useState(null),[re,B]=w.useState(null),[H,I]=w.useState(null),[V,Z]=w.useState(!1),[D,se]=w.useState(null),[Q,ne]=w.useState(!1),[K,Y]=w.useState(null),[J,Ne]=w.useState(null),[pe,te]=w.useState(!1),[Ae,$e]=w.useState(null),[Ee,Ze]=w.useState(!1),[Ye,st]=w.useState(null),[lt,Et]=w.useState(!1),[Bt,Se]=w.useState(!1),[Re,Ue]=w.useState(null),[He,le]=w.useState(!1),[_e,Ke]=w.useState(!1),[tt,v]=w.useState(null),[ee,fe]=w.useState(null),[he,de]=w.useState({accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"ap-south-1",stackName:""}),[Ce,_]=w.useState([]),[X,ge]=w.useState([]),[oe,xe]=w.useState({lambdaName:"",alarmNamePrefix:""}),[we,be]=w.useState({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}),[Me,ye]=w.useState(!1),[Oe,je]=w.useState(null),[qe,pt]=w.useState(!1),[Tt,Dt]=w.useState(null),[Vt,hn]=w.useState(!1),[Wn,vp]=w.useState(null),[ra,FO]=w.useState(""),[Pue,Fue]=w.useState(""),[Bue,BO]=w.useState(""),[Uue,$ue]=w.useState(!1),[Hue,UO]=w.useState("service"),[zue,$O]=w.useState(""),[Sp,mv]=w.useState(!1),[Os,hv]=w.useState(null),[HO,gv]=w.useState(!1),[zO,wp]=w.useState(null),[Tp,Np]=w.useState(""),[Cp,Ap]=w.useState(""),[GO,_p]=w.useState(!1),[VO,Ul]=w.useState(null),[Rp,WO]=w.useState(!1),[Ls,qO]=w.useState(null),[YO,bv]=w.useState(!1),[KO,xv]=w.useState(null),[XO,yv]=w.useState(!1),[ZO,Ev]=w.useState(null),[vv,Sv]=w.useState("datadoghq.com"),[wv,Tv]=w.useState(""),[Nv,Cv]=w.useState(""),[Av,_v]=w.useState("");w.useEffect(()=>{const me=setTimeout(()=>{b(m),p(1)},400);return()=>clearTimeout(me)},[m]);const cn=async(me=!1)=>{me||c(!0);try{const nt=await Ie.listSources({page:u,limit:d,search:g||void 0,type:x.sourceTypes.length>0?x.sourceTypes.join(","):void 0}),yt=nt.sources||[];a(yt),$e(Wt=>Wt&&(yt.find(nr=>nr.id===Wt.id)??Wt)),o(nt.total||0)}catch{me||ae.error("Failed to load sources")}finally{me||c(!1)}},Rv=w.useRef(cn);w.useEffect(()=>{Rv.current=cn},[cn]),w.useEffect(()=>{cn()},[u,d,g,x]),w.useEffect(()=>{const me=ZV?.VITE_SOCKET_URL,nt=(me?me.replace("/socket.io",""):window.location.origin).replace(/\/+$/,""),yt=bo(`${nt}/ws/insight`,{path:"/socket.io",transports:["websocket","polling"],withCredentials:!0}),Wt=()=>{Rv.current(!0)},nr=Bi=>{Bi?.topic&&(Bi.topic==="sources.updated"||Bi.topic.startsWith("sources.")||Bi.topic==="alerts.totals"||Bi.topic.startsWith("alerts."))&&Wt()};return yt.on("insight:alerts:totals",Wt),yt.on("insight:event",nr),()=>{yt.off("insight:alerts:totals",Wt),yt.off("insight:event",nr),yt.disconnect()}},[]),w.useEffect(()=>{if(!r.some(yt=>String(yt.type||"").toLowerCase()==="cloudwatch"&&String(yt.awsDeploymentStatus||"").toLowerCase()==="pending"))return;const nt=window.setInterval(()=>{cn(!0)},7e3);return()=>window.clearInterval(nt)},[r,u,d,g,x]);const QO=async()=>{await cn()},JO=me=>{S(me),p(1)},kv=()=>{I(null),B(null),se(null),C(!0)},eL=me=>{n({to:`/sources/${me.id}`})},tL=me=>{I(me),N(!0)},nL=()=>{V||(N(!1),se(null),B(null))},rL=me=>{Y(r.find(nt=>nt.id===me)??null),ne(!0)},aL=async()=>{if(K){Ne(K.id);try{await Ie.deleteSource(K.id),ae.success("Source deleted"),ne(!1),Y(null),cn()}catch(me){ae.error(me?.response?.data?.error||"Failed to delete source")}finally{Ne(null)}}},sL=async(me,nt,yt)=>{Z(!0);try{if(H)await Ie.updateSource(H.id,{name:me,description:yt}),ae.success("Source updated"),N(!1),cn();else{const Wt=await Ie.createSource({name:me,type:nt,description:yt});if(nt==="prometheus"){const nr=await Ie.getSource(Wt.sourceId);N(!1),B(null),se(null),hv(nr.source),wp(null),mv(!0),cn(),ae.success("Prometheus source created")}else se(Wt.webhookUrl),cn()}}catch(Wt){ae.error(Wt?.response?.data?.error||"Failed to save source")}finally{Z(!1)}},iL=async me=>{st(me),Ze(!0);try{const nt=await Ie.getSourceTokenPolicy(me.id);st(yt=>yt&&{...yt,tokenPolicy:nt.tokenPolicy})}catch{}},oL=async(me,nt)=>{if(Ye){Et(!0);try{const yt=await Ie.updateSourceTokenPolicy(Ye.id,{mode:me,ttlDays:nt});a(Wt=>Wt.map(nr=>nr.id===Ye.id?{...nr,tokenPolicy:yt.tokenPolicy,webhookUrl:yt.webhookUrl||nr.webhookUrl}:nr)),ae.success("Token policy updated"),Ze(!1),st(null)}catch(yt){ae.error(yt?.response?.data?.error||"Failed to update token policy")}finally{Et(!1)}}},lL=async()=>{if(Re){le(!0);try{const me=await Ie.discoverCloudWatch(Re.id,{accessKeyId:he.accessKeyId,secretAccessKey:he.secretAccessKey,sessionToken:he.sessionToken||void 0,region:he.region});v(me),ae.success("Fetched CloudWatch metrics and alarms")}catch(me){ae.error(me?.response?.data?.error||"Failed to fetch CloudWatch metrics/alarms")}finally{le(!1)}}},cL=async()=>{if(Re){Ke(!0);try{const me=await Ie.deployCloudWatch(Re.id,{accessKeyId:he.accessKeyId,secretAccessKey:he.secretAccessKey,sessionToken:he.sessionToken||void 0,region:he.region,stackName:he.stackName,selectedAlarmNames:Ce,selectedMetricKeys:X,naming:{lambdaName:oe.lambdaName,alarmNamePrefix:oe.alarmNamePrefix},alarmDefaults:{threshold:Number(we.threshold||50),period:Number(we.period||60),evaluationPeriods:Number(we.evaluationPeriods||1),statistic:we.statistic,comparisonOperator:we.comparisonOperator,treatMissingData:we.treatMissingData}});fe(me),_(me.deployment.selectedAlarmNames||Ce),xe({lambdaName:me.deployment.lambdaName||oe.lambdaName,alarmNamePrefix:me.deployment.alarmNamePrefix||oe.alarmNamePrefix}),cn(),ae.success("AWS CloudWatch automation deployed")}catch(me){ae.error(me?.response?.data?.error||"Failed to deploy AWS automation")}finally{Ke(!1)}}},uL=async me=>{Ue(me),v(null),fe(null);try{const nt=await Ie.getCloudWatchSetup(me.id);de({accessKeyId:nt.setup.accessKeyId||"",secretAccessKey:nt.setup.secretAccessKey||"",sessionToken:nt.setup.sessionToken||"",region:nt.setup.region||"ap-south-1",stackName:nt.setup.stackName||`meyi-cloudwatch-${me.id.slice(0,8)}`}),xe({lambdaName:nt.setup.lambdaName||`meyi-cloudwatch-forwarder-${me.id.slice(0,8)}`,alarmNamePrefix:nt.setup.alarmNamePrefix||`meyi-${me.id.slice(0,8)}`}),_(Array.isArray(nt.setup.selectedAlarmNames)?nt.setup.selectedAlarmNames:[]),ge(Array.isArray(nt.setup.selectedMetricKeys)?nt.setup.selectedMetricKeys:[])}catch{_(Array.isArray(me.awsSelectedAlarmNames)?me.awsSelectedAlarmNames:[]),ge(Array.isArray(me.awsSelectedMetricKeys)?me.awsSelectedMetricKeys:[]),de({accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"ap-south-1",stackName:`meyi-cloudwatch-${me.id.slice(0,8)}`}),xe({lambdaName:me.awsLambdaName||`meyi-cloudwatch-forwarder-${me.id.slice(0,8)}`,alarmNamePrefix:me.awsAlarmNamePrefix||`meyi-${me.id.slice(0,8)}`})}be({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}),Se(!0)},dL=me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},pL=async()=>{if(Oe){pt(!0);try{const me=await Ie.getGrafanaOnboarding(Oe.id);Dt(me),BO(nt=>nt||me.defaults.contactPointName),UO(nt=>nt||me.defaults.matcherLabel),$O(nt=>nt||me.defaults.matcherValue)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Grafana setup")}finally{pt(!1)}}},fL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},Iv=async()=>{if(Os){gv(!0);try{const me=await Ie.getPrometheusOnboarding(Os.id);wp(me),Np(me.defaults.prometheusBaseUrl||""),Ap(me.defaults.alertmanagerBaseUrl||""),Ul(me.defaults.setupStatus?{status:me.defaults.setupStatus,reason:me.defaults.setupStatusReason||""}:null)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Prometheus setup")}finally{gv(!1)}}},mL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},hL=async()=>{if(Os){if(!Tp.trim()||!Cp.trim()){ae.error("Prometheus URL and Alertmanager URL are required");return}_p(!0),Ul(null);try{const me=await Ie.checkPrometheusStatus(Os.id,{prometheusBaseUrl:Tp.trim(),alertmanagerBaseUrl:Cp.trim(),timeoutSeconds:20});Ul({status:me.status,reason:me.reason}),me.status==="configured"?ae.success("Prometheus setup verified"):me.status==="not_yet"?ae.info("Prometheus changes are not visible yet"):ae.error(me.reason||"Prometheus setup verification failed"),cn()}catch(me){ae.error(me?.response?.data?.error||"Failed to check Prometheus setup")}finally{_p(!1)}}},Dv=async()=>{if(Ls){bv(!0);try{const me=await Ie.getDatadogOnboarding(Ls.id);xv(me),Sv(nt=>nt||me.defaults.site),Tv(nt=>nt||me.defaults.webhookName)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Datadog setup")}finally{bv(!1)}}},gL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},bL=async()=>{if(Ls){yv(!0);try{const me=await Ie.setupDatadog(Ls.id,{site:vv||"datadoghq.com",datadogApiKey:Nv,datadogAppKey:Av,webhookName:wv||void 0});Ev(me),ae.success("Datadog source configured")}catch(me){ae.error(me?.response?.data?.error||"Datadog setup failed")}finally{yv(!1)}}};w.useEffect(()=>{!Me||!Oe||pL()},[Me,Oe]),w.useEffect(()=>{!Sp||!Os||Iv()},[Sp,Os]),w.useEffect(()=>{!Rp||!Ls||Dv()},[Rp,Ls]);const kp=r.filter(me=>{const nt=!x.status||KV(me)===x.status,yt=!x.region||VV(me)===x.region;return nt&&yt}),Ov=kp.length,xL=Math.max(1,Math.ceil(Ov/d)),yL=he.accessKeyId.trim().toUpperCase().startsWith("ASIA"),EL=!!(he.accessKeyId&&he.secretAccessKey&&(!yL||he.sessionToken));return e?s.jsx(lo,{to:"/alerts"}):s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Sources"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Monitoring sources connected to this workspace"})]}),s.jsxs(ie,{onClick:kv,disabled:l,children:[s.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Add source"]})]}),s.jsx(HV,{search:m,filters:x,loading:l,onSearchChange:me=>{h(me),p(1)},onFiltersChange:JO,onRefresh:QO}),s.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:l&&r.length===0?s.jsx(qr,{variant:"cards"}):kp.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center border rounded-md border-dashed h-64 bg-muted/20",children:[s.jsx("h3",{className:"text-lg font-medium mb-1",children:m||x.status||x.region?"No matching sources":"No sources yet"}),s.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mb-4",children:m||x.status||x.region?"Try a different search or filter.":"Add a webhook source to start receiving alerts from your monitoring tools."}),!m&&!x.status&&!x.region&&s.jsxs(ie,{onClick:kv,children:[s.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Add First Source"]})]}):s.jsx(XV,{sources:kp,deletingId:J,onView:eL,onEdit:tL,onDelete:rL,onManageTokenPolicy:iL,onAwsSetup:dL,onGrafanaSetup:fL,onPrometheusSetup:mL,onDatadogSetup:gL})}),s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(cI,{currentPage:u,pageSize:d,totalPages:xL,total:Ov||i,onPageChange:me=>p(me),onPageSizeChange:me=>{f(me),p(1)}})}),s.jsx(pV,{open:Q,onOpenChange:me=>{J||ne(me)},source:K,onConfirm:aL}),s.jsx(uV,{open:T,source:H,submitting:V,createdWebhookUrl:D,initialType:re,onClose:nL,onSubmit:sL,onWebhookModalClose:()=>{se(null),N(!1),B(null)}}),s.jsx(DV,{open:A,onOpenChange:C,onCreated:cn,onOpenCostSources:t}),s.jsx(OV,{open:k,source:G,onOpenChange:me=>{O(me),me||q(null)},onCreated:cn,onAccessKeyDeploy:me=>{O(!1),q(null),uL(me)}}),s.jsx(MV,{open:M,source:P,onOpenChange:me=>{R(me),me||(B(null),z(null))},onCreated:cn}),s.jsx(BV,{open:j,onOpenChange:me=>{U(me),me||B(null)},onCreated:cn}),s.jsx(fV,{open:Ee,source:Ye,submitting:lt,onOpenChange:me=>{Ze(me),me||st(null)},onSubmit:oL}),s.jsx(gV,{open:Bt,loadingDiscover:He,deploying:_e,discoveringReady:EL,credentials:he,naming:oe,alarmDefaults:we,selectedAlarmNames:Ce,selectedMetricKeys:X,discoverData:tt,deployData:ee,templateDownloadUrl:ee?.templateDownloadUrl||null,onChangeCredentials:me=>de(nt=>({...nt,...me})),onChangeNaming:me=>xe(nt=>({...nt,...me})),onChangeAlarmDefaults:me=>be(nt=>({...nt,...me})),onToggleAlarm:(me,nt)=>_(yt=>nt?Array.from(new Set([...yt,me])):yt.filter(Wt=>Wt!==me)),onToggleMetric:(me,nt)=>ge(yt=>nt?Array.from(new Set([...yt,me])):yt.filter(Wt=>Wt!==me)),onDiscover:lL,onDeploy:cL,onOpenChange:me=>{Se(me),me||(Ue(null),v(null),fe(null),_([]),ge([]),xe({lambdaName:"",alarmNamePrefix:""}),be({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}))}}),s.jsx(CV,{open:pe,source:Ae,onOpenChange:me=>{te(me),me||$e(null)}}),s.jsx(xV,{open:Sp,data:zO,loading:HO,prometheusBaseUrl:Tp,alertmanagerBaseUrl:Cp,checkingStatus:GO,statusResult:VO,onPrometheusBaseUrlChange:Np,onAlertmanagerBaseUrlChange:Ap,onCheckStatus:hL,onRefresh:Iv,onOpenChange:me=>{mv(me),me||(hv(null),wp(null),Np(""),Ap(""),Ul(null),_p(!1))}}),s.jsx(EV,{open:Rp,data:KO,loading:YO,configuring:XO,result:ZO,site:vv,webhookName:wv,datadogApiKey:Nv,datadogAppKey:Av,onSiteChange:Sv,onWebhookNameChange:Tv,onDatadogApiKeyChange:Cv,onDatadogAppKeyChange:_v,onRefresh:Dv,onConfigure:bL,onOpenChange:me=>{WO(me),me||(qO(null),xv(null),Ev(null),Cv(""),_v(""))}})]})}const lw={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom",mono:"CU",color:"#5A6B7B"}};function ws(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function JV(e){return lw[ws(e.type)]||lw.custom}function pI(e){const t=ws(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsRegion||"us-east-1":t==="prometheus"?e.prometheusEnvironment||"production":"multi"}function fI(e){const t=ws(e.type);return t==="cloudwatch"?`aws ****4821 - ${e.awsStackName||"sns:prod-alarms"}`:t==="cloudtrail"?`aws ****4821 - ${e.awsStackName||"cloudtrail:security"}`:t==="grafana"?e.grafanaBaseUrl||e.webhookUrl:t==="prometheus"&&(e.alertmanagerBaseUrl||e.prometheusReceiverName)||e.webhookUrl}function Jg(e){const t=ws(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsDeploymentStatus||"not_started":t==="grafana"?e.grafanaSetupStatus||"not_started":t==="prometheus"?e.prometheusSetupStatus||"not_started":t==="datadog"?e.deliveryStatus||"not_started":e.deliveryStatus||"unknown"}function cw(e){const t=ws(e.type),n=String(Jg(e)).toLowerCase();return t==="cloudwatch"||t==="cloudtrail"?n==="deployed":t==="grafana"||t==="prometheus"?n==="configured":t==="datadog"?n==="healthy"||n==="configured":!!(e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt)}function eW(e){if(!e)return"Never";const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"just now";const n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n} minute${n===1?"":"s"} ago`;const r=Math.floor(n/60);if(r<24)return`${r} hour${r===1?"":"s"} ago`;const a=Math.floor(r/24);return`${a} day${a===1?"":"s"} ago`}function tW(e){const t=String(e||"").toLowerCase();return t==="critical"?"im-sev-critical":t==="high"?"im-sev-high":t==="medium"?"im-sev-medium":"im-sev-low"}const uw=[{accessorKey:"createdAt",header:({column:e})=>s.jsx(dt,{column:e,title:"Created Date"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-xs whitespace-nowrap",children:new Date(e.original.createdAt).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})})},{accessorKey:"alertName",header:({column:e})=>s.jsx(dt,{column:e,title:"Alarm name"}),cell:({row:e})=>s.jsx("div",{className:"max-w-[240px] truncate text-sm font-semibold",title:e.original.alertName,children:e.original.alertName})},{accessorKey:"severity",header:({column:e})=>s.jsx(dt,{column:e,title:"Severity"}),cell:({row:e})=>s.jsx("span",{className:`im-severity-pill ${tW(e.original.severity)}`,children:e.original.severity})},{accessorKey:"status",header:({column:e})=>s.jsx(dt,{column:e,title:"State"}),cell:({row:e})=>{const t=(e.original.status||"firing").toLowerCase(),n=["open","firing","active"].includes(t),r=t==="suppressed",a=t==="converted",i=t==="resolved"||t==="closed";let o="Firing",l="im-state-firing";return r?(o="Suppressed",l="im-state-suppressed"):a?(o="Converted",l="im-state-converted"):i?(o="Resolved",l="im-state-resolved"):n||(o=t.charAt(0).toUpperCase()+t.slice(1)),s.jsx("span",{className:l,children:o})}},{id:"resource",accessorFn:e=>e.resourceName||e.resourceId||"",header:({column:e})=>s.jsx(dt,{column:e,title:"Resource"}),cell:({row:e})=>{const t=`${e.original.resourceName||e.original.resourceId} · ${e.original.resourceType}`;return s.jsx("div",{className:"max-w-[200px] truncate font-mono text-sm",title:t,children:t})}},{accessorKey:"accountId",header:({column:e})=>s.jsx(dt,{column:e,title:"Account ID"}),cell:({row:e})=>{const t=e.original.accountId||e.original.additionalConfiguration?.accountId||"—";return s.jsx("div",{className:"max-w-[140px] truncate font-mono text-xs text-muted-foreground",title:t,children:t})}},{id:"tags",header:({column:e})=>s.jsx(dt,{column:e,title:"Tags"}),cell:({row:e})=>{const t=e.original,n=t.tags||t.additionalConfiguration?.tags||{},r=Object.entries(n);return r.length===0?s.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):s.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[220px]",children:[r.slice(0,3).map(([a,i])=>s.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[11px] bg-secondary text-secondary-foreground font-mono",children:[a,":",i]},a)),r.length>3&&s.jsxs("span",{className:"text-[10px] text-muted-foreground self-center",children:["+",r.length-3]})]})}},{id:"action",header:()=>s.jsx("span",{children:"Action"}),enableSorting:!1,cell:({row:e})=>s.jsx(Ei,{className:"im-link-button",to:`/alert/${e.original.id}`,children:"View"})}];function nW({alarms:e}){const[t,n]=w.useState([]),r=w.useMemo(()=>e,[e]),a=gl({data:r,columns:uw,state:{sorting:t},onSortingChange:n,getCoreRowModel:hl(),getSortedRowModel:Ad(),getPaginationRowModel:mk(),initialState:{pagination:{pageSize:10}}});return s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[s.jsx("div",{className:"im-table-card",children:s.jsxs(Oa,{children:[s.jsx(La,{children:a.getHeaderGroups().map(i=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:i.headers.map(o=>s.jsx(gn,{children:o.isPlaceholder?null:Rr(o.column.columnDef.header,o.getContext())},o.id))},i.id))}),s.jsx(ja,{children:a.getRowModel().rows?.length?a.getRowModel().rows.map(i=>s.jsx(Ft,{className:"group/row hover:bg-muted/30",children:i.getVisibleCells().map(o=>s.jsx(Pt,{children:Rr(o.column.columnDef.cell,o.getContext())},o.id))},i.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:uw.length,className:"h-24 text-center",children:"No alarms found for this source."})})})]})}),s.jsx(bl,{table:a,className:"mt-auto"})]})}function rW({source:e,saving:t,onSave:n}){const[r,a]=w.useState(e.name);w.useEffect(()=>a(e.name),[e.name]);const i=e.prometheusEnvironment||"production";return s.jsxs("section",{className:"im-panel im-config-panel",children:[s.jsx("h3",{children:"Configuration"}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Instance name"}),s.jsx(Xe,{value:r,onChange:o=>a(o.target.value)})]}),s.jsxs("div",{className:"im-form-grid-2",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Source type"}),s.jsx(Xe,{value:e.type,readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Region"}),s.jsx(Xe,{value:pI(e),readOnly:!0})]})]}),s.jsxs("div",{className:"im-form-grid-2",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Environment"}),s.jsx(Xe,{value:i,readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Delivery status"}),s.jsx(Xe,{value:e.deliveryStatus||"unknown",readOnly:!0})]})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Endpoint / account"}),s.jsx(Xe,{value:fI(e),readOnly:!0})]}),s.jsxs("div",{className:"im-config-actions",children:[s.jsx(ie,{className:"im-primary-button",onClick:()=>n({name:r}),disabled:t,children:t?"Saving...":"Save changes"}),s.jsx(ie,{variant:"outline",onClick:()=>a(e.name),disabled:t,children:"Cancel"})]})]})}function aW({source:e,disabling:t,testing:n,onBack:r,onToggleActive:a,onTest:i}){const o=JV(e),l=e.name.toLowerCase().startsWith(o.label.toLowerCase())?e.name:`${o.label} - ${e.name}`,c=[fI(e),pI(e),"production"].filter(Boolean).join(" - ");let u="Active",p="im-status-soft";if(!e.isActive)u="Disabled";else{const d=String(Jg(e)).toLowerCase();d==="failed"||e.deliveryStatus==="failed"?(u="Failed",p="im-status-soft error"):d==="pending"||d==="not_yet"||d==="checking"?(u="Deploying",p="im-status-soft degraded"):d==="not_started"&&(u="Not Started",p="im-status-soft degraded")}return s.jsxs("div",{className:"im-source-detail-header",children:[s.jsxs("div",{className:"im-source-detail-title",children:[s.jsx(ie,{variant:"outline",size:"icon",className:"im-detail-back-button","aria-label":"Back to sources",onClick:r,children:s.jsx(Vr,{className:"h-4 w-4"})}),s.jsx("span",{className:"im-provider-badge im-detail-provider-badge",style:{backgroundColor:o.color},children:o.mono}),s.jsxs("div",{children:[s.jsxs("div",{className:"im-title-row",children:[s.jsx("h2",{children:l}),s.jsx("span",{className:p,children:u})]}),s.jsx("p",{children:c})]})]}),s.jsxs("div",{className:"im-source-detail-actions",children:[s.jsx(ie,{variant:"outline",onClick:a,disabled:t,children:e.isActive?"Disable":"Enable"}),s.jsx(ie,{variant:"outline",onClick:i,disabled:n,children:n?"Testing...":"Test connection"})]})]})}const If=[{id:"overview",label:"Overview"},{id:"alarms",label:"Alarms"},{id:"configuration",label:"Configuration"},{id:"normalization",label:"Normalization"},{id:"dedup",label:"Dedup"},{id:"grouping",label:"Grouping"},{id:"workflows",label:"Workflows"},{id:"logs",label:"Logs"},{id:"test",label:"Test"}];function sW({activeTab:e,showSetup:t,onChange:n}){const r=t?[...If.slice(0,3),{id:"setup",label:"Setup"},...If.slice(3)]:If;return s.jsx("div",{className:"im-detail-tabs",children:r.map(a=>s.jsx("button",{type:"button",className:e===a.id?"is-active":"",onClick:()=>n(a.id),children:a.label},a.id))})}const dw=[{accessorKey:"timestamp",header:({column:e})=>s.jsx(dt,{column:e,title:"Timestamp"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-sm",children:new Date(e.original.timestamp).toLocaleTimeString()})},{accessorKey:"httpStatus",header:({column:e})=>s.jsx(dt,{column:e,title:"HTTP"}),cell:({row:e})=>s.jsx("span",{className:e.original.httpStatus>=400?"im-danger-text font-mono":"im-success-text font-mono",children:e.original.httpStatus})},{accessorKey:"sourceIp",header:({column:e})=>s.jsx(dt,{column:e,title:"Source IP"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-sm",children:e.original.sourceIp})},{accessorKey:"payloadSize",header:({column:e})=>s.jsx(dt,{column:e,title:"Payload"}),cell:({row:e})=>s.jsxs("span",{className:"font-mono text-sm",children:[(e.original.payloadSize/1024).toFixed(1)," KB"]})},{accessorKey:"result",header:({column:e})=>s.jsx(dt,{column:e,title:"Result"}),cell:({row:e})=>s.jsx("span",{className:e.original.result==="normalised"?"im-result-good":"im-result-warn",children:e.original.result})}];function iW({logs:e,search:t,onSearchChange:n}){const[r,a]=w.useState([]),i=w.useMemo(()=>e,[e]),o=gl({data:i,columns:dw,state:{sorting:r},onSortingChange:a,getCoreRowModel:hl(),getSortedRowModel:Ad(),getPaginationRowModel:mk(),initialState:{pagination:{pageSize:10}}});return s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[s.jsxs("div",{className:"im-search-wrap",children:[s.jsx(gs,{className:"im-search-icon",size:14,"aria-hidden":"true"}),s.jsx(Xe,{value:t,onChange:l=>n(l.target.value),placeholder:"Search logs...",className:"im-search-input"})]}),s.jsx("div",{className:"im-table-card",children:s.jsxs(Oa,{children:[s.jsx(La,{children:o.getHeaderGroups().map(l=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:l.headers.map(c=>s.jsx(gn,{children:c.isPlaceholder?null:Rr(c.column.columnDef.header,c.getContext())},c.id))},l.id))}),s.jsx(ja,{children:o.getRowModel().rows?.length?o.getRowModel().rows.map(l=>s.jsx(Ft,{className:"group/row hover:bg-muted/30",children:l.getVisibleCells().map(c=>s.jsx(Pt,{children:Rr(c.column.columnDef.cell,c.getContext())},c.id))},l.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:dw.length,className:"h-24 text-center",children:"No logs found."})})})]})}),s.jsx(bl,{table:o,className:"mt-auto"})]})}function oW({overview:e}){const t=Math.max(1,...e.summary.weeklyRate.map(i=>i.count)),n=e.summary.weeklyRate.some(i=>i.count>0);let r="Active";if(!e.source.isActive)r="Disabled";else{const i=String(Jg(e.source)).toLowerCase();i==="failed"||e.source.deliveryStatus==="failed"?r="Failed":i==="pending"||i==="not_yet"||i==="checking"?r="Deploying":i==="not_started"&&(r="Not Started")}async function a(){try{await navigator.clipboard.writeText(e.summary.webhookEndpoint),ae.success("Webhook URL copied")}catch{ae.error("Failed to copy webhook URL")}}return s.jsxs("div",{className:"im-source-overview-grid",children:[s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Status"}),s.jsx("strong",{className:"im-inline-status",children:r})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Last alarm"}),s.jsx("strong",{children:eW(e.summary.lastAlarmAt)})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Alarms today"}),s.jsx("strong",{children:e.summary.alarmsToday})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Errors (1h)"}),s.jsx("strong",{className:"im-danger-text",children:e.summary.errorsLastHour})]}),s.jsxs("section",{className:"im-panel im-rate-panel",children:[s.jsx("h3",{children:"7-day alarm rate"}),n?s.jsx("div",{className:"im-bar-chart",children:e.summary.weeklyRate.map(i=>s.jsxs("div",{className:"im-bar-item",children:[s.jsx("span",{style:{height:`${Math.max(36,i.count/t*124)}px`}}),s.jsx("em",{children:i.day})]},i.day))}):s.jsx("div",{className:"im-rate-empty",children:"No alarms received in the last 7 days."})]}),s.jsxs("section",{className:"im-panel im-webhook-panel",children:[s.jsx("h3",{children:"Webhook endpoint"}),s.jsxs("div",{className:"im-webhook-copy-row",children:[s.jsx("code",{children:e.summary.webhookEndpoint}),s.jsx("button",{type:"button","aria-label":"Copy webhook URL",onClick:a,children:s.jsx(yn,{size:16})})]}),e.summary.authTokenPreview&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem",fontSize:"0.85rem",color:"var(--im-text-muted)"},children:"Auth Token (Bearer)"}),s.jsxs("div",{className:"im-webhook-copy-row",children:[s.jsx("code",{children:e.summary.authTokenPreview}),s.jsx("button",{type:"button","aria-label":"Copy auth token",onClick:()=>{navigator.clipboard.writeText(e.summary.authTokenPreview),ae.success("Auth token copied")},children:s.jsx(yn,{size:16})})]})]})]})]})}function lW({source:e,loading:t,cloudWatch:n,cloudTrail:r,grafana:a,prometheus:i,datadog:o}){return s.jsx("div",{className:"im-source-setup-tab",children:s.jsx(lI,{type:ws(e.type),webhookUrl:e.webhookUrl,loading:t,cloudWatch:n,cloudTrail:r,grafana:a,prometheus:i,datadog:o})})}const cW=`{
110
+ Webhook URL: ${N.webhook.url}`),ae.success("Contact point details copied")),window.open(`${pe}/alerting/notifications/receivers/new`,"_blank","noopener,noreferrer")};return s.jsx(kt,{open:e,onOpenChange:pe=>!Q&&n(pe),children:s.jsxs(It,{className:"max-h-[92vh] w-[min(96vw,920px)] max-w-none overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx(Uh,{className:"h-5 w-5 text-orange-500"}),"Grafana Source Wizard"]}),s.jsx(Kt,{children:"Create a Grafana source and configure Grafana alerts to send webhooks to Meyi Connect."})]}),s.jsx("div",{className:"border-b pb-4",children:s.jsx("div",{className:"mx-auto flex max-w-2xl items-center justify-center",children:aw.map(({step:pe,label:te,Icon:Ae},$e)=>s.jsxs("div",{className:"flex flex-1 items-center",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-2",children:[s.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-full border shadow-sm transition ${a>=pe?"border-primary bg-primary text-primary-foreground":"border-border bg-muted text-muted-foreground"}`,children:a>pe?s.jsx(Yt,{className:"h-5 w-5"}):s.jsx(Ae,{className:"h-5 w-5"})}),s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:`text-sm font-semibold ${a>=pe?"text-foreground":"text-muted-foreground"}`,children:te}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Step ",pe]})]})]}),$e<aw.length-1&&s.jsx("div",{className:`mt-[-26px] h-px flex-1 ${a>pe?"bg-primary":"bg-border"}`})]},pe))})}),a===1?s.jsxs("div",{className:"grid gap-4 md:grid-cols-[1.1fr_0.9fr]",children:[s.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[s.jsx("div",{className:"mb-2 text-sm font-semibold",children:"How Grafana setup works"}),s.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[s.jsx("p",{children:"Meyi Connect creates a webhook source and generates a Grafana contact point target."}),s.jsx("p",{children:"If you provide a Grafana service account token, Meyi Connect can create the Grafana webhook contact point through Grafana APIs."})]})]}),s.jsxs("div",{className:"rounded-xl border p-4",children:[s.jsx("div",{className:"text-sm font-semibold",children:"Setup options"}),s.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[s.jsx("li",{children:"Automatic: Grafana URL + service account token."}),s.jsx("li",{children:"Optional routing: add a notification policy matcher route."}),s.jsx("li",{children:"Manual: copy webhook URL and configure contact point in Grafana UI."})]})]})]}):null,a===2?s.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source Name"}),s.jsx(Xe,{value:o,onChange:pe=>l(pe.target.value),disabled:p})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:c,onChange:pe=>u(pe.target.value),disabled:p,placeholder:"Optional"})]})]}):null,a===3?s.jsx("div",{className:"space-y-4",children:f&&!N?s.jsx("div",{className:"flex min-h-[180px] items-center justify-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("div",{className:"min-w-0 flex-1 rounded-md border bg-muted/20 p-2 text-xs break-all",children:N.webhook.url}),s.jsx(LV,{value:N.webhook.url})]})]}),s.jsx("div",{className:"rounded-xl border bg-muted/20 p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Hh,{className:"mt-0.5 h-4 w-4 text-orange-500"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Manual setup"}),s.jsx("ol",{className:"mt-2 list-inside list-decimal space-y-1 text-xs text-muted-foreground",children:N.manual.steps.map((pe,te)=>s.jsx("li",{children:pe},te))})]})]})}),s.jsxs("div",{className:"space-y-4 rounded-xl border p-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Grafana connection details"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"These values are used for manual setup, service-account navigation, and automatic API setup."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Grafana URL"}),s.jsx(Xe,{value:R,onChange:pe=>j(pe.target.value),placeholder:"http://65.2.144.245:3001",disabled:h||b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Contact Point Name"}),s.jsx(Xe,{value:q,onChange:pe=>P(pe.target.value),disabled:h||b})]})]}),s.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Manual Grafana contact point"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Opens Grafana contact-point creation and copies name, Webhook integration, and webhook URL."})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:J,disabled:!se||b,children:[b?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Save Details"]}),s.jsx(ie,{type:"button",variant:"outline",onClick:Ne,disabled:h||b,children:"Open Grafana Contact Point"})]})]}),O?s.jsx("div",{className:"mt-3 rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-800",children:"Grafana URL and contact point details are saved for this source."}):null]})]}),s.jsxs("div",{className:"space-y-4 rounded-xl border p-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold",children:"Automatic API setup"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paste a Grafana service account token. Saved tokens are encrypted and shown masked when reopened."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Account Token"}),s.jsx(Xe,{type:"password",value:U,onChange:pe=>G(pe.target.value),placeholder:N.defaults.hasAccountToken?xc:"glsa_...",disabled:h}),N.defaults.hasAccountToken?s.jsx("p",{className:"text-xs text-muted-foreground",children:"A token is already saved. Keep the masked value to reuse it, or paste a new token to replace it."}):null]}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:z,onChange:pe=>re(pe.target.checked),disabled:h||b}),"Add notification policy route for matching Grafana alerts"]}),z?s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Matcher Label"}),s.jsx(Xe,{value:B,onChange:pe=>H(pe.target.value),disabled:h||b})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Matcher Value"}),s.jsx(Xe,{value:I,onChange:pe=>V(pe.target.value),disabled:h||b})]})]}):null,s.jsxs(ie,{type:"button",onClick:Y,disabled:!D||h,children:[h?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Configure Grafana"]})]}),C?s.jsxs("div",{className:"space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup completed"}),s.jsxs("div",{children:["Contact point: ",C.contactPointName]}),s.jsxs("div",{children:["Policy updated: ",C.policyUpdated?"Yes":"No"]}),C.matcher?s.jsxs("div",{children:["Matcher: ",C.matcher.label,"=",C.matcher.value]}):null]}):null,!C&&N.setup?.status==="configured"?s.jsxs("div",{className:"space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup completed"}),s.jsxs("div",{children:["Contact point: ",N.setup.contactPointName]}),s.jsxs("div",{children:["Policy updated: ",N.setup.policyUpdated?"Yes":"No"]}),N.setup.matcher?s.jsxs("div",{children:["Matcher: ",N.setup.matcher.label,"=",N.setup.matcher.value]}):null]}):null,!C&&N.setup?.status==="failed"?s.jsxs("div",{className:"space-y-2 rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-800",children:[s.jsx("div",{className:"font-semibold",children:"Grafana setup failed"}),s.jsx("div",{children:N.setup.statusReason||"Retry automatic setup with a valid Grafana URL and token."})]}):null]}):s.jsx("div",{className:"rounded-md border bg-muted/20 p-4 text-sm text-muted-foreground",children:"Setup details are not loaded yet."})}):null,s.jsxs($t,{className:"gap-2",children:[a>1&&a<3?s.jsx(ie,{type:"button",variant:"outline",onClick:()=>i(pe=>pe-1),disabled:Q,children:"Back"}):null,a===1?s.jsx(ie,{type:"button",onClick:()=>i(2),children:"Continue"}):null,a===2?s.jsxs(ie,{type:"button",onClick:K,disabled:!Z||p,children:[p?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Create Source"]}):null,a===3?s.jsxs(s.Fragment,{children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:()=>S&&ne(S),disabled:f||!S,children:[f?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh Setup"]}),s.jsx(ie,{type:"button",onClick:()=>n(!1),disabled:f||h,children:"Close"})]}):null]})]})})}const sw=[{step:1,label:"Overview",Icon:Xu},{step:2,label:"Source",Icon:Qu},{step:3,label:"Setup",Icon:Hh}],PV={docker:kC,linux:jC,kubernetes:SC};function iw({value:e}){const[t,n]=w.useState(!1);return s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:()=>{Vn(e),n(!0),setTimeout(()=>n(!1),1200)},children:[t?s.jsx(Yt,{className:"h-3.5 w-3.5"}):s.jsx(yn,{className:"h-3.5 w-3.5"}),"Copy"]})}function FV({href:e,label:t}){return s.jsx(ie,{type:"button",variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",children:[s.jsx(Lo,{className:"h-3.5 w-3.5"}),t]})})}function BV({open:e,onOpenChange:t,onCreated:n}){const[r,a]=w.useState(1),[i,o]=w.useState("Prometheus"),[l,c]=w.useState(""),[u,p]=w.useState(!1),[d,f]=w.useState(!1),[m,h]=w.useState(null),[g,b]=w.useState(null),[x,S]=w.useState("docker"),[T,N]=w.useState(""),[A,C]=w.useState(""),[k,O]=w.useState(!1),[M,R]=w.useState(null);w.useEffect(()=>{e||(a(1),o("Prometheus"),c(""),p(!1),f(!1),h(null),b(null),S("docker"),N(""),C(""),O(!1),R(null))},[e]);const j=w.useMemo(()=>!!i.trim(),[i]),U=u||d,G=x==="linux"?g?.defaults.linuxCommand:x==="kubernetes"?g?.defaults.kubernetesCommand:g?.defaults.dockerCommand,q=x==="linux"?g?.downloads?.linuxScript:x==="kubernetes"?g?.downloads?.kubernetesYaml:g?.downloads?.dockerScript,P=async()=>{if(!j){ae.error("Source name is required");return}p(!0);try{const H=await Ie.createSource({name:i.trim(),type:"prometheus",description:l.trim()||void 0});h(H.sourceId),a(3),n(),ae.success("Prometheus source created"),f(!0);const I=await Ie.getPrometheusOnboarding(H.sourceId);b(I),N(I.defaults.prometheusBaseUrl||""),C(I.defaults.alertmanagerBaseUrl||""),R(I.defaults.setupStatus?{status:I.defaults.setupStatus,reason:I.defaults.setupStatusReason||""}:null)}catch(H){ae.error(H?.response?.data?.error||"Failed to create Prometheus source")}finally{p(!1),f(!1)}},z=async()=>{if(m){f(!0);try{const H=await Ie.getPrometheusOnboarding(m);b(H),N(H.defaults.prometheusBaseUrl||""),C(H.defaults.alertmanagerBaseUrl||""),R(H.defaults.setupStatus?{status:H.defaults.setupStatus,reason:H.defaults.setupStatusReason||""}:null)}catch(H){ae.error(H?.response?.data?.error||"Failed to load Prometheus setup")}finally{f(!1)}}},re=async()=>{if(m){if(!T.trim()||!A.trim()){ae.error("Prometheus URL and Alertmanager URL are required");return}O(!0),R(null);try{const H=await Ie.checkPrometheusStatus(m,{prometheusBaseUrl:T.trim(),alertmanagerBaseUrl:A.trim(),timeoutSeconds:20});R({status:H.status,reason:H.reason}),H.status==="configured"?ae.success("Prometheus setup verified"):H.status==="not_yet"?ae.info("Prometheus changes are not visible yet"):ae.error(H.reason||"Prometheus setup verification failed"),n()}catch(H){ae.error(H?.response?.data?.error||"Failed to check Prometheus setup")}finally{O(!1)}}},B=M?.status==="configured"?"border-emerald-200 bg-emerald-50 text-emerald-800":M?.status==="failed"?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800";return s.jsx(kt,{open:e,onOpenChange:H=>!U&&t(H),children:s.jsxs(It,{className:"max-h-[92vh] w-[min(96vw,900px)] max-w-none overflow-y-auto",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx(Qu,{className:"h-5 w-5 text-red-500"}),"Prometheus Source Wizard"]}),s.jsx(Kt,{children:"Create a Prometheus source and generate setup automation for Alertmanager."})]}),s.jsx("div",{className:"border-b pb-4",children:s.jsx("div",{className:"mx-auto flex max-w-2xl items-center justify-center",children:sw.map(({step:H,label:I,Icon:V},Z)=>s.jsxs("div",{className:"flex flex-1 items-center",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-2",children:[s.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-full border shadow-sm transition ${r>=H?"border-primary bg-primary text-primary-foreground":"border-border bg-muted text-muted-foreground"}`,children:r>H?s.jsx(Yt,{className:"h-5 w-5"}):s.jsx(V,{className:"h-5 w-5"})}),s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:`text-sm font-semibold ${r>=H?"text-foreground":"text-muted-foreground"}`,children:I}),s.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Step ",H]})]})]}),Z<sw.length-1&&s.jsx("div",{className:`mt-[-26px] h-px flex-1 ${r>H?"bg-primary":"bg-border"}`})]},H))})}),r===1?s.jsxs("div",{className:"grid gap-4 md:grid-cols-[1.1fr_0.9fr]",children:[s.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[s.jsx("div",{className:"mb-2 text-sm font-semibold",children:"How Prometheus automation works"}),s.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[s.jsx("p",{children:"Meyi Connect creates a webhook source, then generates setup artifacts for your Prometheus environment."}),s.jsx("p",{children:"For self-hosted Prometheus, full automation is script-based because Prometheus and Alertmanager APIs do not persistently edit YAML config."})]})]}),s.jsxs("div",{className:"rounded-xl border p-4",children:[s.jsx("div",{className:"text-sm font-semibold",children:"Supported setup methods"}),s.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[s.jsx("li",{children:"Docker: download and run a container setup script."}),s.jsx("li",{children:"Linux service: download and run a local config script."}),s.jsx("li",{children:"Kubernetes: download and apply Prometheus Operator YAML."})]})]})]}):null,r===2?s.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Source Name"}),s.jsx(Xe,{value:i,onChange:H=>o(H.target.value),disabled:u})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:l,onChange:H=>c(H.target.value),disabled:u,placeholder:"Optional"})]})]}):null,r===3?s.jsx("div",{className:"space-y-4",children:d&&!g?s.jsx("div",{className:"flex min-h-[180px] items-center justify-center",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Meyi Webhook URL"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all",children:g.webhook.url})]}),s.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Deployment status check"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"After running the setup artifact, click Check Status. Meyi Connect will verify readiness and Alertmanager config once."})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Prometheus URL"}),s.jsx(Xe,{value:T,onChange:H=>N(H.target.value),placeholder:"http://65.2.144.245:9090"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Alertmanager URL"}),s.jsx(Xe,{value:A,onChange:H=>C(H.target.value),placeholder:"http://65.2.144.245:9093"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{type:"button",variant:"outline",size:"sm",onClick:re,disabled:k,children:[k?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Check Status"]}),M?s.jsxs("div",{className:`rounded-md border px-3 py-1.5 text-xs ${B}`,children:[s.jsx("span",{className:"font-semibold",children:M.status.replace(/_/g," ")}),M.reason?s.jsxs("span",{children:[" - ",M.reason]}):null]}):null]})]}),s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:(g.environments||[]).map(H=>{const I=PV[H.id],V=x===H.id;return s.jsxs("button",{type:"button",onClick:()=>S(H.id),className:`rounded-lg border p-3 text-left transition ${V?"border-primary bg-primary/5 shadow-sm":"bg-background hover:bg-muted/30"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(I,{className:"h-4 w-4 text-primary"}),H.label]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:H.description})]},H.id)})}),s.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:"Automated setup"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Download and run this on the Prometheus host or cluster."})]}),q?s.jsx(FV,{href:q,label:x==="kubernetes"?"Download YAML":"Download Script"}):null]}),G?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"rounded-md border bg-background p-2 text-xs break-all font-mono",children:G}),s.jsx(iw,{value:G})]}):null]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Pe,{children:"Manual alertmanager.yml snippet"}),s.jsx("div",{className:"rounded-md border bg-muted/20 p-2 text-xs break-all font-mono whitespace-pre-wrap",children:g.snippets.alertmanagerConfig}),s.jsx(iw,{value:g.snippets.alertmanagerConfig})]})]}):s.jsx("div",{className:"rounded-md border bg-muted/20 p-4 text-sm text-muted-foreground",children:"Setup details are not loaded yet."})}):null,s.jsxs($t,{className:"gap-2",children:[r>1&&r<3?s.jsx(ie,{type:"button",variant:"outline",onClick:()=>a(H=>H-1),disabled:U,children:"Back"}):null,r===1?s.jsx(ie,{type:"button",onClick:()=>a(2),children:"Continue"}):null,r===2?s.jsxs(ie,{type:"button",onClick:P,disabled:!j||u,children:[u?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Create Source"]}):null,r===3?s.jsxs(s.Fragment,{children:[s.jsxs(ie,{type:"button",variant:"outline",onClick:z,disabled:d||!m,children:[d?s.jsx(Qe,{className:"h-4 w-4 animate-spin"}):null,"Refresh Setup"]}),s.jsx(ie,{type:"button",onClick:()=>t(!1),disabled:d,children:"Close"})]}):null]})]})})}function cI({currentPage:e,pageSize:t,totalPages:n,total:r,onPageChange:a,onPageSizeChange:i,className:o}){const l=tA(e,n),c=r>0;return s.jsxs("div",{className:Fe("flex flex-col sm:flex-row items-center justify-between overflow-clip px-2 gap-4 py-4 border-t mt-4","@max-2xl/content:flex-col-reverse @max-2xl/content:gap-4",o),style:{overflowClipMargin:1},children:[s.jsxs("div",{className:"flex w-full items-center justify-between",children:[c&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",e," of ",n]}),i&&s.jsxs("div",{className:"flex items-center gap-2 @max-2xl/content:flex-row-reverse",children:[s.jsxs(Fo,{value:`${t}`,onValueChange:u=>i(Number(u)),children:[s.jsx(Uo,{className:"h-8 w-[70px]",children:s.jsx(Bo,{placeholder:t})}),s.jsx($o,{side:"top",children:[10,20,30,40,50].map(u=>s.jsx(ba,{value:`${u}`,children:u},u))})]}),s.jsx("p",{className:"hidden text-sm font-medium sm:block",children:"Rows per page"})]})]}),s.jsxs("div",{className:"flex items-center sm:space-x-6 lg:space-x-8",children:[c&&s.jsxs("div",{className:"flex w-[100px] items-center justify-center text-sm font-medium @max-3xl/content:hidden",children:["Page ",e," of ",n]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>a(1),disabled:e<=1,title:"First page",children:[s.jsx("span",{className:"sr-only",children:"Go to first page"}),s.jsx(NC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>a(e-1),disabled:e<=1,title:"Previous page",children:[s.jsx("span",{className:"sr-only",children:"Go to previous page"}),s.jsx(wC,{className:"h-4 w-4"})]}),c&&l.map((u,p)=>s.jsx("div",{className:"flex items-center",children:u==="..."?s.jsx("span",{className:"text-muted-foreground px-1 text-sm",children:"..."}):s.jsx(ie,{variant:e===u?"default":"outline",className:"h-8 min-w-8 px-2",onClick:()=>a(u),children:u})},`${u}-${p}`)),s.jsxs(ie,{variant:"outline",className:"size-8 p-0",onClick:()=>a(e+1),disabled:e>=n,title:"Next page",children:[s.jsx("span",{className:"sr-only",children:"Go to next page"}),s.jsx(TC,{className:"h-4 w-4"})]}),s.jsxs(ie,{variant:"outline",className:"size-8 p-0 @max-md/content:hidden",onClick:()=>a(n),disabled:e>=n,title:"Last page",children:[s.jsx("span",{className:"sr-only",children:"Go to last page"}),s.jsx(CC,{className:"h-4 w-4"})]})]})]})]})}const kf={sourceTypes:[],status:"",region:""},UV=[{label:"CloudWatch",value:"cloudwatch"},{label:"Level 1 Security",value:"cloudtrail"},{label:"Grafana",value:"grafana"},{label:"Prometheus",value:"prometheus"},{label:"Datadog",value:"datadog"},{label:"Custom",value:"custom"}];function $V(){return{sourceTypes:[...kf.sourceTypes],status:kf.status,region:kf.region}}function HV({search:e,filters:t,loading:n,onSearchChange:r,onFiltersChange:a,onRefresh:i}){const o=[{label:"Active",value:"active"},{label:"Degraded",value:"degraded"},{label:"Error",value:"error"},{label:"Disabled",value:"disabled"}],l=[{label:"Global",value:"global"},{label:"AWS",value:"aws"},{label:"K8s",value:"k8s"},{label:"Datadog",value:"datadog"},{label:"Multi",value:"multi"}];return s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{type:"text",value:e,onChange:c=>r(c.target.value),placeholder:"Search sources...",className:"h-9 w-[150px] lg:w-[250px] pl-8",disabled:n}),e&&s.jsxs(ie,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground",onClick:()=>r(""),children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Clear"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Type",options:UV,selected:t.sourceTypes,onChange:c=>a({...t,sourceTypes:c})}),s.jsx(Qn,{title:"Status",options:o,selected:t.status?[t.status]:[],onChange:c=>a({...t,status:c[0]||""})}),s.jsx(Qn,{title:"Region",options:l,selected:t.region?[t.region]:[],onChange:c=>a({...t,region:c[0]||""})})]})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs(ie,{variant:"outline",size:"sm",onClick:i,disabled:n,className:"h-8 hidden lg:flex",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",n&&"animate-spin")}),"Refresh"]})})]})}const ow={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus / Alertmanager",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom / SDK",mono:"CU",color:"#5A6B7B"}};function Vo(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function zV(e){const t=Vo(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsDeploymentStatus||"not_started":t==="grafana"?e.grafanaSetupStatus||"not_started":t==="prometheus"?e.prometheusSetupStatus||"not_started":e.deliveryStatus||"unknown"}function uI(e){if(!e.isActive)return"disabled";const t=String(zV(e)).toLowerCase();return t==="failed"?"error":t==="pending"||t==="not_yet"||t==="checking"||t==="not_started"?"degraded":"active"}function GV(e){return e==="error"?"Error":e==="degraded"?"Degraded":e==="disabled"?"Disabled":"Active"}function dI(e){const t=Vo(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsRegion||"aws":t==="prometheus"?e.prometheusEnvironment||"k8s":t==="datadog"?"datadog":t==="grafana"?"multi":"global"}function VV(e){return dI(e)}function WV(e){const t=Vo(e.type);return t==="grafana"?e.grafanaBaseUrl||e.webhookUrl:t==="prometheus"?e.alertmanagerBaseUrl||e.prometheusReceiverName||"alertmanager.yml":t==="cloudwatch"?`${e.awsStackName||"aws"} - ${e.webhookUrl}`:t==="cloudtrail"?`${e.awsStackName||"aws"} - cloudtrail:security`:t==="datadog"?e.webhookUrl:e.description||e.webhookUrl}function qV(e){const t=e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt;if(!t)return"Never";const n=Date.now()-new Date(t).getTime();if(!Number.isFinite(n)||n<0)return"just now";const r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r} minute${r===1?"":"s"} ago`;const a=Math.floor(r/60);if(a<24)return`${a} hour${a===1?"":"s"} ago`;const i=Math.floor(a/24);return`${i} day${i===1?"":"s"} ago`}function YV(e){const t=Math.max(0,Number(e||0));return t===0?[3,3,3,3,3,3,3,3]:[.32,.56,.42,.8,.62,.48,.92,.72].map(n=>Math.max(3,Math.round(16*Math.min(1,n+Math.min(t,100)/300))))}function KV(e){return uI(e)}function Br({title:e,onClick:t,children:n}){return s.jsx("button",{className:"im-icon-button",type:"button",title:e,"aria-label":e,onClick:t,children:n})}function XV({sources:e,...t}){const[n,r]=w.useState({}),a=5,o=["cloudwatch","cloudtrail","grafana","prometheus","datadog","meyi_pulse","pagerduty","custom"].map(l=>({type:l,meta:ow[l]||ow.custom,instances:e.filter(c=>Vo(c.type)===l)})).filter(l=>l.instances.length>0);return s.jsx("div",{className:"im-source-groups",children:o.map(l=>s.jsxs("section",{className:"im-source-group",children:[s.jsxs("div",{className:"im-source-group-header",children:[s.jsx("span",{className:"im-provider-badge",style:{backgroundColor:l.meta.color},children:l.meta.mono}),s.jsx("span",{className:"im-group-title",children:l.meta.label}),s.jsxs("span",{className:"im-count-pill",children:[l.instances.length," ",l.instances.length===1?"instance":"instances"]}),s.jsx(Ku,{className:"im-header-chevron",size:14,"aria-hidden":"true"})]}),s.jsxs("div",{children:[l.instances.slice(((n[l.type]||1)-1)*a,(n[l.type]||1)*a).map(c=>{const u=Vo(c.type),p=uI(c),d=Number(c.alertCount??0);return s.jsxs("div",{className:"im-source-row",onClick:()=>t.onView(c),children:[s.jsx("span",{className:`im-status-dot im-status-${p}`}),s.jsxs("div",{className:"im-source-name",children:[s.jsxs("div",{className:"im-source-title-line",children:[s.jsx("strong",{children:c.name}),s.jsx("span",{className:`im-status-pill im-status-pill-${p}`,children:GV(p)})]}),s.jsx("span",{children:WV(c)})]}),s.jsxs("div",{className:"im-row-metric",children:[s.jsx("span",{children:"Region / env"}),s.jsxs("strong",{children:[dI(c),"/production"]})]}),s.jsxs("div",{className:"im-row-metric",children:[s.jsx("span",{children:"Last alert"}),s.jsx("strong",{children:qV(c)})]}),s.jsxs("div",{className:"im-alarms-metric",children:[s.jsx("span",{children:"Alerts today"}),s.jsxs("div",{children:[s.jsx("strong",{children:d}),d>0?s.jsx("span",{className:"im-sparkline","aria-hidden":"true",children:YV(d).map((f,m)=>s.jsx("span",{style:{height:f}},`${c.id}-${m}`))}):s.jsx("span",{className:"im-zero-sparkline",children:"No alerts"})]})]}),Number(c.webhookFailureCount||0)>0?s.jsxs("div",{className:"im-alarms-metric",children:[s.jsx("span",{className:"text-red-500",children:"Failed deliveries"}),s.jsx("div",{children:s.jsx("strong",{className:"text-red-500",children:c.webhookFailureCount||0})})]}):s.jsx("div",{}),s.jsxs("div",{className:"im-row-actions",children:[s.jsx(Br,{title:"Copy webhook URL",onClick:f=>{f.stopPropagation(),Vn(c.webhookUrl).then(m=>{m?ae.success("Webhook URL copied"):ae.error("Failed to copy webhook URL")})},children:s.jsx(yn,{size:15})}),s.jsx(Br,{title:"Token policy",onClick:f=>{f.stopPropagation(),t.onManageTokenPolicy(c)},children:s.jsx(VF,{size:15})}),u==="cloudwatch"&&s.jsx(Br,{title:"CloudWatch setup",onClick:f=>{f.stopPropagation(),t.onAwsSetup(c)},children:s.jsx(lu,{size:15})}),u==="cloudtrail"&&s.jsx(Br,{title:"Level 1 Security setup",onClick:f=>{f.stopPropagation(),t.onAwsSetup(c)},children:s.jsx(lu,{size:15})}),u==="grafana"&&s.jsx(Br,{title:"Grafana setup",onClick:f=>{f.stopPropagation(),t.onGrafanaSetup(c)},children:s.jsx(Uh,{size:15})}),u==="prometheus"&&s.jsx(Br,{title:"Prometheus setup",onClick:f=>{f.stopPropagation(),t.onPrometheusSetup(c)},children:s.jsx(IC,{size:15})}),u==="datadog"&&s.jsx(Br,{title:"Datadog setup",onClick:f=>{f.stopPropagation(),t.onDatadogSetup(c)},children:s.jsx(OC,{size:15})}),s.jsx(Br,{title:"Edit source",onClick:f=>{f.stopPropagation(),t.onEdit(c)},children:s.jsx(Zu,{size:15})}),s.jsx(Br,{title:"Delete source",onClick:f=>{f.stopPropagation(),t.onDelete(c.id)},children:s.jsx(ll,{size:15})})]})]},c.id)}),l.instances.length>a&&s.jsxs("div",{className:"im-group-pagination",children:[s.jsxs("span",{children:[Math.min(((n[l.type]||1)-1)*a+1,l.instances.length),"-",Math.min((n[l.type]||1)*a,l.instances.length)," of ",l.instances.length]}),s.jsxs("div",{className:"im-pager",children:[s.jsx("button",{type:"button",disabled:(n[l.type]||1)<=1,onClick:()=>r(c=>({...c,[l.type]:Math.max(1,(c[l.type]||1)-1)})),children:"‹"}),Array.from({length:Math.ceil(l.instances.length/a)},(c,u)=>u+1).map(c=>s.jsx("button",{type:"button",className:(n[l.type]||1)===c?"is-active":"",onClick:()=>r(u=>({...u,[l.type]:c})),children:c},c)),s.jsx("button",{type:"button",disabled:(n[l.type]||1)>=Math.ceil(l.instances.length/a),onClick:()=>r(c=>({...c,[l.type]:Math.min(Math.ceil(l.instances.length/a),(c[l.type]||1)+1)})),children:"›"})]})]})]})]},l.type))})}const ZV={};function QV(){const{isReadOnly:e,openCostSources:t}=ur(),n=St(),[r,a]=w.useState([]),[i,o]=w.useState(0),[l,c]=w.useState(!0),[u,p]=w.useState(1),[d,f]=w.useState(10),[m,h]=w.useState(""),[g,b]=w.useState(""),[x,S]=w.useState(()=>$V()),[T,N]=w.useState(!1),[A,C]=w.useState(!1),[k,O]=w.useState(!1),[M,R]=w.useState(!1),[j,U]=w.useState(!1),[G,q]=w.useState(null),[P,z]=w.useState(null),[re,B]=w.useState(null),[H,I]=w.useState(null),[V,Z]=w.useState(!1),[D,se]=w.useState(null),[Q,ne]=w.useState(!1),[K,Y]=w.useState(null),[J,Ne]=w.useState(null),[pe,te]=w.useState(!1),[Ae,$e]=w.useState(null),[Ee,Ze]=w.useState(!1),[Ye,st]=w.useState(null),[lt,Et]=w.useState(!1),[Bt,Se]=w.useState(!1),[Re,Ue]=w.useState(null),[He,le]=w.useState(!1),[_e,Ke]=w.useState(!1),[tt,v]=w.useState(null),[ee,fe]=w.useState(null),[he,de]=w.useState({accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"ap-south-1",stackName:""}),[Ce,_]=w.useState([]),[X,ge]=w.useState([]),[oe,xe]=w.useState({lambdaName:"",alarmNamePrefix:""}),[we,be]=w.useState({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}),[Me,ye]=w.useState(!1),[Oe,je]=w.useState(null),[qe,pt]=w.useState(!1),[Tt,Dt]=w.useState(null),[Vt,hn]=w.useState(!1),[Wn,vp]=w.useState(null),[ra,FO]=w.useState(""),[Pue,Fue]=w.useState(""),[Bue,BO]=w.useState(""),[Uue,$ue]=w.useState(!1),[Hue,UO]=w.useState("service"),[zue,$O]=w.useState(""),[Sp,mv]=w.useState(!1),[Os,hv]=w.useState(null),[HO,gv]=w.useState(!1),[zO,wp]=w.useState(null),[Tp,Np]=w.useState(""),[Cp,Ap]=w.useState(""),[GO,_p]=w.useState(!1),[VO,Ul]=w.useState(null),[Rp,WO]=w.useState(!1),[Ls,qO]=w.useState(null),[YO,bv]=w.useState(!1),[KO,xv]=w.useState(null),[XO,yv]=w.useState(!1),[ZO,Ev]=w.useState(null),[vv,Sv]=w.useState("datadoghq.com"),[wv,Tv]=w.useState(""),[Nv,Cv]=w.useState(""),[Av,_v]=w.useState("");w.useEffect(()=>{const me=setTimeout(()=>{b(m),p(1)},400);return()=>clearTimeout(me)},[m]);const cn=async(me=!1)=>{me||c(!0);try{const nt=await Ie.listSources({page:u,limit:d,search:g||void 0,type:x.sourceTypes.length>0?x.sourceTypes.join(","):void 0}),yt=nt.sources||[];a(yt),$e(Wt=>Wt&&(yt.find(nr=>nr.id===Wt.id)??Wt)),o(nt.total||0)}catch{me||ae.error("Failed to load sources")}finally{me||c(!1)}},Rv=w.useRef(cn);w.useEffect(()=>{Rv.current=cn},[cn]),w.useEffect(()=>{cn()},[u,d,g,x]),w.useEffect(()=>{const me=ZV?.VITE_SOCKET_URL,nt=(me?me.replace("/socket.io",""):window.location.origin).replace(/\/+$/,""),yt=bo(`${nt}/ws/insight`,{path:"/socket.io",transports:["websocket","polling"],withCredentials:!0}),Wt=()=>{Rv.current(!0)},nr=Bi=>{Bi?.topic&&(Bi.topic==="sources.updated"||Bi.topic.startsWith("sources.")||Bi.topic==="alerts.totals"||Bi.topic.startsWith("alerts."))&&Wt()};return yt.on("insight:alerts:totals",Wt),yt.on("insight:event",nr),()=>{yt.off("insight:alerts:totals",Wt),yt.off("insight:event",nr),yt.disconnect()}},[]),w.useEffect(()=>{if(!r.some(yt=>String(yt.type||"").toLowerCase()==="cloudwatch"&&String(yt.awsDeploymentStatus||"").toLowerCase()==="pending"))return;const nt=window.setInterval(()=>{cn(!0)},7e3);return()=>window.clearInterval(nt)},[r,u,d,g,x]);const QO=async()=>{await cn()},JO=me=>{S(me),p(1)},kv=()=>{I(null),B(null),se(null),C(!0)},eL=me=>{n({to:`/sources/${me.id}`})},tL=me=>{I(me),N(!0)},nL=()=>{V||(N(!1),se(null),B(null))},rL=me=>{Y(r.find(nt=>nt.id===me)??null),ne(!0)},aL=async()=>{if(K){Ne(K.id);try{await Ie.deleteSource(K.id),ae.success("Source deleted"),ne(!1),Y(null),cn()}catch(me){ae.error(me?.response?.data?.error||"Failed to delete source")}finally{Ne(null)}}},sL=async(me,nt,yt)=>{Z(!0);try{if(H)await Ie.updateSource(H.id,{name:me,description:yt}),ae.success("Source updated"),N(!1),cn();else{const Wt=await Ie.createSource({name:me,type:nt,description:yt});if(nt==="prometheus"){const nr=await Ie.getSource(Wt.sourceId);N(!1),B(null),se(null),hv(nr.source),wp(null),mv(!0),cn(),ae.success("Prometheus source created")}else se(Wt.webhookUrl),cn()}}catch(Wt){ae.error(Wt?.response?.data?.error||"Failed to save source")}finally{Z(!1)}},iL=async me=>{st(me),Ze(!0);try{const nt=await Ie.getSourceTokenPolicy(me.id);st(yt=>yt&&{...yt,tokenPolicy:nt.tokenPolicy})}catch{}},oL=async(me,nt)=>{if(Ye){Et(!0);try{const yt=await Ie.updateSourceTokenPolicy(Ye.id,{mode:me,ttlDays:nt});a(Wt=>Wt.map(nr=>nr.id===Ye.id?{...nr,tokenPolicy:yt.tokenPolicy,webhookUrl:yt.webhookUrl||nr.webhookUrl}:nr)),ae.success("Token policy updated"),Ze(!1),st(null)}catch(yt){ae.error(yt?.response?.data?.error||"Failed to update token policy")}finally{Et(!1)}}},lL=async()=>{if(Re){le(!0);try{const me=await Ie.discoverCloudWatch(Re.id,{accessKeyId:he.accessKeyId,secretAccessKey:he.secretAccessKey,sessionToken:he.sessionToken||void 0,region:he.region});v(me),ae.success("Fetched CloudWatch metrics and alarms")}catch(me){ae.error(me?.response?.data?.error||"Failed to fetch CloudWatch metrics/alarms")}finally{le(!1)}}},cL=async()=>{if(Re){Ke(!0);try{const me=await Ie.deployCloudWatch(Re.id,{accessKeyId:he.accessKeyId,secretAccessKey:he.secretAccessKey,sessionToken:he.sessionToken||void 0,region:he.region,stackName:he.stackName,selectedAlarmNames:Ce,selectedMetricKeys:X,naming:{lambdaName:oe.lambdaName,alarmNamePrefix:oe.alarmNamePrefix},alarmDefaults:{threshold:Number(we.threshold||50),period:Number(we.period||60),evaluationPeriods:Number(we.evaluationPeriods||1),statistic:we.statistic,comparisonOperator:we.comparisonOperator,treatMissingData:we.treatMissingData}});fe(me),_(me.deployment.selectedAlarmNames||Ce),xe({lambdaName:me.deployment.lambdaName||oe.lambdaName,alarmNamePrefix:me.deployment.alarmNamePrefix||oe.alarmNamePrefix}),cn(),ae.success("AWS CloudWatch automation deployed")}catch(me){ae.error(me?.response?.data?.error||"Failed to deploy AWS automation")}finally{Ke(!1)}}},uL=async me=>{Ue(me),v(null),fe(null);try{const nt=await Ie.getCloudWatchSetup(me.id);de({accessKeyId:nt.setup.accessKeyId||"",secretAccessKey:nt.setup.secretAccessKey||"",sessionToken:nt.setup.sessionToken||"",region:nt.setup.region||"ap-south-1",stackName:nt.setup.stackName||`meyi-cloudwatch-${me.id.slice(0,8)}`}),xe({lambdaName:nt.setup.lambdaName||`meyi-cloudwatch-forwarder-${me.id.slice(0,8)}`,alarmNamePrefix:nt.setup.alarmNamePrefix||`meyi-${me.id.slice(0,8)}`}),_(Array.isArray(nt.setup.selectedAlarmNames)?nt.setup.selectedAlarmNames:[]),ge(Array.isArray(nt.setup.selectedMetricKeys)?nt.setup.selectedMetricKeys:[])}catch{_(Array.isArray(me.awsSelectedAlarmNames)?me.awsSelectedAlarmNames:[]),ge(Array.isArray(me.awsSelectedMetricKeys)?me.awsSelectedMetricKeys:[]),de({accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"ap-south-1",stackName:`meyi-cloudwatch-${me.id.slice(0,8)}`}),xe({lambdaName:me.awsLambdaName||`meyi-cloudwatch-forwarder-${me.id.slice(0,8)}`,alarmNamePrefix:me.awsAlarmNamePrefix||`meyi-${me.id.slice(0,8)}`})}be({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}),Se(!0)},dL=me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},pL=async()=>{if(Oe){pt(!0);try{const me=await Ie.getGrafanaOnboarding(Oe.id);Dt(me),BO(nt=>nt||me.defaults.contactPointName),UO(nt=>nt||me.defaults.matcherLabel),$O(nt=>nt||me.defaults.matcherValue)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Grafana setup")}finally{pt(!1)}}},fL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},Iv=async()=>{if(Os){gv(!0);try{const me=await Ie.getPrometheusOnboarding(Os.id);wp(me),Np(me.defaults.prometheusBaseUrl||""),Ap(me.defaults.alertmanagerBaseUrl||""),Ul(me.defaults.setupStatus?{status:me.defaults.setupStatus,reason:me.defaults.setupStatusReason||""}:null)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Prometheus setup")}finally{gv(!1)}}},mL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},hL=async()=>{if(Os){if(!Tp.trim()||!Cp.trim()){ae.error("Prometheus URL and Alertmanager URL are required");return}_p(!0),Ul(null);try{const me=await Ie.checkPrometheusStatus(Os.id,{prometheusBaseUrl:Tp.trim(),alertmanagerBaseUrl:Cp.trim(),timeoutSeconds:20});Ul({status:me.status,reason:me.reason}),me.status==="configured"?ae.success("Prometheus setup verified"):me.status==="not_yet"?ae.info("Prometheus changes are not visible yet"):ae.error(me.reason||"Prometheus setup verification failed"),cn()}catch(me){ae.error(me?.response?.data?.error||"Failed to check Prometheus setup")}finally{_p(!1)}}},Dv=async()=>{if(Ls){bv(!0);try{const me=await Ie.getDatadogOnboarding(Ls.id);xv(me),Sv(nt=>nt||me.defaults.site),Tv(nt=>nt||me.defaults.webhookName)}catch(me){ae.error(me?.response?.data?.error||"Failed to load Datadog setup")}finally{bv(!1)}}},gL=async me=>{window.sessionStorage.setItem(`insightSourceInitialTab:${me.id}`,"setup"),n({to:`/sources/${me.id}`})},bL=async()=>{if(Ls){yv(!0);try{const me=await Ie.setupDatadog(Ls.id,{site:vv||"datadoghq.com",datadogApiKey:Nv,datadogAppKey:Av,webhookName:wv||void 0});Ev(me),ae.success("Datadog source configured")}catch(me){ae.error(me?.response?.data?.error||"Datadog setup failed")}finally{yv(!1)}}};w.useEffect(()=>{!Me||!Oe||pL()},[Me,Oe]),w.useEffect(()=>{!Sp||!Os||Iv()},[Sp,Os]),w.useEffect(()=>{!Rp||!Ls||Dv()},[Rp,Ls]);const kp=r.filter(me=>{const nt=!x.status||KV(me)===x.status,yt=!x.region||VV(me)===x.region;return nt&&yt}),Ov=kp.length,xL=Math.max(1,Math.ceil(Ov/d)),yL=he.accessKeyId.trim().toUpperCase().startsWith("ASIA"),EL=!!(he.accessKeyId&&he.secretAccessKey&&(!yL||he.sessionToken));return e?s.jsx(lo,{to:"/alerts"}):s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Sources"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Monitoring sources connected to this workspace"})]}),s.jsxs(ie,{onClick:kv,disabled:l,children:[s.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Add source"]})]}),s.jsx(HV,{search:m,filters:x,loading:l,onSearchChange:me=>{h(me),p(1)},onFiltersChange:JO,onRefresh:QO}),s.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:l&&r.length===0?s.jsx(qr,{variant:"cards"}):kp.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center border rounded-md border-dashed h-64 bg-muted/20",children:[s.jsx("h3",{className:"text-lg font-medium mb-1",children:m||x.status||x.region?"No matching sources":"No sources yet"}),s.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mb-4",children:m||x.status||x.region?"Try a different search or filter.":"Add a webhook source to start receiving alerts from your monitoring tools."}),!m&&!x.status&&!x.region&&s.jsxs(ie,{onClick:kv,children:[s.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Add First Source"]})]}):s.jsx(XV,{sources:kp,deletingId:J,onView:eL,onEdit:tL,onDelete:rL,onManageTokenPolicy:iL,onAwsSetup:dL,onGrafanaSetup:fL,onPrometheusSetup:mL,onDatadogSetup:gL})}),s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(cI,{currentPage:u,pageSize:d,totalPages:xL,total:Ov||i,onPageChange:me=>p(me),onPageSizeChange:me=>{f(me),p(1)}})}),s.jsx(pV,{open:Q,onOpenChange:me=>{J||ne(me)},source:K,onConfirm:aL}),s.jsx(uV,{open:T,source:H,submitting:V,createdWebhookUrl:D,initialType:re,onClose:nL,onSubmit:sL,onWebhookModalClose:()=>{se(null),N(!1),B(null)}}),s.jsx(DV,{open:A,onOpenChange:C,onCreated:cn,onOpenCostSources:t}),s.jsx(OV,{open:k,source:G,onOpenChange:me=>{O(me),me||q(null)},onCreated:cn,onAccessKeyDeploy:me=>{O(!1),q(null),uL(me)}}),s.jsx(MV,{open:M,source:P,onOpenChange:me=>{R(me),me||(B(null),z(null))},onCreated:cn}),s.jsx(BV,{open:j,onOpenChange:me=>{U(me),me||B(null)},onCreated:cn}),s.jsx(fV,{open:Ee,source:Ye,submitting:lt,onOpenChange:me=>{Ze(me),me||st(null)},onSubmit:oL}),s.jsx(gV,{open:Bt,loadingDiscover:He,deploying:_e,discoveringReady:EL,credentials:he,naming:oe,alarmDefaults:we,selectedAlarmNames:Ce,selectedMetricKeys:X,discoverData:tt,deployData:ee,templateDownloadUrl:ee?.templateDownloadUrl||null,onChangeCredentials:me=>de(nt=>({...nt,...me})),onChangeNaming:me=>xe(nt=>({...nt,...me})),onChangeAlarmDefaults:me=>be(nt=>({...nt,...me})),onToggleAlarm:(me,nt)=>_(yt=>nt?Array.from(new Set([...yt,me])):yt.filter(Wt=>Wt!==me)),onToggleMetric:(me,nt)=>ge(yt=>nt?Array.from(new Set([...yt,me])):yt.filter(Wt=>Wt!==me)),onDiscover:lL,onDeploy:cL,onOpenChange:me=>{Se(me),me||(Ue(null),v(null),fe(null),_([]),ge([]),xe({lambdaName:"",alarmNamePrefix:""}),be({threshold:"50",period:"60",evaluationPeriods:"1",statistic:"Average",comparisonOperator:"GreaterThanOrEqualToThreshold",treatMissingData:"breaching"}))}}),s.jsx(CV,{open:pe,source:Ae,onOpenChange:me=>{te(me),me||$e(null)}}),s.jsx(xV,{open:Sp,data:zO,loading:HO,prometheusBaseUrl:Tp,alertmanagerBaseUrl:Cp,checkingStatus:GO,statusResult:VO,onPrometheusBaseUrlChange:Np,onAlertmanagerBaseUrlChange:Ap,onCheckStatus:hL,onRefresh:Iv,onOpenChange:me=>{mv(me),me||(hv(null),wp(null),Np(""),Ap(""),Ul(null),_p(!1))}}),s.jsx(EV,{open:Rp,data:KO,loading:YO,configuring:XO,result:ZO,site:vv,webhookName:wv,datadogApiKey:Nv,datadogAppKey:Av,onSiteChange:Sv,onWebhookNameChange:Tv,onDatadogApiKeyChange:Cv,onDatadogAppKeyChange:_v,onRefresh:Dv,onConfigure:bL,onOpenChange:me=>{WO(me),me||(qO(null),xv(null),Ev(null),Cv(""),_v(""))}})]})}const lw={cloudwatch:{label:"CloudWatch",mono:"CW",color:"#E67E22"},cloudtrail:{label:"Level 1 Security",mono:"L1",color:"#D35400"},grafana:{label:"Grafana",mono:"GF",color:"#C0392B"},prometheus:{label:"Prometheus",mono:"PR",color:"#8E44AD"},datadog:{label:"Datadog",mono:"DD",color:"#7048C4"},meyi_pulse:{label:"Meyi Pulse",mono:"MP",color:"#1A5276"},pagerduty:{label:"PagerDuty",mono:"PD",color:"#2E7D32"},custom:{label:"Custom",mono:"CU",color:"#5A6B7B"}};function ws(e){return String(e||"custom").toLowerCase().replace(/[\s-]+/g,"_")}function JV(e){return lw[ws(e.type)]||lw.custom}function pI(e){const t=ws(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsRegion||"us-east-1":t==="prometheus"?e.prometheusEnvironment||"production":"multi"}function fI(e){const t=ws(e.type);return t==="cloudwatch"?`aws ****4821 - ${e.awsStackName||"sns:prod-alarms"}`:t==="cloudtrail"?`aws ****4821 - ${e.awsStackName||"cloudtrail:security"}`:t==="grafana"?e.grafanaBaseUrl||e.webhookUrl:t==="prometheus"&&(e.alertmanagerBaseUrl||e.prometheusReceiverName)||e.webhookUrl}function Jg(e){const t=ws(e.type);return t==="cloudwatch"||t==="cloudtrail"?e.awsDeploymentStatus||"not_started":t==="grafana"?e.grafanaSetupStatus||"not_started":t==="prometheus"?e.prometheusSetupStatus||"not_started":t==="datadog"?e.deliveryStatus||"not_started":e.deliveryStatus||"unknown"}function cw(e){const t=ws(e.type),n=String(Jg(e)).toLowerCase();return t==="cloudwatch"||t==="cloudtrail"?n==="deployed":t==="grafana"||t==="prometheus"?n==="configured":t==="datadog"?n==="healthy"||n==="configured":!!(e.lastWebhookReceivedAt||e.lastSuccessfulWebhookAt)}function eW(e){if(!e)return"Never";const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"just now";const n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n} minute${n===1?"":"s"} ago`;const r=Math.floor(n/60);if(r<24)return`${r} hour${r===1?"":"s"} ago`;const a=Math.floor(r/24);return`${a} day${a===1?"":"s"} ago`}function tW(e){const t=String(e||"").toLowerCase();return t==="critical"?"im-sev-critical":t==="high"?"im-sev-high":t==="medium"?"im-sev-medium":"im-sev-low"}const uw=[{accessorKey:"createdAt",header:({column:e})=>s.jsx(dt,{column:e,title:"Created Date"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-xs whitespace-nowrap",children:new Date(e.original.createdAt).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})})},{accessorKey:"alertName",header:({column:e})=>s.jsx(dt,{column:e,title:"Alert name"}),cell:({row:e})=>s.jsx("div",{className:"max-w-[240px] truncate text-sm font-semibold",title:e.original.alertName,children:e.original.alertName})},{accessorKey:"severity",header:({column:e})=>s.jsx(dt,{column:e,title:"Severity"}),cell:({row:e})=>s.jsx("span",{className:`im-severity-pill ${tW(e.original.severity)}`,children:e.original.severity})},{accessorKey:"status",header:({column:e})=>s.jsx(dt,{column:e,title:"State"}),cell:({row:e})=>{const t=(e.original.status||"firing").toLowerCase(),n=["open","firing","active"].includes(t),r=t==="suppressed",a=t==="converted",i=t==="resolved"||t==="closed";let o="Firing",l="im-state-firing";return r?(o="Suppressed",l="im-state-suppressed"):a?(o="Converted",l="im-state-converted"):i?(o="Resolved",l="im-state-resolved"):n||(o=t.charAt(0).toUpperCase()+t.slice(1)),s.jsx("span",{className:l,children:o})}},{id:"resource",accessorFn:e=>e.resourceName||e.resourceId||"",header:({column:e})=>s.jsx(dt,{column:e,title:"Resource"}),cell:({row:e})=>{const t=`${e.original.resourceName||e.original.resourceId} · ${e.original.resourceType}`;return s.jsx("div",{className:"max-w-[200px] truncate font-mono text-sm",title:t,children:t})}},{accessorKey:"accountId",header:({column:e})=>s.jsx(dt,{column:e,title:"Account ID"}),cell:({row:e})=>{const t=e.original.accountId||e.original.additionalConfiguration?.accountId||"—";return s.jsx("div",{className:"max-w-[140px] truncate font-mono text-xs text-muted-foreground",title:t,children:t})}},{id:"tags",header:({column:e})=>s.jsx(dt,{column:e,title:"Tags"}),cell:({row:e})=>{const t=e.original,n=t.tags||t.additionalConfiguration?.tags||{},r=Object.entries(n);return r.length===0?s.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):s.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[220px]",children:[r.slice(0,3).map(([a,i])=>s.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[11px] bg-secondary text-secondary-foreground font-mono",children:[a,":",i]},a)),r.length>3&&s.jsxs("span",{className:"text-[10px] text-muted-foreground self-center",children:["+",r.length-3]})]})}},{id:"action",header:()=>s.jsx("span",{children:"Action"}),enableSorting:!1,cell:({row:e})=>s.jsx(Ei,{className:"im-link-button",to:`/alert/${e.original.id}`,children:"View"})}];function nW({alarms:e}){const[t,n]=w.useState([]),r=w.useMemo(()=>e,[e]),a=gl({data:r,columns:uw,state:{sorting:t},onSortingChange:n,getCoreRowModel:hl(),getSortedRowModel:Ad(),getPaginationRowModel:mk(),initialState:{pagination:{pageSize:10}}});return s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[s.jsx("div",{className:"im-table-card",children:s.jsxs(Oa,{children:[s.jsx(La,{children:a.getHeaderGroups().map(i=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:i.headers.map(o=>s.jsx(gn,{children:o.isPlaceholder?null:Rr(o.column.columnDef.header,o.getContext())},o.id))},i.id))}),s.jsx(ja,{children:a.getRowModel().rows?.length?a.getRowModel().rows.map(i=>s.jsx(Ft,{className:"group/row hover:bg-muted/30",children:i.getVisibleCells().map(o=>s.jsx(Pt,{children:Rr(o.column.columnDef.cell,o.getContext())},o.id))},i.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:uw.length,className:"h-24 text-center",children:"No alerts found for this source."})})})]})}),s.jsx(bl,{table:a,className:"mt-auto"})]})}function rW({source:e,saving:t,onSave:n}){const[r,a]=w.useState(e.name);w.useEffect(()=>a(e.name),[e.name]);const i=e.prometheusEnvironment||"production";return s.jsxs("section",{className:"im-panel im-config-panel",children:[s.jsx("h3",{children:"Configuration"}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Instance name"}),s.jsx(Xe,{value:r,onChange:o=>a(o.target.value)})]}),s.jsxs("div",{className:"im-form-grid-2",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Source type"}),s.jsx(Xe,{value:e.type,readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Region"}),s.jsx(Xe,{value:pI(e),readOnly:!0})]})]}),s.jsxs("div",{className:"im-form-grid-2",children:[s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Environment"}),s.jsx(Xe,{value:i,readOnly:!0})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Delivery status"}),s.jsx(Xe,{value:e.deliveryStatus||"unknown",readOnly:!0})]})]}),s.jsxs("div",{className:"im-form-row",children:[s.jsx(Pe,{children:"Endpoint / account"}),s.jsx(Xe,{value:fI(e),readOnly:!0})]}),s.jsxs("div",{className:"im-config-actions",children:[s.jsx(ie,{className:"im-primary-button",onClick:()=>n({name:r}),disabled:t,children:t?"Saving...":"Save changes"}),s.jsx(ie,{variant:"outline",onClick:()=>a(e.name),disabled:t,children:"Cancel"})]})]})}function aW({source:e,disabling:t,testing:n,onBack:r,onToggleActive:a,onTest:i}){const o=JV(e),l=e.name.toLowerCase().startsWith(o.label.toLowerCase())?e.name:`${o.label} - ${e.name}`,c=[fI(e),pI(e),"production"].filter(Boolean).join(" - ");let u="Active",p="im-status-soft";if(!e.isActive)u="Disabled";else{const d=String(Jg(e)).toLowerCase();d==="failed"||e.deliveryStatus==="failed"?(u="Failed",p="im-status-soft error"):d==="pending"||d==="not_yet"||d==="checking"?(u="Deploying",p="im-status-soft degraded"):d==="not_started"&&(u="Not Started",p="im-status-soft degraded")}return s.jsxs("div",{className:"im-source-detail-header",children:[s.jsxs("div",{className:"im-source-detail-title",children:[s.jsx(ie,{variant:"outline",size:"icon",className:"im-detail-back-button","aria-label":"Back to sources",onClick:r,children:s.jsx(Vr,{className:"h-4 w-4"})}),s.jsx("span",{className:"im-provider-badge im-detail-provider-badge",style:{backgroundColor:o.color},children:o.mono}),s.jsxs("div",{children:[s.jsxs("div",{className:"im-title-row",children:[s.jsx("h2",{children:l}),s.jsx("span",{className:p,children:u})]}),s.jsx("p",{children:c})]})]}),s.jsxs("div",{className:"im-source-detail-actions",children:[s.jsx(ie,{variant:"outline",onClick:a,disabled:t,children:e.isActive?"Disable":"Enable"}),s.jsx(ie,{variant:"outline",onClick:i,disabled:n,children:n?"Testing...":"Test connection"})]})]})}const If=[{id:"overview",label:"Overview"},{id:"alarms",label:"Alarms"},{id:"configuration",label:"Configuration"},{id:"normalization",label:"Normalization"},{id:"dedup",label:"Dedup"},{id:"grouping",label:"Grouping"},{id:"workflows",label:"Workflows"},{id:"logs",label:"Logs"},{id:"test",label:"Test"}];function sW({activeTab:e,showSetup:t,onChange:n}){const r=t?[...If.slice(0,3),{id:"setup",label:"Setup"},...If.slice(3)]:If;return s.jsx("div",{className:"im-detail-tabs",children:r.map(a=>s.jsx("button",{type:"button",className:e===a.id?"is-active":"",onClick:()=>n(a.id),children:a.label},a.id))})}const dw=[{accessorKey:"timestamp",header:({column:e})=>s.jsx(dt,{column:e,title:"Timestamp"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-sm",children:new Date(e.original.timestamp).toLocaleTimeString()})},{accessorKey:"httpStatus",header:({column:e})=>s.jsx(dt,{column:e,title:"HTTP"}),cell:({row:e})=>s.jsx("span",{className:e.original.httpStatus>=400?"im-danger-text font-mono":"im-success-text font-mono",children:e.original.httpStatus})},{accessorKey:"sourceIp",header:({column:e})=>s.jsx(dt,{column:e,title:"Source IP"}),cell:({row:e})=>s.jsx("span",{className:"font-mono text-sm",children:e.original.sourceIp})},{accessorKey:"payloadSize",header:({column:e})=>s.jsx(dt,{column:e,title:"Payload"}),cell:({row:e})=>s.jsxs("span",{className:"font-mono text-sm",children:[(e.original.payloadSize/1024).toFixed(1)," KB"]})},{accessorKey:"result",header:({column:e})=>s.jsx(dt,{column:e,title:"Result"}),cell:({row:e})=>s.jsx("span",{className:e.original.result==="normalised"?"im-result-good":"im-result-warn",children:e.original.result})}];function iW({logs:e,search:t,onSearchChange:n}){const[r,a]=w.useState([]),i=w.useMemo(()=>e,[e]),o=gl({data:i,columns:dw,state:{sorting:r},onSortingChange:a,getCoreRowModel:hl(),getSortedRowModel:Ad(),getPaginationRowModel:mk(),initialState:{pagination:{pageSize:10}}});return s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[s.jsxs("div",{className:"im-search-wrap",children:[s.jsx(gs,{className:"im-search-icon",size:14,"aria-hidden":"true"}),s.jsx(Xe,{value:t,onChange:l=>n(l.target.value),placeholder:"Search logs...",className:"im-search-input"})]}),s.jsx("div",{className:"im-table-card",children:s.jsxs(Oa,{children:[s.jsx(La,{children:o.getHeaderGroups().map(l=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:l.headers.map(c=>s.jsx(gn,{children:c.isPlaceholder?null:Rr(c.column.columnDef.header,c.getContext())},c.id))},l.id))}),s.jsx(ja,{children:o.getRowModel().rows?.length?o.getRowModel().rows.map(l=>s.jsx(Ft,{className:"group/row hover:bg-muted/30",children:l.getVisibleCells().map(c=>s.jsx(Pt,{children:Rr(c.column.columnDef.cell,c.getContext())},c.id))},l.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:dw.length,className:"h-24 text-center",children:"No logs found."})})})]})}),s.jsx(bl,{table:o,className:"mt-auto"})]})}function oW({overview:e}){const t=Math.max(1,...e.summary.weeklyRate.map(i=>i.count)),n=e.summary.weeklyRate.some(i=>i.count>0);let r="Active";if(!e.source.isActive)r="Disabled";else{const i=String(Jg(e.source)).toLowerCase();i==="failed"||e.source.deliveryStatus==="failed"?r="Failed":i==="pending"||i==="not_yet"||i==="checking"?r="Deploying":i==="not_started"&&(r="Not Started")}async function a(){try{await navigator.clipboard.writeText(e.summary.webhookEndpoint),ae.success("Webhook URL copied")}catch{ae.error("Failed to copy webhook URL")}}return s.jsxs("div",{className:"im-source-overview-grid",children:[s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Status"}),s.jsx("strong",{className:"im-inline-status",children:r})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Last alert"}),s.jsx("strong",{children:eW(e.summary.lastAlarmAt)})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Alerts today"}),s.jsx("strong",{children:e.summary.alarmsToday})]}),s.jsxs("div",{className:"im-stat",children:[s.jsx("span",{children:"Errors (1h)"}),s.jsx("strong",{className:"im-danger-text",children:e.summary.errorsLastHour})]}),s.jsxs("section",{className:"im-panel im-rate-panel",children:[s.jsx("h3",{children:"7-day alert rate"}),n?s.jsx("div",{className:"im-bar-chart",children:e.summary.weeklyRate.map(i=>s.jsxs("div",{className:"im-bar-item",children:[s.jsx("span",{style:{height:`${Math.max(36,i.count/t*124)}px`}}),s.jsx("em",{children:i.day})]},i.day))}):s.jsx("div",{className:"im-rate-empty",children:"No alerts received in the last 7 days."})]}),s.jsxs("section",{className:"im-panel im-webhook-panel",children:[s.jsx("h3",{children:"Webhook endpoint"}),s.jsxs("div",{className:"im-webhook-copy-row",children:[s.jsx("code",{children:e.summary.webhookEndpoint}),s.jsx("button",{type:"button","aria-label":"Copy webhook URL",onClick:a,children:s.jsx(yn,{size:16})})]}),e.summary.authTokenPreview&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem",fontSize:"0.85rem",color:"var(--im-text-muted)"},children:"Auth Token (Bearer)"}),s.jsxs("div",{className:"im-webhook-copy-row",children:[s.jsx("code",{children:e.summary.authTokenPreview}),s.jsx("button",{type:"button","aria-label":"Copy auth token",onClick:()=>{navigator.clipboard.writeText(e.summary.authTokenPreview),ae.success("Auth token copied")},children:s.jsx(yn,{size:16})})]})]})]})]})}function lW({source:e,loading:t,cloudWatch:n,cloudTrail:r,grafana:a,prometheus:i,datadog:o}){return s.jsx("div",{className:"im-source-setup-tab",children:s.jsx(lI,{type:ws(e.type),webhookUrl:e.webhookUrl,loading:t,cloudWatch:n,cloudTrail:r,grafana:a,prometheus:i,datadog:o})})}const cW=`{
111
111
  "AlarmName": "prod-cpu-high-i-0abc",
112
112
  "NewStateValue": "ALARM",
113
113
  "NewStateReason": "Threshold crossed: 1 datapoint [92.4]",
@@ -118,13 +118,13 @@ Webhook URL: ${N.webhook.url}`),ae.success("Contact point details copied")),wind
118
118
  "Dimensions": [{"name":"InstanceId","value":"i-0abc12"}],
119
119
  "Threshold": 80
120
120
  }
121
- }`;function uW({result:e,running:t,onRun:n}){return s.jsxs("div",{className:"im-test-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx("h3",{children:"Sample payload"}),s.jsx("pre",{className:"im-code-panel",children:cW}),s.jsxs("div",{className:"im-test-actions",children:[s.jsx(ie,{className:"im-primary-button",onClick:n,disabled:t,children:t?"Running...":"Run test"}),s.jsx("span",{children:"Validates parsing only. No alarm is created."})]})]}),s.jsxs("section",{className:"im-panel im-normalised-panel",children:[s.jsx("h3",{children:"Normalised envelope"}),e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-test-result-summary",children:[s.jsx("span",{children:e.accepted?"Accepted":"Rejected"}),s.jsx("span",{children:e.createsAlarm?"Creates alarm":"No alarm created"})]}),s.jsx("pre",{className:"im-code-panel",children:JSON.stringify(e.envelope,null,2)})]}):s.jsx("div",{className:"im-empty-envelope",children:"Run a test to see the normalised envelope."})]})]})}function dW(e,t=[]){let n=[];function r(i,o){const l=y.createContext(o);l.displayName=i+"Context";const c=n.length;n=[...n,o];const u=d=>{const{scope:f,children:m,...h}=d,g=f?.[e]?.[c]||l,b=y.useMemo(()=>h,Object.values(h));return s.jsx(g.Provider,{value:b,children:m})};u.displayName=i+"Provider";function p(d,f){const m=f?.[e]?.[c]||l,h=y.useContext(m);if(h)return h;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,p]}const a=()=>{const i=n.map(o=>y.createContext(o));return function(l){const c=l?.[e]||i;return y.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return a.scopeName=e,[r,pW(a,...t)]}function pW(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((l,{useScope:c,scopeName:u})=>{const d=c(i)[`__scope${u}`];return{...l,...d}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}function pw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fW(...e){return t=>{let n=!1;const r=e.map(a=>{const i=pw(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():pw(e[a],null)}}}}function mI(...e){return y.useCallback(fW(...e),e)}function mW(e,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(e?.(a),n===!1||!a.defaultPrevented)return t?.(a)}}var hW=Symbol.for("radix.slottable");function gW(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=hW,t}var hI="AlertDialog",[bW]=dW(hI,[HA]),ta=HA(),gI=e=>{const{__scopeAlertDialog:t,...n}=e,r=ta(t);return s.jsx(rg,{...r,...n,modal:!0})};gI.displayName=hI;var xW="AlertDialogTrigger",yW=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(u8,{...a,...r,ref:t})});yW.displayName=xW;var EW="AlertDialogPortal",bI=e=>{const{__scopeAlertDialog:t,...n}=e,r=ta(t);return s.jsx(ag,{...r,...n})};bI.displayName=EW;var vW="AlertDialogOverlay",xI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(ld,{...a,...r,ref:t})});xI.displayName=vW;var ri="AlertDialogContent",[SW,wW]=bW(ri),TW=gW("AlertDialogContent"),yI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...a}=e,i=ta(n),o=y.useRef(null),l=mI(t,o),c=y.useRef(null);return s.jsx(i8,{contentName:ri,titleName:EI,docsSlug:"alert-dialog",children:s.jsx(SW,{scope:n,cancelRef:c,children:s.jsxs(cd,{role:"alertdialog",...i,...a,ref:l,onOpenAutoFocus:mW(a.onOpenAutoFocus,u=>{u.preventDefault(),c.current?.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[s.jsx(TW,{children:r}),s.jsx(CW,{contentRef:o})]})})})});yI.displayName=ri;var EI="AlertDialogTitle",vI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(sg,{...a,...r,ref:t})});vI.displayName=EI;var SI="AlertDialogDescription",wI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(ig,{...a,...r,ref:t})});wI.displayName=SI;var NW="AlertDialogAction",TI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(og,{...a,...r,ref:t})});TI.displayName=NW;var NI="AlertDialogCancel",CI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:a}=wW(NI,n),i=ta(n),o=mI(t,a);return s.jsx(og,{...i,...r,ref:o})});CI.displayName=NI;var CW=({contentRef:e})=>{const t=`\`${ri}\` requires a description for the component to be accessible for screen reader users.
121
+ }`;function uW({result:e,running:t,onRun:n}){return s.jsxs("div",{className:"im-test-grid",children:[s.jsxs("section",{className:"im-panel",children:[s.jsx("h3",{children:"Sample payload"}),s.jsx("pre",{className:"im-code-panel",children:cW}),s.jsxs("div",{className:"im-test-actions",children:[s.jsx(ie,{className:"im-primary-button",onClick:n,disabled:t,children:t?"Running...":"Run test"}),s.jsx("span",{children:"Validates parsing only. No alert is created."})]})]}),s.jsxs("section",{className:"im-panel im-normalised-panel",children:[s.jsx("h3",{children:"Normalised envelope"}),e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-test-result-summary",children:[s.jsx("span",{children:e.accepted?"Accepted":"Rejected"}),s.jsx("span",{children:e.createsAlarm?"Creates alert":"No alert created"})]}),s.jsx("pre",{className:"im-code-panel",children:JSON.stringify(e.envelope,null,2)})]}):s.jsx("div",{className:"im-empty-envelope",children:"Run a test to see the normalised envelope."})]})]})}function dW(e,t=[]){let n=[];function r(i,o){const l=y.createContext(o);l.displayName=i+"Context";const c=n.length;n=[...n,o];const u=d=>{const{scope:f,children:m,...h}=d,g=f?.[e]?.[c]||l,b=y.useMemo(()=>h,Object.values(h));return s.jsx(g.Provider,{value:b,children:m})};u.displayName=i+"Provider";function p(d,f){const m=f?.[e]?.[c]||l,h=y.useContext(m);if(h)return h;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,p]}const a=()=>{const i=n.map(o=>y.createContext(o));return function(l){const c=l?.[e]||i;return y.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return a.scopeName=e,[r,pW(a,...t)]}function pW(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((l,{useScope:c,scopeName:u})=>{const d=c(i)[`__scope${u}`];return{...l,...d}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}function pw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fW(...e){return t=>{let n=!1;const r=e.map(a=>{const i=pw(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():pw(e[a],null)}}}}function mI(...e){return y.useCallback(fW(...e),e)}function mW(e,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(e?.(a),n===!1||!a.defaultPrevented)return t?.(a)}}var hW=Symbol.for("radix.slottable");function gW(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=hW,t}var hI="AlertDialog",[bW]=dW(hI,[HA]),ta=HA(),gI=e=>{const{__scopeAlertDialog:t,...n}=e,r=ta(t);return s.jsx(rg,{...r,...n,modal:!0})};gI.displayName=hI;var xW="AlertDialogTrigger",yW=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(u8,{...a,...r,ref:t})});yW.displayName=xW;var EW="AlertDialogPortal",bI=e=>{const{__scopeAlertDialog:t,...n}=e,r=ta(t);return s.jsx(ag,{...r,...n})};bI.displayName=EW;var vW="AlertDialogOverlay",xI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(ld,{...a,...r,ref:t})});xI.displayName=vW;var ri="AlertDialogContent",[SW,wW]=bW(ri),TW=gW("AlertDialogContent"),yI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...a}=e,i=ta(n),o=y.useRef(null),l=mI(t,o),c=y.useRef(null);return s.jsx(i8,{contentName:ri,titleName:EI,docsSlug:"alert-dialog",children:s.jsx(SW,{scope:n,cancelRef:c,children:s.jsxs(cd,{role:"alertdialog",...i,...a,ref:l,onOpenAutoFocus:mW(a.onOpenAutoFocus,u=>{u.preventDefault(),c.current?.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[s.jsx(TW,{children:r}),s.jsx(CW,{contentRef:o})]})})})});yI.displayName=ri;var EI="AlertDialogTitle",vI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(sg,{...a,...r,ref:t})});vI.displayName=EI;var SI="AlertDialogDescription",wI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(ig,{...a,...r,ref:t})});wI.displayName=SI;var NW="AlertDialogAction",TI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,a=ta(n);return s.jsx(og,{...a,...r,ref:t})});TI.displayName=NW;var NI="AlertDialogCancel",CI=y.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:a}=wW(NI,n),i=ta(n),o=mI(t,a);return s.jsx(og,{...i,...r,ref:o})});CI.displayName=NI;var CW=({contentRef:e})=>{const t=`\`${ri}\` requires a description for the component to be accessible for screen reader users.
122
122
 
123
123
  You can add a description to the \`${ri}\` by passing a \`${SI}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
124
124
 
125
125
  Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${ri}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
126
126
 
127
- For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return y.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},AW=gI,_W=bI,RW=xI,kW=yI,IW=TI,DW=CI,OW=vI,LW=wI;function Od({...e}){return s.jsx(AW,{"data-slot":"alert-dialog",...e})}function jW({...e}){return s.jsx(_W,{"data-slot":"alert-dialog-portal",...e})}function MW({className:e,...t}){return s.jsx(RW,{"data-slot":"alert-dialog-overlay",className:Fe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Ld({className:e,...t}){return s.jsxs(jW,{children:[s.jsx(MW,{}),s.jsx(kW,{"data-slot":"alert-dialog-content",className:Fe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function jd({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-header",className:Fe("flex flex-col gap-2 text-center sm:text-start",e),...t})}function Md({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-footer",className:Fe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Pd({className:e,...t}){return s.jsx(OW,{"data-slot":"alert-dialog-title",className:Fe("text-lg font-semibold",e),...t})}function Fd({className:e,...t}){return s.jsx(LW,{"data-slot":"alert-dialog-description",className:Fe("text-muted-foreground text-sm",e),...t})}function Bd({className:e,...t}){return s.jsx(IW,{className:Fe(Kh(),e),...t})}function Ud({className:e,...t}){return s.jsx(DW,{className:Fe(Kh({variant:"outline"}),e),...t})}function PW({sourceId:e}={}){const{isReadOnly:t}=ur(),[n,r]=w.useState([]),[a,i]=w.useState(!0),[o,l]=w.useState(null),c=St(),u=async()=>{try{const d=await Ie.listNormalizationConfigs(e);d.ok&&r(d.configs)}catch(d){ae.error(d.message)}finally{i(!1)}};w.useEffect(()=>{u()},[e]);const p=async()=>{if(o)try{await Ie.deleteNormalizationConfig(o),ae.success("Rule deleted"),l(null),await u()}catch(d){ae.error(d.message)}};return s.jsxs("div",{className:"h-full flex flex-col gap-6 p-6 overflow-y-auto",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(PC,{className:"w-5 h-5 text-primary"}),s.jsx("h1",{className:"text-xl font-bold",children:"Normalization Rules"})]}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Map incoming webhook payloads to canonical alarm fields using YAML + Handlebars templates."})]}),!t&&s.jsxs(ie,{onClick:()=>c({to:`/pipeline/normalization/new${e?`?sourceId=${e}`:""}`}),children:[s.jsx(Wr,{className:"w-4 h-4 mr-2"})," Add Rule"]})]}),a?s.jsx("div",{className:"flex justify-center p-8 text-muted-foreground",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):n.length===0?s.jsxs("div",{className:"p-8 text-center text-muted-foreground border border-dashed rounded-lg bg-muted/10",children:[s.jsx("p",{className:"mb-4",children:"No normalization rules yet — the built-in normalizer is active."}),!t&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>c({to:`/pipeline/normalization/new${e?`?sourceId=${e}`:""}`}),children:"Add your first rule"})]}):s.jsx("div",{className:"rounded-md border",children:s.jsxs(Oa,{children:[s.jsx(La,{children:s.jsxs(Ft,{children:[s.jsx(gn,{className:"w-[80px]",children:"Priority"}),s.jsx(gn,{children:"Name"}),s.jsx(gn,{children:"Scope"}),s.jsx(gn,{className:"w-[100px]",children:"Status"}),!t&&s.jsx(gn,{className:"w-[100px] text-right",children:"Actions"})]})}),s.jsx(ja,{children:n.map((d,f)=>s.jsxs(Ft,{className:d.isActive?"":"opacity-50",children:[s.jsx(Pt,{className:"font-mono text-muted-foreground",children:d.priority}),s.jsx(Pt,{className:"font-medium max-w-[220px] truncate",title:d.name,children:d.name}),s.jsx(Pt,{className:"text-muted-foreground text-xs max-w-[180px] truncate",title:d.sourceId?`source: ${d.sourceId}`:d.sourceType?d.sourceType:"global",children:d.sourceId?`source: ${d.sourceId}`:d.sourceType?d.sourceType:"global"}),s.jsx(Pt,{children:s.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full border font-medium ${d.isActive?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":"bg-muted/50 text-muted-foreground border-border"}`,children:d.isActive?"active":"inactive"})}),!t&&s.jsx(Pt,{className:"text-right",children:s.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[s.jsx(ie,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>c({to:`/pipeline/normalization/${d.id}/edit${e?`?sourceId=${e}`:""}`}),children:s.jsx(Zu,{className:"w-4 h-4"})}),s.jsx(ie,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-red-500",onClick:()=>l(d.id),children:s.jsx(ll,{className:"w-4 h-4"})})]})})]},d.id))})]})}),s.jsx(Od,{open:!!o,onOpenChange:d=>{d||l(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete normalization rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms matched by this rule will fall through to the next rule."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:p,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function FW(e){return e.sourceId?`Source ${e.sourceId.slice(0,8)}`:e.sourceType?`Any ${e.sourceType} alarm`:"Any unmatched alarm"}function BW({embedded:e=!1,basePath:t="/pipeline/dedup",sourceId:n}={}){const{isReadOnly:r}=ur(),[a,i]=w.useState([]),[o,l]=w.useState(!0),[c,u]=w.useState(null),p=St(),d=async()=>{try{l(!0);const b=await Ie.listDedupConfigs(n);b.ok&&i(b.configs)}catch(b){ae.error(b.message||"Failed to load dedup rules")}finally{l(!1)}};w.useEffect(()=>{d()},[n]);const f=async b=>{const x=!b.isActive;i(S=>S.map(T=>T.id===b.id?{...T,isActive:x}:T));try{await Ie.updateDedupConfig(b.id,{isActive:x}),ae.success(x?"Rule enabled":"Rule disabled")}catch(S){i(T=>T.map(N=>N.id===b.id?{...N,isActive:b.isActive}:N)),ae.error(S.message||"Failed to update rule")}},m=async()=>{if(c)try{await Ie.deleteDedupConfig(c),ae.success("Deleted"),u(null),await d()}catch(b){ae.error(b.message||"Failed to delete dedup rule")}},h=a.filter(b=>b.isActive).length,g=a.filter(b=>b.flapThreshold>0).length;return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Dedup rules"}),s.jsx("p",{children:"How repeated alarms are suppressed before grouping"})]}),!r&&s.jsxs(ie,{onClick:()=>p({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"w-4 h-4"})," New rule"]})]}),!o&&a.length>0&&s.jsxs("div",{className:"im-pipeline-stats-row",children:[s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",children:s.jsx(il,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:a.length}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Total rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-success)"},children:s.jsx(o4,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:h}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Active rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-warning, #b7860b)"},children:s.jsx(Ta,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:g}),s.jsx("div",{className:"im-pipeline-stat-label",children:"With flap detection"})]})]})]}),o?s.jsx("div",{className:"im-loading-panel",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):a.length===0?s.jsxs("div",{className:"im-empty-panel",children:[s.jsx("p",{children:"No dedup rules yet. Alarms pass through using the default fingerprint."}),!r&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>p({to:`${t}/new`}),children:"Add your first rule"})]}):s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-pipeline-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Priority"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Matches"}),s.jsx("th",{children:"Dedup key"}),s.jsx("th",{children:"Window"}),s.jsx("th",{children:"Flap"}),s.jsx("th",{children:"Active"}),!r&&s.jsx("th",{})]})}),s.jsx("tbody",{children:a.map(b=>s.jsxs("tr",{className:b.isActive?"":"is-muted",children:[s.jsxs("td",{children:[s.jsx("span",{className:"im-drag-handle",children:"::"}),s.jsx("strong",{children:b.priority})]}),s.jsx("td",{className:"im-workflow-name",children:b.name}),s.jsx("td",{children:FW(b)}),s.jsx("td",{children:(b.keyFields??[]).map(x=>s.jsx("span",{className:"im-tag",children:x},x))}),s.jsxs("td",{children:[Math.round(b.windowSeconds/60),"m"]}),s.jsxs("td",{children:[b.flapThreshold,"x / ",Math.round(b.flapWindowSeconds/60),"m - ",b.onFlap]}),s.jsx("td",{children:s.jsx("button",{type:"button",className:`im-toggle ${b.isActive?"is-on":""}`,"aria-label":"Dedup rule status",disabled:r,onClick:()=>!r&&f(b)})}),!r&&s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button","aria-label":"Dedup rule actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",children:[s.jsx(Lt,{onClick:()=>p({to:`${t}/${b.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>u(b.id),0),children:"Delete"})]})]})})]},b.id))})]})}),s.jsx(Od,{open:!!c,onOpenChange:b=>{b||u(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete dedup rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms that matched this rule will use the default fingerprint."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:m,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function UW(e){return e.sourceId?`Source ${e.sourceId.slice(0,8)}`:e.sourceType?`Any ${e.sourceType} alarm`:"Any unmatched alarm"}function $W({embedded:e=!1,basePath:t="/pipeline/grouping",sourceId:n}={}){const{isReadOnly:r}=ur(),[a,i]=w.useState([]),[o,l]=w.useState(!0),[c,u]=w.useState(null),p=St(),d=async()=>{try{l(!0);const b=await Ie.listGroupingConfigs(n);b.ok&&i(b.configs)}catch(b){ae.error(b.message||"Failed to load grouping rules")}finally{l(!1)}};w.useEffect(()=>{d()},[n]);const f=async b=>{const x=!b.isActive;i(S=>S.map(T=>T.id===b.id?{...T,isActive:x}:T));try{await Ie.updateGroupingConfig(b.id,{isActive:x}),ae.success(x?"Rule enabled":"Rule disabled")}catch(S){i(T=>T.map(N=>N.id===b.id?{...N,isActive:b.isActive}:N)),ae.error(S.message||"Failed to update rule")}},m=async()=>{if(c)try{await Ie.deleteGroupingConfig(c),ae.success("Deleted"),u(null),await d()}catch(b){ae.error(b.message||"Failed to delete grouping rule")}},h=a.filter(b=>b.isActive).length,g=a.filter(b=>b.incidentTitleTemplate).length;return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Grouping rules"}),s.jsx("p",{children:"How unmatched alarms are combined into incidents"})]}),!r&&s.jsxs(ie,{onClick:()=>p({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"w-4 h-4"})," New rule"]})]}),!o&&a.length>0&&s.jsxs("div",{className:"im-pipeline-stats-row",children:[s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",children:s.jsx(zh,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:a.length}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Total rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-success)"},children:s.jsx(Ta,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:h}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Active rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-primary)"},children:s.jsx(di,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:g}),s.jsx("div",{className:"im-pipeline-stat-label",children:"With title template"})]})]})]}),o?s.jsx("div",{className:"im-loading-panel",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):a.length===0?s.jsxs("div",{className:"im-empty-panel",children:[s.jsx("p",{children:"No grouping rules yet. Alarms are routed individually using defaults."}),!r&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>p({to:`${t}/new`}),children:"Add your first rule"})]}):s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-pipeline-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Priority"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Matches"}),s.jsx("th",{children:"Group by"}),s.jsx("th",{children:"Title template"}),s.jsx("th",{children:"Window"}),s.jsx("th",{children:"Active"}),!r&&s.jsx("th",{})]})}),s.jsx("tbody",{children:a.map(b=>s.jsxs("tr",{className:b.isActive?"":"is-muted",children:[s.jsxs("td",{children:[s.jsx("span",{className:"im-drag-handle",children:"::"}),s.jsx("strong",{children:b.priority})]}),s.jsx("td",{className:"im-workflow-name",children:b.name}),s.jsx("td",{children:UW(b)}),s.jsx("td",{children:(b.groupBy??[]).map(x=>s.jsx("span",{className:"im-tag",children:x},x))}),s.jsx("td",{className:"im-grouping-template-cell",children:b.incidentTitleTemplate?s.jsx("code",{className:"im-template-preview",children:b.incidentTitleTemplate}):s.jsx("span",{style:{color:"var(--im-fg-subtle)"},children:"—"})}),s.jsxs("td",{children:[Math.round(b.timeoutSeconds/60),"m / ",b.maxAlarms," max"]}),s.jsx("td",{children:s.jsx("button",{type:"button",className:`im-toggle ${b.isActive?"is-on":""}`,"aria-label":"Grouping rule status",disabled:r,onClick:()=>!r&&f(b)})}),!r&&s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button","aria-label":"Grouping rule actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",children:[s.jsx(Lt,{onClick:()=>p({to:`${t}/${b.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>u(b.id),0),children:"Delete"})]})]})})]},b.id))})]})}),s.jsx(Od,{open:!!c,onOpenChange:b=>{b||u(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete grouping rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms matched by this rule will fall through to the next rule."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:m,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const $r={async listWorkflows(e){return(await Te.get("/workflows",{params:{sourceId:e}})).data.workflows},async parseYaml(e){return(await Te.post("/workflows/parse-yaml",{yaml:e})).data},async getWorkflow(e){return(await Te.get(`/workflows/${e}`)).data.workflow},async createWorkflow(e){return(await Te.post("/workflows",e)).data.workflow},async updateWorkflow(e,t){return(await Te.put(`/workflows/${e}`,t)).data.workflow},async deleteWorkflow(e){await Te.delete(`/workflows/${e}`)},async toggleActive(e,t){return(await Te.patch(`/workflows/${e}/toggle`,{isActive:t})).data.workflow},async reorderWorkflows(e){await Te.put("/workflows/reorder",{orderedIds:e})},async getExecutions(e){return(await Te.get(`/workflows/${e}/executions`)).data.executions},async getRecentExecutions(e=50){return(await Te.get("/workflows/executions/recent",{params:{limit:e}})).data.executions}},AI=6048e5,HW=864e5,yc=43200,fw=1440,mw=Symbol.for("constructDateFrom");function Xr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&mw in e?e[mw](t):e instanceof Date?new e.constructor(t):new Date(t)}function en(e,t){return Xr(t||e,e)}let zW={};function El(){return zW}function Wo(e,t){const n=El(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,a=en(e,t?.in),i=a.getDay(),o=(i<r?7:0)+i-r;return a.setDate(a.getDate()-o),a.setHours(0,0,0,0),a}function Su(e,t){return Wo(e,{...t,weekStartsOn:1})}function _I(e,t){const n=en(e,t?.in),r=n.getFullYear(),a=Xr(n,0);a.setFullYear(r+1,0,4),a.setHours(0,0,0,0);const i=Su(a),o=Xr(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);const l=Su(o);return n.getTime()>=i.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function wu(e){const t=en(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function $d(e,...t){const n=Xr.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function hw(e,t){const n=en(e,t?.in);return n.setHours(0,0,0,0),n}function GW(e,t,n){const[r,a]=$d(n?.in,e,t),i=hw(r),o=hw(a),l=+i-wu(i),c=+o-wu(o);return Math.round((l-c)/HW)}function VW(e,t){const n=_I(e,t),r=Xr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Su(r)}function qc(e,t){const n=+en(e)-+en(t);return n<0?-1:n>0?1:n}function WW(e){return Xr(e,Date.now())}function qW(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function YW(e){return!(!qW(e)&&typeof e!="number"||isNaN(+en(e)))}function KW(e,t,n){const[r,a]=$d(n?.in,e,t),i=r.getFullYear()-a.getFullYear(),o=r.getMonth()-a.getMonth();return i*12+o}function XW(e){return t=>{const r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function ZW(e,t){return+en(e)-+en(t)}function QW(e,t){const n=en(e,t?.in);return n.setHours(23,59,59,999),n}function JW(e,t){const n=en(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function eq(e,t){const n=en(e,t?.in);return+QW(n,t)==+JW(n,t)}function tq(e,t,n){const[r,a,i]=$d(n?.in,e,e,t),o=qc(a,i),l=Math.abs(KW(a,i));if(l<1)return 0;a.getMonth()===1&&a.getDate()>27&&a.setDate(30),a.setMonth(a.getMonth()-o*l);let c=qc(a,i)===-o;eq(r)&&l===1&&qc(r,i)===1&&(c=!1);const u=o*(l-+c);return u===0?0:u}function nq(e,t,n){const r=ZW(e,t)/1e3;return XW(n?.roundingMethod)(r)}function rq(e,t){const n=en(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const aq={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},sq=(e,t,n)=>{let r;const a=aq[e];return typeof a=="string"?r=a:t===1?r=a.one:r=a.other.replace("{{count}}",t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Df(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const iq={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},oq={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},lq={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},cq={date:Df({formats:iq,defaultWidth:"full"}),time:Df({formats:oq,defaultWidth:"full"}),dateTime:Df({formats:lq,defaultWidth:"full"})},uq={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},dq=(e,t,n,r)=>uq[e];function Qi(e){return(t,n)=>{const r=n?.context?String(n.context):"standalone";let a;if(r==="formatting"&&e.formattingValues){const o=e.defaultFormattingWidth||e.defaultWidth,l=n?.width?String(n.width):o;a=e.formattingValues[l]||e.formattingValues[o]}else{const o=e.defaultWidth,l=n?.width?String(n.width):e.defaultWidth;a=e.values[l]||e.values[o]}const i=e.argumentCallback?e.argumentCallback(t):t;return a[i]}}const pq={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},fq={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},mq={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},hq={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},gq={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},bq={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},xq=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},yq={ordinalNumber:xq,era:Qi({values:pq,defaultWidth:"wide"}),quarter:Qi({values:fq,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Qi({values:mq,defaultWidth:"wide"}),day:Qi({values:hq,defaultWidth:"wide"}),dayPeriod:Qi({values:gq,defaultWidth:"wide",formattingValues:bq,defaultFormattingWidth:"wide"})};function Ji(e){return(t,n={})=>{const r=n.width,a=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(a);if(!i)return null;const o=i[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?vq(l,d=>d.test(o)):Eq(l,d=>d.test(o));let u;u=e.valueCallback?e.valueCallback(c):c,u=n.valueCallback?n.valueCallback(u):u;const p=t.slice(o.length);return{value:u,rest:p}}}function Eq(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function vq(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Sq(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const a=r[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;const l=t.slice(a.length);return{value:o,rest:l}}}const wq=/^(\d+)(th|st|nd|rd)?/i,Tq=/\d+/i,Nq={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Cq={any:[/^b/i,/^(a|c)/i]},Aq={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},_q={any:[/1/i,/2/i,/3/i,/4/i]},Rq={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},kq={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Iq={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Dq={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Oq={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Lq={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},jq={ordinalNumber:Sq({matchPattern:wq,parsePattern:Tq,valueCallback:e=>parseInt(e,10)}),era:Ji({matchPatterns:Nq,defaultMatchWidth:"wide",parsePatterns:Cq,defaultParseWidth:"any"}),quarter:Ji({matchPatterns:Aq,defaultMatchWidth:"wide",parsePatterns:_q,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ji({matchPatterns:Rq,defaultMatchWidth:"wide",parsePatterns:kq,defaultParseWidth:"any"}),day:Ji({matchPatterns:Iq,defaultMatchWidth:"wide",parsePatterns:Dq,defaultParseWidth:"any"}),dayPeriod:Ji({matchPatterns:Oq,defaultMatchWidth:"any",parsePatterns:Lq,defaultParseWidth:"any"})},RI={code:"en-US",formatDistance:sq,formatLong:cq,formatRelative:dq,localize:yq,match:jq,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Mq(e,t){const n=en(e,t?.in);return GW(n,rq(n))+1}function Pq(e,t){const n=en(e,t?.in),r=+Su(n)-+VW(n);return Math.round(r/AI)+1}function kI(e,t){const n=en(e,t?.in),r=n.getFullYear(),a=El(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,o=Xr(t?.in||e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=Wo(o,t),c=Xr(t?.in||e,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const u=Wo(c,t);return+n>=+l?r+1:+n>=+u?r:r-1}function Fq(e,t){const n=El(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=kI(e,t),i=Xr(t?.in||e,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Wo(i,t)}function Bq(e,t){const n=en(e,t?.in),r=+Wo(n,t)-+Fq(n,t);return Math.round(r/AI)+1}function vt(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const sa={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return vt(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):vt(n+1,2)},d(e,t){return vt(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h(e,t){return vt(e.getHours()%12||12,t.length)},H(e,t){return vt(e.getHours(),t.length)},m(e,t){return vt(e.getMinutes(),t.length)},s(e,t){return vt(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return vt(a,t.length)}},$s={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},gw={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return sa.y(e,t)},Y:function(e,t,n,r){const a=kI(e,r),i=a>0?a:1-a;if(t==="YY"){const o=i%100;return vt(o,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):vt(i,t.length)},R:function(e,t){const n=_I(e);return vt(n,t.length)},u:function(e,t){const n=e.getFullYear();return vt(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return vt(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return vt(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return sa.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return vt(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const a=Bq(e,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):vt(a,t.length)},I:function(e,t,n){const r=Pq(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):vt(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):sa.d(e,t)},D:function(e,t,n){const r=Mq(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):vt(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const a=e.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return vt(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const a=e.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return vt(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),a=r===0?7:r;switch(t){case"i":return String(a);case"ii":return vt(a,t.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const a=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let a;switch(r===12?a=$s.noon:r===0?a=$s.midnight:a=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let a;switch(r>=17?a=$s.evening:r>=12?a=$s.afternoon:r>=4?a=$s.morning:a=$s.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return sa.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):sa.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):vt(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):vt(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):sa.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):sa.s(e,t)},S:function(e,t){return sa.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return xw(r);case"XXXX":case"XX":return Ga(r);default:return Ga(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return xw(r);case"xxxx":case"xx":return Ga(r);default:return Ga(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+bw(r,":");default:return"GMT"+Ga(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+bw(r,":");default:return"GMT"+Ga(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return vt(r,t.length)},T:function(e,t,n){return vt(+e,t.length)}};function bw(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),a=Math.trunc(r/60),i=r%60;return i===0?n+String(a):n+String(a)+t+vt(i,2)}function xw(e,t){return e%60===0?(e>0?"-":"+")+vt(Math.abs(e)/60,2):Ga(e,t)}function Ga(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),a=vt(Math.trunc(r/60),2),i=vt(r%60,2);return n+a+t+i}const yw=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},II=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},Uq=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return yw(e,t);let i;switch(r){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",yw(r,t)).replace("{{time}}",II(a,t))},$q={p:II,P:Uq},Hq=/^D+$/,zq=/^Y+$/,Gq=["D","DD","YY","YYYY"];function Vq(e){return Hq.test(e)}function Wq(e){return zq.test(e)}function qq(e,t,n){const r=Yq(e,t,n);if(console.warn(r),Gq.includes(e))throw new RangeError(r)}function Yq(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Kq=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Xq=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Zq=/^'([^]*?)'?$/,Qq=/''/g,Jq=/[a-zA-Z]/;function eY(e,t,n){const r=El(),a=r.locale??RI,i=r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=en(e,n?.in);if(!YW(l))throw new RangeError("Invalid time value");let c=t.match(Xq).map(p=>{const d=p[0];if(d==="p"||d==="P"){const f=$q[d];return f(p,a.formatLong)}return p}).join("").match(Kq).map(p=>{if(p==="''")return{isToken:!1,value:"'"};const d=p[0];if(d==="'")return{isToken:!1,value:tY(p)};if(gw[d])return{isToken:!0,value:p};if(d.match(Jq))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:p}});a.localize.preprocessor&&(c=a.localize.preprocessor(l,c));const u={firstWeekContainsDate:i,weekStartsOn:o,locale:a};return c.map(p=>{if(!p.isToken)return p.value;const d=p.value;(Wq(d)||Vq(d))&&qq(d,t,String(e));const f=gw[d[0]];return f(l,d,a.localize,u)}).join("")}function tY(e){const t=e.match(Zq);return t?t[1].replace(Qq,"'"):e}function nY(e,t,n){const r=El(),a=n?.locale??r.locale??RI,i=2520,o=qc(e,t);if(isNaN(o))throw new RangeError("Invalid time value");const l=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:o}),[c,u]=$d(n?.in,...o>0?[t,e]:[e,t]),p=nq(u,c),d=(wu(u)-wu(c))/1e3,f=Math.round((p-d)/60);let m;if(f<2)return n?.includeSeconds?p<5?a.formatDistance("lessThanXSeconds",5,l):p<10?a.formatDistance("lessThanXSeconds",10,l):p<20?a.formatDistance("lessThanXSeconds",20,l):p<40?a.formatDistance("halfAMinute",0,l):p<60?a.formatDistance("lessThanXMinutes",1,l):a.formatDistance("xMinutes",1,l):f===0?a.formatDistance("lessThanXMinutes",1,l):a.formatDistance("xMinutes",f,l);if(f<45)return a.formatDistance("xMinutes",f,l);if(f<90)return a.formatDistance("aboutXHours",1,l);if(f<fw){const h=Math.round(f/60);return a.formatDistance("aboutXHours",h,l)}else{if(f<i)return a.formatDistance("xDays",1,l);if(f<yc){const h=Math.round(f/fw);return a.formatDistance("xDays",h,l)}else if(f<yc*2)return m=Math.round(f/yc),a.formatDistance("aboutXMonths",m,l)}if(m=tq(u,c),m<12){const h=Math.round(f/yc);return a.formatDistance("xMonths",h,l)}else{const h=m%12,g=Math.trunc(m/12);return h<3?a.formatDistance("aboutXYears",g,l):h<9?a.formatDistance("overXYears",g,l):a.formatDistance("almostXYears",g+1,l)}}function rY(e,t){return nY(e,WW(e),t)}function aY({open:e,onOpenChange:t,workflow:n}){const[r,a]=y.useState([]),[i,o]=y.useState(!1),[l,c]=y.useState("");y.useEffect(()=>{e&&n&&u()},[e,n]);const u=async()=>{if(n){o(!0);try{const f=await $r.getExecutions(n.id);a(f)}catch(f){console.error("Failed to load executions:",f)}finally{o(!1)}}},p=f=>{switch(f){case"completed":return s.jsxs(zt,{className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",children:[s.jsx(jS,{className:"h-3 w-3 mr-1"})," Completed"]});case"failed":return s.jsxs(zt,{className:"bg-red-500/10 text-red-400 border-red-500/20",children:[s.jsx(RC,{className:"h-3 w-3 mr-1"})," Failed"]});case"running":return s.jsxs(zt,{className:"bg-blue-500/10 text-blue-400 border-blue-500/20",children:[s.jsx(Ta,{className:"h-3 w-3 mr-1 animate-pulse"})," Running"]});default:return s.jsx(zt,{className:"bg-zinc-500/10 text-zinc-400 border-zinc-500/20",children:f})}},d=r.filter(f=>f.id.toLowerCase().includes(l.toLowerCase())||f.alertName&&f.alertName.toLowerCase().includes(l.toLowerCase())||f.errorMessage&&f.errorMessage.toLowerCase().includes(l.toLowerCase()));return s.jsx(kt,{open:e,onOpenChange:t,children:s.jsxs(It,{className:"w-[90vw] max-w-6xl max-h-[85vh] flex flex-col p-0",children:[s.jsxs(jt,{className:"p-6 pb-4 border-b bg-muted/30",children:[s.jsxs(Mt,{className:"text-2xl font-bold flex items-center gap-2",children:[s.jsx(Ta,{className:"h-6 w-6 text-primary"}),"Execution History: ",n?.name]}),s.jsx(Kt,{children:"View recent triggers and action outcomes for this workflow."})]}),s.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col p-6 gap-4",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{placeholder:"Search by alert name or error message...",value:l,onChange:f=>c(f.target.value),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto border rounded-xl bg-muted/10",children:s.jsxs(Oa,{children:[s.jsx(La,{className:"bg-muted/50 sticky top-0 z-10 backdrop-blur-sm",children:s.jsxs(Ft,{className:"hover:bg-transparent",children:[s.jsx(gn,{children:"Triggered At"}),s.jsx(gn,{children:"Alert Name"}),s.jsx(gn,{children:"Status"}),s.jsx(gn,{children:"Actions Executed"})]})}),s.jsx(ja,{children:i?s.jsx(Ft,{children:s.jsx(Pt,{colSpan:4,className:"h-24 text-center text-muted-foreground",children:"Loading execution history..."})}):d.length===0?s.jsx(Ft,{children:s.jsx(Pt,{colSpan:4,className:"h-24 text-center text-muted-foreground",children:"No executions found."})}):d.map(f=>s.jsxs(Ft,{children:[s.jsxs(Pt,{className:"font-medium",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rs,{className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{children:eY(new Date(f.triggeredAt),"MMM d, HH:mm:ss")})]}),s.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:rY(new Date(f.triggeredAt),{addSuffix:!0})})]}),s.jsx(Pt,{children:s.jsx("div",{className:"font-medium max-w-[260px] truncate",title:f.alertName||"Unknown Alert",children:f.alertName||"Unknown Alert"})}),s.jsx(Pt,{children:p(f.status)}),s.jsx(Pt,{children:s.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.actionsExecuted&&f.actionsExecuted.length>0?f.actionsExecuted.map((m,h)=>s.jsxs(zt,{variant:"outline",className:`text-[10px] py-0 px-2 flex items-center gap-1 ${m.status==="success"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":m.status==="skipped"?"bg-muted text-muted-foreground":"bg-red-500/10 text-red-600 border-red-500/20"}`,title:m.error||m.type,children:[m.type.replace("_"," "),m.status==="success"?s.jsx(jS,{className:"h-2.5 w-2.5"}):m.status==="skipped"?s.jsx("span",{className:"text-[9px]",children:"Skip"}):s.jsx(bs,{className:"h-2.5 w-2.5"})]},h)):s.jsx("span",{className:"text-muted-foreground text-xs italic",children:"None"})})})]},f.id))})]})})]})]})})}function sY(e){const t=e.toLowerCase(),n=[];return t.includes("critical")&&n.push("critical"),t.includes("high")&&n.push("high"),t.includes("medium")&&n.push("medium"),t.includes("cloudwatch")&&n.push("cloudwatch"),t.includes("prometheus")&&n.push("prometheus"),t.includes("datadog")&&n.push("datadog"),n.length===0&&n.push("low","info","any"),n.slice(0,4)}function iY(e){const t=e.toLowerCase(),n=[];return t.includes("incident")&&n.push("INC"),t.includes("notify")&&n.push("NTF"),t.includes("sop")&&n.push("SOP"),n.length?n:["INC","NTF"]}function oY(e){if(!e)return"Never";const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"Never";const n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)} minutes ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lY({embedded:e=!1,basePath:t="/workflows",sourceId:n}={}){const[r,a]=y.useState([]),[i,o]=y.useState(!0),[l,c]=y.useState(""),[u,p]=y.useState(""),[d,f]=y.useState(""),[m,h]=y.useState(!1),[g,b]=y.useState(),[x,S]=y.useState(),[T,N]=y.useState(!1),A=St(),C=async()=>{try{o(!0),a(await $r.listWorkflows(n))}catch(R){ae.error(R.message||"Failed to load workflows")}finally{o(!1)}};y.useEffect(()=>{C()},[n]);const k=y.useMemo(()=>r.filter(R=>{const j=`${R.name} ${R.yamlDefinition}`.toLowerCase();return!(l&&!j.includes(l.toLowerCase())||u==="active"&&!R.isActive||u==="disabled"&&R.isActive||d&&!R.yamlDefinition.toLowerCase().includes(d))}),[r,l,u,d]),O=async R=>{try{await $r.toggleActive(R.id,!R.isActive),ae.success(`Workflow ${R.isActive?"disabled":"enabled"}`),C()}catch(j){ae.error(j.message||"Failed to toggle workflow")}},M=async()=>{if(x){N(!0);try{await $r.deleteWorkflow(x.id),ae.success("Workflow deleted"),S(void 0),C()}catch(R){ae.error(R.message||"Failed to delete workflow")}finally{N(!1)}}};return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Workflows"}),s.jsx("p",{children:"Rules that control how alarms become incidents"})]}),s.jsxs(ie,{onClick:()=>A({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"h-4 w-4"}),"New workflow"]})]}),s.jsxs("div",{className:"im-filters-bar",children:[s.jsx("div",{className:"im-search-wrap",children:s.jsx("input",{className:"im-search-input",value:l,onChange:R=>c(R.target.value),placeholder:"Search workflows..."})}),s.jsx(Bn,{label:"Select status",value:u,onValueChange:p,options:[{label:"All statuses",value:""},{label:"Active",value:"active"},{label:"Disabled",value:"disabled"}]}),s.jsx(Bn,{label:"Select source",value:d,onValueChange:f,options:[{label:"All sources",value:""},{label:"CloudWatch",value:"cloudwatch"},{label:"Prometheus",value:"prometheus"}]})]}),s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-workflow-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Triggers"}),s.jsx("th",{children:"Actions"}),s.jsx("th",{children:"Last matched"}),s.jsx("th",{children:"Todaymodified"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:i?s.jsx("tr",{children:s.jsx("td",{colSpan:7,className:"im-empty-cell",children:"Loading workflows..."})}):k.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:7,className:"im-empty-cell",children:"No workflows found."})}):k.map((R,j)=>{const U=!R.isActive&&j===2;return s.jsxs("tr",{onClick:()=>A({to:`${t}/${R.id}/edit`}),children:[s.jsx("td",{children:U?s.jsx("span",{className:"im-draft-pill",children:"Draft"}):s.jsx("button",{type:"button",className:`im-toggle ${R.isActive?"is-on":""}`,onClick:G=>{G.stopPropagation(),O(R)},"aria-label":"Toggle workflow"})}),s.jsx("td",{className:"im-workflow-name",children:R.name}),s.jsx("td",{children:sY(R.yamlDefinition).map(G=>s.jsx("span",{className:"im-tag",children:G},G))}),s.jsx("td",{children:iY(R.yamlDefinition).map(G=>s.jsx("span",{className:`im-action-tag im-action-${G.toLowerCase()}`,children:G},G))}),s.jsx("td",{children:j<2?`${j===0?"3":"18"} minutes ago`:"Never"}),s.jsxs("td",{children:[s.jsx("strong",{children:j===0?"122":j===1?"41":"03"}),s.jsx("span",{className:"im-inline-age",children:oY(R.updatedAt)})]}),s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button",onClick:G=>G.stopPropagation(),"aria-label":"Workflow actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",onClick:G=>G.stopPropagation(),children:[s.jsx(Lt,{onSelect:()=>A({to:`${t}/${R.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{onSelect:()=>{setTimeout(()=>{b(R),h(!0)},0)},children:"History"}),s.jsx(Lt,{onSelect:G=>{G.preventDefault(),O(R)},children:R.isActive?"Disable":"Enable"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>S(R),0),children:"Delete"})]})]})})]},R.id)})})]})}),s.jsx(aY,{open:m,onOpenChange:h,workflow:g}),s.jsx(Od,{open:!!x,onOpenChange:R=>!R&&S(void 0),children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete workflow?"}),s.jsxs(Fd,{children:["This will permanently delete ",s.jsx("strong",{children:x?.name}),"."]})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:()=>{M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function cY({sourceId:e}){const t=St(),[n,r]=w.useState("overview"),[a,i]=w.useState(null),[o,l]=w.useState([]),[c,u]=w.useState([]),[p,d]=w.useState(""),[f,m]=w.useState(null),[h,g]=w.useState(!1),[b,x]=w.useState(null),[S,T]=w.useState(null),[N,A]=w.useState(null),[C,k]=w.useState(null),[O,M]=w.useState(null),[R,j]=w.useState(!0),[U,G]=w.useState(!1),[q,P]=w.useState(!1),[z,re]=w.useState(!1),B=w.useCallback(async()=>{const D=await Ie.getSourceOverview(e);i({source:D.source,summary:D.summary})},[e]);w.useEffect(()=>{j(!0),B().catch(()=>ae.error("Failed to load source")).finally(()=>j(!1))},[B]),w.useEffect(()=>{if(!a)return;const D=`insightSourceInitialTab:${e}`,se=window.sessionStorage.getItem(D);se==="setup"&&!cw(a.source)&&r("setup"),se&&window.sessionStorage.removeItem(D)},[e,a]),w.useEffect(()=>{n==="alarms"&&Ie.listSourceAlarms(e,{page:1,limit:20}).then(D=>l(D.alarms||[])).catch(()=>ae.error("Failed to load source alarms"))},[n,e]),w.useEffect(()=>{if(n!=="logs")return;const D=setTimeout(()=>{Ie.listSourceLogs(e,{page:1,limit:20,search:p||void 0}).then(se=>u(se.logs||[])).catch(()=>ae.error("Failed to load source logs"))},200);return()=>clearTimeout(D)},[n,e,p]),w.useEffect(()=>{if(n!=="setup"||!a)return;const D=a.source,se=ws(D.type);g(!0);const Q=D.id.slice(0,8);(se==="cloudwatch"?Ie.getCloudWatchConsoleDeploy(D.id,{region:D.awsRegion||"ap-south-1",stackName:D.awsStackName||`meyi-cloudwatch-${Q}`,lambdaName:D.awsLambdaName||`meyi-cloudwatch-forwarder-${Q}`}).then(x):se==="cloudtrail"?Ie.getCloudTrailConsoleDeploy(D.id,{region:D.awsRegion||"ap-south-1",stackName:D.awsStackName||`meyi-cloudtrail-${Q}`,createNewTrail:D.awsCreateNewTrail!==!1}).then(T):se==="grafana"?Ie.getGrafanaOnboarding(D.id).then(A):se==="prometheus"?Ie.getPrometheusOnboarding(D.id).then(k):se==="datadog"?Ie.getDatadogOnboarding(D.id).then(M):Promise.resolve()).catch(K=>ae.error(K?.response?.data?.error||"Failed to load setup details")).finally(()=>g(!1))},[n,a]);async function H(D){G(!0);try{await Ie.updateSource(e,D),await B(),ae.success("Source updated")}catch(se){ae.error(se?.response?.data?.error||"Failed to update source")}finally{G(!1)}}async function I(){if(a){re(!0);try{await Ie.updateSource(e,{isActive:!a.source.isActive}),await B(),ae.success(a.source.isActive?"Source disabled":"Source enabled")}catch(D){ae.error(D?.response?.data?.error||"Failed to update source")}finally{re(!1)}}}async function V(){P(!0);try{const D=await Ie.testSource(e);m(D),r("test"),ae.success("Source test completed")}catch(D){ae.error(D?.response?.data?.error||"Source test failed")}finally{P(!1)}}if(R)return s.jsx("div",{className:"im-page im-source-detail-page im-center-panel",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin"})});if(!a)return s.jsx("div",{className:"im-page im-source-detail-page im-empty-panel",children:"Source not found."});const Z=!cw(a.source);return s.jsxs("div",{className:"im-page im-source-detail-page",children:[s.jsx(aW,{source:a.source,disabling:z,testing:q,onBack:()=>{window.history.length>1?window.history.back():t({to:"/sources"})},onToggleActive:I,onTest:V}),s.jsx(sW,{activeTab:n,showSetup:Z,onChange:r}),n==="overview"&&s.jsx(oW,{overview:a}),n==="alarms"&&s.jsx(nW,{alarms:o}),n==="configuration"&&s.jsx(rW,{source:a.source,saving:U,onSave:H}),n==="logs"&&s.jsx(iW,{logs:c,search:p,onSearchChange:d}),n==="setup"&&s.jsx(lW,{source:a.source,loading:h,cloudWatch:b,cloudTrail:S,grafana:N,prometheus:C,datadog:O}),n==="test"&&s.jsx(uW,{result:f,running:q,onRun:V}),n==="normalization"&&s.jsx(PW,{sourceId:e}),n==="dedup"&&s.jsx(BW,{sourceId:e}),n==="grouping"&&s.jsx($W,{sourceId:e}),n==="workflows"&&s.jsx(lY,{sourceId:e})]})}function DI({alert:e,open:t,onConfirm:n,onCancel:r,converting:a}){return s.jsx(kt,{open:t,onOpenChange:i=>!i&&r(),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx($h,{className:"h-5 w-5 text-primary"}),"Convert Alert to Incident"]}),s.jsx(Kt,{children:"This will create a new incident from the alert and run AI-powered RCA analysis on it."})]}),e&&s.jsxs("div",{className:"rounded-lg bg-muted/50 border p-3 space-y-2 text-sm",children:[s.jsxs("div",{className:"text-muted-foreground",children:["Are you sure you want to convert ",s.jsxs("strong",{className:"text-foreground font-semibold",children:['"',e.alertName,'"']})," to an incident? This will trigger AI-powered root cause analysis and notify assigned responders."]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-muted-foreground",children:"Resource"}),s.jsx("span",{className:"font-medium truncate",children:e.resourceName})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-muted-foreground",children:"Type"}),s.jsx("span",{children:e.resourceType})]}),e.tags&&Object.keys(e.tags).length>0&&s.jsxs("div",{className:"flex items-center gap-1.5 mt-2 flex-wrap",children:[s.jsx(ed,{size:12,className:"text-muted-foreground shrink-0"}),Object.entries(e.tags).map(([i,o])=>s.jsxs("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:[i,":",o]},i))]})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:r,disabled:a,children:"Cancel"}),s.jsx(ie,{onClick:n,disabled:a,children:a?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin"})," Converting…"]}):"Convert to Incident"})]})]})})}function OI({open:e,onConfirm:t,onCancel:n,deleting:r}){return s.jsx(kt,{open:e,onOpenChange:a=>!a&&!r&&n(),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Delete alert?"}),s.jsx(Kt,{children:"This will permanently delete this alert. It will no longer be visible in the alerts list."})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:n,disabled:r,children:"Cancel"}),s.jsx(ie,{variant:"destructive",onClick:t,disabled:r,children:r?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Deleting…"]}):"Delete"})]})]})})}function LI({open:e,alert:t,submitting:n,onClose:r,onSubmit:a}){const[i,o]=w.useState(""),[l,c]=w.useState(""),[u,p]=w.useState(""),[d,f]=w.useState("");w.useEffect(()=>{if(e&&t){o(t.alertName||""),c(t.description||""),p(t.severity||"");const g=t.tags||{};f(Object.entries(g).map(([b,x])=>`${b}: ${x}`).join(", "))}},[e,t]);const m=g=>{const b={};if(!g.trim())return b;if(g.trim().startsWith("{"))try{const x=JSON.parse(g);if(typeof x=="object"&&x!==null){for(const[S,T]of Object.entries(x))b[S]=String(T);return b}}catch{}return g.split(",").forEach(x=>{const S=x.includes(":")?x.split(":"):x.split("=");if(S.length>=2){const T=S[0].trim(),N=S.slice(1).join(":").trim();T&&(b[T]=N)}}),b},h=g=>{if(g.preventDefault(),!i.trim()){ae.error("Name is required");return}a({alertName:i.trim(),description:l.trim()||void 0,severity:u.trim()||void 0,tags:m(d)})};return s.jsx(kt,{open:e,onOpenChange:g=>!g&&!n&&r(),children:s.jsxs(It,{className:"max-w-md",children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Edit Alert"})}),s.jsxs("form",{id:"alert-form",onSubmit:h,className:"flex flex-col gap-4 mt-2",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Title ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{id:"alert-name",value:i,onChange:g=>o(g.target.value),placeholder:"e.g. CPU Spike on API Server",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:l,onChange:g=>c(g.target.value),placeholder:"Description",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Severity"}),s.jsx(Bn,{label:"Select severity",className:"im-single-select-full",value:u,onValueChange:p,disabled:n,options:[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Tags"}),s.jsx(Xe,{value:d,onChange:g=>f(g.target.value),placeholder:"project: meyiconnect, env: dev",disabled:n,className:"font-mono text-xs"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Format: key: value, key: value"})]})]}),s.jsxs($t,{children:[s.jsx(ie,{type:"button",variant:"outline",onClick:r,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",form:"alert-form",disabled:n||!i.trim(),children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Changes"})]})]})]})})}function uY({search:e,onSearchChange:t,severityFilter:n,onSeverityChange:r,sourceFilter:a,onSourceChange:i,sources:o,loading:l,onRefresh:c,children:u}){const[p,d]=w.useState([]),[f,m]=w.useState(["1h"]),h=o.map(S=>({label:S.name,value:S.id})),g=[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}],b=[{label:"normalised",value:"normalised"},{label:"suppressed",value:"suppressed"}],x=[{label:"Last 1 hour",value:"1h"},{label:"Last 24 hours",value:"24h"},{label:"Last 7 days",value:"7d"}];return s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{placeholder:"Search name, resource, metric, fingerprint...",value:e,onChange:S=>t(S.target.value),className:"h-9 w-[150px] lg:w-[250px] pl-8"}),e&&s.jsxs(ie,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground",onClick:()=>t(""),children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Clear"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Severity",options:g,selected:n,onChange:r}),s.jsx(Qn,{title:"Result",options:b,selected:p,onChange:d}),s.jsx(Qn,{title:"Time Range",options:x,selected:f,onChange:m}),s.jsx(Qn,{title:"Source",options:h,selected:a,onChange:i})]})]}),(c||u)&&s.jsxs("div",{className:"flex items-center gap-2",children:[c&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:c,disabled:l,className:"h-8 hidden lg:flex",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",l&&"animate-spin")}),"Refresh"]}),u]})]})}function Ew(e){if(!e)return"-";const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0"),a=t.getSeconds().toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),o=(t.getMonth()+1).toString().padStart(2,"0"),l=t.getFullYear();return`${i}/${o}/${l} ${n}:${r}:${a}`}const dY=e=>[{accessorKey:"alertName",header:({column:t})=>s.jsx(dt,{column:t,title:"Name"}),cell:({row:t})=>{const n=t.getValue("alertName");return s.jsx("div",{className:"max-w-[280px] truncate font-medium text-sm",title:n,children:n})}},{accessorKey:"sourceName",header:({column:t})=>s.jsx(dt,{column:t,title:"Source"}),cell:({row:t})=>{const n=t.getValue("sourceName")||"—";return s.jsx("div",{className:"max-w-[140px] truncate text-muted-foreground",title:n,children:n})}},{accessorKey:"resourceName",header:({column:t})=>s.jsx(dt,{column:t,title:"Resource"}),cell:({row:t})=>{const n=t.getValue("resourceName")||"—";return s.jsx("div",{className:"max-w-[180px] truncate",title:n,children:n})}},{accessorKey:"accountId",header:({column:t})=>s.jsx(dt,{column:t,title:"Account ID"}),cell:({row:t})=>{const n=t.original.accountId||t.original.additionalConfiguration?.accountId||"—";return s.jsx("div",{className:"max-w-[140px] truncate font-mono text-xs text-muted-foreground",title:n,children:n})}},{id:"groupName",header:({column:t})=>s.jsx(dt,{column:t,title:"Group"}),cell:({row:t})=>{const r=t.original.additionalConfiguration?.groupName||"—";return s.jsx("div",{className:"max-w-[140px] truncate text-muted-foreground",title:r,children:r})}},{id:"tags",header:({column:t})=>s.jsx(dt,{column:t,title:"Tags"}),cell:({row:t})=>{const n=t.original.tags||{},r=Object.entries(n);return r.length===0?s.jsx("span",{className:"text-muted-foreground",children:"—"}):s.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[200px]",children:[r.slice(0,2).map(([a,i])=>s.jsxs("span",{className:"text-[11px] bg-muted px-1.5 py-0.5 rounded font-mono truncate",children:[a,":",i]},a)),r.length>2&&s.jsxs("span",{className:"text-[10px] text-muted-foreground self-center",children:["+",r.length-2]})]})}},{accessorKey:"severity",header:({column:t})=>s.jsx(dt,{column:t,title:"Severity"}),cell:({row:t})=>{const n=t.getValue("severity"),a={critical:"bg-red-500/15 text-red-500 border-red-500/30",high:"bg-orange-500/15 text-orange-500 border-orange-500/30",medium:"bg-amber-500/15 text-amber-500 border-amber-500/30",low:"bg-sky-500/15 text-sky-500 border-sky-500/30"}[n]||"";return s.jsx(zt,{variant:"outline",className:`capitalize text-[11px] ${a}`,children:n})}},{id:"downTime",header:({column:t})=>s.jsx(dt,{column:t,title:"Down Time"}),cell:({row:t})=>{const n=t.original.downTime;return s.jsx("div",{className:"text-muted-foreground tabular-nums",children:Ew(n)})}},{accessorKey:"createdAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Created At"}),cell:({row:t})=>s.jsx("div",{className:"text-muted-foreground tabular-nums",children:Ew(t.getValue("createdAt"))})},{id:"actions",cell:({row:t})=>{const n=t.original;return s.jsx("div",{onClick:r=>r.stopPropagation(),children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsxs(ie,{variant:"ghost",className:"h-8 w-8 p-0",children:[s.jsx("span",{className:"sr-only",children:"Open menu"}),s.jsx(hs,{className:"h-4 w-4"})]})}),s.jsxs(Lr,{align:"end",children:[s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onEdit(n)},children:[s.jsx(Ju,{className:"h-4 w-4 mr-2"})," Edit"]}),n.status==="open"&&s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onConvert(n)},children:[s.jsx($h,{className:"h-4 w-4 mr-2"})," Convert to Incident"]}),n.incidentId&&s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onViewIncident(n.incidentId)},children:[s.jsx(DC,{className:"h-4 w-4 mr-2"})," View Incident"]}),e.sopsByAlertName?.[n.alertName]?s.jsx(Lt,{asChild:!0,children:s.jsxs(Ei,{to:`/sops/${e.sopsByAlertName[n.alertName]}`,className:"w-full flex items-center cursor-pointer",onClick:r=>r.stopPropagation(),children:[s.jsx(di,{className:"h-4 w-4 mr-2"}),"View SOP"]})}):e.onGenerateSop?s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onGenerateSop(n)},disabled:e.generatingSopId===n.id,children:[e.generatingSopId===n.id?s.jsx(Qe,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(ol,{className:"h-4 w-4 mr-2"}),"Generate SOP"]}):null,s.jsx(Ci,{}),s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onDelete(n.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(ll,{className:"h-4 w-4 mr-2"})," Delete"]})]})]})})}}];function pY({data:e,total:t,page:n,limit:r,loading:a,onPageChange:i,onLimitChange:o,onViewIncident:l,onViewAlert:c,onEdit:u,onDelete:p,onConvert:d,onGenerateSop:f,generatingSopId:m,sopsByAlertName:h,renderFilters:g}){const[b,x]=w.useState({}),[S,T]=w.useState([]),N=w.useMemo(()=>dY({onEdit:u,onDelete:p,onConvert:d,onGenerateSop:f,generatingSopId:m,sopsByAlertName:h,onViewIncident:l,onViewAlert:c}),[u,p,d,f,m,h,l,c]),A=Math.max(1,Math.ceil(t/r)),C=w.useMemo(()=>[],[]),k=gl({data:e,columns:N,state:{pagination:{pageIndex:n-1,pageSize:r},columnVisibility:b,columnFilters:C,sorting:S},pageCount:A,manualPagination:!0,manualFiltering:!0,onSortingChange:T,getSortedRowModel:Ad(),onPaginationChange:O=>{const M=typeof O=="function"?O({pageIndex:n-1,pageSize:r}):O;M.pageIndex+1!==n&&i(M.pageIndex+1),M.pageSize!==r&&o(M.pageSize)},onColumnVisibilityChange:x,getCoreRowModel:hl()});return a&&e.length===0?s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[g?.(k),s.jsx(qr,{variant:"table"})]}):s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[g?.(k),s.jsx("div",{className:"rounded-md border overflow-hidden bg-card text-card-foreground",children:s.jsxs(Oa,{children:[s.jsx(La,{children:k.getHeaderGroups().map(O=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:O.headers.map(M=>s.jsx(gn,{children:M.isPlaceholder?null:Rr(M.column.columnDef.header,M.getContext())},M.id))},O.id))}),s.jsx(ja,{children:k.getRowModel().rows?.length?k.getRowModel().rows.map(O=>s.jsx(Ft,{"data-state":O.getIsSelected()&&"selected",className:`group/row hover:bg-muted/30 ${c?"cursor-pointer":""}`,onClick:()=>c?.(O.original.id),children:O.getVisibleCells().map(M=>s.jsx(Pt,{children:Rr(M.column.columnDef.cell,M.getContext())},M.id))},O.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:N.length,className:"h-24 text-center",children:"No alerts found."})})})]})}),s.jsx(bl,{table:k,className:"mt-auto"})]})}const fY={};function mY({onViewIncident:e,onViewAlert:t}){const[n,r]=w.useState([]),[a,i]=w.useState(0),[o,l]=w.useState(!0),[c,u]=w.useState(1),[p,d]=w.useState(10),[f,m]=w.useState(""),[h,g]=w.useState(""),[b,x]=w.useState(""),[S,T]=w.useState(""),[N,A]=w.useState([]),[C,k]=w.useState(null),[O,M]=w.useState(!1),[R,j]=w.useState(null),[U,G]=w.useState(null),[q,P]=w.useState(null),[z,re]=w.useState(!1);w.useEffect(()=>{const Q=setTimeout(()=>{g(f),u(1)},350);return()=>clearTimeout(Q)},[f]);const B=w.useCallback(async(Q=!1)=>{Q||l(!0);try{const ne=await Ie.listAlerts({page:c,limit:p,severity:b||void 0,sourceId:S||void 0,search:h||void 0});r(ne.alerts??[]),i(ne.total??0)}catch{Q||ae.error("Failed to load alerts")}finally{Q||l(!1)}},[c,p,b,S,h]);w.useEffect(()=>{B()},[B]);const H=w.useRef(B);w.useEffect(()=>{H.current=B},[B]),w.useEffect(()=>{Ie.listSources({page:1,limit:200}).then(Q=>A(Q.sources??[])).catch(()=>A([]))},[]);const I=w.useCallback(async()=>{try{await Promise.all([Ie.listAlerts({page:1,limit:1,status:"all",severity:"critical"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"high"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"medium"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"low"})])}catch{}},[]);w.useEffect(()=>{I();const Q=setInterval(I,3e4);return()=>clearInterval(Q)},[I]);const V=w.useRef(I);w.useEffect(()=>{V.current=I},[I]),w.useEffect(()=>{const Q=fY?.VITE_SOCKET_URL,ne=(Q?Q.replace("/socket.io",""):window.location.origin).replace(/\/+$/,""),K=bo(`${ne}/ws/insight`,{path:"/socket.io",transports:["websocket","polling"],withCredentials:!0}),Y=()=>{Promise.all([H.current(!0),V.current()])};return K.on("insight:alerts:totals",Y),K.on("insight:event",J=>{(J?.topic==="alerts.totals"||J?.topic?.startsWith("alerts."))&&Y()}),K.on("connect",Y),()=>{K.disconnect()}},[]);const Z=async()=>{if(C){M(!0);try{const Q=await Ie.convertAlert(C.id);ae.success("Alert converted to incident"),B(),I(),e(Q.incidentId)}catch(Q){ae.error(Q?.response?.data?.error??"Failed to convert alert")}finally{M(!1),k(null)}}},D=async()=>{if(R){G(R);try{await Ie.deleteAlert(R),ae.success("Alert deleted"),j(null),B(),I()}catch{ae.error("Failed to delete alert")}finally{G(null)}}},se=async Q=>{if(q){re(!0);try{await Ie.updateAlert(q.id,Q),ae.success("Alert updated"),P(null),B(),I()}catch{ae.error("Failed to update alert")}finally{re(!1)}}};return s.jsxs("div",{className:"space-y-6",children:[s.jsx(pY,{data:n,total:a,page:c,limit:p,loading:o,onPageChange:u,onLimitChange:Q=>{d(Q),u(1)},onViewIncident:e,onViewAlert:t,onEdit:Q=>P(Q),onDelete:Q=>j(Q),onConvert:Q=>k(Q),renderFilters:Q=>s.jsxs(s.Fragment,{children:[s.jsx("div",{children:s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Alarm search"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Every alarm received by the collector across all sources"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>B(),disabled:o,className:"h-8",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",o&&"animate-spin")}),"Refresh"]}),s.jsx(Mg,{table:Q})]})]})}),s.jsx(uY,{search:f,onSearchChange:m,severityFilter:b?[b]:[],onSeverityChange:ne=>{x(ne[0]??""),u(1)},sourceFilter:S?[S]:[],onSourceChange:ne=>{T(ne[0]??""),u(1)},sources:N,loading:o})]})}),s.jsx(DI,{alert:C,open:!!C,onConfirm:Z,onCancel:()=>k(null),converting:O}),s.jsx(OI,{open:!!R,onConfirm:D,onCancel:()=>j(null),deleting:!!U}),s.jsx(LI,{open:!!q,alert:q,submitting:z,onClose:()=>P(null),onSubmit:se})]})}const vw=[{key:"queue",label:"Queued",icon:HF},{key:"normalization",label:"Normalised",icon:PC},{key:"dedup",label:"Dedup",icon:il},{key:"grouping",label:"Grouped",icon:FF},{key:"workflow",label:"Workflow",icon:ei}];function hY(e,t){return e?e.status==="error"?s.jsx(RC,{className:"w-4 h-4 text-destructive"}):e.status==="suppressed"?s.jsx(bs,{className:"w-4 h-4 text-yellow-500"}):e.status==="ok"||e.status==="created"||e.status==="buffering"||e.status==="flushed"||e.status==="completed"?s.jsx(ei,{className:"w-4 h-4 text-emerald-500"}):s.jsx(rs,{className:"w-4 h-4 text-muted-foreground/50"}):s.jsx(rs,{className:"w-4 h-4 text-muted-foreground/40"})}function gY(e){if(!e)return null;const t={ok:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",created:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",error:"bg-red-500/10 text-red-500 border-red-500/20",suppressed:"bg-yellow-500/10 text-yellow-600 border-yellow-500/20",buffering:"bg-blue-500/10 text-blue-500 border-blue-500/20",flushed:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",completed:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",dlq:"bg-red-500/10 text-red-500 border-red-500/20",fallback:"bg-orange-500/10 text-orange-500 border-orange-500/20"}[e.status]??"bg-muted/50 text-muted-foreground border-border";return s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${t}`,children:e.status})}function bY({alarmId:e}){const[t,n]=w.useState([]),[r,a]=w.useState(!0),[i,o]=w.useState(null);if(w.useEffect(()=>{e&&(a(!0),Ie.getPipelineEvents(e).then(u=>{u.ok&&n(u.events)}).catch(u=>o(u.message)).finally(()=>a(!1)))},[e]),r)return s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[s.jsx(Qe,{className:"w-3.5 h-3.5 animate-spin"}),"Loading pipeline lifecycle…"]});if(i)return s.jsxs("div",{className:"text-sm text-muted-foreground py-2",children:["Pipeline events unavailable — ",i]});const l={};for(const u of t)l[u.stage]=u;const c=!!l.dlq;return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Processing Lifecycle"}),c&&s.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded bg-red-500/15 text-red-500 border border-red-500/20 uppercase tracking-wide",children:"DLQ"})]}),s.jsx("div",{className:"flex items-stretch gap-0",children:vw.map((u,p)=>{const d=l[u.key];u.icon;const f=p===vw.length-1;return s.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0 group",children:[s.jsx("div",{className:`
127
+ For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return y.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},AW=gI,_W=bI,RW=xI,kW=yI,IW=TI,DW=CI,OW=vI,LW=wI;function Od({...e}){return s.jsx(AW,{"data-slot":"alert-dialog",...e})}function jW({...e}){return s.jsx(_W,{"data-slot":"alert-dialog-portal",...e})}function MW({className:e,...t}){return s.jsx(RW,{"data-slot":"alert-dialog-overlay",className:Fe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Ld({className:e,...t}){return s.jsxs(jW,{children:[s.jsx(MW,{}),s.jsx(kW,{"data-slot":"alert-dialog-content",className:Fe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function jd({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-header",className:Fe("flex flex-col gap-2 text-center sm:text-start",e),...t})}function Md({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-footer",className:Fe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Pd({className:e,...t}){return s.jsx(OW,{"data-slot":"alert-dialog-title",className:Fe("text-lg font-semibold",e),...t})}function Fd({className:e,...t}){return s.jsx(LW,{"data-slot":"alert-dialog-description",className:Fe("text-muted-foreground text-sm",e),...t})}function Bd({className:e,...t}){return s.jsx(IW,{className:Fe(Kh(),e),...t})}function Ud({className:e,...t}){return s.jsx(DW,{className:Fe(Kh({variant:"outline"}),e),...t})}function PW({sourceId:e}={}){const{isReadOnly:t}=ur(),[n,r]=w.useState([]),[a,i]=w.useState(!0),[o,l]=w.useState(null),c=St(),u=async()=>{try{const d=await Ie.listNormalizationConfigs(e);d.ok&&r(d.configs)}catch(d){ae.error(d.message)}finally{i(!1)}};w.useEffect(()=>{u()},[e]);const p=async()=>{if(o)try{await Ie.deleteNormalizationConfig(o),ae.success("Rule deleted"),l(null),await u()}catch(d){ae.error(d.message)}};return s.jsxs("div",{className:"h-full flex flex-col gap-6 p-6 overflow-y-auto",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(PC,{className:"w-5 h-5 text-primary"}),s.jsx("h1",{className:"text-xl font-bold",children:"Normalization Rules"})]}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Map incoming webhook payloads to canonical alarm fields using YAML + Handlebars templates."})]}),!t&&s.jsxs(ie,{onClick:()=>c({to:`/pipeline/normalization/new${e?`?sourceId=${e}`:""}`}),children:[s.jsx(Wr,{className:"w-4 h-4 mr-2"})," Add Rule"]})]}),a?s.jsx("div",{className:"flex justify-center p-8 text-muted-foreground",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):n.length===0?s.jsxs("div",{className:"p-8 text-center text-muted-foreground border border-dashed rounded-lg bg-muted/10",children:[s.jsx("p",{className:"mb-4",children:"No normalization rules yet — the built-in normalizer is active."}),!t&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>c({to:`/pipeline/normalization/new${e?`?sourceId=${e}`:""}`}),children:"Add your first rule"})]}):s.jsx("div",{className:"rounded-md border",children:s.jsxs(Oa,{children:[s.jsx(La,{children:s.jsxs(Ft,{children:[s.jsx(gn,{className:"w-[80px]",children:"Priority"}),s.jsx(gn,{children:"Name"}),s.jsx(gn,{children:"Scope"}),s.jsx(gn,{className:"w-[100px]",children:"Status"}),!t&&s.jsx(gn,{className:"w-[100px] text-right",children:"Actions"})]})}),s.jsx(ja,{children:n.map((d,f)=>s.jsxs(Ft,{className:d.isActive?"":"opacity-50",children:[s.jsx(Pt,{className:"font-mono text-muted-foreground",children:d.priority}),s.jsx(Pt,{className:"font-medium max-w-[220px] truncate",title:d.name,children:d.name}),s.jsx(Pt,{className:"text-muted-foreground text-xs max-w-[180px] truncate",title:d.sourceId?`source: ${d.sourceId}`:d.sourceType?d.sourceType:"global",children:d.sourceId?`source: ${d.sourceId}`:d.sourceType?d.sourceType:"global"}),s.jsx(Pt,{children:s.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full border font-medium ${d.isActive?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":"bg-muted/50 text-muted-foreground border-border"}`,children:d.isActive?"active":"inactive"})}),!t&&s.jsx(Pt,{className:"text-right",children:s.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[s.jsx(ie,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>c({to:`/pipeline/normalization/${d.id}/edit${e?`?sourceId=${e}`:""}`}),children:s.jsx(Zu,{className:"w-4 h-4"})}),s.jsx(ie,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-red-500",onClick:()=>l(d.id),children:s.jsx(ll,{className:"w-4 h-4"})})]})})]},d.id))})]})}),s.jsx(Od,{open:!!o,onOpenChange:d=>{d||l(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete normalization rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms matched by this rule will fall through to the next rule."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:p,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function FW(e){return e.sourceId?`Source ${e.sourceId.slice(0,8)}`:e.sourceType?`Any ${e.sourceType} alarm`:"Any unmatched alarm"}function BW({embedded:e=!1,basePath:t="/pipeline/dedup",sourceId:n}={}){const{isReadOnly:r}=ur(),[a,i]=w.useState([]),[o,l]=w.useState(!0),[c,u]=w.useState(null),p=St(),d=async()=>{try{l(!0);const b=await Ie.listDedupConfigs(n);b.ok&&i(b.configs)}catch(b){ae.error(b.message||"Failed to load dedup rules")}finally{l(!1)}};w.useEffect(()=>{d()},[n]);const f=async b=>{const x=!b.isActive;i(S=>S.map(T=>T.id===b.id?{...T,isActive:x}:T));try{await Ie.updateDedupConfig(b.id,{isActive:x}),ae.success(x?"Rule enabled":"Rule disabled")}catch(S){i(T=>T.map(N=>N.id===b.id?{...N,isActive:b.isActive}:N)),ae.error(S.message||"Failed to update rule")}},m=async()=>{if(c)try{await Ie.deleteDedupConfig(c),ae.success("Deleted"),u(null),await d()}catch(b){ae.error(b.message||"Failed to delete dedup rule")}},h=a.filter(b=>b.isActive).length,g=a.filter(b=>b.flapThreshold>0).length;return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Dedup rules"}),s.jsx("p",{children:"How repeated alarms are suppressed before grouping"})]}),!r&&s.jsxs(ie,{onClick:()=>p({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"w-4 h-4"})," New rule"]})]}),!o&&a.length>0&&s.jsxs("div",{className:"im-pipeline-stats-row",children:[s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",children:s.jsx(il,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:a.length}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Total rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-success)"},children:s.jsx(o4,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:h}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Active rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-warning, #b7860b)"},children:s.jsx(Ta,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:g}),s.jsx("div",{className:"im-pipeline-stat-label",children:"With flap detection"})]})]})]}),o?s.jsx("div",{className:"im-loading-panel",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):a.length===0?s.jsxs("div",{className:"im-empty-panel",children:[s.jsx("p",{children:"No dedup rules yet. Alarms pass through using the default fingerprint."}),!r&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>p({to:`${t}/new`}),children:"Add your first rule"})]}):s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-pipeline-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Priority"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Matches"}),s.jsx("th",{children:"Dedup key"}),s.jsx("th",{children:"Window"}),s.jsx("th",{children:"Flap"}),s.jsx("th",{children:"Active"}),!r&&s.jsx("th",{})]})}),s.jsx("tbody",{children:a.map(b=>s.jsxs("tr",{className:b.isActive?"":"is-muted",children:[s.jsxs("td",{children:[s.jsx("span",{className:"im-drag-handle",children:"::"}),s.jsx("strong",{children:b.priority})]}),s.jsx("td",{className:"im-workflow-name",children:b.name}),s.jsx("td",{children:FW(b)}),s.jsx("td",{children:(b.keyFields??[]).map(x=>s.jsx("span",{className:"im-tag",children:x},x))}),s.jsxs("td",{children:[Math.round(b.windowSeconds/60),"m"]}),s.jsxs("td",{children:[b.flapThreshold,"x / ",Math.round(b.flapWindowSeconds/60),"m - ",b.onFlap]}),s.jsx("td",{children:s.jsx("button",{type:"button",className:`im-toggle ${b.isActive?"is-on":""}`,"aria-label":"Dedup rule status",disabled:r,onClick:()=>!r&&f(b)})}),!r&&s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button","aria-label":"Dedup rule actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",children:[s.jsx(Lt,{onClick:()=>p({to:`${t}/${b.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>u(b.id),0),children:"Delete"})]})]})})]},b.id))})]})}),s.jsx(Od,{open:!!c,onOpenChange:b=>{b||u(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete dedup rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms that matched this rule will use the default fingerprint."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:m,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function UW(e){return e.sourceId?`Source ${e.sourceId.slice(0,8)}`:e.sourceType?`Any ${e.sourceType} alarm`:"Any unmatched alarm"}function $W({embedded:e=!1,basePath:t="/pipeline/grouping",sourceId:n}={}){const{isReadOnly:r}=ur(),[a,i]=w.useState([]),[o,l]=w.useState(!0),[c,u]=w.useState(null),p=St(),d=async()=>{try{l(!0);const b=await Ie.listGroupingConfigs(n);b.ok&&i(b.configs)}catch(b){ae.error(b.message||"Failed to load grouping rules")}finally{l(!1)}};w.useEffect(()=>{d()},[n]);const f=async b=>{const x=!b.isActive;i(S=>S.map(T=>T.id===b.id?{...T,isActive:x}:T));try{await Ie.updateGroupingConfig(b.id,{isActive:x}),ae.success(x?"Rule enabled":"Rule disabled")}catch(S){i(T=>T.map(N=>N.id===b.id?{...N,isActive:b.isActive}:N)),ae.error(S.message||"Failed to update rule")}},m=async()=>{if(c)try{await Ie.deleteGroupingConfig(c),ae.success("Deleted"),u(null),await d()}catch(b){ae.error(b.message||"Failed to delete grouping rule")}},h=a.filter(b=>b.isActive).length,g=a.filter(b=>b.incidentTitleTemplate).length;return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Grouping rules"}),s.jsx("p",{children:"How unmatched alarms are combined into incidents"})]}),!r&&s.jsxs(ie,{onClick:()=>p({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"w-4 h-4"})," New rule"]})]}),!o&&a.length>0&&s.jsxs("div",{className:"im-pipeline-stats-row",children:[s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",children:s.jsx(zh,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:a.length}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Total rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-success)"},children:s.jsx(Ta,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:h}),s.jsx("div",{className:"im-pipeline-stat-label",children:"Active rules"})]})]}),s.jsxs("div",{className:"im-pipeline-stat-card",children:[s.jsx("div",{className:"im-pipeline-stat-icon",style:{color:"var(--im-primary)"},children:s.jsx(di,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"im-pipeline-stat-value",children:g}),s.jsx("div",{className:"im-pipeline-stat-label",children:"With title template"})]})]})]}),o?s.jsx("div",{className:"im-loading-panel",children:s.jsx(Qe,{className:"h-6 w-6 animate-spin"})}):a.length===0?s.jsxs("div",{className:"im-empty-panel",children:[s.jsx("p",{children:"No grouping rules yet. Alarms are routed individually using defaults."}),!r&&s.jsx(ie,{variant:"outline",size:"sm",onClick:()=>p({to:`${t}/new`}),children:"Add your first rule"})]}):s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-pipeline-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Priority"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Matches"}),s.jsx("th",{children:"Group by"}),s.jsx("th",{children:"Title template"}),s.jsx("th",{children:"Window"}),s.jsx("th",{children:"Active"}),!r&&s.jsx("th",{})]})}),s.jsx("tbody",{children:a.map(b=>s.jsxs("tr",{className:b.isActive?"":"is-muted",children:[s.jsxs("td",{children:[s.jsx("span",{className:"im-drag-handle",children:"::"}),s.jsx("strong",{children:b.priority})]}),s.jsx("td",{className:"im-workflow-name",children:b.name}),s.jsx("td",{children:UW(b)}),s.jsx("td",{children:(b.groupBy??[]).map(x=>s.jsx("span",{className:"im-tag",children:x},x))}),s.jsx("td",{className:"im-grouping-template-cell",children:b.incidentTitleTemplate?s.jsx("code",{className:"im-template-preview",children:b.incidentTitleTemplate}):s.jsx("span",{style:{color:"var(--im-fg-subtle)"},children:"—"})}),s.jsxs("td",{children:[Math.round(b.timeoutSeconds/60),"m / ",b.maxAlarms," max"]}),s.jsx("td",{children:s.jsx("button",{type:"button",className:`im-toggle ${b.isActive?"is-on":""}`,"aria-label":"Grouping rule status",disabled:r,onClick:()=>!r&&f(b)})}),!r&&s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button","aria-label":"Grouping rule actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",children:[s.jsx(Lt,{onClick:()=>p({to:`${t}/${b.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>u(b.id),0),children:"Delete"})]})]})})]},b.id))})]})}),s.jsx(Od,{open:!!c,onOpenChange:b=>{b||u(null)},children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete grouping rule?"}),s.jsx(Fd,{children:"This action cannot be undone. Alarms matched by this rule will fall through to the next rule."})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:m,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const $r={async listWorkflows(e){return(await Te.get("/workflows",{params:{sourceId:e}})).data.workflows},async parseYaml(e){return(await Te.post("/workflows/parse-yaml",{yaml:e})).data},async getWorkflow(e){return(await Te.get(`/workflows/${e}`)).data.workflow},async createWorkflow(e){return(await Te.post("/workflows",e)).data.workflow},async updateWorkflow(e,t){return(await Te.put(`/workflows/${e}`,t)).data.workflow},async deleteWorkflow(e){await Te.delete(`/workflows/${e}`)},async toggleActive(e,t){return(await Te.patch(`/workflows/${e}/toggle`,{isActive:t})).data.workflow},async reorderWorkflows(e){await Te.put("/workflows/reorder",{orderedIds:e})},async getExecutions(e){return(await Te.get(`/workflows/${e}/executions`)).data.executions},async getRecentExecutions(e=50){return(await Te.get("/workflows/executions/recent",{params:{limit:e}})).data.executions}},AI=6048e5,HW=864e5,yc=43200,fw=1440,mw=Symbol.for("constructDateFrom");function Xr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&mw in e?e[mw](t):e instanceof Date?new e.constructor(t):new Date(t)}function en(e,t){return Xr(t||e,e)}let zW={};function El(){return zW}function Wo(e,t){const n=El(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,a=en(e,t?.in),i=a.getDay(),o=(i<r?7:0)+i-r;return a.setDate(a.getDate()-o),a.setHours(0,0,0,0),a}function Su(e,t){return Wo(e,{...t,weekStartsOn:1})}function _I(e,t){const n=en(e,t?.in),r=n.getFullYear(),a=Xr(n,0);a.setFullYear(r+1,0,4),a.setHours(0,0,0,0);const i=Su(a),o=Xr(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);const l=Su(o);return n.getTime()>=i.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function wu(e){const t=en(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function $d(e,...t){const n=Xr.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function hw(e,t){const n=en(e,t?.in);return n.setHours(0,0,0,0),n}function GW(e,t,n){const[r,a]=$d(n?.in,e,t),i=hw(r),o=hw(a),l=+i-wu(i),c=+o-wu(o);return Math.round((l-c)/HW)}function VW(e,t){const n=_I(e,t),r=Xr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Su(r)}function qc(e,t){const n=+en(e)-+en(t);return n<0?-1:n>0?1:n}function WW(e){return Xr(e,Date.now())}function qW(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function YW(e){return!(!qW(e)&&typeof e!="number"||isNaN(+en(e)))}function KW(e,t,n){const[r,a]=$d(n?.in,e,t),i=r.getFullYear()-a.getFullYear(),o=r.getMonth()-a.getMonth();return i*12+o}function XW(e){return t=>{const r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function ZW(e,t){return+en(e)-+en(t)}function QW(e,t){const n=en(e,t?.in);return n.setHours(23,59,59,999),n}function JW(e,t){const n=en(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function eq(e,t){const n=en(e,t?.in);return+QW(n,t)==+JW(n,t)}function tq(e,t,n){const[r,a,i]=$d(n?.in,e,e,t),o=qc(a,i),l=Math.abs(KW(a,i));if(l<1)return 0;a.getMonth()===1&&a.getDate()>27&&a.setDate(30),a.setMonth(a.getMonth()-o*l);let c=qc(a,i)===-o;eq(r)&&l===1&&qc(r,i)===1&&(c=!1);const u=o*(l-+c);return u===0?0:u}function nq(e,t,n){const r=ZW(e,t)/1e3;return XW(n?.roundingMethod)(r)}function rq(e,t){const n=en(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const aq={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},sq=(e,t,n)=>{let r;const a=aq[e];return typeof a=="string"?r=a:t===1?r=a.one:r=a.other.replace("{{count}}",t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Df(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const iq={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},oq={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},lq={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},cq={date:Df({formats:iq,defaultWidth:"full"}),time:Df({formats:oq,defaultWidth:"full"}),dateTime:Df({formats:lq,defaultWidth:"full"})},uq={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},dq=(e,t,n,r)=>uq[e];function Qi(e){return(t,n)=>{const r=n?.context?String(n.context):"standalone";let a;if(r==="formatting"&&e.formattingValues){const o=e.defaultFormattingWidth||e.defaultWidth,l=n?.width?String(n.width):o;a=e.formattingValues[l]||e.formattingValues[o]}else{const o=e.defaultWidth,l=n?.width?String(n.width):e.defaultWidth;a=e.values[l]||e.values[o]}const i=e.argumentCallback?e.argumentCallback(t):t;return a[i]}}const pq={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},fq={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},mq={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},hq={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},gq={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},bq={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},xq=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},yq={ordinalNumber:xq,era:Qi({values:pq,defaultWidth:"wide"}),quarter:Qi({values:fq,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Qi({values:mq,defaultWidth:"wide"}),day:Qi({values:hq,defaultWidth:"wide"}),dayPeriod:Qi({values:gq,defaultWidth:"wide",formattingValues:bq,defaultFormattingWidth:"wide"})};function Ji(e){return(t,n={})=>{const r=n.width,a=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(a);if(!i)return null;const o=i[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?vq(l,d=>d.test(o)):Eq(l,d=>d.test(o));let u;u=e.valueCallback?e.valueCallback(c):c,u=n.valueCallback?n.valueCallback(u):u;const p=t.slice(o.length);return{value:u,rest:p}}}function Eq(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function vq(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Sq(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const a=r[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;const l=t.slice(a.length);return{value:o,rest:l}}}const wq=/^(\d+)(th|st|nd|rd)?/i,Tq=/\d+/i,Nq={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Cq={any:[/^b/i,/^(a|c)/i]},Aq={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},_q={any:[/1/i,/2/i,/3/i,/4/i]},Rq={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},kq={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Iq={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Dq={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Oq={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Lq={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},jq={ordinalNumber:Sq({matchPattern:wq,parsePattern:Tq,valueCallback:e=>parseInt(e,10)}),era:Ji({matchPatterns:Nq,defaultMatchWidth:"wide",parsePatterns:Cq,defaultParseWidth:"any"}),quarter:Ji({matchPatterns:Aq,defaultMatchWidth:"wide",parsePatterns:_q,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ji({matchPatterns:Rq,defaultMatchWidth:"wide",parsePatterns:kq,defaultParseWidth:"any"}),day:Ji({matchPatterns:Iq,defaultMatchWidth:"wide",parsePatterns:Dq,defaultParseWidth:"any"}),dayPeriod:Ji({matchPatterns:Oq,defaultMatchWidth:"any",parsePatterns:Lq,defaultParseWidth:"any"})},RI={code:"en-US",formatDistance:sq,formatLong:cq,formatRelative:dq,localize:yq,match:jq,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Mq(e,t){const n=en(e,t?.in);return GW(n,rq(n))+1}function Pq(e,t){const n=en(e,t?.in),r=+Su(n)-+VW(n);return Math.round(r/AI)+1}function kI(e,t){const n=en(e,t?.in),r=n.getFullYear(),a=El(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,o=Xr(t?.in||e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=Wo(o,t),c=Xr(t?.in||e,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const u=Wo(c,t);return+n>=+l?r+1:+n>=+u?r:r-1}function Fq(e,t){const n=El(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=kI(e,t),i=Xr(t?.in||e,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Wo(i,t)}function Bq(e,t){const n=en(e,t?.in),r=+Wo(n,t)-+Fq(n,t);return Math.round(r/AI)+1}function vt(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const sa={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return vt(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):vt(n+1,2)},d(e,t){return vt(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h(e,t){return vt(e.getHours()%12||12,t.length)},H(e,t){return vt(e.getHours(),t.length)},m(e,t){return vt(e.getMinutes(),t.length)},s(e,t){return vt(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return vt(a,t.length)}},$s={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},gw={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return sa.y(e,t)},Y:function(e,t,n,r){const a=kI(e,r),i=a>0?a:1-a;if(t==="YY"){const o=i%100;return vt(o,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):vt(i,t.length)},R:function(e,t){const n=_I(e);return vt(n,t.length)},u:function(e,t){const n=e.getFullYear();return vt(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return vt(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return vt(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return sa.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return vt(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const a=Bq(e,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):vt(a,t.length)},I:function(e,t,n){const r=Pq(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):vt(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):sa.d(e,t)},D:function(e,t,n){const r=Mq(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):vt(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const a=e.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return vt(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const a=e.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return vt(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),a=r===0?7:r;switch(t){case"i":return String(a);case"ii":return vt(a,t.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const a=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let a;switch(r===12?a=$s.noon:r===0?a=$s.midnight:a=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let a;switch(r>=17?a=$s.evening:r>=12?a=$s.afternoon:r>=4?a=$s.morning:a=$s.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return sa.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):sa.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):vt(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):vt(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):sa.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):sa.s(e,t)},S:function(e,t){return sa.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return xw(r);case"XXXX":case"XX":return Ga(r);default:return Ga(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return xw(r);case"xxxx":case"xx":return Ga(r);default:return Ga(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+bw(r,":");default:return"GMT"+Ga(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+bw(r,":");default:return"GMT"+Ga(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return vt(r,t.length)},T:function(e,t,n){return vt(+e,t.length)}};function bw(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),a=Math.trunc(r/60),i=r%60;return i===0?n+String(a):n+String(a)+t+vt(i,2)}function xw(e,t){return e%60===0?(e>0?"-":"+")+vt(Math.abs(e)/60,2):Ga(e,t)}function Ga(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),a=vt(Math.trunc(r/60),2),i=vt(r%60,2);return n+a+t+i}const yw=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},II=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},Uq=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return yw(e,t);let i;switch(r){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",yw(r,t)).replace("{{time}}",II(a,t))},$q={p:II,P:Uq},Hq=/^D+$/,zq=/^Y+$/,Gq=["D","DD","YY","YYYY"];function Vq(e){return Hq.test(e)}function Wq(e){return zq.test(e)}function qq(e,t,n){const r=Yq(e,t,n);if(console.warn(r),Gq.includes(e))throw new RangeError(r)}function Yq(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Kq=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Xq=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Zq=/^'([^]*?)'?$/,Qq=/''/g,Jq=/[a-zA-Z]/;function eY(e,t,n){const r=El(),a=r.locale??RI,i=r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=en(e,n?.in);if(!YW(l))throw new RangeError("Invalid time value");let c=t.match(Xq).map(p=>{const d=p[0];if(d==="p"||d==="P"){const f=$q[d];return f(p,a.formatLong)}return p}).join("").match(Kq).map(p=>{if(p==="''")return{isToken:!1,value:"'"};const d=p[0];if(d==="'")return{isToken:!1,value:tY(p)};if(gw[d])return{isToken:!0,value:p};if(d.match(Jq))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:p}});a.localize.preprocessor&&(c=a.localize.preprocessor(l,c));const u={firstWeekContainsDate:i,weekStartsOn:o,locale:a};return c.map(p=>{if(!p.isToken)return p.value;const d=p.value;(Wq(d)||Vq(d))&&qq(d,t,String(e));const f=gw[d[0]];return f(l,d,a.localize,u)}).join("")}function tY(e){const t=e.match(Zq);return t?t[1].replace(Qq,"'"):e}function nY(e,t,n){const r=El(),a=n?.locale??r.locale??RI,i=2520,o=qc(e,t);if(isNaN(o))throw new RangeError("Invalid time value");const l=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:o}),[c,u]=$d(n?.in,...o>0?[t,e]:[e,t]),p=nq(u,c),d=(wu(u)-wu(c))/1e3,f=Math.round((p-d)/60);let m;if(f<2)return n?.includeSeconds?p<5?a.formatDistance("lessThanXSeconds",5,l):p<10?a.formatDistance("lessThanXSeconds",10,l):p<20?a.formatDistance("lessThanXSeconds",20,l):p<40?a.formatDistance("halfAMinute",0,l):p<60?a.formatDistance("lessThanXMinutes",1,l):a.formatDistance("xMinutes",1,l):f===0?a.formatDistance("lessThanXMinutes",1,l):a.formatDistance("xMinutes",f,l);if(f<45)return a.formatDistance("xMinutes",f,l);if(f<90)return a.formatDistance("aboutXHours",1,l);if(f<fw){const h=Math.round(f/60);return a.formatDistance("aboutXHours",h,l)}else{if(f<i)return a.formatDistance("xDays",1,l);if(f<yc){const h=Math.round(f/fw);return a.formatDistance("xDays",h,l)}else if(f<yc*2)return m=Math.round(f/yc),a.formatDistance("aboutXMonths",m,l)}if(m=tq(u,c),m<12){const h=Math.round(f/yc);return a.formatDistance("xMonths",h,l)}else{const h=m%12,g=Math.trunc(m/12);return h<3?a.formatDistance("aboutXYears",g,l):h<9?a.formatDistance("overXYears",g,l):a.formatDistance("almostXYears",g+1,l)}}function rY(e,t){return nY(e,WW(e),t)}function aY({open:e,onOpenChange:t,workflow:n}){const[r,a]=y.useState([]),[i,o]=y.useState(!1),[l,c]=y.useState("");y.useEffect(()=>{e&&n&&u()},[e,n]);const u=async()=>{if(n){o(!0);try{const f=await $r.getExecutions(n.id);a(f)}catch(f){console.error("Failed to load executions:",f)}finally{o(!1)}}},p=f=>{switch(f){case"completed":return s.jsxs(zt,{className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",children:[s.jsx(jS,{className:"h-3 w-3 mr-1"})," Completed"]});case"failed":return s.jsxs(zt,{className:"bg-red-500/10 text-red-400 border-red-500/20",children:[s.jsx(RC,{className:"h-3 w-3 mr-1"})," Failed"]});case"running":return s.jsxs(zt,{className:"bg-blue-500/10 text-blue-400 border-blue-500/20",children:[s.jsx(Ta,{className:"h-3 w-3 mr-1 animate-pulse"})," Running"]});default:return s.jsx(zt,{className:"bg-zinc-500/10 text-zinc-400 border-zinc-500/20",children:f})}},d=r.filter(f=>f.id.toLowerCase().includes(l.toLowerCase())||f.alertName&&f.alertName.toLowerCase().includes(l.toLowerCase())||f.errorMessage&&f.errorMessage.toLowerCase().includes(l.toLowerCase()));return s.jsx(kt,{open:e,onOpenChange:t,children:s.jsxs(It,{className:"w-[90vw] max-w-6xl max-h-[85vh] flex flex-col p-0",children:[s.jsxs(jt,{className:"p-6 pb-4 border-b bg-muted/30",children:[s.jsxs(Mt,{className:"text-2xl font-bold flex items-center gap-2",children:[s.jsx(Ta,{className:"h-6 w-6 text-primary"}),"Execution History: ",n?.name]}),s.jsx(Kt,{children:"View recent triggers and action outcomes for this workflow."})]}),s.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col p-6 gap-4",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{placeholder:"Search by alert name or error message...",value:l,onChange:f=>c(f.target.value),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto border rounded-xl bg-muted/10",children:s.jsxs(Oa,{children:[s.jsx(La,{className:"bg-muted/50 sticky top-0 z-10 backdrop-blur-sm",children:s.jsxs(Ft,{className:"hover:bg-transparent",children:[s.jsx(gn,{children:"Triggered At"}),s.jsx(gn,{children:"Alert Name"}),s.jsx(gn,{children:"Status"}),s.jsx(gn,{children:"Actions Executed"})]})}),s.jsx(ja,{children:i?s.jsx(Ft,{children:s.jsx(Pt,{colSpan:4,className:"h-24 text-center text-muted-foreground",children:"Loading execution history..."})}):d.length===0?s.jsx(Ft,{children:s.jsx(Pt,{colSpan:4,className:"h-24 text-center text-muted-foreground",children:"No executions found."})}):d.map(f=>s.jsxs(Ft,{children:[s.jsxs(Pt,{className:"font-medium",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rs,{className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{children:eY(new Date(f.triggeredAt),"MMM d, HH:mm:ss")})]}),s.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:rY(new Date(f.triggeredAt),{addSuffix:!0})})]}),s.jsx(Pt,{children:s.jsx("div",{className:"font-medium max-w-[260px] truncate",title:f.alertName||"Unknown Alert",children:f.alertName||"Unknown Alert"})}),s.jsx(Pt,{children:p(f.status)}),s.jsx(Pt,{children:s.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.actionsExecuted&&f.actionsExecuted.length>0?f.actionsExecuted.map((m,h)=>s.jsxs(zt,{variant:"outline",className:`text-[10px] py-0 px-2 flex items-center gap-1 ${m.status==="success"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":m.status==="skipped"?"bg-muted text-muted-foreground":"bg-red-500/10 text-red-600 border-red-500/20"}`,title:m.error||m.type,children:[m.type.replace("_"," "),m.status==="success"?s.jsx(jS,{className:"h-2.5 w-2.5"}):m.status==="skipped"?s.jsx("span",{className:"text-[9px]",children:"Skip"}):s.jsx(bs,{className:"h-2.5 w-2.5"})]},h)):s.jsx("span",{className:"text-muted-foreground text-xs italic",children:"None"})})})]},f.id))})]})})]})]})})}function sY(e){const t=e.toLowerCase(),n=[];return t.includes("critical")&&n.push("critical"),t.includes("high")&&n.push("high"),t.includes("medium")&&n.push("medium"),t.includes("cloudwatch")&&n.push("cloudwatch"),t.includes("prometheus")&&n.push("prometheus"),t.includes("datadog")&&n.push("datadog"),n.length===0&&n.push("low","info","any"),n.slice(0,4)}function iY(e){const t=e.toLowerCase(),n=[];return t.includes("incident")&&n.push("INC"),t.includes("notify")&&n.push("NTF"),t.includes("sop")&&n.push("SOP"),n.length?n:["INC","NTF"]}function oY(e){if(!e)return"Never";const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"Never";const n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)} minutes ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lY({embedded:e=!1,basePath:t="/workflows",sourceId:n}={}){const[r,a]=y.useState([]),[i,o]=y.useState(!0),[l,c]=y.useState(""),[u,p]=y.useState(""),[d,f]=y.useState(""),[m,h]=y.useState(!1),[g,b]=y.useState(),[x,S]=y.useState(),[T,N]=y.useState(!1),A=St(),C=async()=>{try{o(!0),a(await $r.listWorkflows(n))}catch(R){ae.error(R.message||"Failed to load workflows")}finally{o(!1)}};y.useEffect(()=>{C()},[n]);const k=y.useMemo(()=>r.filter(R=>{const j=`${R.name} ${R.yamlDefinition}`.toLowerCase();return!(l&&!j.includes(l.toLowerCase())||u==="active"&&!R.isActive||u==="disabled"&&R.isActive||d&&!R.yamlDefinition.toLowerCase().includes(d))}),[r,l,u,d]),O=async R=>{try{await $r.toggleActive(R.id,!R.isActive),ae.success(`Workflow ${R.isActive?"disabled":"enabled"}`),C()}catch(j){ae.error(j.message||"Failed to toggle workflow")}},M=async()=>{if(x){N(!0);try{await $r.deleteWorkflow(x.id),ae.success("Workflow deleted"),S(void 0),C()}catch(R){ae.error(R.message||"Failed to delete workflow")}finally{N(!1)}}};return s.jsxs("div",{className:e?"im-settings-tab-panel":"im-page im-narrow-page",children:[s.jsxs("div",{className:"im-page-header",children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Workflows"}),s.jsx("p",{children:"Rules that control how alerts become incidents"})]}),s.jsxs(ie,{onClick:()=>A({to:`${t}/new${n?`?sourceId=${n}`:""}`}),className:"im-primary-button",children:[s.jsx(Wr,{className:"h-4 w-4"}),"New workflow"]})]}),s.jsxs("div",{className:"im-filters-bar",children:[s.jsx("div",{className:"im-search-wrap",children:s.jsx("input",{className:"im-search-input",value:l,onChange:R=>c(R.target.value),placeholder:"Search workflows..."})}),s.jsx(Bn,{label:"Select status",value:u,onValueChange:p,options:[{label:"All statuses",value:""},{label:"Active",value:"active"},{label:"Disabled",value:"disabled"}]}),s.jsx(Bn,{label:"Select source",value:d,onValueChange:f,options:[{label:"All sources",value:""},{label:"CloudWatch",value:"cloudwatch"},{label:"Prometheus",value:"prometheus"}]})]}),s.jsx("div",{className:"im-table-card im-html-table-card",children:s.jsxs("table",{className:"im-html-table im-workflow-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Triggers"}),s.jsx("th",{children:"Actions"}),s.jsx("th",{children:"Last matched"}),s.jsx("th",{children:"Todaymodified"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:i?s.jsx("tr",{children:s.jsx("td",{colSpan:7,className:"im-empty-cell",children:"Loading workflows..."})}):k.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:7,className:"im-empty-cell",children:"No workflows found."})}):k.map((R,j)=>{const U=!R.isActive&&j===2;return s.jsxs("tr",{onClick:()=>A({to:`${t}/${R.id}/edit`}),children:[s.jsx("td",{children:U?s.jsx("span",{className:"im-draft-pill",children:"Draft"}):s.jsx("button",{type:"button",className:`im-toggle ${R.isActive?"is-on":""}`,onClick:G=>{G.stopPropagation(),O(R)},"aria-label":"Toggle workflow"})}),s.jsx("td",{className:"im-workflow-name",children:R.name}),s.jsx("td",{children:sY(R.yamlDefinition).map(G=>s.jsx("span",{className:"im-tag",children:G},G))}),s.jsx("td",{children:iY(R.yamlDefinition).map(G=>s.jsx("span",{className:`im-action-tag im-action-${G.toLowerCase()}`,children:G},G))}),s.jsx("td",{children:j<2?`${j===0?"3":"18"} minutes ago`:"Never"}),s.jsxs("td",{children:[s.jsx("strong",{children:j===0?"122":j===1?"41":"03"}),s.jsx("span",{className:"im-inline-age",children:oY(R.updatedAt)})]}),s.jsx("td",{children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx("button",{className:"im-icon-button",type:"button",onClick:G=>G.stopPropagation(),"aria-label":"Workflow actions",children:s.jsx(hs,{size:16})})}),s.jsxs(Lr,{align:"end",onClick:G=>G.stopPropagation(),children:[s.jsx(Lt,{onSelect:()=>A({to:`${t}/${R.id}/edit${n?`?sourceId=${n}`:""}`}),children:"Edit"}),s.jsx(Lt,{onSelect:()=>{setTimeout(()=>{b(R),h(!0)},0)},children:"History"}),s.jsx(Lt,{onSelect:G=>{G.preventDefault(),O(R)},children:R.isActive?"Disable":"Enable"}),s.jsx(Lt,{className:"text-destructive focus:text-destructive",onSelect:()=>setTimeout(()=>S(R),0),children:"Delete"})]})]})})]},R.id)})})]})}),s.jsx(aY,{open:m,onOpenChange:h,workflow:g}),s.jsx(Od,{open:!!x,onOpenChange:R=>!R&&S(void 0),children:s.jsxs(Ld,{children:[s.jsxs(jd,{children:[s.jsx(Pd,{children:"Delete workflow?"}),s.jsxs(Fd,{children:["This will permanently delete ",s.jsx("strong",{children:x?.name}),"."]})]}),s.jsxs(Md,{children:[s.jsx(Ud,{children:"Cancel"}),s.jsx(Bd,{onClick:()=>{M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function cY({sourceId:e}){const t=St(),[n,r]=w.useState("overview"),[a,i]=w.useState(null),[o,l]=w.useState([]),[c,u]=w.useState([]),[p,d]=w.useState(""),[f,m]=w.useState(null),[h,g]=w.useState(!1),[b,x]=w.useState(null),[S,T]=w.useState(null),[N,A]=w.useState(null),[C,k]=w.useState(null),[O,M]=w.useState(null),[R,j]=w.useState(!0),[U,G]=w.useState(!1),[q,P]=w.useState(!1),[z,re]=w.useState(!1),B=w.useCallback(async()=>{const D=await Ie.getSourceOverview(e);i({source:D.source,summary:D.summary})},[e]);w.useEffect(()=>{j(!0),B().catch(()=>ae.error("Failed to load source")).finally(()=>j(!1))},[B]),w.useEffect(()=>{if(!a)return;const D=`insightSourceInitialTab:${e}`,se=window.sessionStorage.getItem(D);se==="setup"&&!cw(a.source)&&r("setup"),se&&window.sessionStorage.removeItem(D)},[e,a]),w.useEffect(()=>{n==="alarms"&&Ie.listSourceAlarms(e,{page:1,limit:20}).then(D=>l(D.alarms||[])).catch(()=>ae.error("Failed to load source alarms"))},[n,e]),w.useEffect(()=>{if(n!=="logs")return;const D=setTimeout(()=>{Ie.listSourceLogs(e,{page:1,limit:20,search:p||void 0}).then(se=>u(se.logs||[])).catch(()=>ae.error("Failed to load source logs"))},200);return()=>clearTimeout(D)},[n,e,p]),w.useEffect(()=>{if(n!=="setup"||!a)return;const D=a.source,se=ws(D.type);g(!0);const Q=D.id.slice(0,8);(se==="cloudwatch"?Ie.getCloudWatchConsoleDeploy(D.id,{region:D.awsRegion||"ap-south-1",stackName:D.awsStackName||`meyi-cloudwatch-${Q}`,lambdaName:D.awsLambdaName||`meyi-cloudwatch-forwarder-${Q}`}).then(x):se==="cloudtrail"?Ie.getCloudTrailConsoleDeploy(D.id,{region:D.awsRegion||"ap-south-1",stackName:D.awsStackName||`meyi-cloudtrail-${Q}`,createNewTrail:D.awsCreateNewTrail!==!1}).then(T):se==="grafana"?Ie.getGrafanaOnboarding(D.id).then(A):se==="prometheus"?Ie.getPrometheusOnboarding(D.id).then(k):se==="datadog"?Ie.getDatadogOnboarding(D.id).then(M):Promise.resolve()).catch(K=>ae.error(K?.response?.data?.error||"Failed to load setup details")).finally(()=>g(!1))},[n,a]);async function H(D){G(!0);try{await Ie.updateSource(e,D),await B(),ae.success("Source updated")}catch(se){ae.error(se?.response?.data?.error||"Failed to update source")}finally{G(!1)}}async function I(){if(a){re(!0);try{await Ie.updateSource(e,{isActive:!a.source.isActive}),await B(),ae.success(a.source.isActive?"Source disabled":"Source enabled")}catch(D){ae.error(D?.response?.data?.error||"Failed to update source")}finally{re(!1)}}}async function V(){P(!0);try{const D=await Ie.testSource(e);m(D),r("test"),ae.success("Source test completed")}catch(D){ae.error(D?.response?.data?.error||"Source test failed")}finally{P(!1)}}if(R)return s.jsx("div",{className:"im-page im-source-detail-page im-center-panel",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin"})});if(!a)return s.jsx("div",{className:"im-page im-source-detail-page im-empty-panel",children:"Source not found."});const Z=!cw(a.source);return s.jsxs("div",{className:"im-page im-source-detail-page",children:[s.jsx(aW,{source:a.source,disabling:z,testing:q,onBack:()=>{window.history.length>1?window.history.back():t({to:"/sources"})},onToggleActive:I,onTest:V}),s.jsx(sW,{activeTab:n,showSetup:Z,onChange:r}),n==="overview"&&s.jsx(oW,{overview:a}),n==="alarms"&&s.jsx(nW,{alarms:o}),n==="configuration"&&s.jsx(rW,{source:a.source,saving:U,onSave:H}),n==="logs"&&s.jsx(iW,{logs:c,search:p,onSearchChange:d}),n==="setup"&&s.jsx(lW,{source:a.source,loading:h,cloudWatch:b,cloudTrail:S,grafana:N,prometheus:C,datadog:O}),n==="test"&&s.jsx(uW,{result:f,running:q,onRun:V}),n==="normalization"&&s.jsx(PW,{sourceId:e}),n==="dedup"&&s.jsx(BW,{sourceId:e}),n==="grouping"&&s.jsx($W,{sourceId:e}),n==="workflows"&&s.jsx(lY,{sourceId:e})]})}function DI({alert:e,open:t,onConfirm:n,onCancel:r,converting:a}){return s.jsx(kt,{open:t,onOpenChange:i=>!i&&r(),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2",children:[s.jsx($h,{className:"h-5 w-5 text-primary"}),"Convert Alert to Incident"]}),s.jsx(Kt,{children:"This will create a new incident from the alert and run AI-powered RCA analysis on it."})]}),e&&s.jsxs("div",{className:"rounded-lg bg-muted/50 border p-3 space-y-2 text-sm",children:[s.jsxs("div",{className:"text-muted-foreground",children:["Are you sure you want to convert ",s.jsxs("strong",{className:"text-foreground font-semibold",children:['"',e.alertName,'"']})," to an incident? This will trigger AI-powered root cause analysis and notify assigned responders."]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-muted-foreground",children:"Resource"}),s.jsx("span",{className:"font-medium truncate",children:e.resourceName})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-muted-foreground",children:"Type"}),s.jsx("span",{children:e.resourceType})]}),e.tags&&Object.keys(e.tags).length>0&&s.jsxs("div",{className:"flex items-center gap-1.5 mt-2 flex-wrap",children:[s.jsx(ed,{size:12,className:"text-muted-foreground shrink-0"}),Object.entries(e.tags).map(([i,o])=>s.jsxs("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:[i,":",o]},i))]})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:r,disabled:a,children:"Cancel"}),s.jsx(ie,{onClick:n,disabled:a,children:a?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin"})," Converting…"]}):"Convert to Incident"})]})]})})}function OI({open:e,onConfirm:t,onCancel:n,deleting:r}){return s.jsx(kt,{open:e,onOpenChange:a=>!a&&!r&&n(),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Delete alert?"}),s.jsx(Kt,{children:"This will permanently delete this alert. It will no longer be visible in the alerts list."})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:n,disabled:r,children:"Cancel"}),s.jsx(ie,{variant:"destructive",onClick:t,disabled:r,children:r?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Deleting…"]}):"Delete"})]})]})})}function LI({open:e,alert:t,submitting:n,onClose:r,onSubmit:a}){const[i,o]=w.useState(""),[l,c]=w.useState(""),[u,p]=w.useState(""),[d,f]=w.useState("");w.useEffect(()=>{if(e&&t){o(t.alertName||""),c(t.description||""),p(t.severity||"");const g=t.tags||{};f(Object.entries(g).map(([b,x])=>`${b}: ${x}`).join(", "))}},[e,t]);const m=g=>{const b={};if(!g.trim())return b;if(g.trim().startsWith("{"))try{const x=JSON.parse(g);if(typeof x=="object"&&x!==null){for(const[S,T]of Object.entries(x))b[S]=String(T);return b}}catch{}return g.split(",").forEach(x=>{const S=x.includes(":")?x.split(":"):x.split("=");if(S.length>=2){const T=S[0].trim(),N=S.slice(1).join(":").trim();T&&(b[T]=N)}}),b},h=g=>{if(g.preventDefault(),!i.trim()){ae.error("Name is required");return}a({alertName:i.trim(),description:l.trim()||void 0,severity:u.trim()||void 0,tags:m(d)})};return s.jsx(kt,{open:e,onOpenChange:g=>!g&&!n&&r(),children:s.jsxs(It,{className:"max-w-md",children:[s.jsx(jt,{children:s.jsx(Mt,{children:"Edit Alert"})}),s.jsxs("form",{id:"alert-form",onSubmit:h,className:"flex flex-col gap-4 mt-2",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Pe,{children:["Title ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(Xe,{id:"alert-name",value:i,onChange:g=>o(g.target.value),placeholder:"e.g. CPU Spike on API Server",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Description"}),s.jsx(Xe,{value:l,onChange:g=>c(g.target.value),placeholder:"Description",disabled:n})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Severity"}),s.jsx(Bn,{label:"Select severity",className:"im-single-select-full",value:u,onValueChange:p,disabled:n,options:[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{children:"Tags"}),s.jsx(Xe,{value:d,onChange:g=>f(g.target.value),placeholder:"project: meyiconnect, env: dev",disabled:n,className:"font-mono text-xs"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Format: key: value, key: value"})]})]}),s.jsxs($t,{children:[s.jsx(ie,{type:"button",variant:"outline",onClick:r,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",form:"alert-form",disabled:n||!i.trim(),children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Changes"})]})]})]})})}function uY({search:e,onSearchChange:t,severityFilter:n,onSeverityChange:r,sourceFilter:a,onSourceChange:i,sources:o,loading:l,onRefresh:c,children:u}){const[p,d]=w.useState([]),[f,m]=w.useState(["1h"]),h=o.map(S=>({label:S.name,value:S.id})),g=[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}],b=[{label:"normalised",value:"normalised"},{label:"suppressed",value:"suppressed"}],x=[{label:"Last 1 hour",value:"1h"},{label:"Last 24 hours",value:"24h"},{label:"Last 7 days",value:"7d"}];return s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(gs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{placeholder:"Search name, resource, metric, fingerprint...",value:e,onChange:S=>t(S.target.value),className:"h-9 w-[150px] lg:w-[250px] pl-8"}),e&&s.jsxs(ie,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground",onClick:()=>t(""),children:[s.jsx(Hn,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Clear"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Severity",options:g,selected:n,onChange:r}),s.jsx(Qn,{title:"Result",options:b,selected:p,onChange:d}),s.jsx(Qn,{title:"Time Range",options:x,selected:f,onChange:m}),s.jsx(Qn,{title:"Source",options:h,selected:a,onChange:i})]})]}),(c||u)&&s.jsxs("div",{className:"flex items-center gap-2",children:[c&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:c,disabled:l,className:"h-8 hidden lg:flex",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",l&&"animate-spin")}),"Refresh"]}),u]})]})}function Ew(e){if(!e)return"-";const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0"),a=t.getSeconds().toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),o=(t.getMonth()+1).toString().padStart(2,"0"),l=t.getFullYear();return`${i}/${o}/${l} ${n}:${r}:${a}`}const dY=e=>[{accessorKey:"alertName",header:({column:t})=>s.jsx(dt,{column:t,title:"Name"}),cell:({row:t})=>{const n=t.getValue("alertName");return s.jsx("div",{className:"max-w-[280px] truncate font-medium text-sm",title:n,children:n})}},{accessorKey:"sourceName",header:({column:t})=>s.jsx(dt,{column:t,title:"Source"}),cell:({row:t})=>{const n=t.getValue("sourceName")||"—";return s.jsx("div",{className:"max-w-[140px] truncate text-muted-foreground",title:n,children:n})}},{accessorKey:"resourceName",header:({column:t})=>s.jsx(dt,{column:t,title:"Resource"}),cell:({row:t})=>{const n=t.getValue("resourceName")||"—";return s.jsx("div",{className:"max-w-[180px] truncate",title:n,children:n})}},{accessorKey:"accountId",header:({column:t})=>s.jsx(dt,{column:t,title:"Account ID"}),cell:({row:t})=>{const n=t.original.accountId||t.original.additionalConfiguration?.accountId||"—";return s.jsx("div",{className:"max-w-[140px] truncate font-mono text-xs text-muted-foreground",title:n,children:n})}},{id:"groupName",header:({column:t})=>s.jsx(dt,{column:t,title:"Group"}),cell:({row:t})=>{const r=t.original.additionalConfiguration?.groupName||"—";return s.jsx("div",{className:"max-w-[140px] truncate text-muted-foreground",title:r,children:r})}},{id:"tags",header:({column:t})=>s.jsx(dt,{column:t,title:"Tags"}),cell:({row:t})=>{const n=t.original.tags||{},r=Object.entries(n);return r.length===0?s.jsx("span",{className:"text-muted-foreground",children:"—"}):s.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[200px]",children:[r.slice(0,2).map(([a,i])=>s.jsxs("span",{className:"text-[11px] bg-muted px-1.5 py-0.5 rounded font-mono truncate",children:[a,":",i]},a)),r.length>2&&s.jsxs("span",{className:"text-[10px] text-muted-foreground self-center",children:["+",r.length-2]})]})}},{accessorKey:"severity",header:({column:t})=>s.jsx(dt,{column:t,title:"Severity"}),cell:({row:t})=>{const n=t.getValue("severity"),a={critical:"bg-red-500/15 text-red-500 border-red-500/30",high:"bg-orange-500/15 text-orange-500 border-orange-500/30",medium:"bg-amber-500/15 text-amber-500 border-amber-500/30",low:"bg-sky-500/15 text-sky-500 border-sky-500/30"}[n]||"";return s.jsx(zt,{variant:"outline",className:`capitalize text-[11px] ${a}`,children:n})}},{id:"downTime",header:({column:t})=>s.jsx(dt,{column:t,title:"Down Time"}),cell:({row:t})=>{const n=t.original.downTime;return s.jsx("div",{className:"text-muted-foreground tabular-nums",children:Ew(n)})}},{accessorKey:"createdAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Created At"}),cell:({row:t})=>s.jsx("div",{className:"text-muted-foreground tabular-nums",children:Ew(t.getValue("createdAt"))})},{id:"actions",cell:({row:t})=>{const n=t.original;return s.jsx("div",{onClick:r=>r.stopPropagation(),children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsxs(ie,{variant:"ghost",className:"h-8 w-8 p-0",children:[s.jsx("span",{className:"sr-only",children:"Open menu"}),s.jsx(hs,{className:"h-4 w-4"})]})}),s.jsxs(Lr,{align:"end",children:[s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onEdit(n)},children:[s.jsx(Ju,{className:"h-4 w-4 mr-2"})," Edit"]}),n.status==="open"&&s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onConvert(n)},children:[s.jsx($h,{className:"h-4 w-4 mr-2"})," Convert to Incident"]}),n.incidentId&&s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onViewIncident(n.incidentId)},children:[s.jsx(DC,{className:"h-4 w-4 mr-2"})," View Incident"]}),e.sopsByAlertName?.[n.alertName]?s.jsx(Lt,{asChild:!0,children:s.jsxs(Ei,{to:`/sops/${e.sopsByAlertName[n.alertName]}`,className:"w-full flex items-center cursor-pointer",onClick:r=>r.stopPropagation(),children:[s.jsx(di,{className:"h-4 w-4 mr-2"}),"View SOP"]})}):e.onGenerateSop?s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onGenerateSop(n)},disabled:e.generatingSopId===n.id,children:[e.generatingSopId===n.id?s.jsx(Qe,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(ol,{className:"h-4 w-4 mr-2"}),"Generate SOP"]}):null,s.jsx(Ci,{}),s.jsxs(Lt,{onClick:r=>{r.stopPropagation(),e.onDelete(n.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(ll,{className:"h-4 w-4 mr-2"})," Delete"]})]})]})})}}];function pY({data:e,total:t,page:n,limit:r,loading:a,onPageChange:i,onLimitChange:o,onViewIncident:l,onViewAlert:c,onEdit:u,onDelete:p,onConvert:d,onGenerateSop:f,generatingSopId:m,sopsByAlertName:h,renderFilters:g}){const[b,x]=w.useState({}),[S,T]=w.useState([]),N=w.useMemo(()=>dY({onEdit:u,onDelete:p,onConvert:d,onGenerateSop:f,generatingSopId:m,sopsByAlertName:h,onViewIncident:l,onViewAlert:c}),[u,p,d,f,m,h,l,c]),A=Math.max(1,Math.ceil(t/r)),C=w.useMemo(()=>[],[]),k=gl({data:e,columns:N,state:{pagination:{pageIndex:n-1,pageSize:r},columnVisibility:b,columnFilters:C,sorting:S},pageCount:A,manualPagination:!0,manualFiltering:!0,onSortingChange:T,getSortedRowModel:Ad(),onPaginationChange:O=>{const M=typeof O=="function"?O({pageIndex:n-1,pageSize:r}):O;M.pageIndex+1!==n&&i(M.pageIndex+1),M.pageSize!==r&&o(M.pageSize)},onColumnVisibilityChange:x,getCoreRowModel:hl()});return a&&e.length===0?s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[g?.(k),s.jsx(qr,{variant:"table"})]}):s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[g?.(k),s.jsx("div",{className:"rounded-md border overflow-hidden bg-card text-card-foreground",children:s.jsxs(Oa,{children:[s.jsx(La,{children:k.getHeaderGroups().map(O=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:O.headers.map(M=>s.jsx(gn,{children:M.isPlaceholder?null:Rr(M.column.columnDef.header,M.getContext())},M.id))},O.id))}),s.jsx(ja,{children:k.getRowModel().rows?.length?k.getRowModel().rows.map(O=>s.jsx(Ft,{"data-state":O.getIsSelected()&&"selected",className:`group/row hover:bg-muted/30 ${c?"cursor-pointer":""}`,onClick:()=>c?.(O.original.id),children:O.getVisibleCells().map(M=>s.jsx(Pt,{children:Rr(M.column.columnDef.cell,M.getContext())},M.id))},O.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:N.length,className:"h-24 text-center",children:"No alerts found."})})})]})}),s.jsx(bl,{table:k,className:"mt-auto"})]})}const fY={};function mY({onViewIncident:e,onViewAlert:t}){const[n,r]=w.useState([]),[a,i]=w.useState(0),[o,l]=w.useState(!0),[c,u]=w.useState(1),[p,d]=w.useState(10),[f,m]=w.useState(""),[h,g]=w.useState(""),[b,x]=w.useState(""),[S,T]=w.useState(""),[N,A]=w.useState([]),[C,k]=w.useState(null),[O,M]=w.useState(!1),[R,j]=w.useState(null),[U,G]=w.useState(null),[q,P]=w.useState(null),[z,re]=w.useState(!1);w.useEffect(()=>{const Q=setTimeout(()=>{g(f),u(1)},350);return()=>clearTimeout(Q)},[f]);const B=w.useCallback(async(Q=!1)=>{Q||l(!0);try{const ne=await Ie.listAlerts({page:c,limit:p,severity:b||void 0,sourceId:S||void 0,search:h||void 0});r(ne.alerts??[]),i(ne.total??0)}catch{Q||ae.error("Failed to load alerts")}finally{Q||l(!1)}},[c,p,b,S,h]);w.useEffect(()=>{B()},[B]);const H=w.useRef(B);w.useEffect(()=>{H.current=B},[B]),w.useEffect(()=>{Ie.listSources({page:1,limit:200}).then(Q=>A(Q.sources??[])).catch(()=>A([]))},[]);const I=w.useCallback(async()=>{try{await Promise.all([Ie.listAlerts({page:1,limit:1,status:"all",severity:"critical"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"high"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"medium"}),Ie.listAlerts({page:1,limit:1,status:"all",severity:"low"})])}catch{}},[]);w.useEffect(()=>{I();const Q=setInterval(I,3e4);return()=>clearInterval(Q)},[I]);const V=w.useRef(I);w.useEffect(()=>{V.current=I},[I]),w.useEffect(()=>{const Q=fY?.VITE_SOCKET_URL,ne=(Q?Q.replace("/socket.io",""):window.location.origin).replace(/\/+$/,""),K=bo(`${ne}/ws/insight`,{path:"/socket.io",transports:["websocket","polling"],withCredentials:!0}),Y=()=>{Promise.all([H.current(!0),V.current()])};return K.on("insight:alerts:totals",Y),K.on("insight:event",J=>{(J?.topic==="alerts.totals"||J?.topic?.startsWith("alerts."))&&Y()}),K.on("connect",Y),()=>{K.disconnect()}},[]);const Z=async()=>{if(C){M(!0);try{const Q=await Ie.convertAlert(C.id);ae.success("Alert converted to incident"),B(),I(),e(Q.incidentId)}catch(Q){ae.error(Q?.response?.data?.error??"Failed to convert alert")}finally{M(!1),k(null)}}},D=async()=>{if(R){G(R);try{await Ie.deleteAlert(R),ae.success("Alert deleted"),j(null),B(),I()}catch{ae.error("Failed to delete alert")}finally{G(null)}}},se=async Q=>{if(q){re(!0);try{await Ie.updateAlert(q.id,Q),ae.success("Alert updated"),P(null),B(),I()}catch{ae.error("Failed to update alert")}finally{re(!1)}}};return s.jsxs("div",{className:"space-y-6",children:[s.jsx(pY,{data:n,total:a,page:c,limit:p,loading:o,onPageChange:u,onLimitChange:Q=>{d(Q),u(1)},onViewIncident:e,onViewAlert:t,onEdit:Q=>P(Q),onDelete:Q=>j(Q),onConvert:Q=>k(Q),renderFilters:Q=>s.jsxs(s.Fragment,{children:[s.jsx("div",{children:s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Alert search"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Every alert received by the collector across all sources"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ie,{variant:"outline",size:"sm",onClick:()=>B(),disabled:o,className:"h-8",children:[s.jsx(Ra,{className:Fe("h-4 w-4 mr-2",o&&"animate-spin")}),"Refresh"]}),s.jsx(Mg,{table:Q})]})]})}),s.jsx(uY,{search:f,onSearchChange:m,severityFilter:b?[b]:[],onSeverityChange:ne=>{x(ne[0]??""),u(1)},sourceFilter:S?[S]:[],onSourceChange:ne=>{T(ne[0]??""),u(1)},sources:N,loading:o})]})}),s.jsx(DI,{alert:C,open:!!C,onConfirm:Z,onCancel:()=>k(null),converting:O}),s.jsx(OI,{open:!!R,onConfirm:D,onCancel:()=>j(null),deleting:!!U}),s.jsx(LI,{open:!!q,alert:q,submitting:z,onClose:()=>P(null),onSubmit:se})]})}const vw=[{key:"queue",label:"Queued",icon:HF},{key:"normalization",label:"Normalised",icon:PC},{key:"dedup",label:"Dedup",icon:il},{key:"grouping",label:"Grouped",icon:FF},{key:"workflow",label:"Workflow",icon:ei}];function hY(e,t){return e?e.status==="error"?s.jsx(RC,{className:"w-4 h-4 text-destructive"}):e.status==="suppressed"?s.jsx(bs,{className:"w-4 h-4 text-yellow-500"}):e.status==="ok"||e.status==="created"||e.status==="buffering"||e.status==="flushed"||e.status==="completed"?s.jsx(ei,{className:"w-4 h-4 text-emerald-500"}):s.jsx(rs,{className:"w-4 h-4 text-muted-foreground/50"}):s.jsx(rs,{className:"w-4 h-4 text-muted-foreground/40"})}function gY(e){if(!e)return null;const t={ok:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",created:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",error:"bg-red-500/10 text-red-500 border-red-500/20",suppressed:"bg-yellow-500/10 text-yellow-600 border-yellow-500/20",buffering:"bg-blue-500/10 text-blue-500 border-blue-500/20",flushed:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",completed:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",dlq:"bg-red-500/10 text-red-500 border-red-500/20",fallback:"bg-orange-500/10 text-orange-500 border-orange-500/20"}[e.status]??"bg-muted/50 text-muted-foreground border-border";return s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${t}`,children:e.status})}function bY({alarmId:e}){const[t,n]=w.useState([]),[r,a]=w.useState(!0),[i,o]=w.useState(null);if(w.useEffect(()=>{e&&(a(!0),Ie.getPipelineEvents(e).then(u=>{u.ok&&n(u.events)}).catch(u=>o(u.message)).finally(()=>a(!1)))},[e]),r)return s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[s.jsx(Qe,{className:"w-3.5 h-3.5 animate-spin"}),"Loading pipeline lifecycle…"]});if(i)return s.jsxs("div",{className:"text-sm text-muted-foreground py-2",children:["Pipeline events unavailable — ",i]});const l={};for(const u of t)l[u.stage]=u;const c=!!l.dlq;return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Processing Lifecycle"}),c&&s.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded bg-red-500/15 text-red-500 border border-red-500/20 uppercase tracking-wide",children:"DLQ"})]}),s.jsx("div",{className:"flex items-stretch gap-0",children:vw.map((u,p)=>{const d=l[u.key];u.icon;const f=p===vw.length-1;return s.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0 group",children:[s.jsx("div",{className:`
128
128
  relative z-10 flex items-center justify-center w-8 h-8 rounded-full border-2 transition-all
129
129
  ${d?d.status==="error"||d.status==="dlq"?"border-red-500 bg-red-500/10":d.status==="suppressed"?"border-yellow-500 bg-yellow-500/10":"border-emerald-500 bg-emerald-500/10":"border-border bg-muted/30"}
130
130
  `,children:hY(d,u.key)}),!f&&s.jsx("div",{className:"absolute top-4 left-1/2 w-full h-0.5 -z-0 hidden"}),s.jsxs("div",{className:"mt-2 text-center px-1 min-w-0 w-full",children:[s.jsx("p",{className:`text-[11px] font-medium truncate ${d?"text-foreground":"text-muted-foreground/50"}`,children:u.label}),s.jsx("div",{className:"mt-0.5 flex justify-center",children:gY(d)})]})]},u.key)})}),t.filter(u=>u.status==="error"||u.status==="suppressed"||u.status==="dlq").map(u=>s.jsxs("div",{className:"mt-3 p-2.5 rounded-md bg-muted/40 border border-border/50 text-xs text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-foreground capitalize",children:u.stage})," — ",u.meta?.error??u.meta?.reason??u.status]},u.id))]})}const xY=[{id:"overview",label:"Overview"},{id:"timeline",label:"Timeline"},{id:"payload",label:"Raw Payload"}];function jI(e){if(!e)return"—";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function yY({alert:e}){const t=e.severity==="critical"?"P1":e.severity==="high"?"P2":e.severity==="medium"?"P3":"P4",n=e.accountId||e.additionalConfiguration?.accountId,r=e.additionalConfiguration?.tags||e.tags||{},a=r&&typeof r=="object"&&Object.keys(r).length>0;return s.jsxs("div",{className:"im-inc-overview",children:[s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Alert summary"}),e.description&&s.jsxs("div",{className:"mt-4 p-4 border rounded bg-secondary/20",children:[s.jsx("h4",{className:"font-semibold text-sm mb-2 text-primary flex items-center",children:"Short Description"}),s.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed text-muted-foreground",children:e.description})]}),s.jsxs("div",{className:"im-inc-meta-rows",children:[s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Affected resource"}),s.jsxs("span",{className:"im-mono",children:[e.resourceType," · ",e.resourceName]})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Severity"}),s.jsx("span",{children:s.jsx("span",{className:`im-priority-pill im-priority-${t.toLowerCase()}`,children:e.severity.toUpperCase()})})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Source"}),s.jsxs("span",{className:"im-mono",children:[e.sourceName||"—"," (",e.sourceType,")"]})]}),n&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Account ID"}),s.jsx("span",{className:"im-mono font-semibold",children:n})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Received"}),s.jsx("span",{children:new Date(e.createdAt).toLocaleString()})]}),s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Tags"}),a?s.jsx("div",{className:"flex flex-wrap gap-1.5 justify-end",children:Object.entries(r).map(([i,o])=>s.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs bg-secondary text-secondary-foreground font-mono",children:[s.jsxs("span",{className:"text-muted-foreground mr-1",children:[i,":"]})," ",String(o)]},i))}):s.jsx("span",{children:"—"})]}),e.additionalConfiguration?.groupName&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Group Name"}),s.jsx("span",{className:"im-mono",children:e.additionalConfiguration.groupName})]})]})]}),e.additionalConfiguration&&typeof e.additionalConfiguration=="object"&&Object.keys(e.additionalConfiguration).length>0&&s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Extended Context"}),s.jsx("div",{className:"im-inc-meta-rows",children:Object.entries(e.additionalConfiguration).filter(([i,o])=>i!=="groupName"&&i!=="commonLabels"&&i!=="groupLabels"&&i!=="tags"&&i!=="accountId"&&o).map(([i,o])=>s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:i.replace(/([A-Z])/g," $1").trim().replace(/^\w/,l=>l.toUpperCase())}),s.jsx("span",{className:"im-mono",children:String(o)})]},i))})]})]})}function EY({alert:e}){return s.jsxs("div",{className:"im-inc-overview",children:[s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Processing Lifecycle"}),e.pipelineStatus?s.jsx("div",{style:{padding:"16px"},children:s.jsx(bY,{alarmId:e.id})}):s.jsx("div",{className:"im-inc-empty-inline",children:s.jsx("p",{children:"No pipeline lifecycle information available for this alert."})})]}),s.jsxs("div",{className:"im-inc-card",children:[s.jsx("div",{className:"im-inc-card-title",children:"Deduplication stats"}),s.jsxs("div",{className:"im-inc-meta-rows",children:[s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Duplicate occurrences"}),s.jsxs("span",{className:"im-mono",children:[e.dupCount??0," suppressed"]})]}),e.lastDupAt&&s.jsxs("div",{className:"im-inc-meta-row",children:[s.jsx("span",{children:"Last seen duplicate"}),s.jsxs("span",{className:"im-mono",children:[new Date(e.lastDupAt).toLocaleString()," (",jI(e.lastDupAt),")"]})]})]})]})]})}function vY({alert:e}){const t=JSON.stringify(e.rawPayload,null,2),[n,r]=w.useState(!1),a=()=>{navigator.clipboard.writeText(t),r(!0),ae.success("Payload copied to clipboard"),setTimeout(()=>r(!1),2e3)};return s.jsxs("div",{className:"im-inc-card",children:[s.jsxs("div",{className:"im-inc-card-title flex items-center justify-between",children:["Raw JSON Payload",s.jsxs(ie,{variant:"outline",size:"sm",onClick:a,className:"h-7 text-xs",children:[n?s.jsx(Yt,{className:"mr-1.5 h-3 w-3 text-green-500"}):s.jsx(yn,{className:"mr-1.5 h-3 w-3"}),n?"Copied!":"Copy"]})]}),s.jsx("div",{style:{padding:"16px",overflowX:"auto"},children:s.jsx("pre",{className:"text-xs bg-muted p-4 rounded-md font-mono whitespace-pre-wrap break-all max-w-full",children:t})})]})}function SY({alertId:e,onBack:t,onViewIncident:n}){const{isReadOnly:r}=ur(),[a,i]=w.useState(null),[o,l]=w.useState(!0),[c,u]=w.useState(!1),[p,d]=w.useState(!1),[f,m]=w.useState(!1),[h,g]=w.useState(null),[b,x]=w.useState(!1),[S,T]=w.useState(null),[N,A]=w.useState(null),[C,k]=w.useState(null),[O,M]=w.useState(null),[R,j]=w.useState("overview"),U=w.useCallback(async()=>{try{const B=await Ie.getAlert(e);i(B.alert)}catch{ae.error("Failed to load alert details")}finally{l(!1)}},[e]);w.useEffect(()=>{U()},[U]),w.useEffect(()=>{a?.alertName&&Tr.lookupByAlertName(a.alertName).then(B=>{B&&M(B)}).catch(()=>{})},[a?.alertName]);const G=async()=>{if(a){u(!0);try{const B=await Ie.convertAlert(a.id);ae.success("Alert converted to incident"),n(B.incidentId)}catch{ae.error("Failed to convert alert"),u(!1),d(!1)}}},q=async B=>{if(h){x(!0);try{await Ie.updateAlert(h.id,B),ae.success("Alert updated"),g(null),U()}catch{ae.error("Failed to update alert")}finally{x(!1)}}},P=async()=>{if(S){A(S);try{await Ie.deleteAlert(S),ae.success("Alert deleted"),T(null),t()}catch{ae.error("Failed to delete alert")}finally{A(null)}}},z=async()=>{if(a){k(a.id);try{const B=await Tr.create({title:`SOP: ${a.alertName}`,alertType:a.resourceType,service:a.tags?.project||a.tags?.service||void 0,status:"generating",alert_id:a.id,alert_name:a.alertName,source:a.sourceName||"unknown"});ae.success("SOP generation started"),M(B.id)}catch(B){ae.error(B?.response?.data?.error??"Failed to generate SOP")}finally{k(null)}}};if(o)return s.jsxs("div",{className:"flex h-[50vh] items-center justify-center text-muted-foreground",children:[s.jsx(Qe,{className:"h-6 w-6 animate-spin mr-2"})," Loading alert…"]});if(!a)return s.jsxs("div",{className:"flex flex-col items-center justify-center h-[50vh] text-center space-y-4",children:[s.jsx("div",{className:"rounded-full bg-muted p-4",children:s.jsx(bs,{className:"h-8 w-8 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-lg font-medium",children:"Alert Not Found"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"This alert may have been deleted."})]}),s.jsx(ie,{variant:"outline",onClick:t,children:"Go Back"})]});const re=a.aliasId?`ALT-${String(a.aliasId).padStart(4,"0")}`:"Alert";return s.jsxs("div",{className:"im-inc-detail -m-4",children:[s.jsxs("div",{className:"im-inc-header",children:[s.jsxs("div",{className:"im-inc-header-row1",children:[s.jsx("button",{className:"im-back-button",type:"button",onClick:t,"aria-label":"Back",children:s.jsx(Vr,{size:16})}),s.jsx("span",{className:"im-inc-id im-mono",children:re}),s.jsx("h1",{className:"im-inc-title",children:a.alertName}),s.jsx("span",{className:`im-priority-pill im-priority-${a.severity==="critical"?"p1":a.severity==="high"?"p2":a.severity==="medium"?"p3":"p4"}`,children:a.severity.toUpperCase()})]}),s.jsxs("div",{className:"im-inc-header-row2",children:[s.jsxs("span",{className:"im-inc-time",children:[s.jsx(rs,{size:13})," received ",jI(a.createdAt)]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsxs("span",{className:"im-inc-resource im-mono",children:[a.resourceType," · ",a.resourceName]}),s.jsx("span",{className:"im-inc-sep",children:"·"}),s.jsx("span",{children:a.sourceName||a.sourceType})]}),s.jsxs("div",{className:"im-inc-actions",children:[a.incidentId?s.jsxs(ie,{size:"sm",onClick:()=>n(a.incidentId),children:[s.jsx(DC,{size:13,className:"mr-1"})," View Incident"]}):!r&&a.status==="open"?s.jsxs(ie,{size:"sm",onClick:()=>d(!0),disabled:c||f,children:[s.jsx($h,{size:13,className:"mr-1"})," Convert"]}):null,!r&&s.jsxs(s.Fragment,{children:[s.jsxs(ie,{size:"sm",variant:"outline",onClick:z,disabled:C===a.id||!!O,children:[C===a.id?s.jsx(Qe,{size:13,className:"mr-1 animate-spin"}):s.jsx(ol,{size:13,className:"mr-1"}),O?"SOP Generated":"Generate SOP"]}),s.jsxs(ie,{size:"sm",variant:"outline",onClick:()=>g(a),children:[s.jsx(Zu,{size:13,className:"mr-1"})," Edit"]}),s.jsxs(ie,{size:"sm",variant:"outline",style:{borderColor:"var(--im-error)",color:"var(--im-error)"},onClick:()=>T(a.id),children:[s.jsx(ll,{size:13,className:"mr-1"})," Delete"]})]})]})]}),s.jsx("div",{className:"im-inc-body",children:s.jsxs("div",{className:"im-inc-main",style:{flex:1,minWidth:0},children:[s.jsx("div",{className:"im-inc-tabs",children:xY.map(({id:B,label:H})=>s.jsx("button",{type:"button",className:R===B?"is-active":"",onClick:()=>j(B),children:H},B))}),s.jsxs("div",{className:"im-inc-tab-content",children:[R==="overview"&&s.jsx(yY,{alert:a}),R==="timeline"&&s.jsx(EY,{alert:a}),R==="payload"&&s.jsx(vY,{alert:a})]})]})}),s.jsx(DI,{open:p,alert:a,converting:c,onCancel:()=>d(!1),onConfirm:G}),s.jsx(LI,{alert:h,open:!!h,onClose:()=>g(null),onSubmit:q,submitting:b}),s.jsx(OI,{open:!!S,onCancel:()=>T(null),onConfirm:P,deleting:N===S})]})}function wY(e){const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}const TY={critical:"bg-red-500/15 text-red-500 border-red-500/30",high:"bg-orange-500/15 text-orange-500 border-orange-500/30",medium:"bg-yellow-500/15 text-yellow-600 border-yellow-500/30",low:"bg-green-500/15 text-green-600 border-green-500/30"},NY={approved:"bg-green-500/15 text-green-600 border-green-500/30",pending:"bg-yellow-500/15 text-yellow-600 border-yellow-500/30",draft:"bg-muted text-muted-foreground border-border"};function CY({sop:e,onEdit:t,onDelete:n,onView:r}){const{isReadOnly:a}=ur();return s.jsxs(On,{className:"hover:border-primary/30 transition-colors flex flex-col h-full group",children:[s.jsxs(NA,{className:"pb-2 flex flex-row items-start justify-between space-y-0",children:[s.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary cursor-pointer",onClick:()=>r(e),children:s.jsx(di,{size:18})}),!a&&s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx(ie,{variant:"ghost",size:"icon",className:"h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(_F,{className:"h-4 w-4"})})}),s.jsxs(Lr,{align:"end",children:[s.jsxs(Lt,{onClick:()=>r(e),children:[s.jsx(di,{className:"h-4 w-4 mr-2"})," View"]}),s.jsxs(Lt,{onClick:()=>t(e),children:[s.jsx(Ju,{className:"h-4 w-4 mr-2"})," Edit"]}),s.jsx(Ci,{}),s.jsxs(Lt,{onClick:()=>n(e),className:"text-destructive focus:text-destructive",children:[s.jsx(R4,{className:"h-4 w-4 mr-2"})," Delete"]})]})]})]}),s.jsxs(Ln,{className:"flex-1 flex flex-col gap-3 pt-1",children:[s.jsxs("div",{children:[s.jsx("button",{onClick:()=>r(e),className:"font-semibold text-sm text-card-foreground hover:text-primary transition-colors leading-snug text-left",children:e.title}),s.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:e.sopId})]}),e.description&&s.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:e.description}),s.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-auto",children:[e.severity&&s.jsxs(zt,{variant:"outline",className:`text-[10px] px-1.5 py-0 capitalize ${TY[e.severity]??""}`,children:["• ",e.severity]}),s.jsx(zt,{variant:"outline",className:`text-[10px] px-1.5 py-0 capitalize ${NY[e.status]??""}`,children:e.status})]}),s.jsxs("div",{className:"text-xs flex flex-col gap-1.5 border-t pt-2 mt-1",children:[e.alertType&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(ed,{className:"h-3 w-3 shrink-0"}),s.jsx("span",{className:"truncate",children:e.alertType})]}),e.service&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(zh,{className:"h-3 w-3 shrink-0"}),s.jsx("span",{className:"truncate",children:e.service})]}),s.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Vh,{className:"h-3 w-3"}),e.createdBy??"Manual"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(rs,{className:"h-3 w-3"}),wY(e.updatedAt)]})]})]})]})]})}function Sw(e){if(!e)return"-";const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0"),a=t.getSeconds().toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),o=(t.getMonth()+1).toString().padStart(2,"0"),l=t.getFullYear();return`${i}/${o}/${l} ${n}:${r}:${a}`}const AY={critical:"bg-red-500/15 text-red-500 border-red-500/30",high:"bg-orange-500/15 text-orange-500 border-orange-500/30",medium:"bg-yellow-500/15 text-yellow-600 border-yellow-500/30",low:"bg-green-500/15 text-green-600 border-green-500/30"},_Y=e=>[{accessorKey:"sopId",header:({column:t})=>s.jsx(dt,{column:t,title:"ID"}),cell:({row:t})=>s.jsx("div",{className:"font-medium text-xs text-muted-foreground",children:t.getValue("sopId")})},{accessorKey:"title",header:({column:t})=>s.jsx(dt,{column:t,title:"Name"}),cell:({row:t})=>{const n=t.getValue("title");return s.jsx("div",{className:"max-w-[220px] truncate font-medium text-sm",title:n,children:n})}},{accessorKey:"alertType",header:({column:t})=>s.jsx(dt,{column:t,title:"Alert Type"}),cell:({row:t})=>{const n=t.getValue("alertType");return n?s.jsx("span",{className:"max-w-[180px] truncate block text-sm underline-offset-2 hover:underline",title:n,children:n}):s.jsx("span",{className:"text-muted-foreground",children:"—"})}},{accessorKey:"severity",header:({column:t})=>s.jsx(dt,{column:t,title:"Severity"}),cell:({row:t})=>{const n=t.getValue("severity");return n?s.jsxs(zt,{variant:"outline",className:`text-[11px] capitalize ${AY[n]??""}`,children:["• ",n]}):s.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}},{accessorKey:"updatedAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Updated At"}),cell:({row:t})=>s.jsx("div",{className:"text-sm text-muted-foreground whitespace-nowrap tabular-nums",children:Sw(t.getValue("updatedAt"))})},{accessorKey:"createdAt",header:({column:t})=>s.jsx(dt,{column:t,title:"Created At"}),cell:({row:t})=>s.jsx("div",{className:"text-sm text-muted-foreground whitespace-nowrap tabular-nums",children:Sw(t.getValue("createdAt"))})},{id:"actions",cell:({row:t})=>{const n=t.original;return s.jsx("div",{onClick:r=>r.stopPropagation(),children:s.jsxs(Or,{children:[s.jsx(ea,{asChild:!0,children:s.jsx(ie,{variant:"ghost",size:"icon",className:"h-7 w-7",children:s.jsx(hs,{className:"h-4 w-4"})})}),s.jsxs(Lr,{align:"end",children:[s.jsxs(Lt,{onClick:()=>e.onEdit(n),children:[s.jsx(Ju,{className:"h-4 w-4 mr-2"})," Edit"]}),s.jsx(Ci,{}),s.jsxs(Lt,{onClick:()=>e.onDelete(n),className:"text-destructive focus:text-destructive",children:[s.jsx(ll,{className:"h-4 w-4 mr-2"})," Delete"]})]})]})})}}];function RY({data:e,total:t,page:n,limit:r,loading:a,onPageChange:i,onLimitChange:o,onView:l,onEdit:c,onDelete:u,renderFilters:p}){const[d,f]=w.useState({}),m=w.useMemo(()=>_Y({onEdit:c,onDelete:u}),[c,u]),h=Math.max(1,Math.ceil(t/r));w.useMemo(()=>[],[]);const g=gl({data:e,columns:m,state:{pagination:{pageIndex:n-1,pageSize:r},columnVisibility:d},pageCount:h,manualPagination:!0,manualFiltering:!0,onPaginationChange:b=>{const x=typeof b=="function"?b({pageIndex:n-1,pageSize:r}):b;x.pageIndex+1!==n&&i(x.pageIndex+1),x.pageSize!==r&&o(x.pageSize)},onColumnVisibilityChange:f,getCoreRowModel:hl()});return a&&e.length===0?s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[p?.(g),s.jsx(qr,{variant:"table"})]}):s.jsxs("div",{className:"flex flex-1 flex-col gap-4",children:[p?.(g),s.jsx("div",{className:"rounded-md border overflow-hidden bg-card text-card-foreground",children:s.jsxs(Oa,{children:[s.jsx(La,{children:g.getHeaderGroups().map(b=>s.jsx(Ft,{className:"bg-muted/50 group/row",children:b.headers.map(x=>s.jsx(gn,{children:x.isPlaceholder?null:Rr(x.column.columnDef.header,x.getContext())},x.id))},b.id))}),s.jsx(ja,{children:g.getRowModel().rows?.length?g.getRowModel().rows.map(b=>s.jsx(Ft,{"data-state":b.getIsSelected()&&"selected",className:"cursor-pointer group/row hover:bg-muted/30",onClick:()=>l(b.original.id),children:b.getVisibleCells().map(x=>s.jsx(Pt,{children:Rr(x.column.columnDef.cell,x.getContext())},x.id))},b.id)):s.jsx(Ft,{children:s.jsx(Pt,{colSpan:m.length,className:"h-24 text-center",children:"No SOPs found."})})})]})}),s.jsx(bl,{table:g,className:"mt-auto"})]})}function kY({open:e,editing:t,submitting:n,onSubmit:r,onCancel:a}){const[i,o]=w.useState(""),[l,c]=w.useState(""),[u,p]=w.useState(""),[d,f]=w.useState("medium"),[m,h]=w.useState("draft"),[g,b]=w.useState(""),[x,S]=w.useState(""),[T,N]=w.useState("manual"),[A,C]=w.useState(""),k=w.useRef(null);w.useEffect(()=>{t?(o(t.title),c(t.alertType??""),p(t.service??""),f(t.severity??"medium"),h(t.status??"draft"),b(t.description??""),S(t.steps??""),N("manual"),C("")):(o(""),c(""),p(""),f("medium"),h("draft"),b(""),S(""),N("manual"),C(""))},[t,e]);const O=R=>{R.preventDefault(),r({title:i,alertType:l,service:u,severity:d,status:m,description:g,steps:x})},M=R=>{const j=R.target.files?.[0];if(!j)return;if(j.type!=="text/plain"&&!j.name.endsWith(".md")&&!j.name.endsWith(".txt")){ae.error("Please upload a .txt or .md file");return}C(j.name);const U=new FileReader;U.onload=G=>{const q=G.target?.result;S(q),i||o(j.name.replace(/\.(txt|md)$/i,"")),ae.success("Document loaded successfully")},U.readAsText(j)};return s.jsx(kt,{open:e,onOpenChange:R=>!R&&!n&&a(),children:s.jsxs(It,{className:"sm:max-w-xl max-h-[90vh] overflow-y-auto flex flex-col",children:[s.jsxs(jt,{className:"shrink-0",children:[s.jsx(Mt,{children:t?"Edit SOP Metadata":"Create New SOP"}),s.jsx(Kt,{children:t?"Update the details of this standard operating procedure.":"Create a new runbook for incident response."})]}),s.jsxs("form",{id:"sop-form",onSubmit:O,className:"space-y-5 flex-1",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-title",children:"Title *"}),s.jsx(Xe,{id:"sop-title",value:i,onChange:R=>o(R.target.value),placeholder:"e.g. High CPU mitigation on EC2",required:!0,disabled:n})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-alert-type",children:"Alert Type"}),s.jsx(Xe,{id:"sop-alert-type",value:l,onChange:R=>c(R.target.value),placeholder:"e.g. CPUUtilization",disabled:n})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-service",children:"Service"}),s.jsx(Xe,{id:"sop-service",value:u,onChange:R=>p(R.target.value),placeholder:"e.g. Checkout API",disabled:n})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-severity",children:"Severity"}),s.jsx(Bn,{label:"Select severity",className:"im-single-select-full",value:d,onValueChange:f,disabled:n,options:[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-status",children:"Initial Status"}),s.jsx(Bn,{label:"Select status",className:"im-single-select-full",value:m,onValueChange:h,disabled:n,options:[{label:"Draft",value:"draft"},{label:"Pending",value:"pending"},{label:"Approved",value:"approved"}]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{htmlFor:"sop-description",children:"Description"}),s.jsx(Ho,{id:"sop-description",value:g,onChange:R=>b(R.target.value),placeholder:"Brief summary of what this SOP covers…",rows:2,disabled:n})]}),!t&&s.jsx("div",{className:"pt-1",children:s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Pe,{children:"Runbook Content Generation"}),s.jsxs(Qh,{value:T,onValueChange:R=>N(R),className:"w-full",children:[s.jsxs(rd,{className:"grid w-full grid-cols-2 mb-4",children:[s.jsxs(as,{value:"manual",disabled:n,children:[s.jsx(di,{className:"w-3.5 h-3.5 mr-2"})," Manual"]}),s.jsxs(as,{value:"upload",disabled:n,children:[s.jsx(MS,{className:"w-3.5 h-3.5 mr-2"})," Upload"]})]}),s.jsxs(ss,{value:"manual",className:"space-y-2 mt-0",children:[s.jsx(Ho,{value:x,onChange:R=>S(R.target.value),placeholder:"Step-by-step remediation instructions (Markdown supported)…",rows:4,disabled:n,className:"font-mono text-xs"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"You can format this with Markdown."})]}),s.jsx(ss,{value:"upload",className:"space-y-2 mt-0",children:s.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center bg-muted/20 hover:bg-muted/40 transition-colors cursor-pointer",onClick:()=>k.current?.click(),children:[s.jsx("input",{type:"file",ref:k,className:"hidden",accept:".txt,.md,text/plain,text/markdown",onChange:M,disabled:n}),A?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-10 w-10 bg-green-500/10 text-green-600 rounded-full flex items-center justify-center mb-2",children:s.jsx(ei,{className:"h-5 w-5"})}),s.jsxs("p",{className:"text-sm font-medium text-foreground text-center",children:["Loaded ",A]}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Click to replace or edit manually in the Manual tab."})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-10 w-10 bg-muted text-muted-foreground rounded-full flex items-center justify-center mb-2",children:s.jsx(MS,{className:"h-5 w-5"})}),s.jsx("p",{className:"text-sm font-medium text-foreground text-center",children:"Upload Document"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Drag and drop or click to upload a .txt or .md file"})]})]})})]})]})}),t&&s.jsx("div",{className:"pt-2",children:s.jsxs("p",{className:"text-sm text-muted-foreground bg-muted/50 p-3 rounded-md",children:[s.jsx(di,{className:"h-4 w-4 inline-block mr-2 -mt-0.5"}),"To edit the runbook contents, please save these metadata changes and click ",s.jsx("strong",{children:"Edit Runbook"})," on the detail page."]})})]}),s.jsxs($t,{className:"shrink-0 mt-2",children:[s.jsx(ie,{variant:"outline",onClick:a,disabled:n,children:"Cancel"}),s.jsx(ie,{type:"submit",form:"sop-form",disabled:n||!i.trim(),children:n?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"}),"Saving…"]}):t?"Save Changes":"Create SOP"})]})]})})}function IY({open:e,onConfirm:t,onCancel:n,deleting:r}){return s.jsx(kt,{open:e,onOpenChange:a=>!a&&!r&&n(),children:s.jsxs(It,{children:[s.jsxs(jt,{children:[s.jsx(Mt,{children:"Delete SOP?"}),s.jsx(Kt,{children:"This will permanently delete this standard operating procedure. This action cannot be undone."})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:n,disabled:r,children:"Cancel"}),s.jsx(ie,{variant:"destructive",onClick:t,disabled:r,children:r?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"}),"Deleting…"]}):"Delete"})]})]})})}function DY({open:e,submitting:t,onSubmit:n,onCancel:r}){const[a,i]=w.useState("");w.useEffect(()=>{e&&i("")},[e]);const o=l=>{l.preventDefault(),a.trim()&&n(a)};return s.jsx(kt,{open:e,onOpenChange:l=>!l&&!t&&r(),children:s.jsxs(It,{className:"sm:max-w-md",children:[s.jsxs(jt,{children:[s.jsxs(Mt,{className:"flex items-center gap-2 text-foreground",children:[s.jsx(ol,{className:"w-5 h-5"}),"Generate SOP with AI"]}),s.jsx(Kt,{children:"Provide a prompt and our AI will generate a complete runbook for you."})]}),s.jsxs("form",{id:"sop-ai-form",onSubmit:o,className:"space-y-4 py-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Pe,{htmlFor:"ai-prompt",children:"Prompt *"}),s.jsx(Ho,{id:"ai-prompt",value:a,onChange:l=>i(l.target.value),placeholder:"e.g. Write a detailed runbook for investigating and resolving high memory usage on an EC2 instance running Redis.",rows:4,disabled:t,autoFocus:!0,required:!0})]}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["A new SOP will be created in a ",s.jsx("strong",{children:"Generating"})," state. You will be able to review and edit the generated runbook."]})]}),s.jsxs($t,{children:[s.jsx(ie,{variant:"outline",onClick:r,disabled:t,children:"Cancel"}),s.jsx(ie,{type:"submit",form:"sop-ai-form",disabled:t||!a.trim(),children:t?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"}),"Generating…"]}):"Generate"})]})]})})}function ww({search:e,onSearchChange:t,severityFilter:n,onSeverityChange:r,statusFilter:a,onStatusChange:i,onRefresh:o,loading:l,children:c}){const u=[{label:"Critical",value:"critical"},{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}],p=[{label:"Approved",value:"approved"},{label:"Pending",value:"pending"},{label:"Draft",value:"draft"},{label:"Generating",value:"generating"}];return s.jsxs("div",{className:"flex w-full flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-1 flex-col items-start gap-3 sm:flex-row sm:items-center",children:[s.jsxs("div",{className:"relative w-full sm:max-w-[280px]",children:[s.jsx(gs,{className:"pointer-events-none absolute left-2.5 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(Xe,{value:e,onChange:d=>t(d.target.value),placeholder:"Search SOPs...",className:"h-8 w-full min-w-0 pl-9 pr-8"}),e&&s.jsx("button",{onClick:()=>t(""),className:"absolute right-2.5 top-2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:s.jsx(Hn,{className:"h-4 w-4"})})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Qn,{title:"Severity",options:u,selected:n,onChange:r}),s.jsx(Qn,{title:"Status",options:p,selected:a,onChange:i})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:o,disabled:l,className:"h-8",children:[s.jsx(Ra,{className:Fe("h-4 w-4",l&&"animate-spin")}),"Refresh"]}),c]})]})}function OY({onViewSop:e}){const{isReadOnly:t}=ur(),[n,r]=w.useState([]),[a,i]=w.useState(0),[o,l]=w.useState(!0),[c,u]=w.useState(1),[p,d]=w.useState(10),[f,m]=w.useState(""),[h,g]=w.useState(""),[b,x]=w.useState(""),[S,T]=w.useState(""),[N,A]=w.useState(()=>{try{return sessionStorage.getItem("insight-sop-view")||"table"}catch{return"table"}}),[C,k]=w.useState(!1),[O,M]=w.useState(null),[R,j]=w.useState(!1),[U,G]=w.useState(null),[q,P]=w.useState(!1),[z,re]=w.useState(!1),[B,H]=w.useState(!1);w.useEffect(()=>{const ne=setTimeout(()=>{g(f),u(1)},400);return()=>clearTimeout(ne)},[f]);const I=w.useCallback(async()=>{l(!0);try{const ne=await Tr.list({page:c,limit:p,search:h||void 0,severity:b||void 0,status:S||void 0});r(ne.sops??[]),i(ne.total??0)}catch{ae.error("Failed to load SOPs")}finally{l(!1)}},[c,p,h,b,S]);w.useEffect(()=>{I()},[I]);const V=async ne=>{j(!0);try{O?(await Tr.update(O.id,ne),ae.success("SOP updated")):(await Tr.create(ne),ae.success("SOP created")),k(!1),M(null),I()}catch(K){ae.error(K?.response?.data?.error??"Failed to save SOP")}finally{j(!1)}},Z=async ne=>{H(!0);try{const K=ne.length>50?ne.substring(0,50)+"...":ne;await Tr.create({title:K,prompt:ne,status:"generating"}),ae.success("SOP generation started"),re(!1),I()}catch(K){ae.error(K.response?.data?.error??"Failed to generate SOP")}finally{H(!1)}},D=async()=>{if(U){P(!0);try{await Tr.delete(U.id),ae.success("SOP deleted"),G(null),I()}catch{ae.error("Failed to delete SOP")}finally{P(!1)}}},se=ne=>{A(ne);try{sessionStorage.setItem("insight-sop-view",ne)}catch{}},Q=Math.max(1,Math.ceil(a/p));return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between w-full",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(LS,{className:"h-6 w-6 text-primary"}),s.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"SOP Library"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("div",{className:"flex bg-muted/50 p-1 rounded-md border",children:[s.jsxs(ie,{size:"sm",variant:N==="card"?"secondary":"ghost",onClick:()=>se("card"),children:[s.jsx(XF,{className:"h-4 w-4"})," Card"]}),s.jsxs(ie,{size:"sm",variant:N==="table"?"secondary":"ghost",onClick:()=>se("table"),children:[s.jsx(w4,{className:"h-3.5 w-3.5"})," Table"]})]}),!t&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ie,{variant:"default",onClick:()=>re(!0),children:[s.jsx(ol,{className:"h-4 w-4 mr-2"}),"Generate with AI"]}),s.jsxs(ie,{onClick:()=>{M(null),k(!0)},children:[s.jsx(WP,{className:"h-4 w-4 mr-2"}),"New SOP"]})]})]})]}),s.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Runbooks, response playbooks and standard operating procedures."})]}),N==="card"&&s.jsx(ww,{search:f,onSearchChange:ne=>{m(ne),u(1)},severityFilter:b?[b]:[],onSeverityChange:ne=>{x(ne[0]??""),u(1)},statusFilter:S?[S]:[],onStatusChange:ne=>{T(ne[0]??""),u(1)},onRefresh:I,loading:o}),N==="table"?s.jsx(RY,{data:n,total:a,page:c,limit:p,loading:o,onPageChange:u,onLimitChange:ne=>{d(ne),u(1)},onEdit:ne=>{M(ne),k(!0)},onDelete:G,onView:ne=>e(ne),renderFilters:ne=>s.jsx(ww,{search:f,onSearchChange:K=>{m(K),u(1)},severityFilter:b?[b]:[],onSeverityChange:K=>{x(K[0]??""),u(1)},statusFilter:S?[S]:[],onStatusChange:K=>{T(K[0]??""),u(1)},onRefresh:I,loading:o,children:s.jsx(Mg,{table:ne})})}):o?s.jsx(qr,{variant:"cards"}):n.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center rounded-xl border-2 border-dashed p-12 text-center",children:[s.jsx("div",{className:"bg-muted mx-auto flex h-16 w-16 items-center justify-center rounded-full mb-4",children:s.jsx(LS,{className:"h-7 w-7 text-muted-foreground"})}),s.jsx("h3",{className:"text-base font-semibold",children:f||b||S?"No matching SOPs":"No SOPs yet"}),s.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground max-w-sm mx-auto",children:f||b||S?"Try adjusting your filters.":"Create your first SOP to build a runbook library for your team."}),!f&&!b&&!S&&s.jsxs(ie,{onClick:()=>{M(null),k(!0)},className:"mt-5",children:[s.jsx(Wr,{className:"h-4 w-4"})," Create First SOP"]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:n.map(ne=>s.jsx(CY,{sop:ne,onEdit:K=>{M(K),k(!0)},onDelete:G,onView:K=>e(K.id)},ne.id))}),n.length>0&&s.jsx(cI,{currentPage:c,pageSize:p,totalPages:Q,total:a,onPageChange:ne=>u(ne),onPageSizeChange:ne=>{d(ne),u(1)}})]}),s.jsx(kY,{open:C,editing:O,submitting:R,onSubmit:V,onCancel:()=>{k(!1),M(null)}}),s.jsx(IY,{open:!!U,onConfirm:D,onCancel:()=>G(null),deleting:q}),s.jsx(DY,{open:z,submitting:B,onSubmit:Z,onCancel:()=>re(!1)})]})}function ft(){return ft=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ft.apply(null,arguments)}const vl=(function(e){if(e==null)return PY;if(typeof e=="function")return Hd(e);if(typeof e=="object")return Array.isArray(e)?LY(e):jY(e);if(typeof e=="string")return MY(e);throw new Error("Expected function, string, or object as test")});function LY(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=vl(e[n]);return Hd(r);function r(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function jY(e){const t=e;return Hd(n);function n(r){const a=r;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function MY(e){return Hd(t);function t(n){return n&&n.type===e}}function Hd(e){return t;function t(n,r,a){return!!(FY(n)&&e.call(this,n,typeof r=="number"?r:void 0,a||void 0))}}function PY(){return!0}function FY(e){return e!==null&&typeof e=="object"&&"type"in e}const MI=[],BY=!0,Tu=!1,xo="skip";function eb(e,t,n,r){let a;typeof t=="function"&&typeof n!="function"?(r=n,n=t):a=t;const i=vl(a),o=r?-1:1;l(e,void 0,[])();function l(c,u,p){const d=c&&typeof c=="object"?c:{};if(typeof d.type=="string"){const m=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(c.type+(m?"<"+m+">":""))+")"})}return f;function f(){let m=MI,h,g,b;if((!t||i(c,u,p[p.length-1]||void 0))&&(m=UY(n(c,p)),m[0]===Tu))return m;if("children"in c&&c.children){const x=c;if(x.children&&m[0]!==xo)for(g=(r?x.children.length:-1)+o,b=p.concat(x);g>-1&&g<x.children.length;){const S=x.children[g];if(h=l(S,g,b)(),h[0]===Tu)return h;g=typeof h[1]=="number"?h[1]:g+o}}return m}}}function UY(e){return Array.isArray(e)?e:typeof e=="number"?[BY,e]:e==null?MI:[e]}function kn(e,t,n,r){let a,i,o;typeof t=="function"&&typeof n!="function"?(i=void 0,o=t,a=n):(i=t,o=n,a=r),eb(e,i,l,a);function l(c,u){const p=u[u.length-1],d=p?p.children.indexOf(c):void 0;return o(c,d,p)}}function Xs(e){return"children"in e?PI(e):"value"in e?e.value:""}function $Y(e){return e.type==="text"?e.value:"children"in e?PI(e):""}function PI(e){let t=-1;const n=[];for(;++t<e.children.length;)n[t]=$Y(e.children[t]);return n.join("")}const HY={}.hasOwnProperty;function zY(e,t,n){const r=vl(t),a=t&&typeof t=="object"&&"cascade"in t?t.cascade:void 0,i=a??!0;return o(e);function o(l,c,u){const p=[];if(!r(l,c,u))return;if(GY(l)){let m=-1;for(;++m<l.children.length;){const h=o(l.children[m],m,l);h&&p.push(h)}if(i&&l.children.length>0&&p.length===0)return}const d={};let f;for(f in l)HY.call(l,f)&&(d[f]=f==="children"?p:l[f]);return d}}function GY(e){return"children"in e&&e.children!==void 0}var Ec={exports:{}},Tw;function VY(){return Tw||(Tw=1,(function(e,t){function n(r){let a=[],i;for(let o of r.split(",").map(l=>l.trim()))if(/^-?\d+$/.test(o))a.push(parseInt(o,10));else if(i=o.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/)){let[l,c,u,p]=i;if(c&&p){c=parseInt(c),p=parseInt(p);const d=c<p?1:-1;(u==="-"||u===".."||u==="‥")&&(p+=d);for(let f=c;f!==p;f+=d)a.push(f)}}return a}t.default=n,e.exports=n})(Ec,Ec.exports)),Ec.exports}var WY=VY();const qY=Bu(WY);ht.displayName="clike";ht.aliases=[];function ht(e){e.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}}pr.displayName="c";pr.aliases=[];function pr(e){e.register(ht),e.languages.c=e.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/}),e.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}}),e.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},e.languages.c.string],char:e.languages.c.char,comment:e.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:e.languages.c}}}}),e.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/}),delete e.languages.c.boolean}Ts.displayName="cpp";Ts.aliases=[];function Ts(e){e.register(pr),(function(t){var n=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,r=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return n.source});t.languages.cpp=t.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return n.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:n,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),t.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return r})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),t.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:t.languages.cpp}}}}),t.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),t.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:t.languages.extend("cpp",{})}}),t.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},t.languages.cpp["base-clause"])})(e)}zd.displayName="arduino";zd.aliases=["ino"];function zd(e){e.register(Ts),e.languages.arduino=e.languages.extend("cpp",{keyword:/\b(?:String|array|bool|boolean|break|byte|case|catch|continue|default|do|double|else|finally|for|function|goto|if|in|instanceof|int|integer|long|loop|new|null|return|setup|string|switch|throw|try|void|while|word)\b/,constant:/\b(?:ANALOG_MESSAGE|DEFAULT|DIGITAL_MESSAGE|EXTERNAL|FIRMATA_STRING|HIGH|INPUT|INPUT_PULLUP|INTERNAL|INTERNAL1V1|INTERNAL2V56|LED_BUILTIN|LOW|OUTPUT|REPORT_ANALOG|REPORT_DIGITAL|SET_PIN_MODE|SYSEX_START|SYSTEM_RESET)\b/,builtin:/\b(?:Audio|BSSID|Bridge|Client|Console|EEPROM|Esplora|EsploraTFT|Ethernet|EthernetClient|EthernetServer|EthernetUDP|File|FileIO|FileSystem|Firmata|GPRS|GSM|GSMBand|GSMClient|GSMModem|GSMPIN|GSMScanner|GSMServer|GSMVoiceCall|GSM_SMS|HttpClient|IPAddress|IRread|Keyboard|KeyboardController|LiquidCrystal|LiquidCrystal_I2C|Mailbox|Mouse|MouseController|PImage|Process|RSSI|RobotControl|RobotMotor|SD|SPI|SSID|Scheduler|Serial|Server|Servo|SoftwareSerial|Stepper|Stream|TFT|Task|USBHost|WiFi|WiFiClient|WiFiServer|WiFiUDP|Wire|YunClient|YunServer|abs|addParameter|analogRead|analogReadResolution|analogReference|analogWrite|analogWriteResolution|answerCall|attach|attachGPRS|attachInterrupt|attached|autoscroll|available|background|beep|begin|beginPacket|beginSD|beginSMS|beginSpeaker|beginTFT|beginTransmission|beginWrite|bit|bitClear|bitRead|bitSet|bitWrite|blink|blinkVersion|buffer|changePIN|checkPIN|checkPUK|checkReg|circle|cityNameRead|cityNameWrite|clear|clearScreen|click|close|compassRead|config|connect|connected|constrain|cos|countryNameRead|countryNameWrite|createChar|cursor|debugPrint|delay|delayMicroseconds|detach|detachInterrupt|digitalRead|digitalWrite|disconnect|display|displayLogos|drawBMP|drawCompass|encryptionType|end|endPacket|endSMS|endTransmission|endWrite|exists|exitValue|fill|find|findUntil|flush|gatewayIP|get|getAsynchronously|getBand|getButton|getCurrentCarrier|getIMEI|getKey|getModifiers|getOemKey|getPINUsed|getResult|getSignalStrength|getSocket|getVoiceCallStatus|getXChange|getYChange|hangCall|height|highByte|home|image|interrupts|isActionDone|isDirectory|isListening|isPIN|isPressed|isValid|keyPressed|keyReleased|keyboardRead|knobRead|leftToRight|line|lineFollowConfig|listen|listenOnLocalhost|loadImage|localIP|lowByte|macAddress|maintain|map|max|messageAvailable|micros|millis|min|mkdir|motorsStop|motorsWrite|mouseDragged|mouseMoved|mousePressed|mouseReleased|move|noAutoscroll|noBlink|noBuffer|noCursor|noDisplay|noFill|noInterrupts|noListenOnLocalhost|noStroke|noTone|onReceive|onRequest|open|openNextFile|overflow|parseCommand|parseFloat|parseInt|parsePacket|pauseMode|peek|pinMode|playFile|playMelody|point|pointTo|position|pow|prepare|press|print|printFirmwareVersion|printVersion|println|process|processInput|pulseIn|put|random|randomSeed|read|readAccelerometer|readBlue|readButton|readBytes|readBytesUntil|readGreen|readJoystickButton|readJoystickSwitch|readJoystickX|readJoystickY|readLightSensor|readMessage|readMicrophone|readNetworks|readRed|readSlider|readString|readStringUntil|readTemperature|ready|rect|release|releaseAll|remoteIP|remoteNumber|remotePort|remove|requestFrom|retrieveCallingNumber|rewindDirectory|rightToLeft|rmdir|robotNameRead|robotNameWrite|run|runAsynchronously|runShellCommand|runShellCommandAsynchronously|running|scanNetworks|scrollDisplayLeft|scrollDisplayRight|seek|sendAnalog|sendDigitalPortPair|sendDigitalPorts|sendString|sendSysex|serialEvent|setBand|setBitOrder|setClockDivider|setCursor|setDNS|setDataMode|setFirmwareVersion|setMode|setPINUsed|setSpeed|setTextSize|setTimeout|shiftIn|shiftOut|shutdown|sin|size|sqrt|startLoop|step|stop|stroke|subnetMask|switchPIN|tan|tempoWrite|text|tone|transfer|tuneWrite|turn|updateIR|userNameRead|userNameWrite|voiceCall|waitContinue|width|write|writeBlue|writeGreen|writeJSON|writeMessage|writeMicroseconds|writeRGB|writeRed|yield)\b/}),e.languages.ino=e.languages.arduino}Sl.displayName="bash";Sl.aliases=["sh","shell"];function Sl(e){(function(t){var n="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",r={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},a={bash:r,environment:{pattern:RegExp("\\$"+n),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+n),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};t.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+n),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:a},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:r}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:a},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:a.entity}}],environment:{pattern:RegExp("\\$?"+n),alias:"constant"},variable:a.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},r.inside=t.languages.bash;for(var i=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],o=a.variable[1].inside,l=0;l<i.length;l++)o[i[l]]=t.languages.bash[i[l]];t.languages.sh=t.languages.bash,t.languages.shell=t.languages.bash})(e)}Ns.displayName="csharp";Ns.aliases=["cs","dotnet"];function Ns(e){e.register(ht),(function(t){function n(I,V){return I.replace(/<<(\d+)>>/g,function(Z,D){return"(?:"+V[+D]+")"})}function r(I,V,Z){return RegExp(n(I,V),"")}function a(I,V){for(var Z=0;Z<V;Z++)I=I.replace(/<<self>>/g,function(){return"(?:"+I+")"});return I.replace(/<<self>>/g,"[^\\s\\S]")}var i={type:"bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void",typeDeclaration:"class enum interface record struct",contextual:"add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)",other:"abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield"};function o(I){return"\\b(?:"+I.trim().replace(/ /g,"|")+")\\b"}var l=o(i.typeDeclaration),c=RegExp(o(i.type+" "+i.typeDeclaration+" "+i.contextual+" "+i.other)),u=o(i.typeDeclaration+" "+i.contextual+" "+i.other),p=o(i.type+" "+i.typeDeclaration+" "+i.other),d=a(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source,2),f=a(/\((?:[^()]|<<self>>)*\)/.source,2),m=/@?\b[A-Za-z_]\w*\b/.source,h=n(/<<0>>(?:\s*<<1>>)?/.source,[m,d]),g=n(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[u,h]),b=/\[\s*(?:,\s*)*\]/.source,x=n(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[g,b]),S=n(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[d,f,b]),T=n(/\(<<0>>+(?:,<<0>>+)+\)/.source,[S]),N=n(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[T,g,b]),A={keyword:c,punctuation:/[<>()?,.:[\]]/},C=/'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source,k=/"(?:\\.|[^\\"\r\n])*"/.source,O=/@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;t.languages.csharp=t.languages.extend("clike",{string:[{pattern:r(/(^|[^$\\])<<0>>/.source,[O]),lookbehind:!0,greedy:!0},{pattern:r(/(^|[^@$\\])<<0>>/.source,[k]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:r(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source,[g]),lookbehind:!0,inside:A},{pattern:r(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[m,N]),lookbehind:!0,inside:A},{pattern:r(/(\busing\s+)<<0>>(?=\s*=)/.source,[m]),lookbehind:!0},{pattern:r(/(\b<<0>>\s+)<<1>>/.source,[l,h]),lookbehind:!0,inside:A},{pattern:r(/(\bcatch\s*\(\s*)<<0>>/.source,[g]),lookbehind:!0,inside:A},{pattern:r(/(\bwhere\s+)<<0>>/.source,[m]),lookbehind:!0},{pattern:r(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[x]),lookbehind:!0,inside:A},{pattern:r(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[N,p,m]),inside:A}],keyword:c,number:/(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,operator:/>>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),t.languages.insertBefore("csharp","number",{range:{pattern:/\.\./,alias:"operator"}}),t.languages.insertBefore("csharp","punctuation",{"named-parameter":{pattern:r(/([(,]\s*)<<0>>(?=\s*:)/.source,[m]),lookbehind:!0,alias:"punctuation"}}),t.languages.insertBefore("csharp","class-name",{namespace:{pattern:r(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[m]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:r(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source,[f]),lookbehind:!0,alias:"class-name",inside:A},"return-type":{pattern:r(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source,[N,g]),inside:A,alias:"class-name"},"constructor-invocation":{pattern:r(/(\bnew\s+)<<0>>(?=\s*[[({])/.source,[N]),lookbehind:!0,inside:A,alias:"class-name"},"generic-method":{pattern:r(/<<0>>\s*<<1>>(?=\s*\()/.source,[m,d]),inside:{function:r(/^<<0>>/.source,[m]),generic:{pattern:RegExp(d),alias:"class-name",inside:A}}},"type-list":{pattern:r(/\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,[l,h,m,N,c.source,f,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:r(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[h,f]),lookbehind:!0,greedy:!0,inside:t.languages.csharp},keyword:c,"class-name":{pattern:RegExp(N),greedy:!0,inside:A},punctuation:/[,()]/}},preprocessor:{pattern:/(^[\t ]*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}});var M=k+"|"+C,R=n(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[M]),j=a(n(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[R]),2),U=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,G=n(/<<0>>(?:\s*\(<<1>>*\))?/.source,[g,j]);t.languages.insertBefore("csharp","class-name",{attribute:{pattern:r(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[U,G]),lookbehind:!0,greedy:!0,inside:{target:{pattern:r(/^<<0>>(?=\s*:)/.source,[U]),alias:"keyword"},"attribute-arguments":{pattern:r(/\(<<0>>*\)/.source,[j]),inside:t.languages.csharp},"class-name":{pattern:RegExp(g),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var q=/:[^}\r\n]+/.source,P=a(n(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[R]),2),z=n(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[P,q]),re=a(n(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[M]),2),B=n(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[re,q]);function H(I,V){return{interpolation:{pattern:r(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[I]),lookbehind:!0,inside:{"format-string":{pattern:r(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[V,q]),lookbehind:!0,inside:{punctuation:/^:/}},punctuation:/^\{|\}$/,expression:{pattern:/[\s\S]+/,alias:"language-csharp",inside:t.languages.csharp}}},string:/[\s\S]+/}}t.languages.insertBefore("csharp","string",{"interpolation-string":[{pattern:r(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source,[z]),lookbehind:!0,greedy:!0,inside:H(z,P)},{pattern:r(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[B]),lookbehind:!0,greedy:!0,inside:H(B,re)}],char:{pattern:RegExp(C),greedy:!0}}),t.languages.dotnet=t.languages.cs=t.languages.csharp})(e)}tn.displayName="markup";tn.aliases=["atom","html","mathml","rss","ssml","svg","xml"];function tn(e){e.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},e.languages.markup.tag.inside["attr-value"].inside.entity=e.languages.markup.entity,e.languages.markup.doctype.inside["internal-subset"].inside=e.languages.markup,e.hooks.add("wrap",function(t){t.type==="entity"&&(t.attributes.title=t.content.value.replace(/&amp;/,"&"))}),Object.defineProperty(e.languages.markup.tag,"addInlined",{value:function(n,r){var a={};a["language-"+r]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:e.languages[r]},a.cdata=/^<!\[CDATA\[|\]\]>$/i;var i={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:a}};i["language-"+r]={pattern:/[\s\S]+/,inside:e.languages[r]};var o={};o[n]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return n}),"i"),lookbehind:!0,greedy:!0,inside:i},e.languages.insertBefore("markup","cdata",o)}}),Object.defineProperty(e.languages.markup.tag,"addAttribute",{value:function(t,n){e.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+t+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[n,"language-"+n],inside:e.languages[n]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),e.languages.html=e.languages.markup,e.languages.mathml=e.languages.markup,e.languages.svg=e.languages.markup,e.languages.xml=e.languages.extend("markup",{}),e.languages.ssml=e.languages.xml,e.languages.atom=e.languages.xml,e.languages.rss=e.languages.xml}Pa.displayName="css";Pa.aliases=[];function Pa(e){(function(t){var n=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;t.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+n.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+n.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+n.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+n.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:n,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},t.languages.css.atrule.inside.rest=t.languages.css;var r=t.languages.markup;r&&(r.tag.addInlined("style","css"),r.tag.addAttribute("style","css"))})(e)}Gd.displayName="diff";Gd.aliases=[];function Gd(e){(function(t){t.languages.diff={coord:[/^(?:\*{3}|-{3}|\+{3}).*$/m,/^@@.*@@$/m,/^\d.*$/m]};var n={"deleted-sign":"-","deleted-arrow":"<","inserted-sign":"+","inserted-arrow":">",unchanged:" ",diff:"!"};Object.keys(n).forEach(function(r){var a=n[r],i=[];/^\w+$/.test(r)||i.push(/\w+/.exec(r)[0]),r==="diff"&&i.push("bold"),t.languages.diff[r]={pattern:RegExp("^(?:["+a+`].*(?:\r
@@ -338,7 +338,7 @@ ${c}
338
338
  ${p}
339
339
 
340
340
  ${m}
341
- `}function mN(e){try{return Pn.load(e)?.name||"new-workflow"}catch{return"new-workflow"}}function hN(e){try{const t=Pn.load(e),n=Array.isArray(t?.triggers?.labels)?t.triggers.labels.map(d=>{if(typeof d!="string")return{key:"env",op:"equals",value:"production"};const f=d.match(/^(\S+)\s+(\S+)\s+'?(.+?)'?$/);return{key:f?.[1]||"env",op:f?.[2]||"equals",value:f?.[3]||"production"}}):Sr.labels;let r="all";const a=[];if(Array.isArray(t?.conditions)){for(const d of t.conditions)if(d?.groupId!=="triggers"&&(d?.operator==="OR"&&(r="any"),Array.isArray(d?.rules)))for(const f of d.rules)f?.field&&f?.operator&&a.push({field:f.field,operator:f.operator,value:Array.isArray(f.value)?f.value.join(", "):String(f.value??"")})}const i=t?.dedup,o={...OO};if(i&&typeof i=="object"){const f=String(i.window||"5m").match(/^(\d+)([smh])$/);if(f&&(o.windowN=parseInt(f[1]),o.windowU=f[2]),Array.isArray(i.key)&&(o.keyFields=i.key),i.resolved==="apply"&&(o.resolvedBehavior="apply"),i.flap&&typeof i.flap=="object"){o.flapEnabled=!0,o.flapThreshold=i.flap.threshold??3;const m=String(i.flap.window||"10m").match(/^(\d+)/);m&&(o.flapWindowN=parseInt(m[1])),o.onFlap=i.flap.on_flap||"elevate"}}const l=t?.grouping,c={...LO};if(l&&typeof l=="object"){c.enabled=l.enabled!==!1,Array.isArray(l.key)&&(c.groupByFields=l.key);const f=String(l.timeout||"5m").match(/^(\d+)([smh])$/);f&&(c.timeoutN=parseInt(f[1]),c.timeoutU=f[2]),l.max_alarms&&(c.maxAlarms=l.max_alarms),l.title&&(c.titleTemplate=l.title),l.severity&&(c.severityResolution=l.severity)}const u=Array.isArray(t?.actions)?t.actions:[],p={...jO,notifyChannels:[]};for(const d of u){const f=d?.type||Object.keys(d||{})[0],m=d?.config||(f?d[f]:{})||{};f==="create_incident"&&(p.createIncident=!0,p.priority=m.priority||"P1",p.assignees=Array.isArray(m.assign_to)?m.assign_to:[]),f==="send_notification"&&(m.channels?(Array.isArray(m.channels)?m.channels:[m.channels]).forEach(g=>p.notifyChannels.push({channel:g,target:""})):m.type&&p.notifyChannels.push({channel:m.type,target:m.target||""})),f==="generate_rca"&&(p.runSopAgent=!0,p.llmModel=m.model||"bedrock")}return{name:t?.name||Sr.name,enabled:t?.enabled===!0||t?.active===!0,severities:Array.isArray(t?.triggers?.severity)&&t.triggers.severity.length?t.triggers.severity:Sr.severities,sources:Array.isArray(t?.triggers?.source)&&t.triggers.source.length?t.triggers.source:Sr.sources,resourceTypes:Array.isArray(t?.triggers?.resource_type)?t.triggers.resource_type:[],metricPattern:typeof t?.triggers?.metric_name=="string"?t.triggers.metric_name:Sr.metricPattern,labels:n,conditionLogic:r,conditions:a,dedup:o,grouping:c,actions:p}}catch{return Sr}}function bue(e,t){switch(e){case"triggers":{const n=[t.severities.join(", ")||"any sev"];return t.sources.length&&n.push(t.sources.join(", ")),n.join(" · ")}case"conditions":return t.conditions.length?`${t.conditions.length} condition${t.conditions.length>1?"s":""} (${t.conditionLogic})`:"none";case"dedup":return`${t.dedup.windowN}${t.dedup.windowU} window · ${t.dedup.keyFields.length} key fields`;case"grouping":return t.grouping.enabled?`by ${t.grouping.groupByFields.join(", ")||"—"} · ${t.grouping.timeoutN}${t.grouping.timeoutU}`:"disabled";case"actions":{const n=[];return t.actions.createIncident&&n.push("incident"),t.actions.notifyChannels.length&&n.push("notify"),t.actions.runSopAgent&&n.push("AI"),n.join(", ")||"none"}}}function xue({form:e,updateForm:t,sourceId:n}){const r=(i,o)=>{t(l=>{const u=l[i].includes(o)?l[i].filter(p=>p!==o):[...l[i],o];return{...l,[i]:u.length?u:[o]}})},a=(i,o)=>{t(l=>({...l,labels:l.labels.map((c,u)=>u===i?{...c,...o}:c)}))};return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Triggers"}),s.jsx("p",{children:"Which alarms this workflow listens for."}),s.jsxs("label",{children:["Workflow name ",s.jsx("span",{children:"*"})]}),s.jsx("input",{value:e.name,onChange:i=>t(o=>({...o,name:i.target.value})),placeholder:"new-workflow"}),s.jsx("label",{children:"Status"}),s.jsxs("div",{className:"im-chip-row",children:[s.jsx("button",{className:e.enabled?"is-active":"",type:"button",onClick:()=>t(i=>({...i,enabled:!0})),children:"enabled"}),s.jsx("button",{className:e.enabled?"":"is-active",type:"button",onClick:()=>t(i=>({...i,enabled:!1})),children:"draft"})]}),s.jsxs("label",{children:["Severity ",s.jsx("span",{children:"*"})]}),s.jsx("div",{className:"im-chip-row",children:cue.map(i=>s.jsx("button",{className:e.severities.includes(i)?"is-active":"",type:"button",onClick:()=>r("severities",i),children:i},i))}),!n&&s.jsxs(s.Fragment,{children:[s.jsx("label",{children:"Source"}),s.jsx("div",{className:"im-chip-row",children:uue.map(i=>s.jsx("button",{className:e.sources.includes(i)?"is-active":"",type:"button",onClick:()=>r("sources",i),children:due[i]||i},i))})]}),s.jsx("label",{children:"Resource type"}),s.jsx("div",{className:"im-chip-row",children:pue.map(i=>s.jsx("button",{className:e.resourceTypes.includes(i)?"is-active":"",type:"button",onClick:()=>r("resourceTypes",i),children:i},i))}),s.jsx("label",{children:"Metric name pattern"}),s.jsx("input",{value:e.metricPattern,onChange:i=>t(o=>({...o,metricPattern:i.target.value})),placeholder:"cpu.* (optional regex)"}),s.jsxs("div",{className:"im-label-header",children:[s.jsx("label",{children:"Label conditions"}),s.jsx("button",{type:"button",onClick:()=>t(i=>({...i,labels:[...i.labels,{key:"",op:"equals",value:""}]})),children:"+ Add"})]}),e.labels.map((i,o)=>s.jsxs("div",{className:"im-label-row",children:[s.jsx("input",{value:i.key,onChange:l=>a(o,{key:l.target.value}),placeholder:"key"}),s.jsxs("select",{value:i.op,onChange:l=>a(o,{op:l.target.value}),children:[s.jsx("option",{value:"equals",children:"equals"}),s.jsx("option",{value:"not_equals",children:"not equals"}),s.jsx("option",{value:"contains",children:"contains"}),s.jsx("option",{value:"matches",children:"matches"})]}),s.jsx("input",{value:i.value,onChange:l=>a(o,{value:l.target.value}),placeholder:"value"}),s.jsx("button",{type:"button",onClick:()=>t(l=>({...l,labels:l.labels.filter((c,u)=>u!==o)})),"aria-label":"Remove",children:s.jsx(Hn,{size:16})})]},o))]})}function yue({form:e,updateForm:t}){const n=()=>t(i=>({...i,conditions:[...i.conditions,{field:"severity",operator:"equals",value:""}]})),r=(i,o)=>t(l=>({...l,conditions:l.conditions.map((c,u)=>u===i?{...c,...o}:c)})),a=i=>t(o=>({...o,conditions:o.conditions.filter((l,c)=>c!==i)}));return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Conditions"}),s.jsx("p",{children:"Additional checks on alarm fields before matching."}),s.jsx("label",{children:"Condition logic"}),s.jsxs("div",{className:"im-chip-row",children:[s.jsx("button",{className:e.conditionLogic==="all"?"is-active":"",type:"button",onClick:()=>t(i=>({...i,conditionLogic:"all"})),children:"All must match (AND)"}),s.jsx("button",{className:e.conditionLogic==="any"?"is-active":"",type:"button",onClick:()=>t(i=>({...i,conditionLogic:"any"})),children:"Any must match (OR)"})]}),s.jsxs("div",{className:"im-label-header",children:[s.jsx("label",{children:"Conditions"}),s.jsxs("button",{type:"button",onClick:n,children:[s.jsx(Wr,{size:14})," Add condition"]})]}),e.conditions.length===0&&s.jsx("p",{style:{fontSize:12,color:"var(--im-fg-muted)",marginTop:4},children:"No extra conditions — all trigger matches pass through."}),e.conditions.map((i,o)=>s.jsxs("div",{className:"im-label-row im-condition-row",children:[s.jsx("select",{value:i.field,onChange:l=>r(o,{field:l.target.value}),children:mue.map(l=>s.jsx("option",{value:l,children:l},l))}),s.jsx("select",{value:i.operator,onChange:l=>r(o,{operator:l.target.value}),children:hue.map(l=>s.jsx("option",{value:l,children:l},l))}),s.jsx("input",{value:i.value,onChange:l=>r(o,{value:l.target.value}),placeholder:"value"}),s.jsx("button",{type:"button",onClick:()=>a(o),"aria-label":"Remove",children:s.jsx(Hn,{size:16})})]},o))]})}function Eue({form:e,updateForm:t}){const n=i=>t(o=>({...o,dedup:{...o.dedup,...i}})),r=i=>{const o=e.dedup.keyFields.includes(i)?e.dedup.keyFields.filter(l=>l!==i):[...e.dedup.keyFields,i];n({keyFields:o.length?o:[i]})},a=e.dedup;return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Dedup settings"}),s.jsx("p",{children:"Collapse repeated alarms within a time window."}),s.jsxs("label",{children:["Dedup window ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:1,value:a.windowN,onChange:i=>n({windowN:parseInt(i.target.value)||1}),style:{width:72}}),s.jsxs("select",{value:a.windowU,onChange:i=>n({windowU:i.target.value}),children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"})]})]}),s.jsxs("label",{children:["Dedup key fields ",s.jsx("span",{children:"*"})]}),s.jsx("div",{className:"im-chip-row",children:fue.map(i=>s.jsx("button",{className:a.keyFields.includes(i)?"is-active":"",type:"button",onClick:()=>r(i),children:i},i))}),s.jsxs("div",{className:"im-key-preview",children:[s.jsx("small",{children:"Key preview"}),s.jsx("code",{children:a.keyFields.join(" | ")})]}),s.jsx("label",{children:"Resolved alarm behaviour"}),s.jsxs("div",{className:"im-radio-group",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",checked:a.resolvedBehavior==="allow",onChange:()=>n({resolvedBehavior:"allow"})}),"Always allow resolved alarms through (default)"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",checked:a.resolvedBehavior==="apply",onChange:()=>n({resolvedBehavior:"apply"})}),"Apply dedup window to resolved alarms too"]})]}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${a.flapEnabled?"is-on":""}`,onClick:()=>n({flapEnabled:!a.flapEnabled}),"aria-label":"Toggle flap detection",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Flap detection"}),s.jsx("small",{children:"Catch alarms toggling rapidly between states."})]})]}),a.flapEnabled&&s.jsxs("div",{className:"im-flap-settings",children:[s.jsxs("div",{children:[s.jsx("label",{children:"Threshold"}),s.jsx("input",{type:"number",min:1,value:a.flapThreshold,onChange:i=>n({flapThreshold:parseInt(i.target.value)||1}),style:{width:64}}),s.jsx("small",{children:" state changes"})]}),s.jsxs("div",{children:[s.jsx("label",{children:"Flap window (min)"}),s.jsx("input",{type:"number",min:1,value:a.flapWindowN,onChange:i=>n({flapWindowN:parseInt(i.target.value)||1}),style:{width:64}})]}),s.jsxs("div",{children:[s.jsx("label",{children:"On flap"}),s.jsxs("select",{value:a.onFlap,onChange:i=>n({onFlap:i.target.value}),children:[s.jsx("option",{value:"elevate",children:"Elevate severity by one level"}),s.jsx("option",{value:"separate",children:"Create separate flap incident"}),s.jsx("option",{value:"suppress",children:"Suppress and log only"})]})]})]})]})}function vue({form:e,updateForm:t}){const n=u=>t(p=>({...p,grouping:{...p.grouping,...u}})),r=e.grouping,[a,i]=y.useState(""),o=u=>{const p=u.trim();!p||r.groupByFields.includes(p)||(n({groupByFields:[...r.groupByFields,p]}),i(""))},l=u=>n({groupByFields:r.groupByFields.filter(p=>p!==u)}),c=r.titleTemplate?r.titleTemplate.replace(/\{resource\.name\}/g,"prod-db-01").replace(/\{metric\.name\}/g,"cpu_utilization").replace(/\{source\}/g,"cloudwatch"):"(uses default: '{resource.name} — {metric.name} incident')";return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Grouping settings"}),s.jsx("p",{children:"Combine related alarms into one incident."}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${r.enabled?"is-on":""}`,onClick:()=>n({enabled:!r.enabled}),"aria-label":"Toggle grouping",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Enable grouping"}),s.jsx("small",{children:"When off, each alarm creates its own incident."})]})]}),r.enabled&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Group by fields ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-tag-input-row",children:[r.groupByFields.map(u=>s.jsxs("span",{className:"im-tag",children:[u,s.jsx("button",{type:"button",onClick:()=>l(u),"aria-label":"Remove",children:s.jsx(Hn,{size:12})})]},u)),s.jsx("input",{value:a,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),o(a))},placeholder:"+ add field, Enter",list:"group-by-suggestions"}),s.jsx("datalist",{id:"group-by-suggestions",children:gue.map(u=>s.jsx("option",{value:u},u))})]}),s.jsxs("div",{className:"im-inline-row",style:{gap:16,flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsxs("label",{children:["Group timeout ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:1,value:r.timeoutN,onChange:u=>n({timeoutN:parseInt(u.target.value)||1}),style:{width:72}}),s.jsxs("select",{value:r.timeoutU,onChange:u=>n({timeoutU:u.target.value}),children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"})]})]})]}),s.jsxs("div",{children:[s.jsxs("label",{children:["Max alarms / group ",s.jsx("span",{children:"*"})]}),s.jsx("input",{type:"number",min:1,value:r.maxAlarms,onChange:u=>n({maxAlarms:parseInt(u.target.value)||1}),style:{width:90}})]})]}),s.jsx("label",{children:"Incident title template"}),s.jsx("input",{value:r.titleTemplate,onChange:u=>n({titleTemplate:u.target.value}),placeholder:"{resource.name} — {metric.name} incident"}),s.jsxs("small",{style:{color:"var(--im-fg-muted)"},children:["Preview: ",c]}),s.jsx("label",{children:"Severity resolution"}),s.jsxs("select",{value:r.severityResolution,onChange:u=>n({severityResolution:u.target.value}),style:{width:280},children:[s.jsx("option",{value:"highest",children:"Highest in group (recommended)"}),s.jsx("option",{value:"first",children:"First alarm"}),s.jsx("option",{value:"fixed",children:"Fixed level"})]})]})]})}function Sue({form:e,updateForm:t,providers:n,users:r,usersLoading:a,onUserSearch:i}){const o=p=>t(d=>({...d,actions:{...d.actions,...p}})),l=e.actions,c=p=>{const d=l.notifyChannels.find(f=>f.channel===p);o(d?{notifyChannels:l.notifyChannels.filter(f=>f.channel!==p)}:{notifyChannels:[...l.notifyChannels,{channel:p,target:""}]})},u=(p,d)=>{o({notifyChannels:l.notifyChannels.map(f=>f.channel===p?{...f,target:d}:f)})};return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Actions"}),s.jsx("p",{children:"What happens when an alarm group matches."}),s.jsxs("div",{className:"im-toggle-row im-action-row",style:{alignItems:"flex-start"},children:[s.jsx("div",{style:{display:"flex",gap:"12px",marginTop:"2px"},children:s.jsx("button",{type:"button",className:`im-toggle ${l.createIncident?"is-on":""}`,onClick:()=>o({createIncident:!l.createIncident}),"aria-label":"Toggle create incident",children:s.jsx("span",{})})}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"12px"},children:[s.jsx("strong",{children:"Create incident"}),l.createIncident&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-inline-row",children:[s.jsx("label",{style:{width:80},children:"Priority"}),s.jsxs("select",{value:l.priority,onChange:p=>o({priority:p.target.value}),children:[s.jsx("option",{value:"auto",children:"Auto priority"}),s.jsx("option",{value:"P1",children:"P1"}),s.jsx("option",{value:"P2",children:"P2"}),s.jsx("option",{value:"P3",children:"P3"}),s.jsx("option",{value:"P4",children:"P4"})]})]}),s.jsxs("div",{className:"im-inline-row",style:{alignItems:"center"},children:[s.jsx("label",{style:{width:80},children:"Assign to"}),s.jsx("div",{style:{flex:1,minWidth:250,maxWidth:400},children:s.jsx(Qce,{selected:l.assignees||[],options:r.map(p=>({label:p.full_name||p.email,value:p.id})),onChange:p=>o({assignees:p}),onSearchChange:i,placeholder:a?"Loading...":"Select users to assign",disabled:a})})]})]})]})]}),s.jsx("label",{children:"Notify channels"}),n.length>0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[s.jsx("div",{className:"im-chip-row",children:n.map(p=>{const d=l.notifyChannels.some(f=>f.channel===p.provider_name);return s.jsx("button",{className:d?"is-active":"",type:"button",onClick:()=>c(p.provider_name),children:p.display_name||p.provider_name},p.id)})}),l.notifyChannels.length>0&&s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"8px",padding:"12px",background:"var(--im-surface-2)",borderRadius:"6px"},children:l.notifyChannels.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[s.jsxs("label",{style:{margin:0,minWidth:"120px",fontWeight:600},children:[p.channel," target ",s.jsx("span",{children:"*"})]}),s.jsx("input",{className:"im-field-input",style:{flex:1,maxWidth:"300px"},placeholder:"Enter target (e.g. email or webhook)",value:p.target,onChange:d=>u(p.channel,d.target.value)})]},p.channel))})]}):s.jsx("p",{style:{fontSize:12,color:"var(--im-fg-muted)"},children:"No notification providers configured. Add them in Settings."}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${l.runSopAgent?"is-on":""}`,onClick:()=>o({runSopAgent:!l.runSopAgent}),"aria-label":"Toggle SOP agent",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Run AI analysis"}),s.jsx("small",{children:"AI-assisted root cause analysis on the incident."})]})]}),l.runSopAgent&&s.jsxs("div",{style:{paddingLeft:16},children:[s.jsx("label",{children:"LLM model"}),s.jsxs("select",{value:l.llmModel,onChange:p=>o({llmModel:p.target.value}),style:{width:260},children:[s.jsx("option",{value:"bedrock",children:"Bedrock (Claude)"}),s.jsx("option",{value:"anthropic",children:"Anthropic API"})]})]}),s.jsx("label",{children:"Escalate after"}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:0,value:l.escalateAfterN,onChange:p=>o({escalateAfterN:parseInt(p.target.value)||0}),placeholder:"0",style:{width:72}}),s.jsx("small",{children:"minutes — if not acknowledged, re-notify escalation channels"})]})]})}function gN({workflowId:e,sourceId:t,onBack:n}){const[r,a]=y.useState(""),[i,o]=y.useState(Sr),[l,c]=y.useState(null),[u,p]=y.useState([]),[d,f]=y.useState(!1),[m,h]=y.useState(!0),[g,b]=y.useState("visual"),[x,S]=y.useState("triggers"),[T,N]=y.useState([]),[A,C]=y.useState(null),[k,O]=y.useState(!1),[M,R]=y.useState([]),[j,U]=y.useState(!1);y.useEffect(()=>{Ie.getNotificationProviders().then(B=>{B.ok&&N(B.providers)}).catch(()=>{}),Ie.getUsers({limit:50}).then(B=>{B.users&&R(B.users)}).catch(()=>{})},[]);const G=y.useCallback(B=>{U(!0),Ie.getUsers({search:B,limit:10}).then(H=>{H.users&&R(H.users)}).catch(()=>{}).finally(()=>U(!1))},[]);y.useEffect(()=>{if(!e){const B=dm(Sr);a(B),o(Sr),h(!1);return}$r.listWorkflows().then(B=>{const H=B.find(V=>V.id===e);if(!H){ae.error("Workflow not found"),n();return}c(H);const I=H.yamlDefinition||dm(Sr);a(I),o(hN(I)),h(!1)}).catch(()=>{ae.error("Failed to load workflow"),n()})},[e]),y.useEffect(()=>{if(m)return;const B=setTimeout(async()=>{try{const H=await $r.parseYaml(r);p(H.ok?[]:H.errors||[])}catch(H){p(H.response?.data?.errors||[H.message||"Failed to parse YAML"])}},500);return()=>clearTimeout(B)},[r,m]);const q=async()=>{if(u.length>0){ae.error("Please fix YAML errors before saving");return}let B;try{B=Pn.load(r)}catch{ae.error("Invalid YAML syntax");return}const H=B?.name||mN(r);f(!0);try{e?(await $r.updateWorkflow(e,{name:H,isActive:B?.active!==!1&&B?.enabled!==!1,priority:B?.priority||0,yamlDefinition:r}),ae.success("Workflow updated")):(await $r.createWorkflow({name:H,isActive:B?.active!==!1&&B?.enabled!==!1,priority:B?.priority||0,yamlDefinition:r,sourceId:t||null}),ae.success("Workflow created")),n()}catch(I){ae.error(I.message||"Failed to save workflow")}finally{f(!1)}},P=B=>{o(H=>{const I=B(H);return a(dm(I)),I})},z=async()=>{O(!0),C(null);try{const B=await $r.parseYaml(r);if(B.ok&&B.definition){const H=B.definition.actions?.map(I=>I.type)??[];C({ok:!0,actions:H})}else C({ok:!1,errors:B.errors})}catch(B){C({ok:!1,errors:[B.message||"Test failed"]})}finally{O(!1)}};if(m)return s.jsx("div",{className:"im-page",children:s.jsx("div",{className:"im-loading-panel",children:"Loading workflow..."})});const re=[{id:"triggers",label:"Triggers"},{id:"conditions",label:"Conditions"},{id:"dedup",label:"Dedup"},{id:"grouping",label:"Grouping"},{id:"actions",label:"Actions"}];return s.jsxs("div",{className:"im-workflow-editor",children:[s.jsxs("div",{className:"im-editor-topbar",children:[s.jsx("button",{className:"im-back-button",type:"button",onClick:n,"aria-label":"Back to workflows",children:s.jsx(Vr,{size:16})}),s.jsx("h2",{children:l?.name||mN(r)}),s.jsx("span",{className:"im-draft-pill",children:l?.isActive?"Active":"Draft"}),s.jsxs("div",{className:"im-editor-actions",children:[s.jsxs("div",{className:"im-mode-toggle",children:[s.jsx("button",{className:g==="visual"?"is-active":"",type:"button",onClick:()=>b("visual"),children:"Visual"}),s.jsx("button",{className:g==="yaml"?"is-active":"",type:"button",onClick:()=>b("yaml"),children:"YAML"})]}),s.jsx(ie,{className:"im-primary-button",onClick:q,disabled:d||u.length>0,children:d?"Saving...":"Save"})]})]}),s.jsxs("div",{className:"im-editor-layout",children:[s.jsxs("aside",{className:"im-editor-steps",children:[s.jsx("strong",{children:"Workflow structure"}),re.map(({id:B,label:H})=>s.jsxs("button",{className:x===B?"is-active":"",type:"button","aria-selected":x===B,onClick:()=>{S(B),b("visual")},children:[s.jsx("span",{children:H}),s.jsx("small",{children:bue(B,i)})]},B))]}),s.jsx("main",{className:"im-editor-main",children:g==="visual"?s.jsxs(s.Fragment,{children:[x==="triggers"&&s.jsx(xue,{form:i,updateForm:P,sourceId:t}),x==="conditions"&&s.jsx(yue,{form:i,updateForm:P}),x==="dedup"&&s.jsx(Eue,{form:i,updateForm:P}),x==="grouping"&&s.jsx(vue,{form:i,updateForm:P}),x==="actions"&&s.jsx(Sue,{form:i,updateForm:P,providers:T,users:M,usersLoading:j,onUserSearch:G})]}):s.jsx("div",{className:"im-yaml-monaco im-yaml-monaco-edit",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:r,theme:"vs-dark",onChange:B=>{const H=B||"";a(H),o(hN(H))},options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",tabSize:2}})})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:r,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})}),s.jsxs("div",{className:"im-test-run",children:[s.jsx("strong",{children:"Test run"}),s.jsx("button",{type:"button",onClick:z,disabled:k,children:k?"Running...":"Run with sample alarm"}),A?s.jsx("div",{className:"im-test-result",children:A.ok?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"im-test-match",children:"MATCH"}),s.jsx("small",{children:"All triggers satisfied"}),A.actions&&A.actions.length>0&&s.jsxs("div",{className:"im-test-actions",children:[s.jsx("small",{children:"Actions that would fire:"}),s.jsx("div",{className:"im-chip-row",children:A.actions.map(B=>s.jsx("span",{className:"im-action-tag",children:B},B))})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"im-test-nomatch",children:"NO MATCH"}),A.errors?.map((B,H)=>s.jsx("small",{children:B},H))]})}):s.jsx("p",{children:"Run to see MATCH/NO-MATCH, group key, and actions."})]})]})]}),u.length>0&&s.jsx("div",{className:"im-editor-errors",children:u.map((B,H)=>s.jsx("div",{children:B},H))})]})}const bN=e=>`name: "My Normalization Rule"
341
+ `}function mN(e){try{return Pn.load(e)?.name||"new-workflow"}catch{return"new-workflow"}}function hN(e){try{const t=Pn.load(e),n=Array.isArray(t?.triggers?.labels)?t.triggers.labels.map(d=>{if(typeof d!="string")return{key:"env",op:"equals",value:"production"};const f=d.match(/^(\S+)\s+(\S+)\s+'?(.+?)'?$/);return{key:f?.[1]||"env",op:f?.[2]||"equals",value:f?.[3]||"production"}}):Sr.labels;let r="all";const a=[];if(Array.isArray(t?.conditions)){for(const d of t.conditions)if(d?.groupId!=="triggers"&&(d?.operator==="OR"&&(r="any"),Array.isArray(d?.rules)))for(const f of d.rules)f?.field&&f?.operator&&a.push({field:f.field,operator:f.operator,value:Array.isArray(f.value)?f.value.join(", "):String(f.value??"")})}const i=t?.dedup,o={...OO};if(i&&typeof i=="object"){const f=String(i.window||"5m").match(/^(\d+)([smh])$/);if(f&&(o.windowN=parseInt(f[1]),o.windowU=f[2]),Array.isArray(i.key)&&(o.keyFields=i.key),i.resolved==="apply"&&(o.resolvedBehavior="apply"),i.flap&&typeof i.flap=="object"){o.flapEnabled=!0,o.flapThreshold=i.flap.threshold??3;const m=String(i.flap.window||"10m").match(/^(\d+)/);m&&(o.flapWindowN=parseInt(m[1])),o.onFlap=i.flap.on_flap||"elevate"}}const l=t?.grouping,c={...LO};if(l&&typeof l=="object"){c.enabled=l.enabled!==!1,Array.isArray(l.key)&&(c.groupByFields=l.key);const f=String(l.timeout||"5m").match(/^(\d+)([smh])$/);f&&(c.timeoutN=parseInt(f[1]),c.timeoutU=f[2]),l.max_alarms&&(c.maxAlarms=l.max_alarms),l.title&&(c.titleTemplate=l.title),l.severity&&(c.severityResolution=l.severity)}const u=Array.isArray(t?.actions)?t.actions:[],p={...jO,notifyChannels:[]};for(const d of u){const f=d?.type||Object.keys(d||{})[0],m=d?.config||(f?d[f]:{})||{};f==="create_incident"&&(p.createIncident=!0,p.priority=m.priority||"P1",p.assignees=Array.isArray(m.assign_to)?m.assign_to:[]),f==="send_notification"&&(m.channels?(Array.isArray(m.channels)?m.channels:[m.channels]).forEach(g=>p.notifyChannels.push({channel:g,target:""})):m.type&&p.notifyChannels.push({channel:m.type,target:m.target||""})),f==="generate_rca"&&(p.runSopAgent=!0,p.llmModel=m.model||"bedrock")}return{name:t?.name||Sr.name,enabled:t?.enabled===!0||t?.active===!0,severities:Array.isArray(t?.triggers?.severity)&&t.triggers.severity.length?t.triggers.severity:Sr.severities,sources:Array.isArray(t?.triggers?.source)&&t.triggers.source.length?t.triggers.source:Sr.sources,resourceTypes:Array.isArray(t?.triggers?.resource_type)?t.triggers.resource_type:[],metricPattern:typeof t?.triggers?.metric_name=="string"?t.triggers.metric_name:Sr.metricPattern,labels:n,conditionLogic:r,conditions:a,dedup:o,grouping:c,actions:p}}catch{return Sr}}function bue(e,t){switch(e){case"triggers":{const n=[t.severities.join(", ")||"any sev"];return t.sources.length&&n.push(t.sources.join(", ")),n.join(" · ")}case"conditions":return t.conditions.length?`${t.conditions.length} condition${t.conditions.length>1?"s":""} (${t.conditionLogic})`:"none";case"dedup":return`${t.dedup.windowN}${t.dedup.windowU} window · ${t.dedup.keyFields.length} key fields`;case"grouping":return t.grouping.enabled?`by ${t.grouping.groupByFields.join(", ")||"—"} · ${t.grouping.timeoutN}${t.grouping.timeoutU}`:"disabled";case"actions":{const n=[];return t.actions.createIncident&&n.push("incident"),t.actions.notifyChannels.length&&n.push("notify"),t.actions.runSopAgent&&n.push("AI"),n.join(", ")||"none"}}}function xue({form:e,updateForm:t,sourceId:n}){const r=(i,o)=>{t(l=>{const u=l[i].includes(o)?l[i].filter(p=>p!==o):[...l[i],o];return{...l,[i]:u.length?u:[o]}})},a=(i,o)=>{t(l=>({...l,labels:l.labels.map((c,u)=>u===i?{...c,...o}:c)}))};return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Triggers"}),s.jsx("p",{children:"Which alerts this workflow listens for."}),s.jsxs("label",{children:["Workflow name ",s.jsx("span",{children:"*"})]}),s.jsx("input",{value:e.name,onChange:i=>t(o=>({...o,name:i.target.value})),placeholder:"new-workflow"}),s.jsx("label",{children:"Status"}),s.jsxs("div",{className:"im-chip-row",children:[s.jsx("button",{className:e.enabled?"is-active":"",type:"button",onClick:()=>t(i=>({...i,enabled:!0})),children:"enabled"}),s.jsx("button",{className:e.enabled?"":"is-active",type:"button",onClick:()=>t(i=>({...i,enabled:!1})),children:"draft"})]}),s.jsxs("label",{children:["Severity ",s.jsx("span",{children:"*"})]}),s.jsx("div",{className:"im-chip-row",children:cue.map(i=>s.jsx("button",{className:e.severities.includes(i)?"is-active":"",type:"button",onClick:()=>r("severities",i),children:i},i))}),!n&&s.jsxs(s.Fragment,{children:[s.jsx("label",{children:"Source"}),s.jsx("div",{className:"im-chip-row",children:uue.map(i=>s.jsx("button",{className:e.sources.includes(i)?"is-active":"",type:"button",onClick:()=>r("sources",i),children:due[i]||i},i))})]}),s.jsx("label",{children:"Resource type"}),s.jsx("div",{className:"im-chip-row",children:pue.map(i=>s.jsx("button",{className:e.resourceTypes.includes(i)?"is-active":"",type:"button",onClick:()=>r("resourceTypes",i),children:i},i))}),s.jsx("label",{children:"Metric name pattern"}),s.jsx("input",{value:e.metricPattern,onChange:i=>t(o=>({...o,metricPattern:i.target.value})),placeholder:"cpu.* (optional regex)"}),s.jsxs("div",{className:"im-label-header",children:[s.jsx("label",{children:"Label conditions"}),s.jsx("button",{type:"button",onClick:()=>t(i=>({...i,labels:[...i.labels,{key:"",op:"equals",value:""}]})),children:"+ Add"})]}),e.labels.map((i,o)=>s.jsxs("div",{className:"im-label-row",children:[s.jsx("input",{value:i.key,onChange:l=>a(o,{key:l.target.value}),placeholder:"key"}),s.jsxs("select",{value:i.op,onChange:l=>a(o,{op:l.target.value}),children:[s.jsx("option",{value:"equals",children:"equals"}),s.jsx("option",{value:"not_equals",children:"not equals"}),s.jsx("option",{value:"contains",children:"contains"}),s.jsx("option",{value:"matches",children:"matches"})]}),s.jsx("input",{value:i.value,onChange:l=>a(o,{value:l.target.value}),placeholder:"value"}),s.jsx("button",{type:"button",onClick:()=>t(l=>({...l,labels:l.labels.filter((c,u)=>u!==o)})),"aria-label":"Remove",children:s.jsx(Hn,{size:16})})]},o))]})}function yue({form:e,updateForm:t}){const n=()=>t(i=>({...i,conditions:[...i.conditions,{field:"severity",operator:"equals",value:""}]})),r=(i,o)=>t(l=>({...l,conditions:l.conditions.map((c,u)=>u===i?{...c,...o}:c)})),a=i=>t(o=>({...o,conditions:o.conditions.filter((l,c)=>c!==i)}));return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Conditions"}),s.jsx("p",{children:"Additional checks on alert fields before matching."}),s.jsx("label",{children:"Condition logic"}),s.jsxs("div",{className:"im-chip-row",children:[s.jsx("button",{className:e.conditionLogic==="all"?"is-active":"",type:"button",onClick:()=>t(i=>({...i,conditionLogic:"all"})),children:"All must match (AND)"}),s.jsx("button",{className:e.conditionLogic==="any"?"is-active":"",type:"button",onClick:()=>t(i=>({...i,conditionLogic:"any"})),children:"Any must match (OR)"})]}),s.jsxs("div",{className:"im-label-header",children:[s.jsx("label",{children:"Conditions"}),s.jsxs("button",{type:"button",onClick:n,children:[s.jsx(Wr,{size:14})," Add condition"]})]}),e.conditions.length===0&&s.jsx("p",{style:{fontSize:12,color:"var(--im-fg-muted)",marginTop:4},children:"No extra conditions — all trigger matches pass through."}),e.conditions.map((i,o)=>s.jsxs("div",{className:"im-label-row im-condition-row",children:[s.jsx("select",{value:i.field,onChange:l=>r(o,{field:l.target.value}),children:mue.map(l=>s.jsx("option",{value:l,children:l},l))}),s.jsx("select",{value:i.operator,onChange:l=>r(o,{operator:l.target.value}),children:hue.map(l=>s.jsx("option",{value:l,children:l},l))}),s.jsx("input",{value:i.value,onChange:l=>r(o,{value:l.target.value}),placeholder:"value"}),s.jsx("button",{type:"button",onClick:()=>a(o),"aria-label":"Remove",children:s.jsx(Hn,{size:16})})]},o))]})}function Eue({form:e,updateForm:t}){const n=i=>t(o=>({...o,dedup:{...o.dedup,...i}})),r=i=>{const o=e.dedup.keyFields.includes(i)?e.dedup.keyFields.filter(l=>l!==i):[...e.dedup.keyFields,i];n({keyFields:o.length?o:[i]})},a=e.dedup;return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Dedup settings"}),s.jsx("p",{children:"Collapse repeated alerts within a time window."}),s.jsxs("label",{children:["Dedup window ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:1,value:a.windowN,onChange:i=>n({windowN:parseInt(i.target.value)||1}),style:{width:72}}),s.jsxs("select",{value:a.windowU,onChange:i=>n({windowU:i.target.value}),children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"})]})]}),s.jsxs("label",{children:["Dedup key fields ",s.jsx("span",{children:"*"})]}),s.jsx("div",{className:"im-chip-row",children:fue.map(i=>s.jsx("button",{className:a.keyFields.includes(i)?"is-active":"",type:"button",onClick:()=>r(i),children:i},i))}),s.jsxs("div",{className:"im-key-preview",children:[s.jsx("small",{children:"Key preview"}),s.jsx("code",{children:a.keyFields.join(" | ")})]}),s.jsx("label",{children:"Resolved alert behaviour"}),s.jsxs("div",{className:"im-radio-group",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",checked:a.resolvedBehavior==="allow",onChange:()=>n({resolvedBehavior:"allow"})}),"Always allow resolved alerts through (default)"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",checked:a.resolvedBehavior==="apply",onChange:()=>n({resolvedBehavior:"apply"})}),"Apply dedup window to resolved alerts too"]})]}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${a.flapEnabled?"is-on":""}`,onClick:()=>n({flapEnabled:!a.flapEnabled}),"aria-label":"Toggle flap detection",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Flap detection"}),s.jsx("small",{children:"Catch alerts toggling rapidly between states."})]})]}),a.flapEnabled&&s.jsxs("div",{className:"im-flap-settings",children:[s.jsxs("div",{children:[s.jsx("label",{children:"Threshold"}),s.jsx("input",{type:"number",min:1,value:a.flapThreshold,onChange:i=>n({flapThreshold:parseInt(i.target.value)||1}),style:{width:64}}),s.jsx("small",{children:" state changes"})]}),s.jsxs("div",{children:[s.jsx("label",{children:"Flap window (min)"}),s.jsx("input",{type:"number",min:1,value:a.flapWindowN,onChange:i=>n({flapWindowN:parseInt(i.target.value)||1}),style:{width:64}})]}),s.jsxs("div",{children:[s.jsx("label",{children:"On flap"}),s.jsxs("select",{value:a.onFlap,onChange:i=>n({onFlap:i.target.value}),children:[s.jsx("option",{value:"elevate",children:"Elevate severity by one level"}),s.jsx("option",{value:"separate",children:"Create separate flap incident"}),s.jsx("option",{value:"suppress",children:"Suppress and log only"})]})]})]})]})}function vue({form:e,updateForm:t}){const n=u=>t(p=>({...p,grouping:{...p.grouping,...u}})),r=e.grouping,[a,i]=y.useState(""),o=u=>{const p=u.trim();!p||r.groupByFields.includes(p)||(n({groupByFields:[...r.groupByFields,p]}),i(""))},l=u=>n({groupByFields:r.groupByFields.filter(p=>p!==u)}),c=r.titleTemplate?r.titleTemplate.replace(/\{resource\.name\}/g,"prod-db-01").replace(/\{metric\.name\}/g,"cpu_utilization").replace(/\{source\}/g,"cloudwatch"):"(uses default: '{resource.name} — {metric.name} incident')";return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Grouping settings"}),s.jsx("p",{children:"Combine related alerts into one incident."}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${r.enabled?"is-on":""}`,onClick:()=>n({enabled:!r.enabled}),"aria-label":"Toggle grouping",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Enable grouping"}),s.jsx("small",{children:"When off, each alert creates its own incident."})]})]}),r.enabled&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Group by fields ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-tag-input-row",children:[r.groupByFields.map(u=>s.jsxs("span",{className:"im-tag",children:[u,s.jsx("button",{type:"button",onClick:()=>l(u),"aria-label":"Remove",children:s.jsx(Hn,{size:12})})]},u)),s.jsx("input",{value:a,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),o(a))},placeholder:"+ add field, Enter",list:"group-by-suggestions"}),s.jsx("datalist",{id:"group-by-suggestions",children:gue.map(u=>s.jsx("option",{value:u},u))})]}),s.jsxs("div",{className:"im-inline-row",style:{gap:16,flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsxs("label",{children:["Group timeout ",s.jsx("span",{children:"*"})]}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:1,value:r.timeoutN,onChange:u=>n({timeoutN:parseInt(u.target.value)||1}),style:{width:72}}),s.jsxs("select",{value:r.timeoutU,onChange:u=>n({timeoutU:u.target.value}),children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"})]})]})]}),s.jsxs("div",{children:[s.jsxs("label",{children:["Max alerts / group ",s.jsx("span",{children:"*"})]}),s.jsx("input",{type:"number",min:1,value:r.maxAlarms,onChange:u=>n({maxAlarms:parseInt(u.target.value)||1}),style:{width:90}})]})]}),s.jsx("label",{children:"Incident title template"}),s.jsx("input",{value:r.titleTemplate,onChange:u=>n({titleTemplate:u.target.value}),placeholder:"{resource.name} — {metric.name} incident"}),s.jsxs("small",{style:{color:"var(--im-fg-muted)"},children:["Preview: ",c]}),s.jsx("label",{children:"Severity resolution"}),s.jsxs("select",{value:r.severityResolution,onChange:u=>n({severityResolution:u.target.value}),style:{width:280},children:[s.jsx("option",{value:"highest",children:"Highest in group (recommended)"}),s.jsx("option",{value:"first",children:"First alert"}),s.jsx("option",{value:"fixed",children:"Fixed level"})]})]})]})}function Sue({form:e,updateForm:t,providers:n,users:r,usersLoading:a,onUserSearch:i}){const o=p=>t(d=>({...d,actions:{...d.actions,...p}})),l=e.actions,c=p=>{const d=l.notifyChannels.find(f=>f.channel===p);o(d?{notifyChannels:l.notifyChannels.filter(f=>f.channel!==p)}:{notifyChannels:[...l.notifyChannels,{channel:p,target:""}]})},u=(p,d)=>{o({notifyChannels:l.notifyChannels.map(f=>f.channel===p?{...f,target:d}:f)})};return s.jsxs("div",{className:"im-visual-form",children:[s.jsx("h3",{children:"Actions"}),s.jsx("p",{children:"What happens when an alert group matches."}),s.jsxs("div",{className:"im-toggle-row im-action-row",style:{alignItems:"flex-start"},children:[s.jsx("div",{style:{display:"flex",gap:"12px",marginTop:"2px"},children:s.jsx("button",{type:"button",className:`im-toggle ${l.createIncident?"is-on":""}`,onClick:()=>o({createIncident:!l.createIncident}),"aria-label":"Toggle create incident",children:s.jsx("span",{})})}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"12px"},children:[s.jsx("strong",{children:"Create incident"}),l.createIncident&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"im-inline-row",children:[s.jsx("label",{style:{width:80},children:"Priority"}),s.jsxs("select",{value:l.priority,onChange:p=>o({priority:p.target.value}),children:[s.jsx("option",{value:"auto",children:"Auto priority"}),s.jsx("option",{value:"P1",children:"P1"}),s.jsx("option",{value:"P2",children:"P2"}),s.jsx("option",{value:"P3",children:"P3"}),s.jsx("option",{value:"P4",children:"P4"})]})]}),s.jsxs("div",{className:"im-inline-row",style:{alignItems:"center"},children:[s.jsx("label",{style:{width:80},children:"Assign to"}),s.jsx("div",{style:{flex:1,minWidth:250,maxWidth:400},children:s.jsx(Qce,{selected:l.assignees||[],options:r.map(p=>({label:p.full_name||p.email,value:p.id})),onChange:p=>o({assignees:p}),onSearchChange:i,placeholder:a?"Loading...":"Select users to assign",disabled:a})})]})]})]})]}),s.jsx("label",{children:"Notify channels"}),n.length>0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[s.jsx("div",{className:"im-chip-row",children:n.map(p=>{const d=l.notifyChannels.some(f=>f.channel===p.provider_name);return s.jsx("button",{className:d?"is-active":"",type:"button",onClick:()=>c(p.provider_name),children:p.display_name||p.provider_name},p.id)})}),l.notifyChannels.length>0&&s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"8px",padding:"12px",background:"var(--im-surface-2)",borderRadius:"6px"},children:l.notifyChannels.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[s.jsxs("label",{style:{margin:0,minWidth:"120px",fontWeight:600},children:[p.channel," target ",s.jsx("span",{children:"*"})]}),s.jsx("input",{className:"im-field-input",style:{flex:1,maxWidth:"300px"},placeholder:"Enter target (e.g. email or webhook)",value:p.target,onChange:d=>u(p.channel,d.target.value)})]},p.channel))})]}):s.jsx("p",{style:{fontSize:12,color:"var(--im-fg-muted)"},children:"No notification providers configured. Add them in Settings."}),s.jsxs("div",{className:"im-toggle-row",children:[s.jsx("button",{type:"button",className:`im-toggle ${l.runSopAgent?"is-on":""}`,onClick:()=>o({runSopAgent:!l.runSopAgent}),"aria-label":"Toggle SOP agent",children:s.jsx("span",{})}),s.jsxs("div",{children:[s.jsx("strong",{children:"Run AI analysis"}),s.jsx("small",{children:"AI-assisted root cause analysis on the incident."})]})]}),l.runSopAgent&&s.jsxs("div",{style:{paddingLeft:16},children:[s.jsx("label",{children:"LLM model"}),s.jsxs("select",{value:l.llmModel,onChange:p=>o({llmModel:p.target.value}),style:{width:260},children:[s.jsx("option",{value:"bedrock",children:"Bedrock (Claude)"}),s.jsx("option",{value:"anthropic",children:"Anthropic API"})]})]}),s.jsx("label",{children:"Escalate after"}),s.jsxs("div",{className:"im-inline-row",children:[s.jsx("input",{type:"number",min:0,value:l.escalateAfterN,onChange:p=>o({escalateAfterN:parseInt(p.target.value)||0}),placeholder:"0",style:{width:72}}),s.jsx("small",{children:"minutes — if not acknowledged, re-notify escalation channels"})]})]})}function gN({workflowId:e,sourceId:t,onBack:n}){const[r,a]=y.useState(""),[i,o]=y.useState(Sr),[l,c]=y.useState(null),[u,p]=y.useState([]),[d,f]=y.useState(!1),[m,h]=y.useState(!0),[g,b]=y.useState("visual"),[x,S]=y.useState("triggers"),[T,N]=y.useState([]),[A,C]=y.useState(null),[k,O]=y.useState(!1),[M,R]=y.useState([]),[j,U]=y.useState(!1);y.useEffect(()=>{Ie.getNotificationProviders().then(B=>{B.ok&&N(B.providers)}).catch(()=>{}),Ie.getUsers({limit:50}).then(B=>{B.users&&R(B.users)}).catch(()=>{})},[]);const G=y.useCallback(B=>{U(!0),Ie.getUsers({search:B,limit:10}).then(H=>{H.users&&R(H.users)}).catch(()=>{}).finally(()=>U(!1))},[]);y.useEffect(()=>{if(!e){const B=dm(Sr);a(B),o(Sr),h(!1);return}$r.listWorkflows().then(B=>{const H=B.find(V=>V.id===e);if(!H){ae.error("Workflow not found"),n();return}c(H);const I=H.yamlDefinition||dm(Sr);a(I),o(hN(I)),h(!1)}).catch(()=>{ae.error("Failed to load workflow"),n()})},[e]),y.useEffect(()=>{if(m)return;const B=setTimeout(async()=>{try{const H=await $r.parseYaml(r);p(H.ok?[]:H.errors||[])}catch(H){p(H.response?.data?.errors||[H.message||"Failed to parse YAML"])}},500);return()=>clearTimeout(B)},[r,m]);const q=async()=>{if(u.length>0){ae.error("Please fix YAML errors before saving");return}let B;try{B=Pn.load(r)}catch{ae.error("Invalid YAML syntax");return}const H=B?.name||mN(r);f(!0);try{e?(await $r.updateWorkflow(e,{name:H,isActive:B?.active!==!1&&B?.enabled!==!1,priority:B?.priority||0,yamlDefinition:r}),ae.success("Workflow updated")):(await $r.createWorkflow({name:H,isActive:B?.active!==!1&&B?.enabled!==!1,priority:B?.priority||0,yamlDefinition:r,sourceId:t||null}),ae.success("Workflow created")),n()}catch(I){ae.error(I.message||"Failed to save workflow")}finally{f(!1)}},P=B=>{o(H=>{const I=B(H);return a(dm(I)),I})},z=async()=>{O(!0),C(null);try{const B=await $r.parseYaml(r);if(B.ok&&B.definition){const H=B.definition.actions?.map(I=>I.type)??[];C({ok:!0,actions:H})}else C({ok:!1,errors:B.errors})}catch(B){C({ok:!1,errors:[B.message||"Test failed"]})}finally{O(!1)}};if(m)return s.jsx("div",{className:"im-page",children:s.jsx("div",{className:"im-loading-panel",children:"Loading workflow..."})});const re=[{id:"triggers",label:"Triggers"},{id:"conditions",label:"Conditions"},{id:"dedup",label:"Dedup"},{id:"grouping",label:"Grouping"},{id:"actions",label:"Actions"}];return s.jsxs("div",{className:"im-workflow-editor",children:[s.jsxs("div",{className:"im-editor-topbar",children:[s.jsx("button",{className:"im-back-button",type:"button",onClick:n,"aria-label":"Back to workflows",children:s.jsx(Vr,{size:16})}),s.jsx("h2",{children:l?.name||mN(r)}),s.jsx("span",{className:"im-draft-pill",children:l?.isActive?"Active":"Draft"}),s.jsxs("div",{className:"im-editor-actions",children:[s.jsxs("div",{className:"im-mode-toggle",children:[s.jsx("button",{className:g==="visual"?"is-active":"",type:"button",onClick:()=>b("visual"),children:"Visual"}),s.jsx("button",{className:g==="yaml"?"is-active":"",type:"button",onClick:()=>b("yaml"),children:"YAML"})]}),s.jsx(ie,{className:"im-primary-button",onClick:q,disabled:d||u.length>0,children:d?"Saving...":"Save"})]})]}),s.jsxs("div",{className:"im-editor-layout",children:[s.jsxs("aside",{className:"im-editor-steps",children:[s.jsx("strong",{children:"Workflow structure"}),re.map(({id:B,label:H})=>s.jsxs("button",{className:x===B?"is-active":"",type:"button","aria-selected":x===B,onClick:()=>{S(B),b("visual")},children:[s.jsx("span",{children:H}),s.jsx("small",{children:bue(B,i)})]},B))]}),s.jsx("main",{className:"im-editor-main",children:g==="visual"?s.jsxs(s.Fragment,{children:[x==="triggers"&&s.jsx(xue,{form:i,updateForm:P,sourceId:t}),x==="conditions"&&s.jsx(yue,{form:i,updateForm:P}),x==="dedup"&&s.jsx(Eue,{form:i,updateForm:P}),x==="grouping"&&s.jsx(vue,{form:i,updateForm:P}),x==="actions"&&s.jsx(Sue,{form:i,updateForm:P,providers:T,users:M,usersLoading:j,onUserSearch:G})]}):s.jsx("div",{className:"im-yaml-monaco im-yaml-monaco-edit",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:r,theme:"vs-dark",onChange:B=>{const H=B||"";a(H),o(hN(H))},options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",tabSize:2}})})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:r,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})}),s.jsxs("div",{className:"im-test-run",children:[s.jsx("strong",{children:"Test run"}),s.jsx("button",{type:"button",onClick:z,disabled:k,children:k?"Running...":"Run with sample alert"}),A?s.jsx("div",{className:"im-test-result",children:A.ok?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"im-test-match",children:"MATCH"}),s.jsx("small",{children:"All triggers satisfied"}),A.actions&&A.actions.length>0&&s.jsxs("div",{className:"im-test-actions",children:[s.jsx("small",{children:"Actions that would fire:"}),s.jsx("div",{className:"im-chip-row",children:A.actions.map(B=>s.jsx("span",{className:"im-action-tag",children:B},B))})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"im-test-nomatch",children:"NO MATCH"}),A.errors?.map((B,H)=>s.jsx("small",{children:B},H))]})}):s.jsx("p",{children:"Run to see MATCH/NO-MATCH, group key, and actions."})]})]})]}),u.length>0&&s.jsx("div",{className:"im-editor-errors",children:u.map((B,H)=>s.jsx("div",{children:B},H))})]})}const bN=e=>`name: "My Normalization Rule"
342
342
  priority: 0
343
343
  is_active: true
344
344
  ${e?`source_id: "${e}"`:'source_type: ""'}
@@ -348,4 +348,4 @@ category_rules:
348
348
  alertname: "High CPU"
349
349
  category: "compute"
350
350
  `;function xN({ruleId:e,sourceId:t,onBack:n}){const[r,a]=y.useState(bN(t)),[i,o]=y.useState(""),[l,c]=y.useState([]),[u,p]=y.useState(!1),[d,f]=y.useState(!1),[m,h]=y.useState(!!e),[g,b]=y.useState(!1);y.useEffect(()=>{e&&Ie.getNormalizationConfig(e).then(A=>{A.ok&&A.config?(a(A.config.yamlDefinition||bN(t)),o(A.config.fieldMapping||""),b(!!A.config.isSystem)):(ae.error("Rule not found"),n()),h(!1)}).catch(()=>{ae.error("Failed to load rule"),n()})},[e]),y.useEffect(()=>{if(m)return;const A=setTimeout(async()=>{f(!0);try{const C=await Ie.parseNormalizationYaml(r);C.ok?c([]):c(C.errors||[])}catch(C){C.response?.data?.errors?c(C.response.data.errors):c([C.message||"Failed to parse YAML"])}finally{f(!1)}},600);return()=>clearTimeout(A)},[r,m]);const x=async()=>{if(l.length>0){ae.error("Please fix YAML errors before saving");return}let A;try{A=Pn.load(r)}catch{ae.error("Invalid YAML syntax");return}if(!A||!A.name||typeof A.name!="string"||!A.name.trim()){ae.error("Name is required in YAML");return}p(!0);try{const C={name:A.name,isActive:A.is_active!==!1,priority:A.priority||0,yamlDefinition:r,fieldMapping:i};e||(C.sourceType=A.source_type||null,C.sourceId=A.source_id||t||null),e?(await Ie.updateNormalizationConfig(e,C),ae.success("Rule updated")):(await Ie.createNormalizationConfig(C),ae.success("Rule created")),n()}catch(C){ae.error(C.message||"Failed to save rule")}finally{p(!1)}},S=(A,C)=>{try{const k=Pn.load(r)||{};k[A]=C,a(Pn.dump(k,{indent:2}))}catch{}},T=async()=>{let A=null;try{A=Pn.load(r)?.source_type}catch{}if(!A){ae.error("Please select a Source Type first to load defaults");return}try{const C=await Ie.getPipelineDefaults(A);C.ok&&C.defaults?.normalization?(a(C.defaults.normalization.yamlDefinition||""),C.defaults.normalization.fieldMapping&&o(C.defaults.normalization.fieldMapping),ae.success(`Loaded defaults for ${A}`)):ae.error(`No normalization defaults found for ${A}`)}catch(C){ae.error(C.response?.data?.error||C.message||"Failed to load defaults")}},N=y.useMemo(()=>{try{return Pn.load(r)}catch{return{}}},[r]);return m?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsxs("div",{className:"flex flex-col h-full bg-background",children:[s.jsxs("div",{className:"flex items-center justify-between border-b px-6 py-4 shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(ie,{variant:"ghost",size:"icon",onClick:n,children:s.jsx(Vr,{className:"h-4 w-4"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-xl font-bold tracking-tight",children:e?"Edit Normalization Rule":"Create Normalization Rule"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Define your rule using the YAML schema and Handlebars templates."})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ie,{variant:"secondary",onClick:T,disabled:u||!N?.source_type,children:"Reset to Default"}),s.jsx(ie,{variant:"outline",onClick:n,disabled:u,children:"Cancel"}),s.jsx(ie,{onClick:x,disabled:u||l.length>0||d,children:u?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving..."]}):"Save Rule"})]})]}),s.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[s.jsxs("div",{className:"flex-1 flex flex-col p-6 pr-3 overflow-hidden",children:[s.jsx("div",{className:"border rounded-md overflow-hidden relative flex-1",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:r,onChange:A=>a(A||""),options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,wordWrap:"on",tabSize:2},theme:"vs-dark"})}),l.length>0&&s.jsxs("div",{className:"mt-4 p-3 bg-destructive/10 border border-destructive/20 text-destructive rounded-md max-h-32 overflow-y-auto",children:[s.jsx("div",{className:"font-semibold text-sm mb-1",children:"YAML Validation Errors:"}),s.jsx("ul",{className:"list-disc pl-5 text-sm",children:l.map((A,C)=>s.jsx("li",{children:A},C))})]})]}),s.jsxs("div",{className:"w-[450px] xl:w-[500px] border-l flex flex-col shrink-0 h-full overflow-y-auto bg-muted/10 p-6 space-y-6",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"font-medium mb-4",children:"Configuration"}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-sm font-medium",children:"Name"}),s.jsx("input",{type:"text",className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",value:N?.name??"",onChange:A=>S("name",A.target.value)})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-sm font-medium",children:"Priority"}),s.jsx("input",{type:"number",className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",value:N?.priority??0,onChange:A=>S("priority",parseInt(A.target.value)||0)})]}),!t&&s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-sm font-medium",children:"Source Type"}),s.jsxs("select",{className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm",value:N?.source_type??"",onChange:A=>S("source_type",A.target.value||null),disabled:g,children:[s.jsx("option",{value:"",children:"— Any (global) —"}),["cloudwatch","grafana","prometheus","custom","cloudtrail"].map(A=>s.jsx("option",{value:A,children:A==="cloudtrail"?"Level 1 Security":A==="pagerduty"?"PagerDuty":A==="cloudwatch"?"CloudWatch":A==="grafana"?"Grafana":A==="prometheus"?"Prometheus":A==="datadog"?"Datadog":A==="meyi_pulse"?"Meyi Pulse":"Custom"},A))]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:N?.is_active??!0,onChange:A=>S("is_active",A.target.checked),className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]})]}),s.jsxs("div",{className:"border-t pt-6",children:[s.jsx("h3",{className:"font-medium mb-4",children:"Legacy Field Mapping"}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Map canonical fields using Handlebars templates. This is persisted separately from YAML."}),s.jsx("textarea",{className:"w-full rounded-md border border-border bg-background px-3 py-2 text-sm font-mono min-h-[200px]",value:i,onChange:A=>o(A.target.value),placeholder:`alertName: "{{labels.alertname}}"
351
- severity: "{{labels.severity}}"`})]})]})]})]})]})}const wue=["cloudwatch","grafana","prometheus","custom","cloudtrail"],Tue={cloudtrail:"Level 1 Security",cloudwatch:"CloudWatch",grafana:"Grafana",prometheus:"Prometheus",datadog:"Datadog",pagerduty:"PagerDuty",custom:"Custom",meyi_pulse:"Meyi Pulse"},Nue=["source","resourceId","alertName","metricName","resourceName","resourceType","state","severity","tenantId"],Cue=[{value:"none",label:"No action"},{value:"elevate_severity",label:"Elevate severity"},{value:"suppress",label:"Suppress flapping"}];function yN(e){return e&&e%3600===0?{n:e/3600,u:"h"}:e&&e%60===0?{n:e/60,u:"m"}:{n:e||0,u:"s"}}function Aue(e,t){return t==="h"?e*3600:t==="m"?e*60:e}function EN({ruleId:e,sourceId:t,onBack:n}){const[r,a]=y.useState("My Dedup Rule"),[i,o]=y.useState(0),[l,c]=y.useState(!0),[u,p]=y.useState(""),[d,f]=y.useState(10),[m,h]=y.useState("m"),[g,b]=y.useState(["source","resourceId","metricName","state"]),[x,S]=y.useState(""),[T,N]=y.useState(!1),[A,C]=y.useState(4),[k,O]=y.useState(10),[M,R]=y.useState("none"),[j,U]=y.useState([]),[G,q]=y.useState(!1),[P,z]=y.useState(!1),[re,B]=y.useState(!!e),[H,I]=y.useState(!1);y.useEffect(()=>{e&&Ie.getDedupConfig(e).then(te=>{if(te.ok&&te.config){const Ae=te.config;a(Ae.name||"My Dedup Rule"),o(Ae.priority??0),c(Ae.isActive!==!1),p(Ae.sourceType||""),I(!!Ae.isSystem);const $e=yN(Ae.windowSeconds??600);f($e.n),h($e.u),b(Ae.keyFields?.length?Ae.keyFields:["source","resourceId","metricName","state"]);const Ee=(Ae.flapThreshold??0)>0&&Ae.onFlap&&Ae.onFlap!=="none";N(!!Ee),C(Ae.flapThreshold??4),O(Math.max(1,Math.round((Ae.flapWindowSeconds??600)/60))),R(Ae.onFlap||"none")}else ae.error("Rule not found"),n();B(!1)}).catch(()=>{ae.error("Failed to load rule"),n()})},[e]);const V=Aue(d,m),Z=k*60,D=T?M:"none",se=g.length?g.join(" | "):"—",Q=y.useCallback(()=>{const te={name:r.trim(),priority:i,is_active:l,source_type:u||"",window_seconds:V,fingerprint:{algo:"sha256",fields:g}};return T&&(te.flap={threshold:A,window_seconds:Z,on_flap:M}),te.on_hit={action:"suppress"},te.on_miss={action:"pass_to_grouping"},Pn.dump(te,{indent:2})},[r,i,l,u,V,g,T,A,Z,M]);y.useEffect(()=>{if(re)return;const te=setTimeout(async()=>{z(!0);try{const Ae=await Ie.parseDedupYaml(Q());U(Ae.ok?[]:Ae.errors||[])}catch(Ae){U(Ae.response?.data?.errors||[Ae.message||"Failed to validate"])}finally{z(!1)}},500);return()=>clearTimeout(te)},[Q,re]);const ne=te=>{const Ae=te.trim();Ae&&(b($e=>$e.includes(Ae)?$e:[...$e,Ae]),S(""))},K=te=>{b(Ae=>Ae.filter($e=>$e!==te))},Y=async()=>{if(!r.trim()){ae.error("Rule name is required");return}if(g.length===0){ae.error("At least one dedup key field is required");return}if(j.length>0){ae.error("Please fix validation errors before saving");return}q(!0);try{const te={name:r.trim(),isActive:l,priority:i,windowSeconds:V,keyFields:g,flapThreshold:T?A:0,flapWindowSeconds:Z,onFlap:D,yamlDefinition:Q()};e||(te.sourceType=u||null,te.sourceId=t||null),e?(await Ie.updateDedupConfig(e,te),ae.success("Rule updated")):(await Ie.createDedupConfig(te),ae.success("Rule created")),n()}catch(te){ae.error(te.message||"Failed to save rule")}finally{q(!1)}},J=async()=>{if(!u){ae.error("Please select a Source Type first to load defaults");return}try{const te=await Ie.getPipelineDefaults(u);if(te.ok&&te.defaults?.dedup?.yamlDefinition){const Ae=Pn.load(te.defaults.dedup.yamlDefinition);Ae.name&&a(Ae.name),Ae.priority!==void 0&&o(Ae.priority),Ae.is_active!==void 0&&c(Ae.is_active);const $e=Ae.window_seconds||300,Ee=yN($e);f(Ee.n),h(Ee.u),Ae.fingerprint?.fields&&b(Ae.fingerprint.fields),Ae.flap?(N(!0),C(Ae.flap.threshold||4),O(Math.max(1,Math.round((Ae.flap.window_seconds||600)/60))),R(Ae.flap.on_flap||"none")):N(!1),ae.success(`Loaded defaults for ${u}`)}else ae.error(`No dedup defaults found for ${u}`)}catch(te){ae.error(te.response?.data?.error||te.message||"Failed to load defaults")}};if(re)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin text-muted-foreground"})});const Ne=Nue.filter(te=>!g.includes(te)),pe=Q();return s.jsxs("div",{className:"im-rule-editor",children:[s.jsxs("div",{className:"im-rule-editor-header",children:[s.jsxs("div",{className:"im-rule-editor-header-left",children:[s.jsx("button",{type:"button",className:"im-icon-button",onClick:n,"aria-label":"Back",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:e?"Edit Dedup Rule":"Create Dedup Rule"}),s.jsx("p",{children:"Define deduplication behaviour and window overrides."})]})]}),s.jsxs("div",{className:"im-rule-editor-header-actions flex gap-2",children:[s.jsx(ie,{variant:"secondary",onClick:J,disabled:G||!u,children:"Reset to Default"}),s.jsx(ie,{variant:"outline",onClick:n,disabled:G,children:"Cancel"}),s.jsx(ie,{className:"im-primary-button",onClick:Y,disabled:G||P||j.length>0,children:G?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Rule"})]})]}),s.jsxs("div",{className:"im-rule-editor-split",children:[s.jsx("main",{className:"im-rule-form-pane",children:s.jsxs("div",{className:"im-rule-form",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Rule name ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{className:"im-field-input im-mono",value:r,onChange:te=>a(te.target.value),placeholder:"My Dedup Rule"})]}),s.jsxs("div",{className:"im-field-row",children:[!t&&s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:220},children:[s.jsx("label",{children:"Applies to — source"}),s.jsxs("select",{className:"im-field-input",value:u,onChange:te=>p(te.target.value),disabled:H,children:[s.jsx("option",{value:"",children:"— Any (global) —"}),wue.map(te=>s.jsx("option",{value:te,children:Tue[te]||te},te))]}),s.jsx("small",{className:"im-field-hint",children:"Empty = applies to alarms from any source."})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Priority"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:i,onChange:te=>o(parseInt(te.target.value)||0)})]})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Dedup window ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-field-inline",children:[s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:d,min:m==="m"?2:m==="s"?120:0,max:m==="m"?5:m==="s"?300:0,onChange:te=>{let Ae=parseInt(te.target.value)||0;m==="m"&&(Ae=Math.max(2,Math.min(5,Ae))),m==="s"&&(Ae=Math.max(120,Math.min(300,Ae))),f(Ae)}}),s.jsxs("select",{className:"im-field-input",style:{width:120},value:m,onChange:te=>{const Ae=te.target.value;h(Ae),Ae==="m"&&f(Math.max(2,Math.min(5,Math.round(d/60)))),Ae==="s"&&f(Math.max(120,Math.min(300,d*60)))},children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"})]})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Dedup key fields ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-chip-input",children:[g.map(te=>s.jsxs("span",{className:"im-chip-active",children:[te,s.jsx("button",{type:"button",onClick:()=>K(te),"aria-label":`Remove ${te}`,children:s.jsx(Hn,{size:12})})]},te)),s.jsx("input",{className:"im-chip-add",value:x,onChange:te=>S(te.target.value),onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),ne(x)),te.key==="Backspace"&&!x&&g.length&&K(g[g.length-1])},placeholder:"+ field, Enter"})]}),Ne.length>0&&s.jsx("div",{className:"im-chip-suggestions",children:Ne.map(te=>s.jsxs("button",{type:"button",className:"im-chip-suggestion",onClick:()=>ne(te),children:["+ ",te]},te))}),s.jsx("div",{className:"im-key-preview-label",children:"Key preview"}),s.jsx("div",{className:"im-key-preview-box",children:se})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-flap-toggle-card",children:[s.jsx("button",{type:"button",className:`im-toggle ${T?"is-on":""}`,"aria-label":"Flap detection",onClick:()=>N(te=>!te)}),s.jsxs("div",{children:[s.jsx("div",{className:"im-flap-toggle-title",children:"Flap detection"}),s.jsx("div",{className:"im-flap-toggle-sub",children:"Catch alarms toggling rapidly between states."})]})]}),T&&s.jsxs("div",{className:"im-flap-fields",children:[s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Threshold"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:A,onChange:te=>C(parseInt(te.target.value)||1)})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Flap window (min)"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:k,min:2,max:5,onChange:te=>O(Math.max(2,Math.min(5,parseInt(te.target.value)||2)))})]}),s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:180},children:[s.jsx("label",{children:"On flap"}),s.jsx("select",{className:"im-field-input",value:M,onChange:te=>R(te.target.value),children:Cue.map(te=>s.jsx("option",{value:te.value,children:te.label},te.value))})]})]}),s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:te=>c(te.target.checked)}),s.jsx("span",{children:"Active"})]}),j.length>0&&s.jsxs("div",{className:"im-validation-errors",children:[s.jsx("div",{className:"im-validation-errors-title",children:"Validation errors"}),s.jsx("ul",{children:j.map((te,Ae)=>s.jsx("li",{children:te},Ae))})]})]})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"}),P&&s.jsx(Qe,{size:12,className:"animate-spin",style:{marginLeft:8,display:"inline"}})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:pe,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})})]})]})]})}const _ue=["cloudwatch","grafana","prometheus","custom","cloudtrail"],Rue={cloudtrail:"Level 1 Security",cloudwatch:"CloudWatch",grafana:"Grafana",prometheus:"Prometheus",datadog:"Datadog",pagerduty:"PagerDuty",custom:"Custom",meyi_pulse:"Meyi Pulse"},kue=["resourceId","alertName","metricName","resourceName","resourceType","severity","state","source","tenantId"],Iue=[{value:"max_of_members",label:"Highest in group"},{value:"first_alarm",label:"First alarm"},{value:"fixed",label:"Fixed level"}];function vN(e){return e&&e%3600===0?{n:e/3600,u:"h"}:e&&e%60===0?{n:e/60,u:"m"}:{n:e||0,u:"s"}}function Due(e,t){return t==="h"?e*3600:t==="m"?e*60:e}function SN(e){return e?e.replace(/\{\{?\s*count\s*\}?\}/gi,"3").replace(/\{\{?\s*resourceName\s*\}?\}/gi,"web-prod-01").replace(/\{\{?\s*resource\.name\s*\}?\}/gi,"web-prod-01").replace(/\{\{?\s*alertName\s*\}?\}/gi,"CPUUtilization").replace(/\{\{?\s*metric\.name\s*\}?\}/gi,"cpu_utilization").replace(/\{\{?\s*severity\s*\}?\}/gi,"critical"):"—"}function wN({ruleId:e,sourceId:t,onBack:n}){const[r,a]=y.useState("My Grouping Strategy"),[i,o]=y.useState(0),[l,c]=y.useState(!0),[u,p]=y.useState(""),[d,f]=y.useState(["resourceId","metricName"]),[m,h]=y.useState(""),[g,b]=y.useState(15),[x,S]=y.useState("m"),[T,N]=y.useState(50),[A,C]=y.useState(""),[k,O]=y.useState(!1),[M,R]=y.useState(""),[j,U]=y.useState(!1),[G,q]=y.useState(""),[P,z]=y.useState("max_of_members"),[re,B]=y.useState(""),[H,I]=y.useState(""),[V,Z]=y.useState([]),[D,se]=y.useState(!1),[Q,ne]=y.useState(!1),[K,Y]=y.useState(!!e),[J,Ne]=y.useState(!1);y.useEffect(()=>{U4.list().then(Se=>{U(Se.some(Re=>Re.isActive))}).catch(console.error),e&&Ie.getGroupingConfig(e).then(Se=>{if(Se.ok&&Se.config){const Re=Se.config;let Ue={};try{Ue=Pn.load(Re.yamlDefinition||"")||{}}catch{}a(Re.name||"My Grouping Strategy"),o(Re.priority??0),c(Re.isActive!==!1),p(Re.sourceType||""),Ne(!!Re.isSystem),f(Re.groupBy?.length?Re.groupBy:["resourceId","metricName"]);const He=vN(Re.timeoutSeconds??900);b(He.n),S(He.u),N(Re.maxAlarms??50),C(Ue.incident_title||Re.incidentTitleTemplate||""),O(Ue.use_ai_generate??Re.useAiGenerate??!1),R(Ue.user_prompt??Re.userPrompt??""),q(Ue.group_name||""),B(Ue.topology_tag_mapping??Re.topologyTagMapping??""),z(Ue.incident_severity||"max_of_members")}else ae.error("Rule not found"),n();Y(!1)}).catch(()=>{ae.error("Failed to load rule"),n()})},[e]);const pe=Due(g,x),te=y.useCallback(()=>{const Se={name:r.trim(),priority:i,is_active:l,source_type:u||void 0,source_id:t||void 0,default_key:d,window_seconds:pe,max_alarms:T,incident_severity:P,group_name_template:G||void 0,topology_tag_mapping:re||void 0,incident_title_template:A||void 0,use_ai_generate:j?k:void 0,user_prompt:j&&k&&M?M:void 0};return Pn.dump(Se,{indent:2})},[r,i,l,u,t,d,pe,T,P,A,G,re,k,M,j]);y.useEffect(()=>{if(K)return;const Se=setTimeout(async()=>{ne(!0);try{const Re=await Ie.parseGroupingYaml(te());Z(Re.ok?[]:Re.errors||[])}catch(Re){Z(Re.response?.data?.errors||[Re.message||"Failed to validate"])}finally{ne(!1)}},500);return()=>clearTimeout(Se)},[te,K]);const Ae=Se=>{const Re=Se.trim();Re&&(f(Ue=>Ue.includes(Re)?Ue:[...Ue,Re]),h(""))},$e=Se=>{f(Re=>Re.filter(Ue=>Ue!==Se))},Ee=re?re.split(",").map(Se=>Se.trim()).filter(Boolean):[],Ze=Se=>{const Re=Se.trim();Re&&(Ee.includes(Re)||B([...Ee,Re].join(", ")),I(""))},Ye=Se=>{B(Ee.filter(Re=>Re!==Se).join(", "))},st=async()=>{if(!r.trim()){ae.error("Rule name is required");return}if(d.length===0){ae.error("At least one group-by field is required");return}if(V.length>0){ae.error("Please fix validation errors before saving");return}se(!0);try{const Se={name:r.trim(),isActive:l,priority:i,timeoutSeconds:pe,maxAlarms:T,groupBy:d,incidentTitleTemplate:A||null,userPrompt:M||null,topologyTagMapping:re||null,yamlDefinition:te()};e||(Se.sourceType=u||null,Se.sourceId=t||null),e?(await Ie.updateGroupingConfig(e,Se),ae.success("Rule updated")):(await Ie.createGroupingConfig(Se),ae.success("Rule created")),n()}catch(Se){ae.error(Se.message||"Failed to save rule")}finally{se(!1)}},lt=async()=>{if(!u){ae.error("Please select a Source Type first to load defaults");return}try{const Se=await Ie.getPipelineDefaults(u);if(Se.ok&&Se.defaults?.grouping?.yamlDefinition){const Re=Pn.load(Se.defaults.grouping.yamlDefinition);Re.name&&a(Re.name),Re.priority!==void 0&&o(Re.priority),Re.is_active!==void 0&&c(Re.is_active),Re.default_key&&f(Re.default_key);const Ue=Re.window_seconds||900,He=vN(Ue);b(He.n),S(He.u),Re.max_alarms!==void 0&&N(Re.max_alarms),Re.incident_severity&&z(Re.incident_severity),Re.topology_tag_mapping&&B(Re.topology_tag_mapping),ae.success(`Loaded defaults for ${u}`)}else ae.error(`No grouping defaults found for ${u}`)}catch(Se){ae.error(Se.response?.data?.error||Se.message||"Failed to load defaults")}};if(K)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin text-muted-foreground"})});const Et=kue.filter(Se=>!d.includes(Se)),Bt=te();return s.jsxs("div",{className:"im-rule-editor",children:[s.jsxs("div",{className:"im-rule-editor-header",children:[s.jsxs("div",{className:"im-rule-editor-header-left",children:[s.jsx("button",{type:"button",className:"im-icon-button",onClick:n,"aria-label":"Back",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:e?"Edit Grouping Rule":"Create Grouping Rule"}),s.jsx("p",{children:"Define correlation windows, grouping keys, and strategies."})]})]}),s.jsxs("div",{className:"im-rule-editor-header-actions flex gap-2",children:[s.jsx(ie,{variant:"secondary",onClick:lt,disabled:D||!u,children:"Reset to Default"}),s.jsx(ie,{variant:"outline",onClick:n,disabled:D,children:"Cancel"}),s.jsx(ie,{className:"im-primary-button",onClick:st,disabled:D||Q||V.length>0,children:D?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Rule"})]})]}),s.jsxs("div",{className:"im-rule-editor-split",children:[s.jsx("main",{className:"im-rule-form-pane",children:s.jsxs("div",{className:"im-rule-form",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Rule name ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{className:"im-field-input im-mono",value:r,onChange:Se=>a(Se.target.value),placeholder:"My Grouping Strategy"})]}),s.jsxs("div",{className:"im-field-row",children:[!t&&s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:220},children:[s.jsx("label",{children:"Applies to — source"}),s.jsxs("select",{className:"im-field-input",value:u,onChange:Se=>p(Se.target.value),disabled:J,children:[s.jsx("option",{value:"",children:"— Any (global) —"}),_ue.map(Se=>s.jsx("option",{value:Se,children:Rue[Se]||Se},Se))]}),s.jsx("small",{className:"im-field-hint",children:"Empty = applies to alarms from any source."})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Priority"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:i,onChange:Se=>o(parseInt(Se.target.value)||0)})]})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Group by fields ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-chip-input",children:[d.map(Se=>s.jsxs("span",{className:"im-chip-active",children:[Se,s.jsx("button",{type:"button",onClick:()=>$e(Se),"aria-label":`Remove ${Se}`,children:s.jsx(Hn,{size:12})})]},Se)),s.jsx("input",{className:"im-chip-add",value:m,onChange:Se=>h(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&(Se.preventDefault(),Ae(m)),Se.key==="Backspace"&&!m&&d.length&&$e(d[d.length-1])},placeholder:"+ field, Enter"})]}),Et.length>0&&s.jsx("div",{className:"im-chip-suggestions",children:Et.map(Se=>s.jsxs("button",{type:"button",className:"im-chip-suggestion",onClick:()=>Ae(Se),children:["+ ",Se]},Se))})]}),s.jsxs("div",{className:"im-field-row",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Group timeout ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-field-inline",children:[s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:g,min:x==="m"?2:x==="s"?120:0,max:x==="m"?5:x==="s"?300:0,onChange:Se=>{let Re=parseInt(Se.target.value)||0;x==="m"&&(Re=Math.max(2,Math.min(5,Re))),x==="s"&&(Re=Math.max(120,Math.min(300,Re))),b(Re)}}),s.jsxs("select",{className:"im-field-input",style:{width:120},value:x,onChange:Se=>{const Re=Se.target.value;S(Re),Re==="m"&&b(Math.max(2,Math.min(5,Math.round(g/60)))),Re==="s"&&b(Math.max(120,Math.min(300,g*60)))},children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"})]})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Max / group ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:100},value:T,onChange:Se=>N(parseInt(Se.target.value)||1)})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Group name template"}),s.jsx("input",{className:"im-field-input im-mono",value:G,onChange:Se=>q(Se.target.value),placeholder:"{{alertName}} on {{severity}}"}),s.jsxs("small",{className:"im-field-hint",children:["Variables: ",s.jsx("code",{children:"{{count}}"})," ",s.jsx("code",{children:"{{resourceName}}"})," ",s.jsx("code",{children:"{{alertName}}"})," ",s.jsx("code",{children:"{{severity}}"})]}),s.jsxs("div",{className:"im-template-preview-row",children:["Preview: ",s.jsx("span",{children:SN(G||"{{alertName}} on {{severity}}")})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{children:"Incident title template"}),j&&s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:k,onChange:Se=>O(Se.target.checked),className:"rounded text-primary focus:ring-primary"}),s.jsx("span",{children:"AI generated incident details"})]})]}),s.jsx("input",{className:"im-field-input im-mono",value:A,onChange:Se=>C(Se.target.value),placeholder:"{{count}} alerts on {{resourceName}}"}),s.jsxs("small",{className:"im-field-hint",children:["Variables: ",s.jsx("code",{children:"{{count}}"})," ",s.jsx("code",{children:"{{resourceName}}"})," ",s.jsx("code",{children:"{{alertName}}"})," ",s.jsx("code",{children:"{{severity}}"})]}),!k&&s.jsxs("div",{className:"im-template-preview-row",children:["Preview: ",s.jsx("span",{children:SN(A||"{{count}} alerts on {{resourceName}}")})]}),k&&s.jsxs("div",{className:"mt-4",children:[s.jsx("label",{className:"block mb-2 text-sm font-medium",children:"AI Prompt Instructions (Optional)"}),s.jsx("textarea",{className:"im-field-input w-full min-h-[120px] resize-y text-sm font-mono p-2",value:M,onChange:Se=>R(Se.target.value),placeholder:"E.g., Format the title as '[Critical] System X Failure' and provide a detailed summary of affected resources."})]})]}),u==="cloudtrail"&&s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Tag Mapping"}),s.jsxs("div",{className:"flex gap-2 mb-2 items-center",children:[s.jsx("input",{className:"im-field-input im-mono",style:{flex:1},value:H,onChange:Se=>I(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&(Se.preventDefault(),Ze(H))},placeholder:"tag1,tag2, Enter or click Add"}),s.jsx(ie,{type:"button",variant:"secondary",onClick:()=>Ze(H),children:"Add"})]}),Ee.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:Ee.map(Se=>s.jsxs("span",{className:"im-chip-active",children:[Se,s.jsx("button",{type:"button",onClick:()=>Ye(Se),"aria-label":`Remove ${Se}`,children:s.jsx(Hn,{size:12})})]},Se))}),s.jsx("small",{className:"im-field-hint",children:"Extracts the specified tags from the account topology for Level 1 Security alerts and groups by their values."})]}),s.jsxs("div",{className:"im-field",style:{maxWidth:320},children:[s.jsx("label",{children:"Severity resolution"}),s.jsx("select",{className:"im-field-input",value:P,onChange:Se=>z(Se.target.value),children:Iue.map(Se=>s.jsx("option",{value:Se.value,children:Se.label},Se.value))})]}),s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:Se=>c(Se.target.checked)}),s.jsx("span",{children:"Active"})]}),V.length>0&&s.jsxs("div",{className:"im-validation-errors",children:[s.jsx("div",{className:"im-validation-errors-title",children:"Validation errors"}),s.jsx("ul",{children:V.map((Se,Re)=>s.jsx("li",{children:Se},Re))})]})]})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"}),Q&&s.jsx(Qe,{size:12,className:"animate-spin",style:{marginLeft:8,display:"inline"}})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:Bt,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})})]})]})]})}function Oue(){return s.jsxs("div",{className:"w-full h-full",children:[s.jsx(Oh,{}),s.jsx(DP,{})]})}const TN=ej({component:Oue});function MO(){const e=Ot({getParentRoute:()=>TN,id:"insight-workspace",component:()=>s.jsx(Oh,{})}),t=e.addChildren([Ot({getParentRoute:()=>e,path:"/",component:()=>s.jsx(lo,{to:"/alerts"})}),Ot({getParentRoute:()=>e,path:"/sources",component:QV}),Ot({getParentRoute:()=>e,path:"/sources/$id",component:()=>{const{id:n}=xr({strict:!1});return s.jsx(cY,{sourceId:n})}}),Ot({getParentRoute:()=>e,path:"/sops",component:()=>{const n=St();return s.jsx(OY,{onViewSop:r=>n({to:`/sops/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/sops/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(zle,{sopId:n,onBack:()=>r({to:"/sops"})})}}),Ot({getParentRoute:()=>e,path:"/workflows/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(gN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/workflows/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(gN,{workflowId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/alerts",component:()=>{const n=St();return s.jsx(mY,{onViewIncident:r=>n({to:`/incidents/${r}`}),onViewAlert:r=>n({to:`/alert/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/alert/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(SY,{alertId:n,onBack:()=>{window.history.length>1?window.history.back():r({to:"/alerts"})},onViewIncident:a=>r({to:`/incidents/${a}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/dashboard",component:()=>s.jsx(lo,{to:"/incidents/operations?tab=dashboard"})}),Ot({getParentRoute:()=>e,path:"/incidents/analytics",component:()=>s.jsx(lo,{to:"/incidents/operations?tab=dashboard&view=analytics"})}),Ot({getParentRoute:()=>e,path:"/incidents",component:()=>s.jsx(lo,{to:"/incidents/operations"})}),Ot({getParentRoute:()=>e,path:"/incidents/operations",component:()=>{const n=St();return s.jsx(Sf,{category:"operations",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/security",component:()=>{const n=St();return s.jsx(Sf,{category:"security",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/cost",component:()=>{const n=St();return s.jsx(Sf,{category:"cost",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(c9,{incidentId:n,onBack:()=>r({to:"/incidents"}),onViewAlert:a=>r({to:`/alert/${a}`})})}}),Ot({getParentRoute:()=>e,path:"/pipeline/normalization/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(xN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/normalization/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(xN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/dedup/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(EN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/dedup/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(EN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/grouping/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(wN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/grouping/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(wN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}})]);return TN.addChildren([t])}function Lue({apiBase:e,token:t,basePath:n="/insight",userRole:r="admin",userId:a,onOpenCostSources:i}){w.useEffect(()=>{EC(e,t)},[e,t]);const o=w.useMemo(()=>dj({routeTree:MO(),basepath:n}),[n]);return s.jsx($4,{role:r,userId:a||"",openCostSources:i,children:s.jsx(mj,{router:o})})}function jue(e,t=6e4){const[n,r]=w.useState(void 0);return w.useEffect(()=>{let a=!0;const i=async()=>{try{const o=await Ie.listIncidents({status:"open",limit:1,...e?{incidentType:e}:{}});a&&r(o.total??0)}catch{}};if(i(),t>0){const o=setInterval(i,t);return()=>{a=!1,clearInterval(o)}}return()=>{a=!1}},[e,t]),n}function PO(e){return[{title:"Incidents",url:"/incidents",icon:"BrainCircuit",roles:["admin","user"],badge:e!==void 0&&e>0?String(e):void 0,items:[{title:"Operations",url:"/incidents/operations",icon:"Wrench",roles:["admin","user"]},{title:"Security",url:"/incidents/security",icon:"Shield",roles:["admin","user"],disabled:!0},{title:"Cost",url:"/incidents/cost",icon:"DollarSign",roles:["admin","user"],disabled:!0}]},{title:"Alarms",url:"/alerts",icon:"Bell",roles:["admin","user"]},{title:"SOPs",url:"/sops",icon:"BookOpen",roles:["admin","user"]},{title:"Sources",url:"/sources",icon:"Plug",roles:["admin"]}]}const Mue=PO();exports.InsightPage=Lue;exports.api=Te;exports.configureApi=EC;exports.createRouteTree=MO;exports.getInsightNavItems=PO;exports.insightNavItems=Mue;exports.useOpenIncidentCount=jue;
351
+ severity: "{{labels.severity}}"`})]})]})]})]})]})}const wue=["cloudwatch","grafana","prometheus","custom","cloudtrail"],Tue={cloudtrail:"Level 1 Security",cloudwatch:"CloudWatch",grafana:"Grafana",prometheus:"Prometheus",datadog:"Datadog",pagerduty:"PagerDuty",custom:"Custom",meyi_pulse:"Meyi Pulse"},Nue=["source","resourceId","alertName","metricName","resourceName","resourceType","state","severity","tenantId"],Cue=[{value:"none",label:"No action"},{value:"elevate_severity",label:"Elevate severity"},{value:"suppress",label:"Suppress flapping"}];function yN(e){return e&&e%3600===0?{n:e/3600,u:"h"}:e&&e%60===0?{n:e/60,u:"m"}:{n:e||0,u:"s"}}function Aue(e,t){return t==="h"?e*3600:t==="m"?e*60:e}function EN({ruleId:e,sourceId:t,onBack:n}){const[r,a]=y.useState("My Dedup Rule"),[i,o]=y.useState(0),[l,c]=y.useState(!0),[u,p]=y.useState(""),[d,f]=y.useState(10),[m,h]=y.useState("m"),[g,b]=y.useState(["source","resourceId","metricName","state"]),[x,S]=y.useState(""),[T,N]=y.useState(!1),[A,C]=y.useState(4),[k,O]=y.useState(10),[M,R]=y.useState("none"),[j,U]=y.useState([]),[G,q]=y.useState(!1),[P,z]=y.useState(!1),[re,B]=y.useState(!!e),[H,I]=y.useState(!1);y.useEffect(()=>{e&&Ie.getDedupConfig(e).then(te=>{if(te.ok&&te.config){const Ae=te.config;a(Ae.name||"My Dedup Rule"),o(Ae.priority??0),c(Ae.isActive!==!1),p(Ae.sourceType||""),I(!!Ae.isSystem);const $e=yN(Ae.windowSeconds??600);f($e.n),h($e.u),b(Ae.keyFields?.length?Ae.keyFields:["source","resourceId","metricName","state"]);const Ee=(Ae.flapThreshold??0)>0&&Ae.onFlap&&Ae.onFlap!=="none";N(!!Ee),C(Ae.flapThreshold??4),O(Math.max(1,Math.round((Ae.flapWindowSeconds??600)/60))),R(Ae.onFlap||"none")}else ae.error("Rule not found"),n();B(!1)}).catch(()=>{ae.error("Failed to load rule"),n()})},[e]);const V=Aue(d,m),Z=k*60,D=T?M:"none",se=g.length?g.join(" | "):"—",Q=y.useCallback(()=>{const te={name:r.trim(),priority:i,is_active:l,source_type:u||"",window_seconds:V,fingerprint:{algo:"sha256",fields:g}};return T&&(te.flap={threshold:A,window_seconds:Z,on_flap:M}),te.on_hit={action:"suppress"},te.on_miss={action:"pass_to_grouping"},Pn.dump(te,{indent:2})},[r,i,l,u,V,g,T,A,Z,M]);y.useEffect(()=>{if(re)return;const te=setTimeout(async()=>{z(!0);try{const Ae=await Ie.parseDedupYaml(Q());U(Ae.ok?[]:Ae.errors||[])}catch(Ae){U(Ae.response?.data?.errors||[Ae.message||"Failed to validate"])}finally{z(!1)}},500);return()=>clearTimeout(te)},[Q,re]);const ne=te=>{const Ae=te.trim();Ae&&(b($e=>$e.includes(Ae)?$e:[...$e,Ae]),S(""))},K=te=>{b(Ae=>Ae.filter($e=>$e!==te))},Y=async()=>{if(!r.trim()){ae.error("Rule name is required");return}if(g.length===0){ae.error("At least one dedup key field is required");return}if(j.length>0){ae.error("Please fix validation errors before saving");return}q(!0);try{const te={name:r.trim(),isActive:l,priority:i,windowSeconds:V,keyFields:g,flapThreshold:T?A:0,flapWindowSeconds:Z,onFlap:D,yamlDefinition:Q()};e||(te.sourceType=u||null,te.sourceId=t||null),e?(await Ie.updateDedupConfig(e,te),ae.success("Rule updated")):(await Ie.createDedupConfig(te),ae.success("Rule created")),n()}catch(te){ae.error(te.message||"Failed to save rule")}finally{q(!1)}},J=async()=>{if(!u){ae.error("Please select a Source Type first to load defaults");return}try{const te=await Ie.getPipelineDefaults(u);if(te.ok&&te.defaults?.dedup?.yamlDefinition){const Ae=Pn.load(te.defaults.dedup.yamlDefinition);Ae.name&&a(Ae.name),Ae.priority!==void 0&&o(Ae.priority),Ae.is_active!==void 0&&c(Ae.is_active);const $e=Ae.window_seconds||300,Ee=yN($e);f(Ee.n),h(Ee.u),Ae.fingerprint?.fields&&b(Ae.fingerprint.fields),Ae.flap?(N(!0),C(Ae.flap.threshold||4),O(Math.max(1,Math.round((Ae.flap.window_seconds||600)/60))),R(Ae.flap.on_flap||"none")):N(!1),ae.success(`Loaded defaults for ${u}`)}else ae.error(`No dedup defaults found for ${u}`)}catch(te){ae.error(te.response?.data?.error||te.message||"Failed to load defaults")}};if(re)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin text-muted-foreground"})});const Ne=Nue.filter(te=>!g.includes(te)),pe=Q();return s.jsxs("div",{className:"im-rule-editor",children:[s.jsxs("div",{className:"im-rule-editor-header",children:[s.jsxs("div",{className:"im-rule-editor-header-left",children:[s.jsx("button",{type:"button",className:"im-icon-button",onClick:n,"aria-label":"Back",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:e?"Edit Dedup Rule":"Create Dedup Rule"}),s.jsx("p",{children:"Define deduplication behaviour and window overrides."})]})]}),s.jsxs("div",{className:"im-rule-editor-header-actions flex gap-2",children:[s.jsx(ie,{variant:"secondary",onClick:J,disabled:G||!u,children:"Reset to Default"}),s.jsx(ie,{variant:"outline",onClick:n,disabled:G,children:"Cancel"}),s.jsx(ie,{className:"im-primary-button",onClick:Y,disabled:G||P||j.length>0,children:G?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Rule"})]})]}),s.jsxs("div",{className:"im-rule-editor-split",children:[s.jsx("main",{className:"im-rule-form-pane",children:s.jsxs("div",{className:"im-rule-form",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Rule name ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{className:"im-field-input im-mono",value:r,onChange:te=>a(te.target.value),placeholder:"My Dedup Rule"})]}),s.jsxs("div",{className:"im-field-row",children:[!t&&s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:220},children:[s.jsx("label",{children:"Applies to — source"}),s.jsxs("select",{className:"im-field-input",value:u,onChange:te=>p(te.target.value),disabled:H,children:[s.jsx("option",{value:"",children:"— Any (global) —"}),wue.map(te=>s.jsx("option",{value:te,children:Tue[te]||te},te))]}),s.jsx("small",{className:"im-field-hint",children:"Empty = applies to alarms from any source."})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Priority"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:i,onChange:te=>o(parseInt(te.target.value)||0)})]})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Dedup window ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-field-inline",children:[s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:d,min:m==="m"?2:m==="s"?120:0,max:m==="m"?5:m==="s"?300:0,onChange:te=>{let Ae=parseInt(te.target.value)||0;m==="m"&&(Ae=Math.max(2,Math.min(5,Ae))),m==="s"&&(Ae=Math.max(120,Math.min(300,Ae))),f(Ae)}}),s.jsxs("select",{className:"im-field-input",style:{width:120},value:m,onChange:te=>{const Ae=te.target.value;h(Ae),Ae==="m"&&f(Math.max(2,Math.min(5,Math.round(d/60)))),Ae==="s"&&f(Math.max(120,Math.min(300,d*60)))},children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"})]})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Dedup key fields ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-chip-input",children:[g.map(te=>s.jsxs("span",{className:"im-chip-active",children:[te,s.jsx("button",{type:"button",onClick:()=>K(te),"aria-label":`Remove ${te}`,children:s.jsx(Hn,{size:12})})]},te)),s.jsx("input",{className:"im-chip-add",value:x,onChange:te=>S(te.target.value),onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),ne(x)),te.key==="Backspace"&&!x&&g.length&&K(g[g.length-1])},placeholder:"+ field, Enter"})]}),Ne.length>0&&s.jsx("div",{className:"im-chip-suggestions",children:Ne.map(te=>s.jsxs("button",{type:"button",className:"im-chip-suggestion",onClick:()=>ne(te),children:["+ ",te]},te))}),s.jsx("div",{className:"im-key-preview-label",children:"Key preview"}),s.jsx("div",{className:"im-key-preview-box",children:se})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-flap-toggle-card",children:[s.jsx("button",{type:"button",className:`im-toggle ${T?"is-on":""}`,"aria-label":"Flap detection",onClick:()=>N(te=>!te)}),s.jsxs("div",{children:[s.jsx("div",{className:"im-flap-toggle-title",children:"Flap detection"}),s.jsx("div",{className:"im-flap-toggle-sub",children:"Catch alarms toggling rapidly between states."})]})]}),T&&s.jsxs("div",{className:"im-flap-fields",children:[s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Threshold"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:A,onChange:te=>C(parseInt(te.target.value)||1)})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Flap window (min)"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:k,min:2,max:5,onChange:te=>O(Math.max(2,Math.min(5,parseInt(te.target.value)||2)))})]}),s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:180},children:[s.jsx("label",{children:"On flap"}),s.jsx("select",{className:"im-field-input",value:M,onChange:te=>R(te.target.value),children:Cue.map(te=>s.jsx("option",{value:te.value,children:te.label},te.value))})]})]}),s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:te=>c(te.target.checked)}),s.jsx("span",{children:"Active"})]}),j.length>0&&s.jsxs("div",{className:"im-validation-errors",children:[s.jsx("div",{className:"im-validation-errors-title",children:"Validation errors"}),s.jsx("ul",{children:j.map((te,Ae)=>s.jsx("li",{children:te},Ae))})]})]})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"}),P&&s.jsx(Qe,{size:12,className:"animate-spin",style:{marginLeft:8,display:"inline"}})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:pe,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})})]})]})]})}const _ue=["cloudwatch","grafana","prometheus","custom","cloudtrail"],Rue={cloudtrail:"Level 1 Security",cloudwatch:"CloudWatch",grafana:"Grafana",prometheus:"Prometheus",datadog:"Datadog",pagerduty:"PagerDuty",custom:"Custom",meyi_pulse:"Meyi Pulse"},kue=["resourceId","alertName","metricName","resourceName","resourceType","severity","state","source","tenantId"],Iue=[{value:"max_of_members",label:"Highest in group"},{value:"first_alarm",label:"First alert"},{value:"fixed",label:"Fixed level"}];function vN(e){return e&&e%3600===0?{n:e/3600,u:"h"}:e&&e%60===0?{n:e/60,u:"m"}:{n:e||0,u:"s"}}function Due(e,t){return t==="h"?e*3600:t==="m"?e*60:e}function SN(e){return e?e.replace(/\{\{?\s*count\s*\}?\}/gi,"3").replace(/\{\{?\s*resourceName\s*\}?\}/gi,"web-prod-01").replace(/\{\{?\s*resource\.name\s*\}?\}/gi,"web-prod-01").replace(/\{\{?\s*alertName\s*\}?\}/gi,"CPUUtilization").replace(/\{\{?\s*metric\.name\s*\}?\}/gi,"cpu_utilization").replace(/\{\{?\s*severity\s*\}?\}/gi,"critical"):"—"}function wN({ruleId:e,sourceId:t,onBack:n}){const[r,a]=y.useState("My Grouping Strategy"),[i,o]=y.useState(0),[l,c]=y.useState(!0),[u,p]=y.useState(""),[d,f]=y.useState(["resourceId","metricName"]),[m,h]=y.useState(""),[g,b]=y.useState(15),[x,S]=y.useState("m"),[T,N]=y.useState(50),[A,C]=y.useState(""),[k,O]=y.useState(!1),[M,R]=y.useState(""),[j,U]=y.useState(!1),[G,q]=y.useState(""),[P,z]=y.useState("max_of_members"),[re,B]=y.useState(""),[H,I]=y.useState(""),[V,Z]=y.useState([]),[D,se]=y.useState(!1),[Q,ne]=y.useState(!1),[K,Y]=y.useState(!!e),[J,Ne]=y.useState(!1);y.useEffect(()=>{U4.list().then(Se=>{U(Se.some(Re=>Re.isActive))}).catch(console.error),e&&Ie.getGroupingConfig(e).then(Se=>{if(Se.ok&&Se.config){const Re=Se.config;let Ue={};try{Ue=Pn.load(Re.yamlDefinition||"")||{}}catch{}a(Re.name||"My Grouping Strategy"),o(Re.priority??0),c(Re.isActive!==!1),p(Re.sourceType||""),Ne(!!Re.isSystem),f(Re.groupBy?.length?Re.groupBy:["resourceId","metricName"]);const He=vN(Re.timeoutSeconds??900);b(He.n),S(He.u),N(Re.maxAlarms??50),C(Ue.incident_title||Re.incidentTitleTemplate||""),O(Ue.use_ai_generate??Re.useAiGenerate??!1),R(Ue.user_prompt??Re.userPrompt??""),q(Ue.group_name||""),B(Ue.topology_tag_mapping??Re.topologyTagMapping??""),z(Ue.incident_severity||"max_of_members")}else ae.error("Rule not found"),n();Y(!1)}).catch(()=>{ae.error("Failed to load rule"),n()})},[e]);const pe=Due(g,x),te=y.useCallback(()=>{const Se={name:r.trim(),priority:i,is_active:l,source_type:u||void 0,source_id:t||void 0,default_key:d,window_seconds:pe,max_alarms:T,incident_severity:P,group_name_template:G||void 0,topology_tag_mapping:re||void 0,incident_title_template:A||void 0,use_ai_generate:j?k:void 0,user_prompt:j&&k&&M?M:void 0};return Pn.dump(Se,{indent:2})},[r,i,l,u,t,d,pe,T,P,A,G,re,k,M,j]);y.useEffect(()=>{if(K)return;const Se=setTimeout(async()=>{ne(!0);try{const Re=await Ie.parseGroupingYaml(te());Z(Re.ok?[]:Re.errors||[])}catch(Re){Z(Re.response?.data?.errors||[Re.message||"Failed to validate"])}finally{ne(!1)}},500);return()=>clearTimeout(Se)},[te,K]);const Ae=Se=>{const Re=Se.trim();Re&&(f(Ue=>Ue.includes(Re)?Ue:[...Ue,Re]),h(""))},$e=Se=>{f(Re=>Re.filter(Ue=>Ue!==Se))},Ee=re?re.split(",").map(Se=>Se.trim()).filter(Boolean):[],Ze=Se=>{const Re=Se.trim();Re&&(Ee.includes(Re)||B([...Ee,Re].join(", ")),I(""))},Ye=Se=>{B(Ee.filter(Re=>Re!==Se).join(", "))},st=async()=>{if(!r.trim()){ae.error("Rule name is required");return}if(d.length===0){ae.error("At least one group-by field is required");return}if(V.length>0){ae.error("Please fix validation errors before saving");return}se(!0);try{const Se={name:r.trim(),isActive:l,priority:i,timeoutSeconds:pe,maxAlarms:T,groupBy:d,incidentTitleTemplate:A||null,userPrompt:M||null,topologyTagMapping:re||null,yamlDefinition:te()};e||(Se.sourceType=u||null,Se.sourceId=t||null),e?(await Ie.updateGroupingConfig(e,Se),ae.success("Rule updated")):(await Ie.createGroupingConfig(Se),ae.success("Rule created")),n()}catch(Se){ae.error(Se.message||"Failed to save rule")}finally{se(!1)}},lt=async()=>{if(!u){ae.error("Please select a Source Type first to load defaults");return}try{const Se=await Ie.getPipelineDefaults(u);if(Se.ok&&Se.defaults?.grouping?.yamlDefinition){const Re=Pn.load(Se.defaults.grouping.yamlDefinition);Re.name&&a(Re.name),Re.priority!==void 0&&o(Re.priority),Re.is_active!==void 0&&c(Re.is_active),Re.default_key&&f(Re.default_key);const Ue=Re.window_seconds||900,He=vN(Ue);b(He.n),S(He.u),Re.max_alarms!==void 0&&N(Re.max_alarms),Re.incident_severity&&z(Re.incident_severity),Re.topology_tag_mapping&&B(Re.topology_tag_mapping),ae.success(`Loaded defaults for ${u}`)}else ae.error(`No grouping defaults found for ${u}`)}catch(Se){ae.error(Se.response?.data?.error||Se.message||"Failed to load defaults")}};if(K)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Qe,{className:"h-8 w-8 animate-spin text-muted-foreground"})});const Et=kue.filter(Se=>!d.includes(Se)),Bt=te();return s.jsxs("div",{className:"im-rule-editor",children:[s.jsxs("div",{className:"im-rule-editor-header",children:[s.jsxs("div",{className:"im-rule-editor-header-left",children:[s.jsx("button",{type:"button",className:"im-icon-button",onClick:n,"aria-label":"Back",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:e?"Edit Grouping Rule":"Create Grouping Rule"}),s.jsx("p",{children:"Define correlation windows, grouping keys, and strategies."})]})]}),s.jsxs("div",{className:"im-rule-editor-header-actions flex gap-2",children:[s.jsx(ie,{variant:"secondary",onClick:lt,disabled:D||!u,children:"Reset to Default"}),s.jsx(ie,{variant:"outline",onClick:n,disabled:D,children:"Cancel"}),s.jsx(ie,{className:"im-primary-button",onClick:st,disabled:D||Q||V.length>0,children:D?s.jsxs(s.Fragment,{children:[s.jsx(Qe,{className:"h-4 w-4 animate-spin mr-2"})," Saving…"]}):"Save Rule"})]})]}),s.jsxs("div",{className:"im-rule-editor-split",children:[s.jsx("main",{className:"im-rule-form-pane",children:s.jsxs("div",{className:"im-rule-form",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Rule name ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{className:"im-field-input im-mono",value:r,onChange:Se=>a(Se.target.value),placeholder:"My Grouping Strategy"})]}),s.jsxs("div",{className:"im-field-row",children:[!t&&s.jsxs("div",{className:"im-field",style:{flex:1,minWidth:220},children:[s.jsx("label",{children:"Applies to — source"}),s.jsxs("select",{className:"im-field-input",value:u,onChange:Se=>p(Se.target.value),disabled:J,children:[s.jsx("option",{value:"",children:"— Any (global) —"}),_ue.map(Se=>s.jsx("option",{value:Se,children:Rue[Se]||Se},Se))]}),s.jsx("small",{className:"im-field-hint",children:"Empty = applies to alarms from any source."})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Priority"}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:90},value:i,onChange:Se=>o(parseInt(Se.target.value)||0)})]})]}),s.jsx("div",{className:"im-field-divider"}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Group by fields ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-chip-input",children:[d.map(Se=>s.jsxs("span",{className:"im-chip-active",children:[Se,s.jsx("button",{type:"button",onClick:()=>$e(Se),"aria-label":`Remove ${Se}`,children:s.jsx(Hn,{size:12})})]},Se)),s.jsx("input",{className:"im-chip-add",value:m,onChange:Se=>h(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&(Se.preventDefault(),Ae(m)),Se.key==="Backspace"&&!m&&d.length&&$e(d[d.length-1])},placeholder:"+ field, Enter"})]}),Et.length>0&&s.jsx("div",{className:"im-chip-suggestions",children:Et.map(Se=>s.jsxs("button",{type:"button",className:"im-chip-suggestion",onClick:()=>Ae(Se),children:["+ ",Se]},Se))})]}),s.jsxs("div",{className:"im-field-row",children:[s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Group timeout ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsxs("div",{className:"im-field-inline",children:[s.jsx("input",{type:"number",className:"im-field-input",style:{width:80},value:g,min:x==="m"?2:x==="s"?120:0,max:x==="m"?5:x==="s"?300:0,onChange:Se=>{let Re=parseInt(Se.target.value)||0;x==="m"&&(Re=Math.max(2,Math.min(5,Re))),x==="s"&&(Re=Math.max(120,Math.min(300,Re))),b(Re)}}),s.jsxs("select",{className:"im-field-input",style:{width:120},value:x,onChange:Se=>{const Re=Se.target.value;S(Re),Re==="m"&&b(Math.max(2,Math.min(5,Math.round(g/60)))),Re==="s"&&b(Math.max(120,Math.min(300,g*60)))},children:[s.jsx("option",{value:"s",children:"seconds"}),s.jsx("option",{value:"m",children:"minutes"})]})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("label",{children:["Max / group ",s.jsx("span",{className:"im-req",children:"*"})]}),s.jsx("input",{type:"number",className:"im-field-input",style:{width:100},value:T,onChange:Se=>N(parseInt(Se.target.value)||1)})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Group name template"}),s.jsx("input",{className:"im-field-input im-mono",value:G,onChange:Se=>q(Se.target.value),placeholder:"{{alertName}} on {{severity}}"}),s.jsxs("small",{className:"im-field-hint",children:["Variables: ",s.jsx("code",{children:"{{count}}"})," ",s.jsx("code",{children:"{{resourceName}}"})," ",s.jsx("code",{children:"{{alertName}}"})," ",s.jsx("code",{children:"{{severity}}"})]}),s.jsxs("div",{className:"im-template-preview-row",children:["Preview: ",s.jsx("span",{children:SN(G||"{{alertName}} on {{severity}}")})]})]}),s.jsxs("div",{className:"im-field",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{children:"Incident title template"}),j&&s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:k,onChange:Se=>O(Se.target.checked),className:"rounded text-primary focus:ring-primary"}),s.jsx("span",{children:"AI generated incident details"})]})]}),s.jsx("input",{className:"im-field-input im-mono",value:A,onChange:Se=>C(Se.target.value),placeholder:"{{count}} alerts on {{resourceName}}"}),s.jsxs("small",{className:"im-field-hint",children:["Variables: ",s.jsx("code",{children:"{{count}}"})," ",s.jsx("code",{children:"{{resourceName}}"})," ",s.jsx("code",{children:"{{alertName}}"})," ",s.jsx("code",{children:"{{severity}}"})]}),!k&&s.jsxs("div",{className:"im-template-preview-row",children:["Preview: ",s.jsx("span",{children:SN(A||"{{count}} alerts on {{resourceName}}")})]}),k&&s.jsxs("div",{className:"mt-4",children:[s.jsx("label",{className:"block mb-2 text-sm font-medium",children:"AI Prompt Instructions (Optional)"}),s.jsx("textarea",{className:"im-field-input w-full min-h-[120px] resize-y text-sm font-mono p-2",value:M,onChange:Se=>R(Se.target.value),placeholder:"E.g., Format the title as '[Critical] System X Failure' and provide a detailed summary of affected resources."})]})]}),u==="cloudtrail"&&s.jsxs("div",{className:"im-field",children:[s.jsx("label",{children:"Tag Mapping"}),s.jsxs("div",{className:"flex gap-2 mb-2 items-center",children:[s.jsx("input",{className:"im-field-input im-mono",style:{flex:1},value:H,onChange:Se=>I(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&(Se.preventDefault(),Ze(H))},placeholder:"tag1,tag2, Enter or click Add"}),s.jsx(ie,{type:"button",variant:"secondary",onClick:()=>Ze(H),children:"Add"})]}),Ee.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:Ee.map(Se=>s.jsxs("span",{className:"im-chip-active",children:[Se,s.jsx("button",{type:"button",onClick:()=>Ye(Se),"aria-label":`Remove ${Se}`,children:s.jsx(Hn,{size:12})})]},Se))}),s.jsx("small",{className:"im-field-hint",children:"Extracts the specified tags from the account topology for Level 1 Security alerts and groups by their values."})]}),s.jsxs("div",{className:"im-field",style:{maxWidth:320},children:[s.jsx("label",{children:"Severity resolution"}),s.jsx("select",{className:"im-field-input",value:P,onChange:Se=>z(Se.target.value),children:Iue.map(Se=>s.jsx("option",{value:Se.value,children:Se.label},Se.value))})]}),s.jsxs("label",{className:"im-checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:Se=>c(Se.target.checked)}),s.jsx("span",{children:"Active"})]}),V.length>0&&s.jsxs("div",{className:"im-validation-errors",children:[s.jsx("div",{className:"im-validation-errors-title",children:"Validation errors"}),s.jsx("ul",{children:V.map((Se,Re)=>s.jsx("li",{children:Se},Re))})]})]})}),s.jsxs("aside",{className:"im-yaml-panel",children:[s.jsxs("div",{className:"im-yaml-title",children:["Live YAML ",s.jsx("span",{children:"· read-only"}),Q&&s.jsx(Qe,{size:12,className:"animate-spin",style:{marginLeft:8,display:"inline"}})]}),s.jsx("div",{className:"im-yaml-monaco",children:s.jsx(el,{height:"100%",defaultLanguage:"yaml",value:Bt,theme:"vs-dark",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",wordWrap:"on",renderLineHighlight:"none",tabSize:2,domReadOnly:!0,contextmenu:!1}})})]})]})]})}function Oue(){return s.jsxs("div",{className:"w-full h-full",children:[s.jsx(Oh,{}),s.jsx(DP,{})]})}const TN=ej({component:Oue});function MO(){const e=Ot({getParentRoute:()=>TN,id:"insight-workspace",component:()=>s.jsx(Oh,{})}),t=e.addChildren([Ot({getParentRoute:()=>e,path:"/",component:()=>s.jsx(lo,{to:"/alerts"})}),Ot({getParentRoute:()=>e,path:"/sources",component:QV}),Ot({getParentRoute:()=>e,path:"/sources/$id",component:()=>{const{id:n}=xr({strict:!1});return s.jsx(cY,{sourceId:n})}}),Ot({getParentRoute:()=>e,path:"/sops",component:()=>{const n=St();return s.jsx(OY,{onViewSop:r=>n({to:`/sops/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/sops/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(zle,{sopId:n,onBack:()=>r({to:"/sops"})})}}),Ot({getParentRoute:()=>e,path:"/workflows/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(gN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/workflows/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(gN,{workflowId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/alerts",component:()=>{const n=St();return s.jsx(mY,{onViewIncident:r=>n({to:`/incidents/${r}`}),onViewAlert:r=>n({to:`/alert/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/alert/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(SY,{alertId:n,onBack:()=>{window.history.length>1?window.history.back():r({to:"/alerts"})},onViewIncident:a=>r({to:`/incidents/${a}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/dashboard",component:()=>s.jsx(lo,{to:"/incidents/operations?tab=dashboard"})}),Ot({getParentRoute:()=>e,path:"/incidents/analytics",component:()=>s.jsx(lo,{to:"/incidents/operations?tab=dashboard&view=analytics"})}),Ot({getParentRoute:()=>e,path:"/incidents",component:()=>s.jsx(lo,{to:"/incidents/operations"})}),Ot({getParentRoute:()=>e,path:"/incidents/operations",component:()=>{const n=St();return s.jsx(Sf,{category:"operations",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/security",component:()=>{const n=St();return s.jsx(Sf,{category:"security",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/cost",component:()=>{const n=St();return s.jsx(Sf,{category:"cost",onViewResult:r=>n({to:`/incidents/${r}`})})}}),Ot({getParentRoute:()=>e,path:"/incidents/$id",component:()=>{const{id:n}=xr({strict:!1}),r=St();return s.jsx(c9,{incidentId:n,onBack:()=>r({to:"/incidents"}),onViewAlert:a=>r({to:`/alert/${a}`})})}}),Ot({getParentRoute:()=>e,path:"/pipeline/normalization/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(xN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/normalization/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(xN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/dedup/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(EN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/dedup/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(EN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/grouping/new",component:()=>{const n=St(),r=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(wN,{sourceId:r,onBack:()=>{window.history.length>1?window.history.back():n({to:r?`/sources/${r}`:"/sources"})}})}}),Ot({getParentRoute:()=>e,path:"/pipeline/grouping/$id/edit",component:()=>{const{id:n}=xr({strict:!1}),r=St(),a=new URLSearchParams(window.location.search).get("sourceId")||void 0;return s.jsx(wN,{ruleId:n,sourceId:a,onBack:()=>{window.history.length>1?window.history.back():r({to:a?`/sources/${a}`:"/sources"})}})}})]);return TN.addChildren([t])}function Lue({apiBase:e,token:t,basePath:n="/insight",userRole:r="admin",userId:a,onOpenCostSources:i}){w.useEffect(()=>{EC(e,t)},[e,t]);const o=w.useMemo(()=>dj({routeTree:MO(),basepath:n}),[n]);return s.jsx($4,{role:r,userId:a||"",openCostSources:i,children:s.jsx(mj,{router:o})})}function jue(e,t=6e4){const[n,r]=w.useState(void 0);return w.useEffect(()=>{let a=!0;const i=async()=>{try{const o=await Ie.listIncidents({status:"open",limit:1,...e?{incidentType:e}:{}});a&&r(o.total??0)}catch{}};if(i(),t>0){const o=setInterval(i,t);return()=>{a=!1,clearInterval(o)}}return()=>{a=!1}},[e,t]),n}function PO(e){return[{title:"Incidents",url:"/incidents",icon:"BrainCircuit",roles:["admin","user"],badge:e!==void 0&&e>0?String(e):void 0,items:[{title:"Operations",url:"/incidents/operations",icon:"Wrench",roles:["admin","user"]},{title:"Security",url:"/incidents/security",icon:"Shield",roles:["admin","user"],disabled:!0},{title:"Cost",url:"/incidents/cost",icon:"DollarSign",roles:["admin","user"],disabled:!0}]},{title:"Alerts",url:"/alerts",icon:"Bell",roles:["admin","user"]},{title:"SOPs",url:"/sops",icon:"BookOpen",roles:["admin","user"]},{title:"Sources",url:"/sources",icon:"Plug",roles:["admin"]}]}const Mue=PO();exports.InsightPage=Lue;exports.api=Te;exports.configureApi=EC;exports.createRouteTree=MO;exports.getInsightNavItems=PO;exports.insightNavItems=Mue;exports.useOpenIncidentCount=jue;