@remit/web-client-dist 0.0.166 → 0.0.167

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.
Files changed (38) hide show
  1. package/assets/{ComposeBody-D4_dXMxI.js → ComposeBody-DBMP_L6f.js} +1 -1
  2. package/assets/{ConfirmDialog-Bv-wZUW8.js → ConfirmDialog-mYcsLfpH.js} +1 -1
  3. package/assets/{ErrorState-CpKap5at.js → ErrorState-CiL2lBLO.js} +1 -1
  4. package/assets/{OnboardingWizard-CXnJl0Jk.js → OnboardingWizard-B8eBjsC0.js} +1 -1
  5. package/assets/{account-form-helpers-B_3eNAXI.js → account-form-helpers-DLRHLpiA.js} +1 -1
  6. package/assets/{accounts-CELu0I53.js → accounts-CVlrpFK9.js} +1 -1
  7. package/assets/{advanced-CUB2rjuO.js → advanced-BBK8vUE4.js} +1 -1
  8. package/assets/{appearance-CccUth7t.js → appearance-4yAmtnOa.js} +1 -1
  9. package/assets/{avatar-B0o-L5k2.js → avatar-BVlTalhx.js} +1 -1
  10. package/assets/{browser-ponyfill-uCvgwKSO.js → browser-ponyfill-WIq-rbQV.js} +1 -1
  11. package/assets/{circle-check-CjfFj9t4.js → circle-check-D8nDD8kQ.js} +1 -1
  12. package/assets/{download-BQXqH-fI.js → download-B7LmjVrD.js} +1 -1
  13. package/assets/{filters-OUTPM4DP.js → filters-0U9nGFvq.js} +1 -1
  14. package/assets/{flagged-CH_hrRso.js → flagged-BC75MZSf.js} +1 -1
  15. package/assets/{folders-Cw3ZIkPn.js → folders-DlB0-yHP.js} +1 -1
  16. package/assets/{index-nZH5hiWh.js → index-C5AJPWBU.js} +1 -1
  17. package/assets/index-CREg5Dk4.js +1 -0
  18. package/assets/{index-D1BASS_Z.js → index-CePn9U7c.js} +4 -4
  19. package/assets/{kbd-BeYagT2K.js → kbd-DL8eIMv9.js} +1 -1
  20. package/assets/{labels-MXWN3pzt.js → labels-CXptB_Sx.js} +1 -1
  21. package/assets/{mail-BgYHZ5z2.js → mail-CpEhi6Ek.js} +3 -3
  22. package/assets/{move-mailbox-picker-BkH6xsJ9.js → move-mailbox-picker-Cm1Cs-B9.js} +1 -1
  23. package/assets/{move-targets-CHj2EXCt.js → move-targets-DMrkyZzc.js} +1 -1
  24. package/assets/{onboarding-BxJaqZvj.js → onboarding-DjDpT0zy.js} +1 -1
  25. package/assets/{rotate-ccw-Q8Q0nPLx.js → rotate-ccw-C-B0PcVX.js} +1 -1
  26. package/assets/{search-C6hAMy-M.js → search-B8-GBSWS.js} +1 -1
  27. package/assets/{senders-DznXO86F.js → senders-BEw6iRem.js} +1 -1
  28. package/assets/settings-craVQrpJ.js +1 -0
  29. package/assets/{settings-screen-CKqDZj0y.js → settings-screen-xu7cceOV.js} +1 -1
  30. package/assets/{suggested-vips-CRhvteeI.js → suggested-vips-CZZbejGo.js} +1 -1
  31. package/assets/{useDebouncedValue-CxOdQRIO.js → useDebouncedValue-Bs28qGoO.js} +1 -1
  32. package/assets/{useLabels-BPt1b8DF.js → useLabels-AtCKW__T.js} +1 -1
  33. package/assets/{useRulePreview-CDdbVDTB.js → useRulePreview-DCBTXuad.js} +1 -1
  34. package/assets/{useSignature-pdt8ld9d.js → useSignature-By_l9zT4.js} +1 -1
  35. package/index.html +1 -1
  36. package/package.json +1 -1
  37. package/assets/index-BSBrI51h.js +0 -1
  38. package/assets/settings-Dptkkp0c.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-D4_dXMxI.js","assets/index-D1BASS_Z.js","assets/index-Ci5tvXtM.css","assets/search-C6hAMy-M.js","assets/avatar-B0o-L5k2.js","assets/kbd-BeYagT2K.js","assets/account-form-helpers-B_3eNAXI.js","assets/useSignature-pdt8ld9d.js","assets/useDebouncedValue-CxOdQRIO.js","assets/useRulePreview-CDdbVDTB.js","assets/ErrorState-CpKap5at.js","assets/format-B6Elex-n.js","assets/move-targets-CHj2EXCt.js","assets/move-mailbox-picker-BkH6xsJ9.js","assets/rotate-ccw-Q8Q0nPLx.js","assets/circle-check-CjfFj9t4.js","assets/ConfirmDialog-Bv-wZUW8.js","assets/useLabels-BPt1b8DF.js"])))=>i.map(i=>d[i]);
2
- import{R as H,c as Dd,r as c,a as de,j as n,C as Rt,X as We,b as W,B as Y,d as lt,S as At,e as ut,f as Gt,L as oa,g as Od,h as Pd,i as Ys,k as nt,T as rt,l as Xt,u as Bn,m as ia,n as Qi,I as la,p as Yi,o as ca,q as Ld,D as ua,s as Gs,O as $d,M as Fd,A as _d,F as Gi,t as zd,v as Bd,w as Kd,x as Ud,y as da,z as fa,P as qd,E as Hd,G as ma,H as ha,_ as Nt,J as Xi,K as Wd,Q as pa,N as Vd,U as Qd,V as Yd,W as Br,Y as Gd,Z as Xd,$ as ye,a0 as Jd,a1 as Zd,a2 as ef,a3 as tf,a4 as sf,a5 as nf,a6 as vo,a7 as rf,a8 as af,a9 as of,aa as ga,ab as Ji,ac as Zi,ad as Dt,ae as Oe,af as _e,ag as Xs,ah as be,ai as xa,aj as ba,ak as va,al as ya,am as Kn,an as bs,ao as Ce,ap as Js,aq as ue,ar as el,as as lf,at as ve,au as tl,av as cf,aw as Un,ax as sl,ay as xt,az as Ve,aA as uf,aB as st,aC as nl,aD as Vt,aE as qn,aF as df,aG as wa,aH as rl,aI as al,aJ as Jt,aK as Hn,aL as Zt,aM as ff,aN as mf,aO as Wn,aP as hf,aQ as ol,aR as vs,aS as pf,aT as ja,aU as gf,aV as xf,aW as il,aX as Sa,aY as ll,aZ as cl,a_ as Ss,a$ as bf,b0 as yo,b1 as vf,b2 as yf,b3 as pt,b4 as Kr,b5 as Ur,b6 as wf,b7 as ul,b8 as jf,b9 as ka,ba as dl,bb as Sf,bc as kf,bd as Cf,be as Nf,bf as Ef,bg as If,bh as Tf,bi as Rf,bj as Mf,bk as Af,bl as Df,bm as Of,bn as Pf,bo as Lf,bp as $f,bq as kt,br as ht,bs as Ff}from"./index-D1BASS_Z.js";import{S as Vn}from"./search-C6hAMy-M.js";import{A as dt,M as Ca,C as _f}from"./avatar-B0o-L5k2.js";import{K as ps}from"./kbd-BeYagT2K.js";import{M as fl,a as zf}from"./account-form-helpers-B_3eNAXI.js";import{R as Bf,u as Kf}from"./useSignature-pdt8ld9d.js";import{u as ml}from"./useDebouncedValue-CxOdQRIO.js";import{B as hl,u as Ot,a as wo,b as qr,n as Uf,S as Na,c as pl,r as Ea,d as gl,e as xl,f as bl,g as qf,h as Hf,i as Wf,j as Vf,k as Qf}from"./useRulePreview-CDdbVDTB.js";import{E as Pt,f as vl}from"./ErrorState-CpKap5at.js";import{f as yl,a as Lt,b as wl,c as On,d as ct,t as Yf}from"./format-B6Elex-n.js";import{P as jo,u as jl,b as Zs,M as it}from"./move-targets-CHj2EXCt.js";import{F as Ia,a as Gf,M as Sl}from"./move-mailbox-picker-BkH6xsJ9.js";import{C as Ta,R as Xf}from"./rotate-ccw-Q8Q0nPLx.js";import{C as Qn}from"./circle-check-CjfFj9t4.js";import{C as Ra}from"./ConfirmDialog-Bv-wZUW8.js";import{u as kl,a as Jf}from"./useLabels-BPt1b8DF.js";function Us(e){if(Zf())e.focus({preventScroll:!0});else{let t=em(e);e.focus(),tm(t)}}let gn=null;function Zf(){if(gn==null){gn=!1;try{document.createElement("div").focus({get preventScroll(){return gn=!0,!0}})}catch{}}return gn}function em(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function tm(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const It=e=>e?.ownerDocument??document,Mt=e=>e&&"window"in e&&e.window===e?e:It(e).defaultView||window;function sm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function nm(e){return sm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let rm=!1;function Cl(){return rm}function ot(e,t){if(!Cl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:nm(s)?s=s.host:s=s.parentNode}return!1}function Me(e){if(Cl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const am=typeof Element<"u"&&"checkVisibility"in Element.prototype;function om(e){const t=Mt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=Mt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function im(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function Nl(e,t){return am?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&om(e)&&im(e,t)&&(!e.parentElement||Nl(e.parentElement,e))}const El=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],lm=El.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";El.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function cm(e,t){return e.matches(lm)&&!um(e)&&(t?.skipVisibilityCheck||Nl(e))}function um(e){let t=e;for(;t!=null;){if(t instanceof Mt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ma=typeof document<"u"?H.useLayoutEffect:()=>{};function dm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function fm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function mm(e){for(;e&&!cm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Mt(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Me(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Me(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Us(s),u()))},i=d=>{(Me(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Me(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Us(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Yn(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function Aa(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function $t(e){let t=null;return()=>(t==null&&(t=e()),t)}const Pn=$t(function(){return Aa(/^Mac/i)}),hm=$t(function(){return Aa(/^iPhone/i)}),Il=$t(function(){return Aa(/^iPad/i)||Pn()&&navigator.maxTouchPoints>1}),Tl=$t(function(){return hm()||Il()}),pm=$t(function(){return Yn(/AppleWebKit/i)&&!gm()}),gm=$t(function(){return Yn(/Chrome/i)}),Rl=$t(function(){return Yn(/Android/i)}),xm=$t(function(){return Yn(/Firefox/i)});function bm(e){return e.pointerType===""&&e.isTrusted?!0:Rl()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function vm(e){return!Rl()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function qs(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;xm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Pn()?r=!0:a=!0);let l=pm()&&Pn()&&!Il()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});qs.isOpening=s,Us(e),e.dispatchEvent(l),qs.isOpening=!1}qs.isOpening=!1;let Et=new Map,Hr=new Set;function So(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);o||(o=new Set,Et.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Et.delete(a)),Et.size===0)){for(let i of Hr)i();Hr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?So():document.addEventListener("DOMContentLoaded",So));function ym(){for(const[e]of Et)"isConnected"in e&&!e.isConnected&&Et.delete(e)}function wm(e){requestAnimationFrame(()=>{ym(),Et.size===0?e():Hr.add(e)})}function Ml(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Wr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Wr.delete(e)});function jm(e,t){if(e===t)return e;let s=Wr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Wr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function Sm(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=ko(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():ko(e[o],null)})}}}function ko(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ks(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Ml(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Dd(o,i):a==="id"&&o&&i?t.id=jm(o,i):a==="ref"&&o&&i?t.ref=Sm(o,i):t[a]=i!==void 0?i:o}}return t}function km(e,t){Ma(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Cm=H.useInsertionEffect??Ma;function yr(e){const t=c.useRef(null);return Cm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ms="default",Vr="",Tn=new WeakMap;function Nm(e){if(Tl()){if(ms==="default"){const t=It(e);Vr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ms="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Tn.set(e,e.style[t]),e.style[t]="none"}}function Co(e){if(Tl()){if(ms!=="disabled")return;ms="restoring",setTimeout(()=>{wm(()=>{if(ms==="restoring"){const t=It(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Vr||""),Vr="",ms="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Tn.has(e)){let t=Tn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Tn.delete(e)}}function No(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let wr=new WeakMap;function Em(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return No(t);if(wr.has(t))return wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Mt(s).HTMLMetaElement&&(s.nonce||s.content)||No(t)||void 0;return r!==void 0&&wr.set(t,r),r}const Al=H.createContext({register:()=>{}});Al.displayName="PressResponderContext";function Dl(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function Im(e){let t=c.useContext(Al);if(t){let{register:s,ref:r,...a}=t;e=ks(a,e),s()}return km(t,e.ref),e}class xn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Eo=Symbol("linkClicked"),Io="react-aria-pressable-style",To="data-react-aria-pressable";function Tm(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...g}=Im(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:w}=Dl(),j=c.useCallback((S,A)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new xn("pressstart",A,S);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),y=c.useCallback((S,A,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let R=new xn("pressend",A,S);a(R),F=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new xn("press",A,S);t(R),F&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),I=yr(y),N=c.useCallback((S,A)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new xn("pressup",A,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=yr(N),C=c.useCallback(S=>{let A=x.current;if(A.isPressed&&A.target){A.didFirePressStart&&A.pointerType!=null&&y(Ut(A.target,S),A.pointerType,!1),A.isPressed=!1,A.isOverTarget=!1,A.activePointerId=null,A.pointerType=null,w(),m||Co(A.target);for(let L of A.disposables)L();A.disposables=[]}},[m,w,y]),M=yr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),O=c.useCallback((S,A)=>{if(!l&&i){let L=new MouseEvent("click",S);fm(L,A),i(dm(L))}},[l,i]),E=c.useMemo(()=>{let S=x.current,A={onKeyDown(T){if(jr(T.nativeEvent,T.currentTarget)&&ot(T.currentTarget,Me(T))){Ro(Me(T),T.key)&&T.preventDefault();let F=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",F=j(T,"keyboard"));let R=T.currentTarget,$=B=>{jr(B,R)&&!B.repeat&&ot(R,Me(B))&&S.target&&k(Ut(S.target,B),"keyboard")};b(It(T.currentTarget),"keyup",Ml($,L),!0),F&&T.stopPropagation(),T.metaKey&&Pn()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ot(T.currentTarget,Me(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!qs.isOpening){let F=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||bm(T.nativeEvent))){let R=j(T,"virtual"),$=k(T,"virtual"),B=I(T,"virtual");D(T),F=R&&$&&B}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",$=k(Ut(T.currentTarget,T),R),B=I(Ut(T.currentTarget,T),R,!0);F=$&&B,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&jr(T,S.target)){Ro(Me(T),T.key)&&T.preventDefault();let F=Me(T),R=ot(S.target,F);I(Ut(S.target,T),"keyboard",R),R&&O(T,S.target),w(),T.key!=="Enter"&&Da(S.target)&&ot(S.target,F)&&!T[Eo]&&(T[Eo]=!0,qs(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let F=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of F.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){A.onPointerDown=R=>{if(R.button!==0||!ot(R.currentTarget,Me(R)))return;if(vm(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let $=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Nm(S.target),$=j(R,S.pointerType);let B=Me(R);"releasePointerCapture"in B&&("hasPointerCapture"in B?B.hasPointerCapture(R.pointerId)&&B.releasePointerCapture(R.pointerId):B.releasePointerCapture(R.pointerId)),b(It(R.currentTarget),"pointerup",T,!1),b(It(R.currentTarget),"pointercancel",F,!1)}$&&R.stopPropagation()},A.onMouseDown=R=>{if(ot(R.currentTarget,Me(R))&&R.button===0){if(f){let $=mm(R.target);$&&S.disposables.push($)}R.stopPropagation()}},A.onPointerUp=R=>{!ot(R.currentTarget,Me(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},A.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ut(S.target,R),S.pointerType))},A.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,I(Ut(S.target,R),S.pointerType,!1),P(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ot(S.target,Me(R))&&S.pointerType!=null){let $=!1,B=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&($?M(R):(Us(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>$=!0,!0),S.disposables.push(()=>clearTimeout(B))}else M(R);S.isOverTarget=!1}},F=R=>{M(R)};A.onDragStart=R=>{ot(R.currentTarget,Me(R))&&M(R)}}return A},[b,l,f,w,m,P,j,D,O]);return c.useEffect(()=>{if(!h)return;const S=It(h.current);if(!S||!S.head||S.getElementById(Io))return;const A=S.createElement("style");A.id=Io;let L=Em(S);L&&(A.nonce=L),A.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-DBMP_L6f.js","assets/index-CePn9U7c.js","assets/index-Ci5tvXtM.css","assets/search-B8-GBSWS.js","assets/avatar-BVlTalhx.js","assets/kbd-DL8eIMv9.js","assets/account-form-helpers-DLRHLpiA.js","assets/useSignature-By_l9zT4.js","assets/useDebouncedValue-Bs28qGoO.js","assets/useRulePreview-DCBTXuad.js","assets/ErrorState-CiL2lBLO.js","assets/format-B6Elex-n.js","assets/move-targets-DMrkyZzc.js","assets/move-mailbox-picker-Cm1Cs-B9.js","assets/rotate-ccw-C-B0PcVX.js","assets/circle-check-D8nDD8kQ.js","assets/ConfirmDialog-mYcsLfpH.js","assets/useLabels-AtCKW__T.js"])))=>i.map(i=>d[i]);
2
+ import{R as H,c as Dd,r as c,a as de,j as n,C as Rt,X as We,b as W,B as Y,d as lt,S as At,e as ut,f as Gt,L as oa,g as Od,h as Pd,i as Ys,k as nt,T as rt,l as Xt,u as Bn,m as ia,n as Qi,I as la,p as Yi,o as ca,q as Ld,D as ua,s as Gs,O as $d,M as Fd,A as _d,F as Gi,t as zd,v as Bd,w as Kd,x as Ud,y as da,z as fa,P as qd,E as Hd,G as ma,H as ha,_ as Nt,J as Xi,K as Wd,Q as pa,N as Vd,U as Qd,V as Yd,W as Br,Y as Gd,Z as Xd,$ as ye,a0 as Jd,a1 as Zd,a2 as ef,a3 as tf,a4 as sf,a5 as nf,a6 as vo,a7 as rf,a8 as af,a9 as of,aa as ga,ab as Ji,ac as Zi,ad as Dt,ae as Oe,af as _e,ag as Xs,ah as be,ai as xa,aj as ba,ak as va,al as ya,am as Kn,an as bs,ao as Ce,ap as Js,aq as ue,ar as el,as as lf,at as ve,au as tl,av as cf,aw as Un,ax as sl,ay as xt,az as Ve,aA as uf,aB as st,aC as nl,aD as Vt,aE as qn,aF as df,aG as wa,aH as rl,aI as al,aJ as Jt,aK as Hn,aL as Zt,aM as ff,aN as mf,aO as Wn,aP as hf,aQ as ol,aR as vs,aS as pf,aT as ja,aU as gf,aV as xf,aW as il,aX as Sa,aY as ll,aZ as cl,a_ as Ss,a$ as bf,b0 as yo,b1 as vf,b2 as yf,b3 as pt,b4 as Kr,b5 as Ur,b6 as wf,b7 as ul,b8 as jf,b9 as ka,ba as dl,bb as Sf,bc as kf,bd as Cf,be as Nf,bf as Ef,bg as If,bh as Tf,bi as Rf,bj as Mf,bk as Af,bl as Df,bm as Of,bn as Pf,bo as Lf,bp as $f,bq as kt,br as ht,bs as Ff}from"./index-CePn9U7c.js";import{S as Vn}from"./search-B8-GBSWS.js";import{A as dt,M as Ca,C as _f}from"./avatar-BVlTalhx.js";import{K as ps}from"./kbd-DL8eIMv9.js";import{M as fl,a as zf}from"./account-form-helpers-DLRHLpiA.js";import{R as Bf,u as Kf}from"./useSignature-By_l9zT4.js";import{u as ml}from"./useDebouncedValue-Bs28qGoO.js";import{B as hl,u as Ot,a as wo,b as qr,n as Uf,S as Na,c as pl,r as Ea,d as gl,e as xl,f as bl,g as qf,h as Hf,i as Wf,j as Vf,k as Qf}from"./useRulePreview-DCBTXuad.js";import{E as Pt,f as vl}from"./ErrorState-CiL2lBLO.js";import{f as yl,a as Lt,b as wl,c as On,d as ct,t as Yf}from"./format-B6Elex-n.js";import{P as jo,u as jl,b as Zs,M as it}from"./move-targets-DMrkyZzc.js";import{F as Ia,a as Gf,M as Sl}from"./move-mailbox-picker-Cm1Cs-B9.js";import{C as Ta,R as Xf}from"./rotate-ccw-C-B0PcVX.js";import{C as Qn}from"./circle-check-D8nDD8kQ.js";import{C as Ra}from"./ConfirmDialog-mYcsLfpH.js";import{u as kl,a as Jf}from"./useLabels-AtCKW__T.js";function Us(e){if(Zf())e.focus({preventScroll:!0});else{let t=em(e);e.focus(),tm(t)}}let gn=null;function Zf(){if(gn==null){gn=!1;try{document.createElement("div").focus({get preventScroll(){return gn=!0,!0}})}catch{}}return gn}function em(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function tm(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const It=e=>e?.ownerDocument??document,Mt=e=>e&&"window"in e&&e.window===e?e:It(e).defaultView||window;function sm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function nm(e){return sm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let rm=!1;function Cl(){return rm}function ot(e,t){if(!Cl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:nm(s)?s=s.host:s=s.parentNode}return!1}function Me(e){if(Cl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const am=typeof Element<"u"&&"checkVisibility"in Element.prototype;function om(e){const t=Mt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=Mt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function im(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function Nl(e,t){return am?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&om(e)&&im(e,t)&&(!e.parentElement||Nl(e.parentElement,e))}const El=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],lm=El.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";El.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function cm(e,t){return e.matches(lm)&&!um(e)&&(t?.skipVisibilityCheck||Nl(e))}function um(e){let t=e;for(;t!=null;){if(t instanceof Mt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ma=typeof document<"u"?H.useLayoutEffect:()=>{};function dm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function fm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function mm(e){for(;e&&!cm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Mt(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Me(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Me(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Us(s),u()))},i=d=>{(Me(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Me(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Us(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function Yn(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function Aa(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function $t(e){let t=null;return()=>(t==null&&(t=e()),t)}const Pn=$t(function(){return Aa(/^Mac/i)}),hm=$t(function(){return Aa(/^iPhone/i)}),Il=$t(function(){return Aa(/^iPad/i)||Pn()&&navigator.maxTouchPoints>1}),Tl=$t(function(){return hm()||Il()}),pm=$t(function(){return Yn(/AppleWebKit/i)&&!gm()}),gm=$t(function(){return Yn(/Chrome/i)}),Rl=$t(function(){return Yn(/Android/i)}),xm=$t(function(){return Yn(/Firefox/i)});function bm(e){return e.pointerType===""&&e.isTrusted?!0:Rl()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function vm(e){return!Rl()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function qs(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;xm()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Pn()?r=!0:a=!0);let l=pm()&&Pn()&&!Il()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});qs.isOpening=s,Us(e),e.dispatchEvent(l),qs.isOpening=!1}qs.isOpening=!1;let Et=new Map,Hr=new Set;function So(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);o||(o=new Set,Et.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Me(r);if(!e(r)||!a)return;let o=Et.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Et.delete(a)),Et.size===0)){for(let i of Hr)i();Hr.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?So():document.addEventListener("DOMContentLoaded",So));function ym(){for(const[e]of Et)"isConnected"in e&&!e.isConnected&&Et.delete(e)}function wm(e){requestAnimationFrame(()=>{ym(),Et.size===0?e():Hr.add(e)})}function Ml(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Wr=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Wr.delete(e)});function jm(e,t){if(e===t)return e;let s=Wr.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=Wr.get(t);return r?(r.forEach(a=>a.current=e),e):t}function Sm(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=ko(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.forEach((a,o)=>{typeof a=="function"?a():ko(e[o],null)})}}}function ko(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ks(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=Ml(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=Dd(o,i):a==="id"&&o&&i?t.id=jm(o,i):a==="ref"&&o&&i?t.ref=Sm(o,i):t[a]=i!==void 0?i:o}}return t}function km(e,t){Ma(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Cm=H.useInsertionEffect??Ma;function yr(e){const t=c.useRef(null);return Cm(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let ms="default",Vr="",Tn=new WeakMap;function Nm(e){if(Tl()){if(ms==="default"){const t=It(e);Vr=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ms="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Tn.set(e,e.style[t]),e.style[t]="none"}}function Co(e){if(Tl()){if(ms!=="disabled")return;ms="restoring",setTimeout(()=>{wm(()=>{if(ms==="restoring"){const t=It(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=Vr||""),Vr="",ms="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Tn.has(e)){let t=Tn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Tn.delete(e)}}function No(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let wr=new WeakMap;function Em(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return No(t);if(wr.has(t))return wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Mt(s).HTMLMetaElement&&(s.nonce||s.content)||No(t)||void 0;return r!==void 0&&wr.set(t,r),r}const Al=H.createContext({register:()=>{}});Al.displayName="PressResponderContext";function Dl(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function Im(e){let t=c.useContext(Al);if(t){let{register:s,ref:r,...a}=t;e=ks(a,e),s()}return km(t,e.ref),e}class xn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Eo=Symbol("linkClicked"),Io="react-aria-pressable-style",To="data-react-aria-pressable";function Tm(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...g}=Im(e),[v,p]=c.useState(!1),x=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:w}=Dl(),j=c.useCallback((S,A)=>{let L=x.current;if(l||L.didFirePressStart)return!1;let T=!0;if(L.isTriggeringEvent=!0,r){let F=new xn("pressstart",A,S);r(F),T=F.shouldStopPropagation}return s&&s(!0),L.isTriggeringEvent=!1,L.didFirePressStart=!0,p(!0),T},[l,r,s]),y=c.useCallback((S,A,L=!0)=>{let T=x.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let R=new xn("pressend",A,S);a(R),F=R.shouldStopPropagation}if(s&&s(!1),p(!1),t&&L&&!l){let R=new xn("press",A,S);t(R),F&&=R.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[l,a,s,t]),I=yr(y),N=c.useCallback((S,A)=>{let L=x.current;if(l)return!1;if(o){L.isTriggeringEvent=!0;let T=new xn("pressup",A,S);return o(T),L.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[l,o]),k=yr(N),C=c.useCallback(S=>{let A=x.current;if(A.isPressed&&A.target){A.didFirePressStart&&A.pointerType!=null&&y(Ut(A.target,S),A.pointerType,!1),A.isPressed=!1,A.isOverTarget=!1,A.activePointerId=null,A.pointerType=null,w(),m||Co(A.target);for(let L of A.disposables)L();A.disposables=[]}},[m,w,y]),M=yr(C);c.useEffect(()=>{l&&x.current.isPressed&&M({currentTarget:x.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(S=>{d&&C(S)},[d,C]),D=c.useCallback(S=>{l||i?.(S)},[l,i]),O=c.useCallback((S,A)=>{if(!l&&i){let L=new MouseEvent("click",S);fm(L,A),i(dm(L))}},[l,i]),E=c.useMemo(()=>{let S=x.current,A={onKeyDown(T){if(jr(T.nativeEvent,T.currentTarget)&&ot(T.currentTarget,Me(T))){Ro(Me(T),T.key)&&T.preventDefault();let F=!0;!S.isPressed&&!T.repeat&&(S.target=T.currentTarget,S.isPressed=!0,S.pointerType="keyboard",F=j(T,"keyboard"));let R=T.currentTarget,$=B=>{jr(B,R)&&!B.repeat&&ot(R,Me(B))&&S.target&&k(Ut(S.target,B),"keyboard")};b(It(T.currentTarget),"keyup",Ml($,L),!0),F&&T.stopPropagation(),T.metaKey&&Pn()&&S.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(S.metaKeyEvents=new Map)},onClick(T){if(!(T&&!ot(T.currentTarget,Me(T)))&&T&&T.button===0&&!S.isTriggeringEvent&&!qs.isOpening){let F=!0;if(l&&T.preventDefault(),!S.ignoreEmulatedMouseEvents&&!S.isPressed&&(S.pointerType==="virtual"||bm(T.nativeEvent))){let R=j(T,"virtual"),$=k(T,"virtual"),B=I(T,"virtual");D(T),F=R&&$&&B}else if(S.isPressed&&S.pointerType!=="keyboard"){let R=S.pointerType||T.nativeEvent.pointerType||"virtual",$=k(Ut(T.currentTarget,T),R),B=I(Ut(T.currentTarget,T),R,!0);F=$&&B,S.isOverTarget=!1,D(T),M(T)}S.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},L=T=>{if(S.isPressed&&S.target&&jr(T,S.target)){Ro(Me(T),T.key)&&T.preventDefault();let F=Me(T),R=ot(S.target,F);I(Ut(S.target,T),"keyboard",R),R&&O(T,S.target),w(),T.key!=="Enter"&&Da(S.target)&&ot(S.target,F)&&!T[Eo]&&(T[Eo]=!0,qs(S.target,T,!1)),S.isPressed=!1,S.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&S.metaKeyEvents?.size){let F=S.metaKeyEvents;S.metaKeyEvents=void 0;for(let R of F.values())S.target?.dispatchEvent(new KeyboardEvent("keyup",R))}};if(typeof PointerEvent<"u"){A.onPointerDown=R=>{if(R.button!==0||!ot(R.currentTarget,Me(R)))return;if(vm(R.nativeEvent)){S.pointerType="virtual";return}S.pointerType=R.pointerType;let $=!0;if(!S.isPressed){S.isPressed=!0,S.isOverTarget=!0,S.activePointerId=R.pointerId,S.target=R.currentTarget,m||Nm(S.target),$=j(R,S.pointerType);let B=Me(R);"releasePointerCapture"in B&&("hasPointerCapture"in B?B.hasPointerCapture(R.pointerId)&&B.releasePointerCapture(R.pointerId):B.releasePointerCapture(R.pointerId)),b(It(R.currentTarget),"pointerup",T,!1),b(It(R.currentTarget),"pointercancel",F,!1)}$&&R.stopPropagation()},A.onMouseDown=R=>{if(ot(R.currentTarget,Me(R))&&R.button===0){if(f){let $=mm(R.target);$&&S.disposables.push($)}R.stopPropagation()}},A.onPointerUp=R=>{!ot(R.currentTarget,Me(R))||S.pointerType==="virtual"||R.button===0&&!S.isPressed&&k(R,S.pointerType||R.pointerType)},A.onPointerEnter=R=>{R.pointerId===S.activePointerId&&S.target&&!S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!0,j(Ut(S.target,R),S.pointerType))},A.onPointerLeave=R=>{R.pointerId===S.activePointerId&&S.target&&S.isOverTarget&&S.pointerType!=null&&(S.isOverTarget=!1,I(Ut(S.target,R),S.pointerType,!1),P(R))};let T=R=>{if(R.pointerId===S.activePointerId&&S.isPressed&&R.button===0&&S.target){if(ot(S.target,Me(R))&&S.pointerType!=null){let $=!1,B=setTimeout(()=>{S.isPressed&&S.target instanceof HTMLElement&&($?M(R):(Us(S.target),S.target.click()))},80);b(R.currentTarget,"click",()=>$=!0,!0),S.disposables.push(()=>clearTimeout(B))}else M(R);S.isOverTarget=!1}},F=R=>{M(R)};A.onDragStart=R=>{ot(R.currentTarget,Me(R))&&M(R)}}return A},[b,l,f,w,m,P,j,D,O]);return c.useEffect(()=>{if(!h)return;const S=It(h.current);if(!S||!S.head||S.getElementById(Io))return;const A=S.createElement("style");A.id=Io;let L=Em(S);L&&(A.nonce=L),A.textContent=`
3
3
  @layer {
4
4
  [${To}] {
5
5
  touch-action: pan-x pan-y pinch-zoom;
@@ -113,6 +113,6 @@ a, a:visited {
113
113
  .block-interactivity-`.concat(e,` {pointer-events: none;}
114
114
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
115
  `)},kx=0,us=[];function Cx(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(kx++)[0],o=c.useState(bc)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Wd([e.lockRef.current],(e.shards||[]).map(pi),!0).filter(Boolean);return p.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,x){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=kn(p),w=s.current,j="deltaX"in p?p.deltaX:w[0]-b[0],y="deltaY"in p?p.deltaY:w[1]-b[1],I,N=p.target,k=Math.abs(j)>Math.abs(y)?"h":"v";if("touches"in p&&k==="h"&&N.type==="range")return!1;var C=window.getSelection(),M=C&&C.anchorNode,P=M?M===N||M.contains(N):!1;if(P)return!1;var D=mi(k,N);if(!D)return!0;if(D?I=k:(I=k==="v"?"h":"v",D=mi(k,N)),!D)return!1;if(!r.current&&"changedTouches"in p&&(j||y)&&(r.current=I),!I)return!0;var O=r.current||I;return wx(O,x,p,O==="h"?j:y)},[]),u=c.useCallback(function(p){var x=p;if(!(!us.length||us[us.length-1]!==o)){var b="deltaY"in x?hi(x):kn(x),w=t.current.filter(function(I){return I.name===x.type&&(I.target===x.target||x.target===I.shadowParent)&&jx(I.delta,b)})[0];if(w&&w.should){x.cancelable&&x.preventDefault();return}if(!w){var j=(i.current.shards||[]).map(pi).filter(Boolean).filter(function(I){return I.contains(x.target)}),y=j.length>0?l(x,j[0]):!i.current.noIsolation;y&&x.cancelable&&x.preventDefault()}}},[]),f=c.useCallback(function(p,x,b,w){var j={name:p,delta:x,target:b,should:w,shadowParent:Nx(b)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(y){return y!==j})},1)},[]),d=c.useCallback(function(p){s.current=kn(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,hi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,kn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return us.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,cs),document.addEventListener("touchmove",u,cs),document.addEventListener("touchstart",d,cs),function(){us=us.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,cs),document.removeEventListener("touchmove",u,cs),document.removeEventListener("touchstart",d,cs)}},[]);var g=e.removeScrollBar,v=e.inert;return c.createElement(c.Fragment,null,v?c.createElement(o,{styles:Sx(a)}):null,g?c.createElement(hx,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Nx(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Ex=tx(xc,Cx);var jc=c.forwardRef(function(e,t){return c.createElement(Zn,Nt({},e,{ref:t,sideCar:Ex}))});jc.classNames=Zn.classNames;var Ix=class extends pa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,r=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=r,u=s.fetchMeta?.fetchMore?.direction,f=i&&u==="forward",d=a&&u==="forward",m=i&&u==="backward",h=a&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Qd(t,s.data),hasPreviousPage:Vd(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function gi(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function Tx(e,t,s){const r=e.slice(0);return r[t]=s,r}var Rx=class extends Yd{#s;#e;#a;#r;#t;#n;#o;#i;#l;#c=[];constructor(e,t,s){super(),this.#s=e,this.#r=s,this.#a=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#a=e,this.#r=t,Br.batch(()=>{const s=this.#t,r=this.#f(this.#a);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,m)=>d!==s[m]),u=i||l,f=u?!0:o.some((d,m)=>{const h=this.#e[m];return!h||!Gd(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(gi(s,a).forEach(d=>{d.destroy()}),gi(a,s).forEach(d=>{d.subscribe(m=>{this.#m(d,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),r=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[r,o=>this.#d(o??r,t,a),()=>this.#u(r,s)]}#u(e,t){return t.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const r=this.#l,a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((o,i)=>o!==r[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Xd(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(r=>{const a=r.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(r):t.set(a,[r])});const s=[];return e.forEach(r=>{const a=this.#s.defaultQueryOptions(r),i=t.get(a.queryHash)?.shift()??new pa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Tx(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,r=t?s:this.#d(e,this.#r?.combine);(t||s!==r)&&Br.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function Ft({queries:e,...t},s){const r=ye(),a=Jd(),o=Zd(),i=c.useMemo(()=>e.map(p=>{const x=r.defaultQueryOptions(p);return x._optimisticResults=a?"isRestoring":"optimistic",x}),[e,r,a]);i.forEach(p=>{ef(p);const x=r.getQueryCache().get(p.queryHash);tf(p,o,x)}),sf(o);const[l]=c.useState(()=>new Rx(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(Br.batchCalls(p)):nf,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,x)=>vo(i[x],p))?u.flatMap((p,x)=>{const b=i[x];if(b&&vo(b,p)){const w=new pa(r,b);return rf(b,w,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=u.find((p,x)=>{const b=i[x];return b&&af({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(v?.error)throw v.error;return f(d())}function Sc(e,t){return of(e,Ix)}function Mx(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>s&&r!==void 0?await r():s,enableBeforeUnload:s,withResolver:r===void 0}}function Ax(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=Mx(e),i=ga(),{history:l}=i,[u,f]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async m=>{function h(b){const w=i.parseLocation(b),j=i.getMatchedRoutes(w.pathname);return j.foundRoute===void 0?{routeId:"__notFound__",fullPath:w.pathname,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}:{routeId:j.foundRoute.id,fullPath:j.foundRoute.fullPath,pathname:w.pathname,params:j.routeParams,search:i.options.parseSearch(b.search)}}const g=h(m.currentLocation),v=h(m.nextLocation);if(g.routeId==="__notFound__"&&v.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:g,next:v});if(!o)return p;if(!p)return!1;const x=await new Promise(b=>{f({status:"blocked",current:g,next:v,action:m.action,proceed:()=>b(!1),reset:()=>b(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),x};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function gt(e){const t=ga({warn:e?.router===void 0}),s=e?.router||t;return Ji(s.stores.__store,Zi(e,s))}function er(e){const t=ga();return Ji(t.stores.location,Zi(e,t))}const Dx=new Set(["outbox","flagged"]),Ox=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Dx.has(s)};function Px(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,r]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Xs(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function kc(e){const{openCompose:t}=Dt(),s=Oe(),r=er(),a=Px(e);return c.useCallback(()=>{if(Ox(r.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,r.pathname,a])}const Lx=e=>e.startsWith("/mail")||e.startsWith("/settings"),$x=({accounts:e})=>{const{state:t}=Dt(),s=er(),r=kc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Lx(s.pathname)||t.isOpen||o?null:n.jsx("button",{type:"button",onClick:r,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:n.jsx(Hm,{className:"size-6"})})},Cc=({trigger:e,children:t,align:s="right"})=>{const[r,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(r&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[r,i,l]),n.jsxs("div",{ref:o,className:"relative",children:[n.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!r)},className:be("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),r&&n.jsx("div",{className:be("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},hs=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:be("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:r}),Xr=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),Nc=({children:e})=>{const{Account:t}=xa();return n.jsx(t,{children:e})},Fx=({email:e,onSignOut:t})=>{const s=Oe(),r=e??"Account";return n.jsxs(Cc,{trigger:n.jsx(dt,{name:r,email:e??void 0,size:"sm"}),align:"right",children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),n.jsx(Xr,{})]}),n.jsxs(hs,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(Oa,{className:"size-4"}),"Settings"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:t,children:[n.jsx(Bl,{className:"size-4"}),"Sign out"]})]})},_x=()=>n.jsx(Nc,{children:({email:e,signOut:t})=>n.jsx(Fx,{email:e,onSignOut:t})}),xi=()=>{const e=ba(),t=va(e);window.open(t,"_blank","noopener,noreferrer")};function Ec({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:xi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Mo,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(Y,{variant:"ghost",size:"sm",icon:n.jsx(Mo,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:xi})}const Ic="/mail/",Ba="/mail/$mailboxId",Tc="/mail/outbox",Rc="/mail/flagged";function Ka(e){return e.some(t=>t.routeId===Ic)}function nn(e){return e.some(t=>t.routeId===Rc)}function tr(e){return e.some(t=>t.routeId===Tc)}function Mc(e){return e.some(t=>t.routeId===Ba)}function zx(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Ba}:${t}`:nn(e)?Rc:tr(e)?Tc:Ka(e)?Ic:""}const An="search-scope";function Bx(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function Ac(e){return nn(e)||tr(e)||Mc(e)}function Dc(e){return e.find(t=>t.routeId===Ba)?.params?.mailboxId}function Kx(e){const t=Dc(e.matches);return t||(Ac(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Ux(e,t){return Ka(e)?{kind:"global"}:nn(e)?{kind:"scoped",chip:{id:An,label:"is:starred"}}:tr(e)?{kind:"scoped",chip:{id:An,label:"in:outbox"}}:Mc(e)?t?{kind:"scoped",chip:{id:An,label:Bx(t)}}:{kind:"pending"}:{kind:"global"}}function qx(e,t,s){return t.kind==="global"?{kind:"global"}:nn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const Oc=({accounts:e})=>{const t=ya({strict:!1}),s=er(),r=t.mailboxId,{t:a}=Kn("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=Ft({queries:e.map(l=>({..._e({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!r)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const f=u.find(m=>m.mailboxId===r);if(!f)continue;const d=Xs(e[l].folderAppointments);return bs(f,d.get(r),o)}return null},Hx=({accounts:e})=>{const s=ya({strict:!1}).mailboxId,r=Ft({queries:e.map(a=>({..._e({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of r){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function Pc(e){const t=Oe(),{searchInput:s}=Ce(),r=Oc({accounts:e}),a=gt({select:l=>l.matches}),o=Ux(a,r),i=c.useCallback(l=>{l===An&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const Lc=[{title:"Navigation",hints:[{action:"focusNext",keys:["j"],description:"Focus next message"},{action:"focusPrevious",keys:["k"],description:"Focus previous message"},{action:"focusNext",keys:["↓"],description:"Focus next message"},{action:"focusPrevious",keys:["↑"],description:"Focus previous message"},{action:"focusFirst",keys:["Home"],description:"Focus first"},{action:"focusLast",keys:["End"],description:"Focus last"},{action:"openFocused",keys:["Enter"],description:"Open focused thread"},{action:"back",keys:["Esc"],description:"Back / close overlay"}]},{title:"Selection",hints:[{action:"toggleSelect",keys:["x"],description:"Toggle select"},{action:"toggleSelect",keys:["Space"],description:"Toggle select"},{action:"extendSelectDown",keys:["Shift","j"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","k"],description:"Extend selection up"},{action:"extendSelectDown",keys:["Shift","↓"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","↑"],description:"Extend selection up"},{action:"selectAll",keys:["⌘","A"],description:"Select all"}]},{title:"Actions",hints:[{action:"reply",keys:["r"],description:"Reply"},{action:"replyAll",keys:["a"],description:"Reply all"},{action:"forward",keys:["f"],description:"Forward"},{action:"delete",keys:["#"],description:"Delete"},{action:"toggleStar",keys:["s"],description:"Star / unstar"},{action:"toggleRead",keys:["u"],description:"Toggle read / unread"}]},{title:"Sender",hints:[{action:"muteSender",keys:["m"],description:"Mute sender"},{action:"blockSender",keys:["b"],description:"Block sender"},{action:"vipSender",keys:["v"],description:"VIP sender"},{action:"markJunk",keys:["!"],description:"Mark junk"}]},{title:"Go to",hints:[{action:"goBrief",keys:["g","b"],description:"Daily brief"},{action:"goInbox",keys:["g","i"],description:"Inbox"},{action:"goSent",keys:["g","s"],description:"Sent"},{action:"goFlagged",keys:["g","f"],description:"Starred"},{action:"goSettings",keys:["g",","],description:"Settings"}]},{title:"View & global",hints:[{action:"toggleIntelligence",keys:["i"],description:"Toggle intelligence"},{action:"toggleDensity",keys:["d"],description:"Toggle density"},{action:"focusSearch",keys:["/"],description:"Focus search"},{action:"compose",keys:["c"],description:"Compose"},{action:"compose",keys:["⌘","N"],description:"Compose"},{action:"help",keys:["?"],description:"Shortcut help"}]}];function Wx(e){for(const t of Lc){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function fs(e){const t=Wx(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Vx={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Qx({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=Ce(),o=kc(e),{scope:i,clearScope:l}=Pc(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=Vx[i.kind];return n.jsx(ep,{search:n.jsx(La,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(Y,{variant:"ghost",size:"sm",icon:n.jsx(Qm,{className:"size-4"}),title:`Compose ${fs("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(Ec,{}),n.jsx(_x,{})]})})}const Ua=({isOpen:e,onClose:t,children:s,ariaLabel:r="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const f=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",f),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",f),document.body.style.overflow=m,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return n.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":r,children:[n.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),n.jsxs("div",{ref:i,className:be("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[n.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:n.jsx(We,{className:"size-5"})})}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},Yx=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const r=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return r?{kind:"text",contentUrl:r.contentUrl}:null},Jr={all:["messages"],detail:e=>[...Jr.all,"detail",e],body:e=>[...Jr.detail(e),"body"]};class Ht extends Error{reason;status;retryAfterSeconds;constructor(t,s,r,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=r,this.retryAfterSeconds=a}}const Gx=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Xx=8,Jx="x-remit-403-reason",Zx=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},eb=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,tb=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},sb=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await lf(e,{headers:r});if(o.status===202)throw new Ht("not-ready","Message body is still syncing",202,Gx(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Jx),f=Zx(o.status,u);throw new Ht(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(tb(t,i))throw new Ht("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(eb(l,i))throw new Ht("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},nb=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),$c=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?Yx(t):null,a=Js(),{getToken:o}=xa(),i=c.useRef(null),l=ye(),u=c.useRef(!1),f=c.useRef(null),d=e&&r?`${e}:${r.contentUrl}`:null;f.current!==d&&(f.current=d,u.current=!1);const m=ue({queryKey:e?[...Jr.body(e),r?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!r)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const v=u.current;return u.current=!1,nb({fetchContent:(p,x)=>sb(p,x,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:el({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:v})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?v<Xx:v<1,retryDelay:(v,p)=>p instanceof Ht&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=m.isLoading&&!!r;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{m.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[m.isSuccess,a]);const g=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:g,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},rb=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=ye(),u=ve(tl()),f=ve(cf()),d=c.useCallback(async v=>{if(r("saving"),o(null),e){const x=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:v.toAddresses,ccAddresses:v.ccAddresses,bccAddresses:v.bccAddresses,subject:v.subject,textBody:v.textBody,htmlBody:v.htmlBody,inReplyTo:v.inReplyTo,references:v.references}});return r("saved"),x}const p=await u.mutateAsync({body:{...v,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:Un().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(v=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(v).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(v=>(i.current&&clearTimeout(i.current),d(v)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:g}},Fc=e=>"text"in e&&!("children"in e),_c=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ab=e=>{let t=_c(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},zc=e=>{const t=e.children.map(s=>Fc(s)?ab(s):zc(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${_c(s)}">${t}</a>`}default:return`<p>${t}</p>`}},bi=e=>e.map(zc).join(""),Bc=e=>Fc(e)?e.text:e.children.map(Bc).join(""),Zr=e=>e.map(Bc).join(`
116
- `),ob=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,vi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),ib=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(vi(a))return{email:a,displayName:r}}if(vi(t))return{email:t}},Dr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=ml(a,200),{data:g}=ue({...sl({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),w=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),y=c.useCallback(()=>{const k=ib(a);k&&b(k)},[a,b]),I=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){w(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),y());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,w,j,y]),N=c.useCallback(()=>{setTimeout(()=>{y(),f(!1)},150)},[y]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(Jm,{email:k.email,displayName:k.displayName,onRemove:()=>w(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:I,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:ob(k)},k.addressId))})]})},lb=({accountId:e})=>{const t=Oe();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(fa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(Lm,{className:"size-3","aria-hidden":"true"})]})]})]})},yi=150,cb=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>yi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},ub=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ue({...xt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},db=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),fb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],mb=["href"],hb=e=>Yi.sanitize(e,{ALLOWED_TAGS:fb,ALLOWED_ATTR:mb}),pb=c.lazy(()=>df(()=>import("./ComposeBody-D4_dXMxI.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),gb=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Kc=[{type:"p",children:[{text:""}]}],xb=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],bb=e=>e?[...xb,{type:"p",children:[{text:e}]}]:Kc,vb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",yb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",wb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},jb=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},Sb=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Zr(a).trim()==="",kb=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:g})=>{const v=Ot(),{isKeyboardOpen:p}=cb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(w=>w.displayName??w.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(ub,{selectedAccountId:e,onSelect:t}),n.jsx(Dr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Dr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Dr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(db,{value:h,onChange:g})]})},qa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Dt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[w,j]=c.useState(!1),[y,I]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),P=c.useRef(f);c.useEffect(()=>{P.current!==f&&(P.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),I(!1),E(Kc),M(!1)))},[f]);const{signature:D}=Kf(N),[O,E]=c.useState(()=>bb(D.plainText)),{data:S}=ue({...uf({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(G=>({email:G,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(G=>({email:G,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(G=>({email:G,displayName:void 0}))),I(!0)),S.subject&&b(S.subject),S.textBody&&E([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:G,cc:ae}=wb(s,e,t?.email);m(G),g(ae),ae.length>0&&j(!0),b(vb(s.envelope.subject))}e==="forward"&&b(yb(s.envelope.subject))}},[e,s,t?.email]);const A=e==="reply"||e==="reply_all"||e==="forward",{data:L}=$c({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:A&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?hb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:B,saveDraft:K,cancelAutoSave:J}=rb({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{B&&u({title:"Couldn't save draft",detail:st(B)??"Saving the draft failed.",error:B})},[B,u]);const ee=ve(tl()),X=ve(nl()),me=ve({...qn(),onError:G=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",G))}}),{data:ce}=ue({...xt(),staleTime:1/0}),te=ce?.accounts.find(G=>G.accountId===N),U=te?zf(te):!1,q=ee.isPending||X.isPending,re=d.length>0&&!!N&&!U;c.useEffect(()=>{if(!N||f&&!C||Sb(d,h,v,x,O))return;const G=Zr(O),ae=bi(O);K({accountId:N,toAddresses:d.map(le=>le.email),ccAddresses:h.length>0?h.map(le=>le.email):void 0,bccAddresses:v.length>0?v.map(le=>le.email):void 0,subject:x||void 0,textBody:G||void 0,htmlBody:ae||void 0})},[N,f,C,d,h,v,x,O,K]);const Ie=c.useCallback(async()=>{if(!N||d.length===0)return;J();const G=s&&(e==="reply"||e==="reply_all")?jb(s):{};let ae=f,le=!1;if(!ae){const Fe=Zr(O),pe=bi(O),ge=await ee.mutateAsync({body:{accountId:N,toAddresses:d.map(Se=>Se.email),ccAddresses:h.length>0?h.map(Se=>Se.email):void 0,bccAddresses:v.length>0?v.map(Se=>Se.email):void 0,subject:x||void 0,textBody:Fe||void 0,htmlBody:pe||void 0,sendImmediately:!0,...G}}).catch(Se=>(u({title:"Couldn't send message",detail:st(Se)??"Saving the draft failed.",error:Se}),null));if(ge===null)return;ae=ge.outboxMessageId,le=!0,i(ae)}await X.mutateAsync({path:{outboxMessageId:ae}}).catch(Fe=>(u({title:"Couldn't send message",detail:st(Fe)??(le?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Fe}),null))!==null&&(l(ae),r())},[N,d,h,v,x,O,e,s,f,ee,X,J,l,i,u,r]),je=c.useCallback(()=>{J(),f&&me.mutate({path:{outboxMessageId:f}}),r()},[J,f,me,r]),V=c.useCallback(G=>{k(G.accountId),a?.(G)},[a]);return n.jsx(rp,{banner:te&&U?n.jsx(lb,{accountId:te.accountId}):void 0,header:n.jsx(kb,{selectedAccountId:N,onAccountChange:V,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:w,setShowCc:j,showBcc:y,setShowBcc:I,subject:x,setSubject:b}),quoted:T||F?n.jsx(Np,{text:T,html:F,senderName:R}):void 0,actionBar:n.jsx(np,{onSend:Ie,onDiscard:je,sending:q,canSend:re,saveStatus:$,unavailableReason:U?"SMTP not configured":void 0,onUnavailable:G=>u({title:"Can't send yet",detail:G})}),children:n.jsx(c.Suspense,{fallback:n.jsx(gb,{}),children:n.jsx(pb,{value:O,onChange:E,onSubmit:Ie,autoFocus:e==="new"})})})},wi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(qa,{mode:e,account:t,sourceMessage:s,onClose:r})}),Uc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),Ha=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},qc=e=>{const{data:t,isLoading:s}=ue({...xt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Ft({queries:r.map(l=>({..._e({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},Cb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Nb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Hc=(e,t)=>e===void 0?e:Cb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Nb(e)?{...e,items:t(e.items)}:e,vt=e=>{const t=[];for(const s of new Set(e))t.push(wa({path:{mailboxId:s}})),t.push(rl({path:{mailboxId:s}}));return t.push(al()),t},rn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),an=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),on=(e,t,s)=>{const r=a=>Hc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},ln=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},yt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Eb=3e3,Ib=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},sr=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},Ln=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),Tb=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),Rb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Hn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=Zt({path:{threadId:s}}),x=vt(sr(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),rn(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,y])=>({queryKey:j,data:y})),w=an(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:Ln(j.items,g,v)}),on(o,x,j=>Ln(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:w}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);ln(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:st(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),yt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Jt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>Tb(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Ib(m,Eb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},nr=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Hn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:st(f),error:f})},onSettled:(f,d,m)=>{yt(a,vt(sr(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},Mb=60,Ab=1.5,Db=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*Ab?{direction:null}:{direction:e<0?"left":"right"}},Ob=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Mb})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=Db(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},Pb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,ji=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Wa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...ff(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Zt({path:{threadId:e}}),g=vt([Pb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),rn(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=an(r,g);return r.setQueriesData({queryKey:h},x=>Hc(x,b=>ji(b,d,m))),on(r,g,x=>ji(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);ln(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function rr(e){return e===void 0?"uncategorized":e}const Lb={inbox:"Inbox",junk:"Junk"},Va=e=>e.destinationMailboxId!==void 0,$b=(e,t)=>{if(Va(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Lb[s]??"another folder"} by Remit`},Fb=(e,t)=>{if(e===jo.MoveToInbox)return t.inboxMailboxId;if(e===jo.MoveToJunk)return t.junkMailboxId},_b=(e,t,s)=>{if(!e||!t)return!1;const r=Va(e)?e.destinationMailboxId:Fb(e.action,s);return r!==void 0&&r===t},zb=(e,t)=>{if(e){if(Va(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},ar=(e,t)=>{const{data:s,isLoading:r}=ue({...xt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Bb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Kb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Qa=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},or=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Junk");return{junkMailboxId:t,isLoading:s}},Wc=e=>{const{data:t}=ue({...xt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Si=(e,t)=>e.filter(s=>!t.has(s.messageId)),Qt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...mf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Zt({path:{threadId:t}}):[],h=vt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],rn(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=an(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Si(p.items,d)}),on(a,h,p=>Si(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);ln(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Ub=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Qa(e),{junkMailboxId:i}=or(e),{moveMessages:l,isPending:u}=Qt({mailboxId:r,threadId:s,accountId:e}),{data:f}=ue({..._e({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=_b(a,r,d),h=zb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Wn(p.fullPath))[0]:void 0;return{show:!0,label:$b(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Vc({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Ub({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(tp,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const ki=(e,t)=>e.filter(s=>!t.has(s.messageId)),qb=e=>e.filter(t=>t.isDeleted!==!0),Yt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...hf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],g=vt(sr(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),rn(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=an(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:ki(x.items,m)}),on(o,g,x=>ki(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);ln(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:st(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),yt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Qc=(e,t=Date.now())=>({value:e,setAt:t}),Hb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Qc(!0,r):delete a.trusted,{...e,flags:a}},Wb=(e,t,s,r)=>{const a=o=>o.map(i=>Hb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ya=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...ol(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=el({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&Wb(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Qc(!f)}}})},isPending:a,error:o,reset:i}};var ir="Dialog",[Yc]=sg(ir),[Vb,at]=Yc(ir),Gc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=ag({prop:r,defaultProp:a??!1,onChange:o,caller:ir});return n.jsx(Vb,{scope:t,triggerRef:l,contentRef:u,contentId:Ir(),titleId:Ir(),descriptionId:Ir(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Gc.displayName=ir;var Xc="DialogTrigger",Qb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Xc,s),o=es(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Xa(a.open),...r,ref:o,onClick:Tt(e.onClick,a.onOpenToggle)})});Qb.displayName=Xc;var Ga="DialogPortal",[Yb,Jc]=Yc(Ga,{forceMount:void 0}),Zc=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=at(Ga,t);return n.jsx(Yb,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Jn,{present:s||o.open,children:n.jsx(hc,{asChild:!0,container:a,children:i})}))})};Zc.displayName=Ga;var $n="DialogOverlay",eu=c.forwardRef((e,t)=>{const s=Jc($n,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at($n,e.__scopeDialog);return o.modal?n.jsx(Jn,{present:r||o.open,children:n.jsx(Xb,{...a,ref:t})}):null});eu.displayName=$n;var Gb=_a("DialogOverlay.RemoveScroll"),Xb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at($n,s),o=kg(),i=es(t,o);return n.jsx(jc,{as:Gb,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Xa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",tu=c.forwardRef((e,t)=>{const s=Jc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(js,e.__scopeDialog);return n.jsx(Jn,{present:r||o.open,children:o.modal?n.jsx(Jb,{...a,ref:t}):n.jsx(Zb,{...a,ref:t})})});tu.displayName=js;var Jb=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(null),a=es(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Wg(o)},[]),n.jsx(su,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Tt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Tt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Tt(e.onFocusOutside,o=>o.preventDefault())})}),Zb=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(su,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),su=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=at(js,s);return Ig(),n.jsx(n.Fragment,{children:n.jsx(fc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(uc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Xa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),nu="DialogTitle",ru=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(nu,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});ru.displayName=nu;var au="DialogDescription",ev=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(au,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});ev.displayName=au;var ou="DialogClose",tv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(ou,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Tt(e.onClick,()=>a.onOpenChange(!1))})});tv.displayName=ou;function Xa(e){return e?"open":"closed"}function sv(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const iu=H.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),cn=()=>{const e=H.useContext(iu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};sv(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
116
+ `),ob=e=>e.displayName?`${e.displayName} <${e.normalizedEmail}>`:e.normalizedEmail,vi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),ib=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(vi(a))return{email:a,displayName:r}}if(vi(t))return{email:t}},Dr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),[i,l]=c.useState(-1),[u,f]=c.useState(!1),d=c.useRef(null),m=c.useRef(null),h=ml(a,200),{data:g}=ue({...sl({query:{q:h,limit:8}}),enabled:h.length>=2}),v=g?.items??[],p=new Set(t.map(k=>k.email.toLowerCase())),x=v.filter(k=>!p.has(k.normalizedEmail.toLowerCase()));c.useEffect(()=>{l(-1),f(x.length>0&&a.length>=2)},[x.length,a.length]);const b=c.useCallback(k=>{p.has(k.email.toLowerCase())||(s([...t,k]),o(""),f(!1))},[t,p,s]),w=c.useCallback(k=>{s(t.filter((C,M)=>M!==k))},[t,s]),j=c.useCallback(k=>{b({email:k.normalizedEmail,displayName:k.displayName}),d.current?.focus()},[b]),y=c.useCallback(()=>{const k=ib(a);k&&b(k)},[a,b]),I=c.useCallback(k=>{if(k.key==="Backspace"&&a===""&&t.length>0){w(t.length-1);return}if(k.key==="Enter"||k.key==="Tab"||k.key===","){if(i>=0&&x[i]){k.preventDefault(),j(x[i]);return}a.trim()&&(k.preventDefault(),y());return}if(k.key==="ArrowDown"&&u){k.preventDefault(),l(C=>C<x.length-1?C+1:0);return}if(k.key==="ArrowUp"&&u){k.preventDefault(),l(C=>C>0?C-1:x.length-1);return}k.key==="Escape"&&(f(!1),l(-1))},[a,t.length,i,x,u,w,j,y]),N=c.useCallback(()=>{setTimeout(()=>{y(),f(!1)},150)},[y]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>d.current?.focus(),onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&d.current?.focus()},children:[t.map((k,C)=>n.jsx(Jm,{email:k.email,displayName:k.displayName,onRemove:()=>w(C)},k.email)),n.jsx("input",{ref:d,id:`address-field-${e}`,type:"text",value:a,onChange:k=>o(k.target.value),onKeyDown:I,onBlur:N,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5"})]})]}),u&&x.length>0&&n.jsx("ul",{ref:m,className:"absolute left-12 right-0 mt-1 bg-surface border border-line rounded-md shadow-lg z-50 max-h-[200px] overflow-auto",children:x.map((k,C)=>n.jsx("li",{className:be("px-3 py-2 text-sm cursor-pointer transition-colors",C===i&&"bg-accent-2-soft"),onMouseDown:M=>{M.preventDefault(),j(k)},onMouseEnter:()=>l(C),children:ob(k)},k.addressId))})]})},lb=({accountId:e})=>{const t=Oe();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(fa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(Lm,{className:"size-3","aria-hidden":"true"})]})]})]})},yi=150,cb=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>yi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},ub=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ue({...xt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},db=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),fb=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],mb=["href"],hb=e=>Yi.sanitize(e,{ALLOWED_TAGS:fb,ALLOWED_ATTR:mb}),pb=c.lazy(()=>df(()=>import("./ComposeBody-DBMP_L6f.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),gb=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),Kc=[{type:"p",children:[{text:""}]}],xb=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],bb=e=>e?[...xb,{type:"p",children:[{text:e}]}]:Kc,vb=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",yb=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",wb=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},jb=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},Sb=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&Zr(a).trim()==="",kb=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:g})=>{const v=Ot(),{isKeyboardOpen:p}=cb();if(!v&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(w=>w.displayName??w.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(ub,{selectedAccountId:e,onSelect:t}),n.jsx(Dr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Dr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Dr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(db,{value:h,onChange:g})]})},qa=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Dt(),{pushError:u}=Ve(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[v,p]=c.useState([]),[x,b]=c.useState(""),[w,j]=c.useState(!1),[y,I]=c.useState(!1),[N,k]=c.useState(t?.accountId),[C,M]=c.useState(!1),P=c.useRef(f);c.useEffect(()=>{P.current!==f&&(P.current=f,f&&(m([]),g([]),p([]),b(""),j(!1),I(!1),E(Kc),M(!1)))},[f]);const{signature:D}=Kf(N),[O,E]=c.useState(()=>bb(D.plainText)),{data:S}=ue({...uf({path:{outboxMessageId:f??""}}),enabled:!!f&&!C});c.useEffect(()=>{!S||C||(m(S.toAddresses.map(G=>({email:G,displayName:void 0}))),S.ccAddresses&&S.ccAddresses.length>0&&(g(S.ccAddresses.map(G=>({email:G,displayName:void 0}))),j(!0)),S.bccAddresses&&S.bccAddresses.length>0&&(p(S.bccAddresses.map(G=>({email:G,displayName:void 0}))),I(!0)),S.subject&&b(S.subject),S.textBody&&E([{type:"p",children:[{text:S.textBody}]}]),k(S.accountId),M(!0))},[S,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:G,cc:ae}=wb(s,e,t?.email);m(G),g(ae),ae.length>0&&j(!0),b(vb(s.envelope.subject))}e==="forward"&&b(yb(s.envelope.subject))}},[e,s,t?.email]);const A=e==="reply"||e==="reply_all"||e==="forward",{data:L}=$c({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:A&&!!s}),T=L?.kind==="text"?L.body:"",F=L?.kind==="html"?hb(L.body):void 0,R=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:B,saveDraft:K,cancelAutoSave:J}=rb({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{B&&u({title:"Couldn't save draft",detail:st(B)??"Saving the draft failed.",error:B})},[B,u]);const ee=ve(tl()),X=ve(nl()),me=ve({...qn(),onError:G=>{u(Vt("Couldn't discard draft","The draft wasn't discarded.",G))}}),{data:ce}=ue({...xt(),staleTime:1/0}),te=ce?.accounts.find(G=>G.accountId===N),U=te?zf(te):!1,q=ee.isPending||X.isPending,re=d.length>0&&!!N&&!U;c.useEffect(()=>{if(!N||f&&!C||Sb(d,h,v,x,O))return;const G=Zr(O),ae=bi(O);K({accountId:N,toAddresses:d.map(le=>le.email),ccAddresses:h.length>0?h.map(le=>le.email):void 0,bccAddresses:v.length>0?v.map(le=>le.email):void 0,subject:x||void 0,textBody:G||void 0,htmlBody:ae||void 0})},[N,f,C,d,h,v,x,O,K]);const Ie=c.useCallback(async()=>{if(!N||d.length===0)return;J();const G=s&&(e==="reply"||e==="reply_all")?jb(s):{};let ae=f,le=!1;if(!ae){const Fe=Zr(O),pe=bi(O),ge=await ee.mutateAsync({body:{accountId:N,toAddresses:d.map(Se=>Se.email),ccAddresses:h.length>0?h.map(Se=>Se.email):void 0,bccAddresses:v.length>0?v.map(Se=>Se.email):void 0,subject:x||void 0,textBody:Fe||void 0,htmlBody:pe||void 0,sendImmediately:!0,...G}}).catch(Se=>(u({title:"Couldn't send message",detail:st(Se)??"Saving the draft failed.",error:Se}),null));if(ge===null)return;ae=ge.outboxMessageId,le=!0,i(ae)}await X.mutateAsync({path:{outboxMessageId:ae}}).catch(Fe=>(u({title:"Couldn't send message",detail:st(Fe)??(le?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:Fe}),null))!==null&&(l(ae),r())},[N,d,h,v,x,O,e,s,f,ee,X,J,l,i,u,r]),je=c.useCallback(()=>{J(),f&&me.mutate({path:{outboxMessageId:f}}),r()},[J,f,me,r]),V=c.useCallback(G=>{k(G.accountId),a?.(G)},[a]);return n.jsx(rp,{banner:te&&U?n.jsx(lb,{accountId:te.accountId}):void 0,header:n.jsx(kb,{selectedAccountId:N,onAccountChange:V,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:v,setBccAddresses:p,showCc:w,setShowCc:j,showBcc:y,setShowBcc:I,subject:x,setSubject:b}),quoted:T||F?n.jsx(Np,{text:T,html:F,senderName:R}):void 0,actionBar:n.jsx(np,{onSend:Ie,onDiscard:je,sending:q,canSend:re,saveStatus:$,unavailableReason:U?"SMTP not configured":void 0,onUnavailable:G=>u({title:"Can't send yet",detail:G})}),children:n.jsx(c.Suspense,{fallback:n.jsx(gb,{}),children:n.jsx(pb,{value:O,onChange:E,onSubmit:Ie,autoFocus:e==="new"})})})},wi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(qa,{mode:e,account:t,sourceMessage:s,onClose:r})}),Uc=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),Ha=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},qc=e=>{const{data:t,isLoading:s}=ue({...xt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=Ft({queries:r.map(l=>({..._e({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},Cb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Nb=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Hc=(e,t)=>e===void 0?e:Cb(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Nb(e)?{...e,items:t(e.items)}:e,vt=e=>{const t=[];for(const s of new Set(e))t.push(wa({path:{mailboxId:s}})),t.push(rl({path:{mailboxId:s}}));return t.push(al()),t},rn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),an=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),on=(e,t,s)=>{const r=a=>Hc(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},ln=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},yt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Eb=3e3,Ib=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},sr=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},Ln=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),Tb=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),Rb=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=ye(),{pushError:i}=Ve(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=ve({...Hn(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),v=h.body.isRead??!0,p=Zt({path:{threadId:s}}),x=vt(sr(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),rn(o,x)]);const b=o.getQueriesData({queryKey:p}).filter(j=>j[1]!==void 0).map(([j,y])=>({queryKey:j,data:y})),w=an(o,x);return o.setQueriesData({queryKey:p},j=>j&&{...j,items:Ln(j.items,g,v)}),on(o,x,j=>Ln(j,g,v)),{threadMessagesPrefix:p,listPrefixes:x,previousThreadMessages:b,previousThreadsList:w}},onSuccess:(h,g)=>{const v=g.body.messageIds??[];for(const p of v)l.current.add(p),u.current.delete(p)},onError:(h,g,v)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(v){for(const b of v.previousThreadMessages)o.setQueryData(b.queryKey,b.data);ln(o,v.previousThreadsList)}const x=g.body.isRead??!0;i({title:x?"Couldn't mark as read":"Couldn't mark as unread",detail:st(h),error:h})},onSettled:(h,g,v,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),yt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Jt({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(v=>!l.current.has(v)&&!u.current.has(v));if(g.length!==0){for(const v of g)u.current.add(v);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>Tb(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Ib(m,Eb,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},nr=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...Hn(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:st(f),error:f})},onSettled:(f,d,m)=>{yt(a,vt(sr(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,isRead:d}})},[i]),isPending:l}},Mb=60,Ab=1.5,Db=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*Ab?{direction:null}:{direction:e<0?"left":"right"}},Ob=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Mb})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=Db(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},Pb=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,ji=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),Wa=({threadId:e,mailboxId:t,messages:s})=>{const r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i,variables:l}=ve({...ff(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=Zt({path:{threadId:e}}),g=vt([Pb(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),rn(r,g)]);const v=r.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})),p=an(r,g);return r.setQueriesData({queryKey:h},x=>Hc(x,b=>ji(b,d,m))),on(r,g,x=>ji(x,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);ln(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function rr(e){return e===void 0?"uncategorized":e}const Lb={inbox:"Inbox",junk:"Junk"},Va=e=>e.destinationMailboxId!==void 0,$b=(e,t)=>{if(Va(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Lb[s]??"another folder"} by Remit`},Fb=(e,t)=>{if(e===jo.MoveToInbox)return t.inboxMailboxId;if(e===jo.MoveToJunk)return t.junkMailboxId},_b=(e,t,s)=>{if(!e||!t)return!1;const r=Va(e)?e.destinationMailboxId:Fb(e.action,s);return r!==void 0&&r===t},zb=(e,t)=>{if(e){if(Va(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},ar=(e,t)=>{const{data:s,isLoading:r}=ue({...xt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Bb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Kb=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},Qa=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},or=e=>{const{mailboxId:t,isLoading:s}=ar(e,"Junk");return{junkMailboxId:t,isLoading:s}},Wc=e=>{const{data:t}=ue({...xt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Si=(e,t)=>e.filter(s=>!t.has(s.messageId)),Qt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=ye(),{pushError:o}=Ve(),{mutate:i,isPending:l}=ve({...mf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?Zt({path:{threadId:t}}):[],h=vt([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],rn(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,x])=>({queryKey:p,data:x})):[],v=an(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Si(p.items,d)}),on(a,h,p=>Si(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:v}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);ln(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:st(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),yt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&i({body:{messageIds:f,destinationMailboxId:d}})},[i]),isPending:l}},Ub=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=Qa(e),{junkMailboxId:i}=or(e),{moveMessages:l,isPending:u}=Qt({mailboxId:r,threadId:s,accountId:e}),{data:f}=ue({..._e({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=_b(a,r,d),h=zb(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const v=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Wn(p.fullPath))[0]:void 0;return{show:!0,label:$b(a,v),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Vc({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a,size:o="sm"}){const i=Ub({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return i.show?n.jsx(tp,{label:i.label,size:o,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:o==="md"?i.filtersHref:void 0}):null}const ki=(e,t)=>e.filter(s=>!t.has(s.messageId)),qb=e=>e.filter(t=>t.isDeleted!==!0),Yt=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=ye(),{pushError:i}=Ve(),{mutate:l,isPending:u}=ve({...hf(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],g=vt(sr(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),rn(o,g)]);const v=t?o.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,b])=>({queryKey:x,data:b})):[],p=an(o,g);return t&&o.setQueriesData({queryKey:h},x=>x&&{...x,items:ki(x.items,m)}),on(o,g,x=>ki(x,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:v,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const v of h.previousThreadMessages)o.setQueryData(v.queryKey,v.data);ln(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:st(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),yt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:Jt({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&l({body:{messageIds:d}})},[l]),isPending:u}},Qc=(e,t=Date.now())=>({value:e,setAt:t}),Hb=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Qc(!0,r):delete a.trusted,{...e,flags:a}},Wb=(e,t,s,r)=>{const a=o=>o.map(i=>Hb(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ya=({messageId:e})=>{const t=ye(),{pushError:s}=Ve(),{mutate:r,isPending:a,error:o,reset:i}=ve({...ol(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=el({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,p])=>({queryKey:v,data:p}));return t.setQueriesData({queryKey:h},v=>v&&Wb(v,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Vt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Qc(!f)}}})},isPending:a,error:o,reset:i}};var ir="Dialog",[Yc]=sg(ir),[Vb,at]=Yc(ir),Gc=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=ag({prop:r,defaultProp:a??!1,onChange:o,caller:ir});return n.jsx(Vb,{scope:t,triggerRef:l,contentRef:u,contentId:Ir(),titleId:Ir(),descriptionId:Ir(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Gc.displayName=ir;var Xc="DialogTrigger",Qb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(Xc,s),o=es(t,a.triggerRef);return n.jsx(bt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Xa(a.open),...r,ref:o,onClick:Tt(e.onClick,a.onOpenToggle)})});Qb.displayName=Xc;var Ga="DialogPortal",[Yb,Jc]=Yc(Ga,{forceMount:void 0}),Zc=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=at(Ga,t);return n.jsx(Yb,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(Jn,{present:s||o.open,children:n.jsx(hc,{asChild:!0,container:a,children:i})}))})};Zc.displayName=Ga;var $n="DialogOverlay",eu=c.forwardRef((e,t)=>{const s=Jc($n,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at($n,e.__scopeDialog);return o.modal?n.jsx(Jn,{present:r||o.open,children:n.jsx(Xb,{...a,ref:t})}):null});eu.displayName=$n;var Gb=_a("DialogOverlay.RemoveScroll"),Xb=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at($n,s),o=kg(),i=es(t,o);return n.jsx(jc,{as:Gb,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(bt.div,{"data-state":Xa(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),js="DialogContent",tu=c.forwardRef((e,t)=>{const s=Jc(js,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=at(js,e.__scopeDialog);return n.jsx(Jn,{present:r||o.open,children:o.modal?n.jsx(Jb,{...a,ref:t}):n.jsx(Zb,{...a,ref:t})})});tu.displayName=js;var Jb=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(null),a=es(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Wg(o)},[]),n.jsx(su,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Tt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Tt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Tt(e.onFocusOutside,o=>o.preventDefault())})}),Zb=c.forwardRef((e,t)=>{const s=at(js,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(su,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),su=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=at(js,s);return Ig(),n.jsx(n.Fragment,{children:n.jsx(fc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(uc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Xa(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),nu="DialogTitle",ru=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(nu,s);return n.jsx(bt.h2,{id:a.titleId,...r,ref:t})});ru.displayName=nu;var au="DialogDescription",ev=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(au,s);return n.jsx(bt.p,{id:a.descriptionId,...r,ref:t})});ev.displayName=au;var ou="DialogClose",tv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=at(ou,s);return n.jsx(bt.button,{type:"button",...r,ref:t,onClick:Tt(e.onClick,()=>a.onOpenChange(!1))})});tv.displayName=ou;function Xa(e){return e?"open":"closed"}function sv(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const iu=H.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),cn=()=>{const e=H.useContext(iu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};sv(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
117
117
  [data-state=closed]
118
118
  ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function nv(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function rv(){return Ja(/^Mac/)}function av(){return Ja(/^iPhone/)}function Ci(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function ov(){return Ja(/^iPad/)||rv()&&navigator.maxTouchPoints>1}function lu(){return av()||ov()}function Ja(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const iv=24,lv=typeof window<"u"?c.useLayoutEffect:c.useEffect;function Ni(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Or=typeof document<"u"&&window.visualViewport;function Ei(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function cu(e){for(Ei(e)&&(e=e.parentElement);e&&!Ei(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const cv=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Cn=0,Pr;function uv(e={}){let{isDisabled:t}=e;lv(()=>{if(!t)return Cn++,Cn===1&&lu()&&(Pr=dv()),()=>{Cn--,Cn===0&&Pr?.()}},[t])}function dv(){let e,t=0,s=m=>{e=cu(m.target),!(e===document.documentElement&&e===document.body)&&(t=m.changedTouches[0].pageY)},r=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let h=m.changedTouches[0].pageY,g=e.scrollTop,v=e.scrollHeight-e.clientHeight;v!==0&&((g<=0&&h>t||g>=v&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;ea(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;ea(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Or&&(Or.height<window.innerHeight?requestAnimationFrame(()=>{Ii(h)}):Or.addEventListener("resize",()=>Ii(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=Ni(fv(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ni(Ps(document,"touchstart",s,{passive:!1,capture:!0}),Ps(document,"touchmove",r,{passive:!1,capture:!0}),Ps(document,"touchend",a,{passive:!1,capture:!0}),Ps(document,"focus",o,!0),Ps(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function fv(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function Ps(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function Ii(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=cu(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let r=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+iv;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function ea(e){return e instanceof HTMLInputElement&&!cv.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function mv(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function hv(...e){return t=>e.forEach(s=>mv(s,t))}function uu(...e){return c.useCallback(hv(...e),e)}const du=new WeakMap;function Ee(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let r={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}r[a]=e.style[a],e.style[a]=o}),!s&&du.set(e,r)}function pv(e,t){if(!e||!(e instanceof HTMLElement))return;let s=du.get(e);s&&(e.style[t]=s[t])}const ke=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Nn(e,t){if(!e)return null;const s=window.getComputedStyle(e),r=s.transform||s.webkitTransform||s.mozTransform;let a=r.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[ke(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[ke(t)?5:4]):null)}function gv(e){return 8*(Math.log(e+1)-2)}function Lr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function xv(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const xe={DURATION:.5,EASE:[.32,.72,0,1]},fu=.4,bv=.25,vv=100,mu=8,qt=16,ta=26,$r="vaul-dragging";function hu(e){const t=H.useRef(e);return H.useEffect(()=>{t.current=e}),H.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function yv({defaultProp:e,onChange:t}){const s=H.useState(e),[r]=s,a=H.useRef(r),o=hu(t);return H.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function pu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=yv({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=hu(s),u=H.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else a(f)},[o,e,a,l]);return[i,u]}function wv({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=pu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=H.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);H.useEffect(()=>{function k(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const v=H.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=H.useMemo(()=>{var k;return(k=s?.findIndex(C=>C===d))!=null?k:null},[s,d]),x=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,b=H.useMemo(()=>{const k=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var C;return(C=s?.map(M=>{const P=typeof M=="string";let D=0;if(P&&(D=parseInt(M,10)),ke(l)){const E=P?D:h?M*k.height:0;return h?l==="bottom"?k.height-E:-k.height+E:E}const O=P?D:h?M*k.width:0;return h?l==="right"?k.width-O:-k.width+O:O}))!=null?C:[]},[s,h,u]),w=H.useMemo(()=>p!==null?b?.[p]:null,[b,p]),j=H.useCallback(k=>{var C;const M=(C=b?.findIndex(P=>P===k))!=null?C:null;i(M),Ee(r.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(l)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`}),b&&M!==b.length-1&&o!==void 0&&M!==o&&M<o?Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"0"}):Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(M,0)])},[r.current,s,b,o,a,m]);H.useEffect(()=>{if(d||e){var k;const C=(k=s?.findIndex(M=>M===e||M===d))!=null?k:-1;b&&C!==-1&&typeof b[C]=="number"&&j(b[C])}},[d,e,s,b,j]);function y({draggedDistance:k,closeDrawer:C,velocity:M,dismissible:P}){if(o===void 0)return;const D=l==="bottom"||l==="right"?(w??0)-k:(w??0)+k,O=p===o-1,E=p===0,S=k>0;if(O&&Ee(a.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),!f&&M>2&&!S){P?C():j(b[0]);return}if(!f&&M>2&&S&&b&&s){j(b[s.length-1]);return}const A=b?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-D)<Math.abs(T-D)?F:T),L=ke(l)?window.innerHeight:window.innerWidth;if(M>fu&&Math.abs(k)<L*.4){const T=S?1:-1;if(T>0&&v&&s){j(b[s.length-1]);return}if(E&&T<0&&P&&C(),p===null)return;j(b[p+T]);return}j(A)}function I({draggedDistance:k}){if(w===null)return;const C=l==="bottom"||l==="right"?w-k:w+k;(l==="bottom"||l==="right")&&C<b[b.length-1]||(l==="top"||l==="left")&&C>b[b.length-1]||Ee(r.current,{transform:ke(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`})}function N(k,C){if(!s||typeof p!="number"||!b||o===void 0)return null;const M=p===o-1;if(p>=o&&C)return 0;if(M&&!C)return 1;if(!x&&!M)return null;const D=M?p+1:p-1,O=M?b[D]-b[D-1]:b[D+1]-b[D],E=k/Math.abs(O);return M?1-E:E}return{isLastSnapPoint:v,activeSnapPoint:d,shouldFade:x,getPercentageDragged:N,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:y,onDrag:I,snapPointsOffset:b}}const jv=()=>()=>{};function Sv(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=cn(),o=H.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ta)/window.innerWidth}H.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;xv(r&&!a?Lr(document.body,{background:"black"}):jv,Lr(u,{transformOrigin:ke(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`}));const f=Lr(u,{borderRadius:`${mu}px`,overflow:"hidden",...ke(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{f(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},xe.DURATION*1e3)}}},[t,s,i])}let Ls=null;function kv({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=H.useState(()=>typeof window<"u"?window.location.href:""),u=H.useRef(0),f=H.useCallback(()=>{if(Ci()&&Ls===null&&e&&!o){Ls={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=H.useCallback(()=>{if(Ci()&&Ls!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ls),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Ls=null}},[i]);return H.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),H.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),H.useEffect(()=>{s||!r||(e?(!window.matchMedia("(display-mode: standalone)").matches&&f(),t||window.setTimeout(()=>{d()},500)):d())},[e,r,i,t,s,f,d]),{restorePositionSetting:d}}function Cv({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=bv,scrollLockTimeout:f=vv,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:v,fixed:p,modal:x=!0,onClose:b,nested:w,noBodyStyles:j=!1,direction:y="bottom",defaultOpen:I=!1,disablePreventScroll:N=!0,snapToSequentialPoint:k=!1,preventScrollRestoration:C=!1,repositionInputs:M=!0,onAnimationEnd:P,container:D,autoFocus:O=!1}){var E,S;const[A=!1,L]=pu({defaultProp:I,prop:e,onChange:Z=>{t?.(Z),!Z&&!w&&Be(),setTimeout(()=>{P?.(Z)},xe.DURATION*1e3),Z&&!x&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Z||(document.body.style.pointerEvents="auto")}}),[T,F]=H.useState(!1),[R,$]=H.useState(!1),[B,K]=H.useState(!1),J=H.useRef(null),ee=H.useRef(null),X=H.useRef(null),me=H.useRef(null),ce=H.useRef(null),te=H.useRef(!1),U=H.useRef(null),q=H.useRef(0),re=H.useRef(!1),Ie=H.useRef(!I),je=H.useRef(0),V=H.useRef(null),G=H.useRef(((E=V.current)==null?void 0:E.getBoundingClientRect().height)||0),ae=H.useRef(((S=V.current)==null?void 0:S.getBoundingClientRect().width)||0),le=H.useRef(0),z=H.useCallback(Z=>{o&&Z===Qe.length-1&&(ee.current=new Date)},[]),{activeSnapPoint:Fe,activeSnapPointIndex:pe,setActiveSnapPoint:ge,onRelease:Se,snapPointsOffset:Qe,onDrag:ts,shouldFade:ze,getPercentageDragged:Ze}=wv({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:v,drawerRef:V,fadeFromIndex:h,overlayRef:J,onSnapPointChange:z,direction:y,container:D,snapToSequentialPoint:k});uv({isDisabled:!A||R||!x||B||!T||!M||!N});const{restorePositionSetting:Be}=kv({isOpen:A,modal:x,nested:w??!1,hasBeenOpened:T,preventScrollRestoration:C,noBodyStyles:j});function Ke(){return(window.innerWidth-ta)/window.innerWidth}function ft(Z){var ie,ne;!d&&!o||V.current&&!V.current.contains(Z.target)||(G.current=((ie=V.current)==null?void 0:ie.getBoundingClientRect().height)||0,ae.current=((ne=V.current)==null?void 0:ne.getBoundingClientRect().width)||0,$(!0),X.current=new Date,lu()&&window.addEventListener("touchend",()=>te.current=!1,{once:!0}),Z.target.setPointerCapture(Z.pointerId),q.current=ke(y)?Z.pageY:Z.pageX)}function Te(Z,ie){var ne;let oe=Z;const he=(ne=window.getSelection())==null?void 0:ne.toString(),fe=V.current?Nn(V.current,y):null,we=new Date;if(oe.tagName==="SELECT"||oe.hasAttribute("data-vaul-no-drag")||oe.closest("[data-vaul-no-drag]"))return!1;if(y==="right"||y==="left")return!0;if(ee.current&&we.getTime()-ee.current.getTime()<500)return!1;if(fe!==null&&(y==="bottom"?fe>0:fe<0))return!0;if(he&&he.length>0)return!1;if(ce.current&&we.getTime()-ce.current.getTime()<f&&fe===0||ie)return ce.current=we,!1;for(;oe;){if(oe.scrollHeight>oe.clientHeight){if(oe.scrollTop!==0)return ce.current=new Date,!1;if(oe.getAttribute("role")==="dialog")return!0}oe=oe.parentNode}return!0}function ss(Z){if(V.current&&R){const ie=y==="bottom"||y==="right"?1:-1,ne=(q.current-(ke(y)?Z.pageY:Z.pageX))*ie,oe=ne>0,he=o&&!d&&!oe;if(he&&pe===0)return;const fe=Math.abs(ne),we=document.querySelector("[data-vaul-drawer-wrapper]"),Pe=y==="bottom"||y==="top"?G.current:ae.current;let Ae=fe/Pe;const He=Ze(fe,oe);if(He!==null&&(Ae=He),he&&Ae>=1||!te.current&&!Te(Z.target,oe))return;if(V.current.classList.add($r),te.current=!0,Ee(V.current,{transition:"none"}),Ee(J.current,{transition:"none"}),o&&ts({draggedDistance:ne}),oe&&!o){const Re=gv(ne),Ye=Math.min(Re*-1,0)*ie;Ee(V.current,{transform:ke(y)?`translate3d(0, ${Ye}px, 0)`:`translate3d(${Ye}px, 0, 0)`});return}const De=1-Ae;if((ze||h&&pe===h-1)&&(r?.(Z,Ae),Ee(J.current,{opacity:`${De}`,transition:"none"},!0)),we&&J.current&&i){const Re=Math.min(Ke()+Ae*(1-Ke()),1),Ye=8-Ae*8,Ge=Math.max(0,14-Ae*14);Ee(we,{borderRadius:`${Ye}px`,transform:ke(y)?`scale(${Re}) translate3d(0, ${Ge}px, 0)`:`scale(${Re}) translate3d(${Ge}px, 0, 0)`,transition:"none"},!0)}if(!o){const Re=fe*ie;Ee(V.current,{transform:ke(y)?`translate3d(0, ${Re}px, 0)`:`translate3d(${Re}px, 0, 0)`})}}}H.useEffect(()=>{window.requestAnimationFrame(()=>{Ie.current=!0})},[]),H.useEffect(()=>{var Z;function ie(){if(!V.current||!M)return;const ne=document.activeElement;if(ea(ne)||re.current){var oe;const he=((oe=window.visualViewport)==null?void 0:oe.height)||0,fe=window.innerHeight;let we=fe-he;const Pe=V.current.getBoundingClientRect().height||0,Ae=Pe>fe*.8;le.current||(le.current=Pe);const He=V.current.getBoundingClientRect().top;if(Math.abs(je.current-we)>60&&(re.current=!re.current),o&&o.length>0&&Qe&&pe){const De=Qe[pe]||0;we+=De}if(je.current=we,Pe>he||re.current){const De=V.current.getBoundingClientRect().height;let Re=De;De>he&&(Re=he-(Ae?He:ta)),p?V.current.style.height=`${De-Math.max(we,0)}px`:V.current.style.height=`${Math.max(Re,he-He)}px`}else nv()||(V.current.style.height=`${le.current}px`);o&&o.length>0&&!re.current?V.current.style.bottom="0px":V.current.style.bottom=`${Math.max(we,0)}px`}}return(Z=window.visualViewport)==null||Z.addEventListener("resize",ie),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",ie)}},[pe,o,Qe]);function Ue(Z){Ne(),b?.(),Z||L(!1),setTimeout(()=>{o&&ge(o[0])},xe.DURATION*1e3)}function _t(){if(!V.current)return;const Z=document.querySelector("[data-vaul-drawer-wrapper]"),ie=Nn(V.current,y);Ee(V.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`}),Ee(J.current,{transition:`opacity ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,opacity:"1"}),i&&ie&&ie>0&&A&&Ee(Z,{borderRadius:`${mu}px`,overflow:"hidden",...ke(y)?{transform:`scale(${Ke()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Ke()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${xe.DURATION}s`,transitionTimingFunction:`cubic-bezier(${xe.EASE.join(",")})`},!0)}function Ne(){!R||!V.current||(V.current.classList.remove($r),te.current=!1,$(!1),me.current=new Date)}function qe(Z){if(!R||!V.current)return;V.current.classList.remove($r),te.current=!1,$(!1),me.current=new Date;const ie=Nn(V.current,y);if(!Z||!Te(Z.target,!1)||!ie||Number.isNaN(ie)||X.current===null)return;const ne=me.current.getTime()-X.current.getTime(),oe=q.current-(ke(y)?Z.pageY:Z.pageX),he=Math.abs(oe)/ne;if(he>.05&&(K(!0),setTimeout(()=>{K(!1)},200)),o){Se({draggedDistance:oe*(y==="bottom"||y==="right"?1:-1),closeDrawer:Ue,velocity:he,dismissible:d}),a?.(Z,!0);return}if(y==="bottom"||y==="right"?oe>0:oe<0){_t(),a?.(Z,!0);return}if(he>fu){Ue(),a?.(Z,!1);return}var fe;const we=Math.min((fe=V.current.getBoundingClientRect().height)!=null?fe:0,window.innerHeight);var Pe;const Ae=Math.min((Pe=V.current.getBoundingClientRect().width)!=null?Pe:0,window.innerWidth),He=y==="left"||y==="right";if(Math.abs(ie)>=(He?Ae:we)*u){Ue(),a?.(Z,!1);return}a?.(Z,!0),_t()}H.useEffect(()=>(A&&(Ee(document.documentElement,{scrollBehavior:"auto"}),ee.current=new Date),()=>{pv(document.documentElement,"scrollBehavior")}),[A]);function mt(Z){const ie=Z?(window.innerWidth-qt)/window.innerWidth:1,ne=Z?-qt:0;U.current&&window.clearTimeout(U.current),Ee(V.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${ie}) translate3d(0, ${ne}px, 0)`:`scale(${ie}) translate3d(${ne}px, 0, 0)`}),!Z&&V.current&&(U.current=setTimeout(()=>{const oe=Nn(V.current,y);Ee(V.current,{transition:"none",transform:ke(y)?`translate3d(0, ${oe}px, 0)`:`translate3d(${oe}px, 0, 0)`})},500))}function ns(Z,ie){if(ie<0)return;const ne=(window.innerWidth-qt)/window.innerWidth,oe=ne+ie*(1-ne),he=-qt+ie*qt;Ee(V.current,{transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`,transition:"none"})}function zt(Z,ie){const ne=ke(y)?window.innerHeight:window.innerWidth,oe=ie?(ne-qt)/ne:1,he=ie?-qt:0;ie&&Ee(V.current,{transition:`transform ${xe.DURATION}s cubic-bezier(${xe.EASE.join(",")})`,transform:ke(y)?`scale(${oe}) translate3d(0, ${he}px, 0)`:`scale(${oe}) translate3d(${he}px, 0, 0)`})}return H.useEffect(()=>{x||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[x]),H.createElement(Gc,{defaultOpen:I,onOpenChange:Z=>{!d&&!Z||(Z?F(!0):Ue(!0),L(Z))},open:A},H.createElement(iu.Provider,{value:{activeSnapPoint:Fe,snapPoints:o,setActiveSnapPoint:ge,drawerRef:V,overlayRef:J,onOpenChange:t,onPress:ft,onRelease:qe,onDrag:ss,dismissible:d,shouldAnimate:Ie,handleOnly:m,isOpen:A,isDragging:R,shouldFade:ze,closeDrawer:Ue,onNestedDrag:ns,onNestedOpenChange:mt,onNestedRelease:zt,keyboardIsOpen:re,modal:x,snapPointsOffset:Qe,activeSnapPointIndex:pe,direction:y,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:j,container:D,autoFocus:O}},s))}const gu=H.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=cn(),f=uu(t,s),d=r&&r.length>0;if(!l)return null;const m=H.useCallback(h=>a(h),[a]);return H.createElement(eu,{onMouseUp:m,ref:f,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});gu.displayName="Drawer.Overlay";const xu=H.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...r},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:f,snapPointsOffset:d,activeSnapPointIndex:m,modal:h,isOpen:g,direction:v,snapPoints:p,container:x,handleOnly:b,shouldAnimate:w,autoFocus:j}=cn(),[y,I]=H.useState(!1),N=uu(a,o),k=H.useRef(null),C=H.useRef(null),M=H.useRef(!1),P=p&&p.length>0;Sv();const D=(E,S,A=0)=>{if(M.current)return!0;const L=Math.abs(E.y),T=Math.abs(E.x),F=T>L,R=["bottom","right"].includes(S)?1:-1;if(S==="left"||S==="right"){if(!(E.x*R<0)&&T>=0&&T<=A)return F}else if(!(E.y*R<0)&&L>=0&&L<=A)return!F;return M.current=!0,!0};H.useEffect(()=>{P&&window.requestAnimationFrame(()=>{I(!0)})},[]);function O(E){k.current=null,M.current=!1,l(E)}return H.createElement(tu,{"data-vaul-drawer-direction":v,"data-vaul-drawer":"","data-vaul-delayed-snap-points":y?"true":"false","data-vaul-snap-points":g&&P?"true":"false","data-vaul-custom-container":x?"true":"false","data-vaul-animate":w?.current?"true":"false",...r,ref:N,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:E=>{b||(r.onPointerDown==null||r.onPointerDown.call(r,E),k.current={x:E.pageX,y:E.pageY},i(E))},onOpenAutoFocus:E=>{s?.(E),j||E.preventDefault()},onPointerDownOutside:E=>{if(e?.(E),!h||E.defaultPrevented){E.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:E=>{if(!h){E.preventDefault();return}},onPointerMove:E=>{if(C.current=E,b||(r.onPointerMove==null||r.onPointerMove.call(r,E),!k.current))return;const S=E.pageY-k.current.y,A=E.pageX-k.current.x,L=E.pointerType==="touch"?10:2;D({x:A,y:S},v,L)?u(E):(Math.abs(A)>L||Math.abs(S)>L)&&(k.current=null)},onPointerUp:E=>{r.onPointerUp==null||r.onPointerUp.call(r,E),k.current=null,M.current=!1,l(E)},onPointerOut:E=>{r.onPointerOut==null||r.onPointerOut.call(r,E),O(C.current)},onContextMenu:E=>{r.onContextMenu==null||r.onContextMenu.call(r,E),C.current&&O(C.current)}})});xu.displayName="Drawer.Content";const Nv=250,Ev=120,bu=H.forwardRef(function({preventCycle:e=!1,children:t,...s},r){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:f,handleOnly:d,isOpen:m,onPress:h,onDrag:g}=cn(),v=H.useRef(null),p=H.useRef(!1);function x(){if(p.current){j();return}window.setTimeout(()=>{b()},Ev)}function b(){if(o||e||p.current){j();return}if(j(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const I=i.findIndex(k=>k===l);if(I===-1)return;const N=i[I+1];u(N)}function w(){v.current=window.setTimeout(()=>{p.current=!0},Nv)}function j(){v.current&&window.clearTimeout(v.current),p.current=!1}return H.createElement("div",{onClick:x,onPointerCancel:j,onPointerDown:y=>{d&&h(y),w()},onPointerMove:y=>{d&&g(y)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},H.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});bu.displayName="Drawer.Handle";function Iv(e){const t=cn(),{container:s=t.container,...r}=e;return H.createElement(Zc,{container:s,...r})}const Je={Root:Cv,Content:xu,Overlay:gu,Portal:Iv,Handle:bu,Title:ru},vu="inline-flex items-center justify-center transition-colors",Tv=be(vu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Rv=be(vu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),un=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=Ot(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:g}=Kn("mail",{useSuspense:!1}),v=c.useCallback((O,E)=>g(O,{defaultValue:E}),[g]),{data:p,isLoading:x,isError:b,error:w,refetch:j}=ue({..._e({path:{accountId:e}}),staleTime:1/0,enabled:l}),y=Wc(e),{createFolder:I}=jl(e),N=c.useMemo(()=>{const O=Zs(p?.items??[],y),E=Xs(y);return O.map(S=>({id:S.mailboxId,label:bs(S,E.get(S.mailboxId),v),searchValue:S.fullPath,isCurrent:S.mailboxId===t}))},[p?.items,y,t,v]),k=c.useCallback(O=>{u(!1),s(O)},[s]),C=c.useCallback(async(O,E)=>{const S=await I(O,E);return{id:S.id,label:S.label}},[I]);c.useEffect(()=>{if(!l||!f)return;const O=S=>{d.current&&!d.current.contains(S.target)&&u(!1)},E=S=>{S.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",O),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",E)}},[l,f]);const M=r||!!a,P=n.jsxs("button",{type:"button",onClick:O=>{O.stopPropagation(),!M&&u(E=>!E)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Tv:Rv,children:[n.jsx(Ia,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),D=x?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):b?n.jsx("div",{className:"p-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>j()})}):n.jsx(Sl,{mailboxes:N,onSelect:k,onCreateFolder:C,onCancel:()=>u(!1),autoFocus:!f,labels:{createLabel:O=>`Create "${O}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:O=>`Move to ${O}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:O=>`No folders match "${O}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[P,l&&n.jsx("div",{id:h,className:be("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:D})]}):n.jsxs(n.Fragment,{children:[P,n.jsx(Je.Root,{open:l,onOpenChange:u,children:n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),n.jsx("div",{className:"flex-1 overflow-hidden",children:D})]})]})})]})},Mv=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=ye(),d=Oe(),{pushError:m}=Ve(),{selectedMessageId:h}=vs({strict:!1}),{mutate:g,isPending:v}=ve({...Hn(),onMutate:async A=>{const L=A.body.isRead??!0,T=new Set(A.body.messageIds??[]),F=Zt({path:{threadId:t}}),R=vt([s]);await Promise.all([f.cancelQueries({queryKey:F}),rn(f,R)]);const $=f.getQueriesData({queryKey:F}).filter(K=>K[1]!==void 0).map(([K,J])=>({queryKey:K,data:J})),B=an(f,R);return f.setQueriesData({queryKey:F},K=>K&&{...K,items:Ln(K.items,T,L)}),on(f,R,K=>Ln(K,T,L)),{threadMessagesPrefix:F,listPrefixes:R,previousThreadMessages:$,previousThreadsList:B}},onError:(A,L,T)=>{if(T){for(const R of T.previousThreadMessages)f.setQueryData(R.queryKey,R.data);ln(f,T.previousThreadsList)}const F=L.body.isRead??!0;m({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:st(A),error:A})},onSettled:(A,L,T,F)=>{F&&(f.invalidateQueries({queryKey:F.threadMessagesPrefix}),yt(f,F.listPrefixes))}}),p=c.useCallback(A=>{h&&A.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:L=>({...L,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:x,isPending:b}=Yt({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:w,isPending:j}=Qt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:y,isPending:I,error:N,reset:k}=Ya({messageId:e}),C=()=>{g({body:{messageIds:[e],isRead:!1}})},M=()=>{x([e])},P=()=>{o&&y(o,i)},D=v||b||j||I,O=D||!o,E=c.useCallback(A=>{w([e],A)},[w,e]),S=o?void 0:"Sender has no parseable address";return n.jsxs("div",{className:"flex flex-col items-end gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[a&&n.jsx(un,{accountId:a,currentMailboxId:s,onMove:E,disabled:D,label:"Move this message"}),n.jsxs(Cc,{trigger:n.jsx(_l,{className:"size-4"}),children:[n.jsxs(hs,{onClick:P,disabled:O,children:[i?n.jsx(Gn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4 opacity-0"}),n.jsx("span",{title:S,children:"Trusted sender"})]}),r&&n.jsxs(hs,{onClick:C,disabled:D,children:[n.jsx(Cs,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(hs,{onClick:u,children:[n.jsx(Fl,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(Xr,{}),n.jsxs(hs,{onClick:M,disabled:D,destructive:!0,children:[n.jsx(rt,{className:"size-4"}),"Delete"]})]})]}),N&&n.jsx("div",{className:"w-64",children:n.jsx(Pt,{variant:"inline",title:"Couldn't update trust",error:N,onRetry:()=>{k(),P()}})})]})},Av=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,r=new MutationObserver(()=>{t(s.classList.contains("dark"))});return r.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>r.disconnect()},[]),e},Dv=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:r,onAlwaysTrust:a})=>n.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:r,className:"text-accent hover:underline",children:"Load once"}),t&&n.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),Ov=(e,t)=>{switch(e){case"auth":return{title:"Your session expired",detail:"Sign in again to reload the message body. Other parts of the app may also stop responding until you do."};case"body-missing":return{title:"Message body is missing in storage",detail:"A sync failure may have left this message without its body bytes. Contact support, or run the reconcile script to refetch from the upstream IMAP server."};case"content-type-mismatch":return{title:"Couldn't load message body",detail:"The server returned an unexpected content type for this part. The message body has not been rendered to keep you safe."};case"spa-shell-leak":return{title:"Couldn't load message body",detail:"The server returned the app shell instead of the message body. This is an infrastructure bug — please report it."};case"not-ready":return{title:"Message body is still syncing",detail:"This message's body hasn't finished downloading from the mail server yet. It should appear shortly — reopen the message to try again."};default:return{title:"Couldn't load message body",detail:t}}},Pv=e=>e instanceof Ht?e.reason:"generic",Lv=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",$v=({error:e,onRetry:t})=>{const s=Pv(e),r=Lv(e),{title:a,detail:o}=Ov(s,r),[i,l]=c.useState(!1),{Account:u}=xa();return i?null:n.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[n.jsx(Gt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"font-medium text-danger",children:a}),n.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&n.jsx(u,{children:({signOut:f})=>n.jsx("button",{type:"button",onClick:()=>f(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&n.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),n.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:n.jsx(We,{className:"size-4","aria-hidden":"true"})})]})]})},Fv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),Ti=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),yu=({bodyParts:e,html:t,text:s,isTrusted:r=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,f]=c.useState(!1),d=r||u,m=Av(),{toggleTrusted:h,isPending:g}=Ya({messageId:a??""}),v=!!e&&e.length>0,{picked:p,data:x,isLoading:b,isError:w,error:j,refetch:y}=$c({messageId:a,bodyParts:e,enabled:v}),I=c.useMemo(()=>yh(e??[]),[e]),N=v&&x?.kind==="html"?x.body:t,k=v&&x?.kind==="text"?x.body:s;if(v){if(b)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Fv,{})});if(w)return n.jsx("div",{className:be("message-body",l),children:n.jsx($v,{error:j,onRetry:()=>y()})});if(!p)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})})}else if(!t&&!s)return n.jsx("div",{className:be("message-body",l),children:n.jsx(Ti,{})});const C=!!(o&&a),M=()=>{!o||g||(f(!0),h(o,!1))};return n.jsx(sc,{className:l,html:N,text:k,isDark:m,category:i,allowImages:d,resolveCid:I,renderBlockedNotice:P=>n.jsx(Dv,{blockedImageCount:P,canAlwaysTrust:C,isTrustPending:g,onLoadOnce:()=>f(!0),onAlwaysTrust:M})})},_v=({messageId:e,threadId:t,mailboxId:s,accountId:r,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:f,onToggleRaw:d,onReply:m,onReplyAll:h,onForward:g})=>{const v=ye(),{deleteMessages:p}=Yt({mailboxId:s,threadId:t}),{moveMessages:x}=Qt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:b}=Ya({messageId:e}),{mutate:w}=ve({...Hn(),onSettled:()=>{v.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),yt(v,vt([s]))}}),j=c.useCallback(k=>{x([e],k)},[x,e]),y=c.useCallback(()=>{p([e])},[p,e]),I=c.useCallback(()=>{w({body:{messageIds:[e],isRead:!a}})},[w,e,a]),N=[];return l&&N.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(Gn,{className:"size-4 text-positive"}):n.jsx(Ys,{className:"size-4"}),onSelect:()=>b(l,u)}),d&&N.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(Fl,{className:"size-4"}),onSelect:d}),n.jsx(tc,{hasThread:!0,onReply:m,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:y,isRead:a,onToggleRead:I,overflowItems:N,moveSlot:r?n.jsx(un,{accountId:r,currentMailboxId:s,onMove:j,label:"Move this message"}):void 0})},zv=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Bv=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=ue({...pf({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(zv,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?n.jsx("div",{className:"message-body",children:n.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):n.jsx("div",{className:"message-body",children:n.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Kv=()=>n.jsx(Gn,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),wu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),ju=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:be("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":be("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(At,{className:be("size-3.5",e&&"fill-current")})}),Uv=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=yl(e.sentDate,"datetime"),i=wu(e,o);return n.jsx(nc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(Xn,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(ju,{isStarred:e.hasStars,onToggleStar:r,isStarPending:a,hoverReveal:!0}),n.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},qv=({threadMessage:e,messageData:t,isLoading:s,isError:r,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:f,accountId:d,showRaw:m,onToggleRaw:h,mobile:g,onReply:v,onReplyAll:p,onForward:x})=>{const b=yl(e.sentDate,"long"),w=!e.isRead,j=t?.envelope.from[0]?.flags?.trusted?.value===!0,y=t?.envelope.from[0]?.addressId,I=wu(e,b),N=e.autoMoved?n.jsx(Vc,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"md"}):null;return n.jsx(rc,{message:I,isFocused:g?!1:i,onHeaderClick:l,senderBadge:j?n.jsx(Kv,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?n.jsx(Xm,{label:"To",addresses:t.envelope.to}):null,indicators:N||!g?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[N,!g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(ju,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(Xn,{className:"size-3.5"})})]}),w&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:n.jsx(Mv,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h}),actionBar:g?n.jsx(_v,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:y,isTrusted:j,showRaw:m,onToggleRaw:h,onReply:v,onReplyAll:p,onForward:x}):void 0,body:s?n.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):r&&gf(a)?n.jsx("div",{className:"mt-3",children:n.jsx(Uc,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(Pt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Bv,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(yu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:j,category:rr(e.category)})})})},Hv=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:f,onForward:d})=>{const[m,h]=c.useState(!1),{data:g,isLoading:v,isError:p,error:x,refetch:b}=ue({...ja({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(qv,{threadMessage:e,messageData:g,isLoading:v,isError:p,error:x,onRetry:()=>b(),isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,showRaw:m,onToggleRaw:()=>h(w=>!w),mobile:l,onReply:u,onReplyAll:f,onForward:d}):n.jsx(Uv,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},Wv=()=>n.jsxs("div",{className:"animate-pulse p-4",children:[n.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),n.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>n.jsxs("div",{className:"flex gap-3 py-3",children:[n.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function Ri({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?n.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[n.jsx(Ns,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",n.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&n.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Is=({threadId:e,mailboxId:t,subject:s,selectedMessageId:r,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:f,onSwipePrevious:d,mobileIntelligenceOpen:m})=>{const h=Ot(),{handlers:g}=Ob({onSwipeLeft:f,onSwipeRight:d}),{accountId:v}=qc(t),{data:p,isLoading:x,isError:b,error:w,refetch:j}=ue({...xf({path:{threadId:e}})}),y=c.useMemo(()=>p?.items??[],[p?.items]),I=y[y.length-1],N=c.useRef(new Map),[k,C]=c.useState(new Set),[M,P]=c.useState(null),[D,O]=c.useState(0);c.useEffect(()=>{if(y.length>0&&e!==M){P(e);const G=new Set([y[y.length-1].threadMessageId]);if(r){const ae=y.find(le=>le.messageId===r);ae&&G.add(ae.threadMessageId)}C(G),O(y.length-1)}},[e,y,M,r]);const E=c.useCallback(G=>{C(ae=>{const le=new Set(ae);return le.has(G)?le.delete(G):le.add(G),le})},[]),S=c.useCallback(G=>{const ae=y[G];if(!ae)return;N.current.get(ae.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),A=c.useCallback(()=>{if(y.length===0)return;const G=Math.min(D+1,y.length-1);O(G),S(G)},[y.length,D,S]),L=c.useCallback(()=>{if(y.length===0)return;const G=Math.max(D-1,0);O(G),S(G)},[y.length,D,S]),T=c.useCallback(()=>{const G=y[D];G&&E(G.threadMessageId)},[y,D,E]),{data:F}=ue({...xt(),staleTime:1/0}),R=F?.accounts?.[0],$=!!R?.smtpHost;Rb({messages:y,expandedIds:k,threadId:e,mailboxId:t,accountId:R?.accountId});const{toggleStar:B,isPending:K,pendingMessageId:J}=Wa({threadId:e,mailboxId:t,messages:y}),[ee,X]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(X(l),u?.())},[l,u]);const{data:me}=ue({...ja({path:{messageId:I?.messageId??""}}),enabled:!!I&&ee!==null}),ce=c.useCallback(()=>{X("reply")},[]),te=c.useCallback(()=>{X("reply_all")},[]),U=c.useCallback(()=>{X("forward")},[]),q=c.useCallback(()=>{X(null),u?.()},[u]);if(Ha({enabled:!x&&y.length>0&&ee===null,bindings:[{key:"j",handler:A,preventDefault:!0},{key:"ArrowDown",handler:A,preventDefault:!0},{key:"k",handler:L,preventDefault:!0},{key:"ArrowUp",handler:L,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},...$?[{key:"r",handler:ce,preventDefault:!0},{key:"R",handler:te,noModifiers:!1,preventDefault:!0},{key:"f",handler:U,preventDefault:!0}]:[]]}),x)return n.jsx(Wv,{});if(b)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Pt,{title:"Couldn't load this conversation",error:w,onRetry:()=>j()})});if(y.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(Uc,{message:"No messages in this thread"})});const re=s||y[0]?.subject||"(No subject)",Ie=y.length,je=G=>n.jsx("div",{children:y.map((ae,le)=>n.jsx("div",{ref:z=>{z&&N.current.set(ae.threadMessageId,z)},children:n.jsx(Hv,{threadMessage:ae,isExpanded:k.has(ae.threadMessageId),isFocused:le===D,onToggle:()=>E(ae.threadMessageId),onToggleStar:()=>B(ae.messageId,ae.hasStars),isStarPending:K&&J===ae.messageId,accountId:v,mobile:G,onReply:G&&$?ce:void 0,onReplyAll:G&&$?te:void 0,onForward:G&&$?U:void 0})},ae.threadMessageId))}),V=n.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[n.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:re}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ie," ",Ie===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[V,a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:je(!1)}),ee!==null&&n.jsx(wi,{mode:ee,account:R,sourceMessage:me,onClose:q})]}):n.jsxs(Hh,{thread:{subject:re,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&n.jsx(Ri,{authenticity:a,onOpenIntelligence:o}),je(!0),ee!==null&&n.jsx(wi,{mode:ee,account:R,sourceMessage:me,onClose:q})]})};function Ts(){const{mailboxNameIndex:e,accountNameIndex:t}=Ce();return{...gt({select:r=>Ac(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Za=e=>e.trim().toLocaleLowerCase(),Vv=/^\d{4}-\d{2}-\d{2}$/;function Mi(e,t,s){if(!Vv.test(s))return;const r=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(r))return{type:e,raw:t,value:s,epochSeconds:Math.floor(r/1e3)}}function Qv(e,t){const s=e.toLowerCase();if(s.startsWith("from:")&&e.length>5)return{type:"from",raw:e,value:e.slice(5)};if(s==="has:attachment")return{type:"hasAttachment",raw:e};if(s==="is:unread")return{type:"isUnread",raw:e};if(s.startsWith("before:")&&e.length>7)return Mi("before",e,e.slice(7));if(s.startsWith("after:")&&e.length>6)return Mi("after",e,e.slice(6));if(s.startsWith("in:")&&e.length>3){const r=e.slice(3),a=t.mailboxesByName?.get(r.toLowerCase());return a?{type:"in",raw:e,value:r,mailboxId:a}:void 0}if(s.startsWith("account:")&&e.length>8){const r=e.slice(8),a=t.accountsByName?.get(r.toLowerCase());return a?{type:"account",raw:e,value:r,accountId:a}:void 0}}function Rs(e,t={}){const s=e.split(/\s+/).filter(o=>o.length>0),r=[],a=[];for(const o of s){const i=Qv(o,t);i?r.push(i):a.push(o)}return{freeText:a.join(" "),tokens:r}}function Yv(e,t){return e.split(/\s+/).filter(s=>s.length>0&&s!==t.raw).join(" ")}function Su(e){switch(e.type){case"from":return`From: ${e.value}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const Gv=20,Xv=new Set(Object.values(it)),Jv=e=>e!==void 0&&Xv.has(e)?e:void 0;function ku({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ce(),r=Ts(),a=gt({select:w=>w.matches}),o=Za(s),{freeText:i,tokens:l}=Rs(o,r),u=i.length>0,f=Jv(t),d=l.some(w=>w.type==="hasAttachment")?!0:void 0,m=l.some(w=>w.type==="isUnread")?!1:void 0,h=l.find(w=>w.type==="after"),g=l.find(w=>w.type==="before"),v=l.find(w=>w.type==="in"),p=Kx({matches:a,callerMailboxId:e,inTokenMailboxId:v?.mailboxId}),{data:x,isLoading:b}=ue({...il({query:{query:i,mailboxId:p,limit:Gv,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...m!==void 0?{isRead:m}:{},...h?{sentDateFrom:h.epochSeconds}:{},...g?{sentDateTo:g.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:x?.items??[],isLoading:u&&b}}const Zv=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),ey=e=>[...e].sort(Zv);function sa(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId??e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:rr(e.category),suspicious:t}}function ty(e,t){const s=new Set,r=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),r.push(a));return r.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const Ai=[{id:"personal",label:"Personal",category:it.personal},{id:"transactional",label:"Transactional",category:it.transactional},{id:"newsletter",label:"Newsletter",category:it.newsletter},{id:"marketing",label:"Marketing",category:it.marketing},{id:"social",label:"Social",category:it.social},{id:"automated",label:"Automated",category:it.automated},{id:"uncategorized",label:"Unclassified",category:it.uncategorized}];function sy(e){const t=new Map(Ai.map(r=>[r.category,[]]));for(const r of e){const a=r.category??it.uncategorized;(t.get(a)??t.get(it.uncategorized))?.push(r)}const s=[];for(const r of Ai){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function Cu(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Nu(e,t){return t.every(s=>{switch(s.type){case"from":{const r=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(r)||e.fromName.toLowerCase().includes(r)}case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const ny={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function ry(e){return ny[e]??e}function ay(e,t){const{folder:s}=Sa(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",subject:e.subject??"(No subject)",snippet:e.snippet??"",date:Lt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Eu(e,t){const{folder:s}=Sa(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function oy(e,t){const{mailboxId:s,folder:r}=Sa(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?Lt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:ry(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function Iu(e,t,s){const r=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))r.has(o.threadId)||(r.add(o.threadId),a.push(oy(o,s)));return a}const iy=768,ly=1024,Tu=e=>e!=="desktop",lr=()=>{const e=wo(`(min-width: ${iy}px)`);return wo(`(min-width: ${ly}px)`)?"desktop":e?"tablet":"phone"},cy=new Set(["hasAttachment","isUnread","before","after"]),Ru=(e,{searchHadSemanticReach:t})=>{const s=[],r=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}cy.has(u.type)&&r.push({type:u.type,label:Su(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:r,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},uy=e=>e.clauses.length>0,Mu=(e,{scope:t="standing",moveMailboxId:s}={})=>({clauses:e.clauses.map((r,a)=>({id:`search-${a}`,field:r.field,value:r.value})),matchOperator:e.matchOperator,moveMailboxId:s,scope:t,name:""}),Au="remit.recentSearches",dy=5;function na(){try{const e=localStorage.getItem(Au);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Di(e){const t=e.trim();if(!t)return na();const s=[t,...na().filter(r=>r!==t)].slice(0,dy);try{localStorage.setItem(Au,JSON.stringify(s))}catch{return s}return s}const fy=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function my(e){const{spam:t}=oc([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let r;for(const[a,o]of s)(!r||o>r.count)&&(r={mailboxId:a,count:o});return r}const hy=(e,t)=>{const s=ve(ll()),{mutate:r,reset:a}=s,o=c.useCallback(()=>{e&&(a(),r({path:{accountId:e},body:qr({matchOperator:t.matchOperator,literalClauses:t.literalClauses})}))},[e,t.matchOperator,t.literalClauses,r,a]);return c.useEffect(()=>{o()},[o]),{seedCount:s.data?.matchedCount,isPending:s.isPending||s.data===void 0,isError:s.isError,error:s.error,retry:o}},Du=({initialRule:e,widenAnchorCount:t=1})=>{const[s,r]=c.useState(e),[a,o]=c.useState(),i=c.useRef(0);return{rule:s,setRule:N=>r(N),handlers:{clauseEdit:a,onStartAddClause:()=>o({mode:"add",draft:{field:Na[0],value:""}}),onStartEditClause:N=>{const k=s.clauses.find(C=>C.id===N);k&&o({mode:"edit",clauseId:N,draft:{field:k.field,value:k.value}})},onRemoveClause:N=>r(k=>({...k,clauses:k.clauses.filter(C=>C.id!==N)})),onChangeDraftField:N=>o(k=>k&&{...k,draft:{...k.draft,field:N}}),onChangeDraftValue:N=>o(k=>k&&{...k,draft:{...k.draft,value:N}}),onSubmitClause:()=>{if(!a)return;const N=a.draft.field,k=Uf(N,a.draft.value);k!==""&&(r(C=>a.mode==="edit"&&a.clauseId?{...C,clauses:C.clauses.map(M=>M.id===a.clauseId?{id:M.id,field:N,value:k}:M)}:(i.current+=1,{...C,clauses:[...C.clauses,{id:`clause-${i.current}`,field:N,value:k}]})),o(void 0))},onCancelClause:()=>o(void 0),onAddWiden:()=>r(N=>({...N,widen:{anchorCount:Math.max(t,1)}})),onRemoveWiden:()=>r(N=>({...N,widen:void 0})),onChangeMatchOperator:N=>r(k=>({...k,matchOperator:N})),onChangeMove:N=>r(k=>({...k,moveMailboxId:N||void 0})),onChangeLabel:N=>r(k=>({...k,labelId:N||void 0})),onChangeScope:N=>r(k=>({...k,scope:N})),onChangeName:N=>r(k=>({...k,name:N})),onChangeUntil:N=>r(k=>({...k,until:N}))}}};function Ou({progress:e,isDone:t,runningLabel:s,onClose:r}){const a=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?a?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(Qn,{className:"size-8 text-positive"}):n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:s}),t&&!a&&n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("p",{className:"font-medium",children:"Done"}),n.jsxs("p",{className:"mt-1 text-xs text-fg-muted",children:[e.appliedCount," of ",e.matchedCount," moved",e.failedCount>0?` · ${e.failedCount} failed`:"","."]})]}),t&&a&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(Y,{variant:"primary",onClick:r,className:"mt-2",children:"Done"})]})}function ra(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Saving rule…"})]})}function Pu({onClose:e}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Qn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Filter saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"You can see it, and when it expires, under Settings › Filters."}),n.jsx(Y,{variant:"primary",onClick:e,className:"mt-2",children:"Done"})]})}function py({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(Qn,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Rule saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"New mail follows it automatically. Moving the mail already in your mailbox didn't run — try again?"}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(Y,{variant:"primary",onClick:e,children:"Move existing mail"}),n.jsx(Y,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function Lu({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't save the rule"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(Y,{variant:"primary",onClick:e,children:"Try again"}),n.jsx(Y,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function gy({accountId:e,conversion:t,seedCount:s,onClose:r}){const[a]=c.useState(()=>Mu(t)),{rule:o,handlers:i}=Du({initialRule:a}),{data:l}=ue({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),u=c.useMemo(()=>Zs(l?.items??[]).map(g=>({id:g.mailboxId,label:Wn(g.fullPath)})),[l?.items]),f=pl(e,Ea(o),s),d=gl(e),m=xl(e),h=()=>{const g=bl(o);if(o.scope==="once"){d.start(g);return}m.createFilter(g,o.scope==="standing"?"standing":"temporary",(o.name??"").trim())};return d.isStarting||d.isRunning||d.isDone?n.jsx(Ou,{progress:d.progress,isDone:d.isDone,runningLabel:"Organizing your mail…",onClose:r}):m.isPending?n.jsx(ra,{}):m.isSuccess?n.jsx(Pu,{onClose:r}):m.isError?n.jsx(Lu,{onRetry:m.reset,onClose:r}):n.jsx(cl,{rule:o,folders:u,preview:f,notice:n.jsx(qp,{notice:{scopedOutFolder:t.scopedOut?.label,droppedFacets:t.droppedFacets.map(g=>g.label),droppedSemantic:t.droppedSemantic}}),semanticAvailable:!1,clauseFields:Na,...i,onCommit:h,onCancel:r})}function xy({open:e,accountId:t,parsed:s,searchHadSemanticReach:r,onClose:a}){const o=c.useMemo(()=>Ru(s,{searchHadSemanticReach:r}),[s,r]),i=c.useMemo(()=>Ea(Mu(o)),[o]),{seedCount:l,isPending:u,isError:f,retry:d}=hy(e?t:void 0,i);return e?n.jsx(ua,{open:e,onClose:a,title:"Filter rule",children:f?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't build the filter"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(Y,{variant:"primary",onClick:d,children:"Try again"}),n.jsx(Y,{variant:"ghost",onClick:a,children:"Not now"})]})]}):u||l===void 0?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Turning your search into a filter…"})]}):n.jsx(gy,{accountId:t,conversion:o,seedCount:l,onClose:a})}):null}function $u({title:e,unreadCount:t,children:s,footer:r,searchFilter:a,searchResults:o,searchLoading:i,relatedResults:l,relatedLoading:u,onSelectSearchResult:f,searchResultsLabel:d="Top matches",relatedResultsLabel:m="Related",searchResultsInBody:h=!1}){const{accounts:g,resultFolderIndex:v,searchQuery:p,searchInput:x,onSearchChange:b,onSearchClear:w,searchViewKey:j}=Ce(),y=Ts(),I=Oe(),N=Ss(),k=lr(),[C,M]=c.useState(!1),[P,D]=c.useState(na),[O,E]=c.useState(!1),S=c.useRef(j);c.useEffect(()=>{S.current!==j&&(S.current=j,M(!1))},[j]);const A=x.trim().length>0,{mailboxesByName:L,accountsByName:T}=y,F=c.useMemo(()=>Rs(x,{mailboxesByName:L,accountsByName:T}),[x,L,T]),R=F.tokens.map(pe=>({label:Su(pe),onRemove:()=>b(Yv(x,pe))})),$=o??[],B=l??[],K=A?[{id:"top",label:d,results:$},{id:"related",label:m,results:B}]:[],ee=!($.length+B.length>0)&&(i===!0||u===!0),{scope:X}=Pc(g),me=gt({select:pe=>pe.matches}),ce=Dc(me),te=qx(me,X,ce?v.get(ce)?.role:void 0),U=te.kind==="global"?my([...$,...B]):void 0,q=U?{kind:"global",onScopeToSpam:()=>I({to:"/mail/$mailboxId",params:{mailboxId:U.mailboxId},search:{q:p||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:te,Ie=F.tokens.find(pe=>pe.type==="account")?.accountId??g[0]?.accountId,je=B.length>0,V=A&&Ie?{onClick:()=>E(!0),disabledReason:uy(Ru(F,{searchHadSemanticReach:je}))?void 0:"Add a sender or words to filter on"}:void 0,G=O&&Ie?n.jsx(xy,{open:O,accountId:Ie,parsed:F,searchHadSemanticReach:je,onClose:()=>E(!1)}):null;if(k==="phone"&&C){const pe=ge=>{D(Di(x)),M(!1),f?.(ge)};return n.jsxs(n.Fragment,{children:[n.jsx(yp,{value:x,onChange:b,onClear:w,onCancel:()=>{M(!1),w()},filter:a,recentSearches:P,onPickRecent:b,makeFilter:V,sections:K,loading:ee,onSelectResult:pe,tokens:R,scope:q}),G]})}const ae=fy({tier:k,hasLiveInput:A,hasCommittedQuery:p.trim().length>0,bodyRendersCommittedResults:h}),le=pe=>{D(Di(x)),f?.(pe)},z=n.jsx(ic,{value:x,sections:K,loading:ee,onSelectResult:le,tokens:R,scope:q,makeFilter:V}),Fe=ae?a?n.jsx(da,{...a,children:z}):n.jsx("div",{className:"h-full overflow-y-auto",children:z}):s;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsx(up,{title:e,unreadCount:t,isDesktop:!1,showSearch:Tu(k),onMenuClick:()=>N?.openNav(),searchValue:x,onSearchChange:b,onSearchClear:w,searchOpen:C,onSearchOpenChange:M}),n.jsx("div",{className:"min-h-0 flex-1",children:Fe}),r,G]})}const by=(e,t,s)=>{const r=e.indexOf(s);if(r===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,r),i=Math.max(a,r);return e.slice(o,i+1)},vy=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,yy=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},Fu=(e,t,s)=>{if(e.length===0)return;const r=t===void 0?-1:e.indexOf(t);if(r===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(r+s,0),e.length-1);return e[a]},_u=e=>{const[t,s]=c.useState(new Set),[r,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(x=>{if(x.has(p))return x;const b=new Set(x);return b.add(p),b})},[]),u=c.useCallback(p=>{s(x=>{if(!x.has(p))return x;const b=new Set(x);return b.delete(p),b})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(x=>p.every(w=>x.has(w))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(x=>{if(x.size===0)return x;const b=yy(x,p);return b.size===x.size?x:b})},[]),v=c.useCallback((p,x,b)=>{const w=vy(p,r,b,x);s(j=>{const y=by(p,w,x);if(y.length===0)return j;const I=new Set(j);for(const N of y)I.add(N);return I}),a(w)},[r]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:f,clearSelection:d,toggleAll:m,selectRange:v,setAnchor:h,anchorId:r,intersectWith:g}},zu=(e,t)=>!t&&e>0,wy=(e,t)=>e==="BACK"&&t,jy=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),i=_u(),{selectedCount:l,toggle:u,clearSelection:f,selectRange:d,setAnchor:m,selectAll:h}=i,g=zu(l,t),v=c.useRef(null),p=c.useRef(!1),x=c.useCallback(()=>{r?.(),f()},[f,r]),b=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),w=c.useCallback(E=>{if(E<0||E>=e.length)return;const S=e[E];if(g){u(S);return}v.current=S,p.current=!1,o(S)},[e,g,u]),j=c.useCallback(()=>{e.length!==0&&w(b<0?0:Math.min(b+1,e.length-1))},[e.length,b,w]),y=c.useCallback(()=>{e.length!==0&&w(b<=0?0:b-1)},[e.length,b,w]),I=c.useCallback(()=>w(0),[w]),N=c.useCallback(()=>w(e.length-1),[w,e.length]),k=c.useCallback(()=>{a&&u(a)},[a,u]),C=c.useCallback((E,S)=>S.shiftKey?(d(e,E,a),!0):S.metaKey||S.ctrlKey?(u(E),!0):(x(),m(E),!1),[e,a,d,u,x,m]),M=c.useCallback(E=>{const S=Fu(e,a,E);S!==void 0&&(d(e,S),v.current=S,p.current=!1,o(S))},[e,a,d]),P=c.useCallback(()=>M(-1),[M]),D=c.useCallback(()=>M(1),[M]),O=c.useCallback(()=>{e.length>0&&h(e)},[e,h]);return{focusedMessageId:a,setFocusedMessageId:o,focusIndex:b,pendingDomFocusRef:v,cursorMovedByPointerRef:p,selection:i,isMultiSelectMode:g,exitSelection:x,moveFocusToIndex:w,focusNext:j,focusPrevious:y,focusFirst:I,focusLast:N,toggleFocusedSelection:k,extendRangeUp:P,extendRangeDown:D,selectAllLoaded:O,handleRowSelect:C}};function Bu(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Sy=e=>{const{mailboxId:t,messages:s}=e,r=ye(),{pushError:a}=Ve(),{mutate:o,isPending:i}=ve({...bf(),onError:(u,f)=>{a({title:f.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:st(u),error:u})},onSettled:(u,f,d)=>{yt(r,vt(sr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,f,d)=>{u.length!==0&&o({body:{messageIds:u,labelId:f,action:d}})},[o]),isPending:i}};function ky({accountId:e,mailboxId:t,messageIds:s}){const{labels:r}=kl(e),{applyLabel:a}=Sy({mailboxId:t}),o=c.useMemo(()=>r.map(i=>({key:i.labelId,label:i.name,icon:n.jsx("span",{className:`size-2.5 rounded-full ${vf(i.color)?yo[i.color]:yo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[r,s,a]);return o.length===0?null:n.jsx(ec,{triggerLabel:"Apply label to selected messages",triggerIcon:n.jsx(yf,{className:"size-4"}),items:o})}const Ku=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,selectedMessageIds:d,moveDisabledHint:m,selectAll:h,statusLabel:g,isCounting:v=!1,progress:p,notice:x})=>{if(e===0)return null;const b=p!==void 0,w=i||l||b,j=!b&&!v,y=!!a&&!!u&&!!f,I=!!u&&!!f&&!!d?.length,N=!!o&&!!u&&!!f&&!m&&!g,k=h?.checked?`All ${e} loaded selected`:`${e} ${e===1?"message":"messages"} selected`;return n.jsxs("div",{className:"sticky top-0 z-10 flex flex-col bg-surface-sunken border-b border-line",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:s,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded hover:bg-surface-raised transition-colors","aria-label":"Clear selection",children:n.jsx(We,{className:"size-4 text-fg-muted"})}),h&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(sn,{"aria-label":"Select all",checked:h.checked,indeterminate:h.indeterminate,onChange:h.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:g??k}),m&&!x&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:m})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[N&&o&&n.jsxs("button",{type:"button",onClick:w?void 0:o,className:"min-h-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Organize similar messages",children:[n.jsx(ut,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),j&&r&&n.jsx("button",{type:"button",onClick:w?void 0:r,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Mark as read","aria-busy":w,children:n.jsx(Cs,{className:"size-4"})}),j&&y&&a&&u&&f&&n.jsx(un,{accountId:u,currentMailboxId:f,onMove:w?()=>{}:a,disabledHint:m,variant:"icon-only",label:"Move selected messages"}),j&&I&&u&&f&&d&&n.jsx(ky,{accountId:u,mailboxId:f,messageIds:d}),j&&n.jsxs("button",{type:"button",onClick:w?void 0:t,className:be("min-h-11 min-w-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors","bg-danger text-canvas hover:bg-danger/90"),"aria-label":"Delete selected messages","aria-busy":i,children:[i?n.jsx(nt,{className:"size-4 animate-spin"}):n.jsx(rt,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),p&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(Pa,{value:p.value,max:p.max,tone:p.tone})}),x&&n.jsx(Xt,{tone:x.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-3 mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[x.text&&n.jsx("span",{children:x.text}),x.action&&n.jsx("button",{type:"button",onClick:x.action.onClick,className:"-my-1 min-h-11 shrink-0 inline-flex items-center px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised",children:x.action.label})]})})]})},eo=c.createContext(null),Cy=e=>{const t=c.useContext(eo);return t?t.rowInteraction(e):null},Ny=()=>{const e=c.useContext(eo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},Ey="[data-message-id]",Iy=e=>Array.from(e.querySelectorAll(Ey)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),Ty=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),Ry=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=Iy(r);s(l=>Ty(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Uu({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=Ot(),u=c.useRef(null),f=Ry(u),d=jy({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:v,selection:p,isMultiSelectMode:x,exitSelection:b,handleRowSelect:w}=d,{selectedIds:j,selectedCount:y,isSelected:I,toggle:N,select:k}=p,{intersectWith:C}=p;c.useEffect(()=>{C(f)},[C,f]),c.useEffect(()=>{const X=g.current;X!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${X}"]`)?.focus())});const M=c.useCallback(X=>{v.current=!0,h(X)},[v,h]),P=c.useCallback(X=>{l||k(X)},[l,k]),D=c.useCallback(()=>{m&&t(m)},[m,t]),[O,E]=c.useState(null),S=c.useCallback(X=>!s||X.length===0?!1:(E(X),!0),[s]),A=c.useCallback(()=>{S(Array.from(j))},[S,j]),L=c.useCallback(()=>O!==null?!0:y>0?S(Array.from(j)):m?S([m]):!1,[O,y,j,m,S]),T=c.useCallback(()=>{O!==null&&(s?.(O),E(null),b())},[O,s,b]),F=c.useCallback(()=>E(null),[]),R=c.useCallback(()=>y===0?!1:(b(),!0),[y,b]),$=f.length>0;c.useEffect(()=>{if(a){if(!$){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:D,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:R,requestDelete:L,toggleDensity:()=>{}},()=>{a.current=null}}},[a,$,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,D,R,L]);const B=c.useMemo(()=>Array.from(j),[j]),K=O!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:B,orderedIds:f,hasList:$,blocksKeyboard:K})},[o,m,B,f,$,K]);const J=Bu(f,m),ee=c.useMemo(()=>({selectedIds:j,selectedCount:y,exitSelection:b,requestDeleteSelection:A,rowInteraction:X=>({focused:X===m,isTabStop:X===J,isDesktop:l,onFocusRow:M,selection:{isChecked:I(X),onToggleCheck:N,onRowSelect:w,isMultiSelectMode:x,onLongPress:P}})}),[j,y,b,A,m,J,l,M,I,N,w,x,P]);return n.jsxs(eo.Provider,{value:ee,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Ra,{isOpen:K,title:wl(O?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:T,onCancel:F})]})}function qu({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=Ny(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(Ku,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const My=({thread:e,active:t=!1,focused:s,isTabStop:r,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:f,onClick:d,onFocusRow:m})=>{const h=ye(),g=e.id,v=Cy(g),p=s??v?.focused??!1,x=r??v?.isTabStop??!1,b=l??v?.selection,w=m??v?.onFocusRow,j=o??v?.isDesktop??!0,y=b?.isChecked??!1,I=b?.isMultiSelectMode??!1,N=b?.onToggleCheck,k=b?.onRowSelect,C=b?.onLongPress,M=c.useCallback(R=>{R.preventDefault(),R.stopPropagation(),N?.(g)},[N,g]),P=c.useCallback(R=>{if(!j){if(I){R.preventDefault(),R.stopPropagation(),N?.(g);return}d?.();return}const $={shiftKey:R.shiftKey,metaKey:R.metaKey,ctrlKey:R.ctrlKey};if(k?.(g,$)){R.preventDefault(),R.stopPropagation(),$.shiftKey&&window.getSelection()?.removeAllRanges();return}d?.()},[j,I,N,k,d,g]),D=c.useCallback(R=>{j&&R.shiftKey&&R.preventDefault()},[j]),O=c.useCallback(()=>{C?.(g)},[C,g]),{longPressProps:E}=Xl({onLongPress:O,delayMs:500,accessibilityDescription:y?"Deselect message":"Select message"}),S=c.useCallback(()=>{h.prefetchQuery(ja({path:{messageId:g}}))},[h,g]),A=c.useCallback(()=>{S(),w?.(g)},[S,w,g]),L=ks({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":y}:{},tabIndex:x?0:-1,onClick:P,onMouseDown:D,onMouseEnter:S,onFocus:A},j||!b?{}:E),T=be(a==="compact"?Ql({active:t,focused:p}):be("group",tn({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",y&&"bg-accent-soft",!j&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?n.jsx(Yl,{thread:e}):n.jsx(Gl,{thread:e,badge:i,selection:b?{checked:y,alwaysVisible:I,onToggle:M}:void 0});return f===void 0?n.jsx("button",{type:"button",...L,className:T,children:F}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:R=>({...R,selectedMessageId:g}),...L,className:T,children:F})},to=c.memo(My),Ay=200,Dy={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},Oi=()=>n.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>n.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[n.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsxs("div",{className:"flex justify-between gap-2",children:[n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),Oy=({accountEmail:e})=>{const t=Oe();return n.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[n.jsx(Gt,{className:"size-3.5 shrink-0"}),n.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),n.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function Py({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=Ce(),d=Ts(),m=Ot(),h=c.useMemo(()=>ey(e.filter(U=>!U.muted?.value)),[e]),[g,v]=c.useState("all"),[p,x]=c.useState("all"),[b,w]=c.useState(new Set),[j,y]=c.useState(!1),I=c.useCallback(U=>{w(q=>{const re=new Set(q);return re.has(U)?re.delete(U):re.add(U),re})},[]),{data:N,isLoading:k,isError:C,refetch:M}=ue({...Kr(),staleTime:6e4}),P=Ft({queries:h.map(U=>({..._e({path:{accountId:U.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),D=c.useMemo(()=>{const U=new Map;for(let q=0;q<h.length;q++){const re=h[q].accountId,je=(P[q]?.data?.items??[]).reduce((V,G)=>V+(G.unseenCount??0),0);U.set(re,je)}return U},[h,P]),O=c.useMemo(()=>h.filter((U,q)=>{const re=P[q];return re?.isError?!Ur(re.error):!1}),[h,P]),{freeText:E,tokens:S}=Rs(u.trim().toLowerCase(),d),{data:A,isFetching:L}=ue({...Kr({query:{query:E,limit:Ay}}),enabled:E.length>0,staleTime:3e4}),T=c.useMemo(()=>{const U=(N?.items??[]).map(sa);return(E?ty(U.filter(re=>Cu(re,E)),(A?.items??[]).map(sa)):U).filter(re=>(g==="all"||re.accountId===g)&&Nu(re,S))},[N,A,g,E,S]),F=c.useMemo(()=>sy(T),[T]),R=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(U=>({id:U.accountId,label:U.email.split("@")[0]??U.email,count:D.get(U.accountId),active:g===U.accountId}))],[h,D,g]),$=c.useMemo(()=>e.filter(U=>U.muted?.value).length,[e]),B=c.useMemo(()=>Array.from(D.values()).reduce((U,q)=>U+q,0),[D]),K=c.useMemo(()=>{const U=Array.from(b).map(q=>Dy[q]).filter(q=>q!=null);return T.filter(q=>(p==="all"||q.category===p)&&U.every(re=>re(q))).map(q=>Eu(q,f))},[T,p,b,f]),{hits:J,isLoading:ee}=ku(),X=c.useMemo(()=>{const U=new Map;for(const re of N?.items??[])U.set(re.messageId,re.threadId);const q=K.map(re=>U.get(re.id)).filter(re=>re!=null);return Iu(J,q,f)},[J,K,N,f]),me=c.useMemo(()=>{const U=Jp(R.map(q=>({id:q.id,label:q.label,count:q.count,active:q.active})));return{categories:U.categories,filters:U.filters,sources:U.sources,sourcesNote:$>0?`+${$} muted`:void 0,selectedCategory:p,activeFilters:b,expanded:j,onExpandedChange:y,onSelectCategory:q=>x(q),onSelectSource:v,onToggleFilter:I,onClear:()=>{x("all"),v("all"),w(new Set)}}},[R,$,p,b,j,I]),ce=F.length===0&&g==="all"&&E.length===0,te=k?n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(Oi,{}),n.jsx(Oi,{})]}):C?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[n.jsx(Gt,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>M(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(Kl,{className:"size-3.5"}),"Try again"]})]}):ce?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]}):n.jsx(Uu,{selectedMessageId:t,onOpen:U=>s?.(U),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i?n.jsx(qu,{onMarkAsRead:l}):null,n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(Qi,{sections:F,Row:to,manageFocus:!1,briefCategory:p,onSelectBriefCategory:x,sources:R,sourcesNote:$>0?`+${$} muted`:void 0,onSelectSource:v,selectedThreadId:t,onSelectThread:s})})]})});return n.jsx($u,{title:"Daily brief",unreadCount:B,footer:m?n.jsx(Wl,{}):void 0,searchFilter:me,searchResults:K,searchLoading:k||L,relatedResults:X,relatedLoading:ee,onSelectSearchResult:r,children:n.jsxs("div",{className:"flex h-full flex-col",children:[O.map(U=>n.jsx(Oy,{accountEmail:U.email,accountId:U.accountId},U.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:te})]})})}const Ly=10,Hu=e=>({q:e?.toLowerCase()??"",limit:Ly}),$y=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function Fy(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":On(t,{month:"short",year:"numeric"})}function Wu(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const _y="We can't verify the sender of this email, which could mean it's from an insecure source.",zy="We couldn't read this sender's address, so we can't confirm who really sent this message.";function By(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?Fy(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Wu(e.fromEmail)}}function Ky(e){return e?.flags?{vip:e.flags.vip?.value===!0,muted:e.flags.muted?.value===!0,blocked:e.flags.blocked?.value===!0,unsubscribed:e.flags.unsubscribed?.value===!0}:{}}function Uy(e,t){const s=t>0?t:void 0;if(Wu(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:zy,similarCount:s};const r=e.authenticity;if(!r)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:_y};if(!r.dkimMismatch)return{verdict:"aligned",fromDomain:r.fromDomain,dkimDomain:r.dkimDomain,summary:r.dkimDomain?`We verified this message was really sent by ${r.fromDomain}.`:"Nothing looks unusual about this sender."};const a=r.fromDomain,o=r.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Vu(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=ue({...sl({query:Hu(s??void 0)}),enabled:!!s,staleTime:3e4}),i=$y(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=ue({...il({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?Lt(b.sentDate*1e3):"",matched:b.matchedChunkType})),g=By(e,i),v=Uy(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},x=Ky(i);return{sender:g,authenticity:v,category:p,flags:x,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:Ur(d),addressErrorIsFatal:Ur(o),addressId:i?.addressId,address:i}}function qy(e,t){const s={...e??{}};for(const[r,a]of Object.entries(t))a==null?delete s[r]:s[r]={...a,setAt:a.setAt??Date.now()};return s}function Qu({addressId:e,senderEmail:t}){const s=ye(),{pushError:r}=Ve(),a=wf({query:Hu(t)}),{mutate:o,isPending:i}=ve({...ol(),onMutate:async u=>{const f=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,m=>m&&{...m,items:m.items.map(h=>h.addressId===u.path.addressId?{...h,flags:qy(h.flags,f)}:h)}),{previous:d}},onError:(u,f,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),r({title:"Couldn't update sender preference",detail:st(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){ul(new Error(`Quick action fired but the sender's address record did not resolve (sender: ${t??"unknown"}). This should never happen — the address row exists.`));return}o({path:{addressId:e},body:{flags:u}})},[e,o,t]),isPending:i}}const Hy=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Yu=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function Wy(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function Vy(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function Qy(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Gu(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const Yy=["personal","newsletter","marketing","automated","transactional","social"],Gy=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},Xy=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function Jy(){return n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"h-8 rounded bg-surface"})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>n.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function Zy({isOpen:e,current:t,onSelect:s,onCancel:r}){return e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:r,children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),n.jsx("div",{className:"mt-4 flex flex-col gap-1",children:Yy.map(a=>n.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),n.jsx("div",{className:"mt-6 flex justify-end",children:n.jsx("button",{type:"button",onClick:r,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function e0({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=Vu(e,s),[d,m]=c.useState(!1),[h,g]=c.useState(!1),v=e.fromEmail??void 0,{updateFlags:p,isPending:x}=Qu({addressId:i,senderEmail:v}),{junkMailboxId:b}=or(r),{inboxMailboxId:w}=Qa(r),{moveMessages:j}=Qt({mailboxId:s??"",threadId:e.threadId,accountId:r}),y=Js(),I=Gy({mailboxId:s,junkMailboxId:b,inboxMailboxId:w}),N=c.useCallback(()=>{w&&j([e.messageId],w)},[w,j,e.messageId]),k=c.useCallback(()=>{b&&(Gu(y,{count:1,senderTrust:e.senderTrust,wasRescuable:Yu(e)}),j([e.messageId],b))},[b,j,e,y]),C=c.useCallback(()=>{},[]),M=c.useCallback(()=>{const R=o?.flags?.vip!==!0;p({vip:{value:R}})},[o?.flags?.vip,p]),P=c.useCallback(()=>{const R=o?.flags?.muted!==!0;p({muted:{value:R}})},[o?.flags?.muted,p]),D=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):m(!0)},[o?.flags?.blocked,p]),O=c.useCallback(()=>{m(!1),p({blocked:{value:!0}})},[p]),E=c.useCallback(()=>{const R=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:R}})},[o?.flags?.unsubscribed,p]),S=c.useCallback(R=>{g(!1),p({category:{value:R}})},[p]),A=i!==void 0,L={onToggleVip:A?M:void 0,onToggleMute:A?P:void 0,onToggleBlock:A?D:void 0,onToggleUnsubscribe:A?E:void 0,onReclassify:A?()=>g(!0):void 0,onNotSpam:I==="notSpam"?N:void 0,onMarkSpam:I==="markSpam"?k:void 0},T=({mailboxId:R,messageId:$,className:B,ariaLabel:K,children:J})=>n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:R},search:ee=>({...ee,selectedMessageId:$}),className:B,"aria-label":K,children:J});if(!o)return n.jsx(Jy,{});const F=Xy({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx(Hl,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:C,actions:L,similarState:F,similarLinkComponent:T,className:"border-l-0 h-full w-full"}),n.jsx(Ra,{isOpen:d,title:"Block this sender?",description:`Messages from ${v??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:x,onConfirm:O,onCancel:()=>m(!1)}),n.jsx(Zy,{isOpen:h,current:o.category.value,onSelect:S,onCancel:()=>g(!1)})]})}const Ms=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(e0,{thread:t,onClose:e,mailboxId:s,accountId:r,hideCloseButton:a}):n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(ut,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[n.jsx(ut,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),Fr="Open a message first",so=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:r,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:f,isStarred:d,moveContext:m})=>{const[h,g]=c.useState(null),v=u??e,p=x=>()=>g(x);return n.jsx(xh,{hasThread:e,isStarred:d,onUnavailable:x=>g(Fr),unavailableHint:h,replyTitle:`Reply ${fs("reply")}`,replyAllTitle:`Reply all ${fs("replyAll")}`,forwardTitle:`Forward ${fs("forward")}`,deleteTitle:`Move to Trash ${fs("delete")}`,flagTitle:`Star ${fs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:v?l:p(Fr),onToggleStar:f,onMove:p(Fr),moveSlot:m?n.jsx(un,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(gh,{open:t,enabled:s,onToggle:r})})},Xu=()=>{const e=ye();return c.useCallback(t=>{const s=Zt({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},Qs=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountConfigId,i=Xu(),{deleteMessages:l}=Yt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{moveMessages:u}=Qt({mailboxId:a??"",threadId:e?.threadId,accountId:o,onAfterOptimisticRemove:r}),{toggleStar:f}=Wa({threadId:e?.threadId??"",mailboxId:a??""}),d=c.useCallback(()=>{e&&l(i(e))},[e,i,l]),m=c.useCallback(x=>{e&&u(i(e),x)},[e,i,u]),h=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[g,v]=c.useState(null),p=c.useCallback(()=>v(null),[]);return{mailboxId:a,accountId:o,isStarred:e?.hasStars,deleteThread:d,moveThread:m,toggleStar:h,composeRequest:g,requestCompose:v,clearComposeRequest:p}},$s={action:null,nextPrefix:null,preventDefault:!1},t0={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},s0={j:{action:"focusNext"},k:{action:"focusPrevious"},arrowdown:{action:"focusNext"},arrowup:{action:"focusPrevious"},home:{action:"focusFirst"},end:{action:"focusLast"},enter:{action:"openFocused"}," ":{action:"toggleSelect"},delete:{action:"delete"},backspace:{action:"delete"},u:{action:"toggleRead"},x:{action:"toggleSelect"},r:{action:"reply"},a:{action:"replyAll"},f:{action:"forward"},"#":{action:"delete"},s:{action:"toggleStar"},m:{action:"muteSender"},b:{action:"blockSender"},v:{action:"vipSender"},"!":{action:"markJunk"},i:{action:"toggleIntelligence"},d:{action:"toggleDensity"},"/":{action:"focusSearch"},c:{action:"compose"},"?":{action:"help"}};function n0(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...$s,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...$s,nextPrefix:t==="g"?null:t};if(r&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(r&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(r)return{...$s,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=t0[s===","?",":s]??null;return{action:i,nextPrefix:null,preventDefault:i!==null}}if(s==="g"&&!e.shiftKey)return{action:null,nextPrefix:"g",preventDefault:!0};if(e.shiftKey){const o=s==="j"||s==="arrowdown";if(o||(s==="k"||s==="arrowup"))return{action:o?"extendSelectDown":"extendSelectUp",nextPrefix:null,preventDefault:!0}}const a=s0[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?$s:{action:a.action,nextPrefix:null,preventDefault:!0}}return $s}function r0(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const a0="data-message-row",o0='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function i0(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(o0);return t?!t.hasAttribute(a0):!1}function l0({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const r=c.useRef(e);r.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const f=n0({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:r0(u.target),onControl:i0(u.target)},a.current);if(i(),a.current=f.nextPrefix,f.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),f.action===null)return;const d=r.current[f.action];d&&(f.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const Pi=(e,t,s)=>{if(!t)return null;const r=e.indexOf(t);if(r===-1)return null;const a=s==="next"?r+1:r-1;return a<0||a>=e.length?null:e[a]},no=()=>{const[e,t]=c.useState(void 0),[s,r]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[f,d]=c.useState(!1),m=c.useCallback(h=>{t(h.focusedMessageId),r(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:m,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:f}},ro=({context:e,orderedIds:t,selectedMessageId:s,enabled:r=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,f=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return l0({enabled:r&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:f,...o}}),{goBack:f,nextMessageId:Pi(t,s,"next")??void 0,previousMessageId:Pi(t,s,"previous")??void 0}};function c0(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Ju(e,t){if(e)return c0(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Zu=c.createContext(null);function cr(){const e=c.useContext(Zu);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function u0({selectedMessageId:e,children:t}){const s=Oe(),{searchInput:r}=Ce(),{selectedThreadId:a,selectedMailboxId:o}=vs({strict:!1}),{data:i}=ue({...Kr(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(P=>P.messageId===e)},[i,e]),u=c.useMemo(()=>Ju(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,selectedMessageId:P,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),d=c.useCallback(P=>{s({to:"/mail",search:D=>({...D,q:r||void 0,selectedMessageId:P.id,selectedThreadId:P.threadId,selectedMailboxId:P.mailboxId})})},[s,r]),m=c.useCallback(P=>{e&&P.includes(e)&&s({to:"/mail",search:D=>({...D,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=Qs({thread:l,onAfterOptimisticRemove:m}),g=c.useCallback(()=>{s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),v=no(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:x}=Yt({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:b}=nr({mailboxId:l?.mailboxId??"",messages:p}),w=c.useCallback(P=>b(P,!0),[b]),j=v.focusedMessageId,I=c.useMemo(()=>i?.items.find(P=>P.messageId===j),[i,j])??l,N=Qs({thread:I}),{nextMessageId:k,previousMessageId:C}=ro({context:v,orderedIds:v.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{v.listCommandsRef.current?.requestDelete()||N.deleteThread()},toggleStar:N.toggleStar,toggleRead:()=>{const P=v.selectedIds.length>0?v.selectedIds:I?[I.messageId]:[];P.length!==0&&b(P,!(I?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),M={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:v,onDeleteMessages:x,onMarkMessagesRead:w,nextMessageId:k,previousMessageId:C};return n.jsx(Zu.Provider,{value:M,children:t})}function ed(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=cr(),{accounts:i}=Ce();return n.jsx(Py,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function d0(){const{conversation:e,actions:t}=cr(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function f0(){const{selectedThread:e}=cr(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function m0(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=cr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ce();return t?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:r,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),n.jsx(Ua,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(ed,{})})}const Fs=Object.assign(u0,{List:ed,Reading:d0,Intelligence:f0,Phone:m0}),h0=()=>al({query:{starred:!0,order:"desc"}});function td(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Sc({queryKey:h0(),queryFn:async({pageParam:f})=>{const{data:d}=await jf({query:{starred:!0,order:"desc",continuationToken:f},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:f=>f.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(f=>f.items??[]),[e]),isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const p0=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function sd({title:e,unreadCount:t,preset:s,selectedCategory:r,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:f,footer:d,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w}){const[j,y]=c.useState(!1),I={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:j,onExpandedChange:y,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx($u,{title:e,unreadCount:t,footer:d,searchFilter:I,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:v,onSelectSearchResult:p,searchResultsLabel:x,relatedResultsLabel:b,searchResultsInBody:w,children:n.jsx(da,{...I,children:f})})}const g0={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function x0({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Ce(),u=Ts(),f=Ot(),[d,m]=c.useState("all"),[h,g]=c.useState(new Set),v=c.useCallback(T=>{g(F=>{const R=new Set(F);return R.has(T)?R.delete(T):R.add(T),R})},[]),p=c.useCallback(()=>{m("all"),g(new Set)},[]),{threads:x,isLoading:b,isError:w,error:j,refetch:y,fetchNextPage:I,hasNextPage:N,isFetchingNextPage:k}=td(),{freeText:C,tokens:M}=Rs(i.trim().toLowerCase(),u),P=c.useMemo(()=>{const T=Array.from(h).map(F=>g0[F]).filter(F=>F!=null);return p0(x).map(sa).filter(F=>(d==="all"||F.category===d)&&T.every(R=>R(F))&&(!C||Cu(F,C))&&Nu(F,M))},[x,d,h,C,M]),D=c.useMemo(()=>eg(),[]),O=c.useMemo(()=>P.map(T=>Eu(T,l)),[P,l]),E=c.useMemo(()=>P.filter(T=>!T.isRead).length,[P]),S=b?"loading":w?"error":P.length===0?"empty":"ready",A=c.useCallback(()=>{const T=va(ba());window.open(T,"_blank","noopener,noreferrer")},[]),L=n.jsx(Uu,{selectedMessageId:e,onOpen:T=>t?.(T),onDeleteMessages:a,commandsRef:s,onTriageContextChange:r,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a?n.jsx(qu,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:P.map(T=>n.jsx(to,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),N?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>I(),disabled:k,children:k?"Loading…":"Load more"}):null]})]})});return n.jsx(sd,{title:"Starred",unreadCount:E,preset:D,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:v,onClearFilters:p,searchResults:O,searchLoading:b,onSelectSearchResult:T=>t?.(T.id),children:n.jsx(Zl,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:S,searchQuery:C?i:void 0,errorMessage:w?vl(j):void 0,onRetry:()=>y(),onReportError:A,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:S==="ready"?L:void 0})})}const nd=c.createContext(null);function ur(){const e=c.useContext(nd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function b0({selectedMessageId:e,children:t}){const s=Oe(),{threads:r}=td(),a=c.useMemo(()=>{if(e)return r.find(y=>y.messageId===e)},[r,e]),o=c.useCallback(y=>{s({to:"/mail/flagged",search:I=>({...I,selectedMessageId:y})})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:y=>({...y,selectedMessageId:void 0})})},[s]),l=c.useCallback(y=>{e&&y.includes(e)&&i()},[e,i]),u=Qs({thread:a,onAfterOptimisticRemove:l}),f=no(),{deleteMessages:d}=Yt({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=nr({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(y=>m(y,!0),[m]),g=f.focusedMessageId,p=c.useMemo(()=>r.find(y=>y.messageId===g),[r,g])??a,x=Qs({thread:p}),{nextMessageId:b,previousMessageId:w}=ro({context:f,orderedIds:f.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{f.listCommandsRef.current?.requestDelete()||x.deleteThread()},toggleStar:x.toggleStar,toggleRead:()=>{const y=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];y.length!==0&&m(y,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:b,previousMessageId:w};return n.jsx(nd.Provider,{value:j,children:t})}function rd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=ur();return n.jsx(x0,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function v0(){const{selectedThread:e,actions:t}=ur(),{intelligenceOpen:s,onToggleIntelligence:r}=Ce(),a=Ss()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Es,{})})]})}function y0(){const{selectedThread:e}=ur(),{onToggleIntelligence:t}=Ce();return n.jsx(Ms,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function w0(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=ur(),{intelligenceOpen:o,onToggleIntelligence:i}=Ce();return e?n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:r?()=>s(r):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),n.jsx(Ua,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(rd,{})})}const _s=Object.assign(b0,{List:rd,Reading:v0,Intelligence:y0,Phone:w0}),j0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},S0=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},k0=()=>{const{state:e,closeCompose:t}=Dt(),s=S0(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=ue({...xt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),f=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const m=j0[e.mode]??"New Message";return n.jsxs(Je.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(Je.Portal,{children:[n.jsx(Je.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(Je.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(Je.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(Je.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:m}),o?n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:n.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[n.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),n.jsx("button",{type:"button",onClick:f,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},C0={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},ad=()=>{const{state:e,closeCompose:t}=Dt(),s=Ot(),{isError:r,error:a,refetch:o}=ue({...xt(),staleTime:1/0});if(!s)return n.jsx(k0,{});if(!e.isOpen)return null;const i=C0[e.mode]??"New Message",l=n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[n.jsx("div",{className:"flex items-center gap-2 min-w-0",children:n.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]});return r?n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(Pt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(qa,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function N0(e){const t=e.toAddresses.join(", ");return{id:e.outboxMessageId,accountId:e.accountId,fromName:e.fromName??e.fromAddress??"Me",fromEmail:e.fromAddress??"",subject:e.subject??"(No subject)",snippet:t?`To: ${t}`:"(No recipients)",timeLabel:Lt(e.updatedAt),isRead:!0}}function E0(e){return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function I0({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map(N0),a=s.map(E0),o=[];return r.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:r}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function ao(){const e=Ss();return!e||e.showNavPane?null:n.jsx(Y,{variant:"ghost",size:"sm",icon:n.jsx(Ca,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const T0=({label:e,count:t})=>n.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),R0=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:W("group",tn({active:t})),children:[n.jsx(Gi,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(Hs,{thread:e}),n.jsx("div",{className:"flex items-center gap-1 shrink-0",children:n.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),r(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:n.jsx(rt,{className:"size-3.5"})})})]}),M0=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:W("group",tn({active:t})),children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(dt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(Hs,{thread:e})]})};function A0({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=Dt(),u=Oe(),f=ye(),{data:d}=ue(Un()),m=c.useMemo(()=>I0({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=ve({...qn(),onSuccess:()=>{f.invalidateQueries({queryKey:ka()})}}),g=b=>{h.mutate({path:{outboxMessageId:b}})},v=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},x=m.length===0;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:x?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(ca,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):m.map(b=>n.jsxs("div",{children:[b.label&&n.jsx(T0,{label:b.label,count:b.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:b.threads.map(w=>b.id==="remit-drafts"?n.jsx(R0,{row:w,isSelected:l.isOpen&&w.id===l.outboxMessageId,onOpen:v,onDelete:g,isDeleting:h.isPending},w.id):n.jsx(M0,{row:w,isSelected:w.id===s,onOpen:p},w.id))})]},b.id))})]})}function D0(e,t,s){const r=new Array(e);return new Proxy(r,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let f=a[u];if(!f){const d=t[u*2];f=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return f}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function ds(e,t,s){let r=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==r.length||l.some((f,d)=>r[d]!==f))&&(r=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{r=l},i}function Li(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const O0=(e,t)=>Math.abs(e-t)<1.01,P0=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let zs;const _r=()=>{if(zs!==void 0)return zs;if(typeof navigator>"u")return zs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zs=!0;const e=navigator.maxTouchPoints;return zs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},$i=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},L0=e=>e,$0=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(r);for(let o=0;o<r;o++)a[o]=t+o;return a},F0=(e,t)=>{const s=e.scrollElement;if(!s)return;const r=e.targetWindow;if(!r)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a($i(s)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const f=u.borderBoxSize[0];if(f){a({width:f.inlineSize,height:f.blockSize});return}}a($i(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Fn={passive:!0},_0=typeof window>"u"?!0:"onscrollend"in window,z0=(e,t,s)=>{const r=e.scrollElement;if(!r)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&_0;let i=0;const l=o?null:P0(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=m=>()=>{i=s(r),l?.(),t(i,m)},f=u(!0),d=u(!1);return r.addEventListener("scroll",f,Fn),o&&r.addEventListener("scrollend",d,Fn),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},B0=(e,t)=>z0(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),K0=(e,t,s)=>{if(s.options.useCachedMeasurements){const r=s.indexFromElement(e),a=s.options.getItemKey(r);return s.itemSizeCache.get(a)??s.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=s.indexFromElement(e),a=s.options.getItemKey(r),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},U0=(e,{adjustments:t=0,behavior:s},r)=>{var a,o;(o=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[r.options.horizontal?"left":"top"]:e+t,behavior:s})},q0=U0;class H0{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,r,a;return((a=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[f,d]of this.elementsCache)if(d===l){this.elementsCache.delete(f);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=r())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=r())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var r,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:L0,rangeExtractor:$0,onChange:()=>{},measureElement:K0,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const g=s[h];g!==void 0&&(o[h]=g)}const i=this.options;let l=null,u=null,f=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,v=this.getMeasurements(),p=h>0?((r=v[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((a=v[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==x)){f=!0;const j=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??v[0]:null;j&&(l=[j.key,this.getScrollOffset()-j.start]);const y=o.followOnAppend===!0?"auto":o.followOnAppend||null;y&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==x)&&(u=y)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,g]=l,v=this.getMeasurements(),{count:p,getItemKey:x}=this.options;let b=0;for(;b<p&&x(b)!==h;)b++;if(b<p){const w=v[b];if(w){const j=w.start+g;j!==this.scrollOffset&&(m=j-this.scrollOffset,this.scrollOffset=j,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,m])},this.notify=s=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,s)},this.maybeNotify=ds(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!_r()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Fn),o.addEventListener("touchend",l,Fn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),r=this.getMaxScrollOffset();if(s<0||s>r)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=ds(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,r,a,o,i,l,u,f)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f}),{key:!1}),this.getMeasurements=ds(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f},d)=>{const m=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let w=this._flatMeasurements;if(!w||w.length<b){const I=new Float64Array(b);w&&h>0&&I.set(w.subarray(0,h*2)),w=I,this._flatMeasurements=w}let j;if(h===0)j=r+a;else{const I=h-1;j=w[I*2]+w[I*2+1]+f}for(let I=h;I<s;I++){const N=o(I),k=m.get(N),C=typeof k=="number"?k:this.options.estimateSize(I);w[I*2]=j,w[I*2+1]=C,j+=C+f}const y=D0(s,w,o);return this.measurementsCache=y,y}const g=this.measurementsCache.slice(0,h),v=new Array(l).fill(void 0),p=new Float64Array(l);let x=0;for(let b=0;b<h;b++){const w=g[b];w&&(v[w.lane]===void 0&&x++,v[w.lane]=b,p[w.lane]=w.end)}for(let b=h;b<s;b++){const w=o(b),j=this.laneAssignments.get(b);let y,I;const N=u==="estimate"||m.has(w);if(j!==void 0&&this.options.lanes>1){y=j;const P=v[y],D=P!==void 0?g[P]:void 0;I=D?D.end+f:r+a}else if(x===l){let P=0,D=p[0],O=v[0];for(let E=1;E<l;E++){const S=p[E];(S<D||S===D&&v[E]<O)&&(P=E,D=S,O=v[E])}y=P,I=D+f,N&&this.laneAssignments.set(b,y)}else y=b%this.options.lanes,I=r+a,N&&this.laneAssignments.set(b,y);const k=m.get(w),C=typeof k=="number"?k:this.options.estimateSize(b),M=I+C;g[b]={index:b,start:I,size:C,end:M,key:w,lane:y},v[y]===void 0&&x++,v[y]=b,p[y]=M}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ds(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=V0(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ds(()=>{let s=null,r=null;const a=this.calculateRange();return a&&(s=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:r,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,a=s.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(s),a=this.options.getItemKey(r),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const f=this._flatMeasurements;if(this.options.lanes===1&&f!==null)u=this.options.getItemKey(s),l=f[s*2],i=f[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,m=r-d;if(m!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,v=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},m,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):v&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=ds(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=r[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=od(0,r.length-1,o?l=>a[l*2]:l=>Li(r[l]).start,s);return Li(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,r,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=s>=i+o?"end":"start"),r==="center"?s+=(a-o)/2:r==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(r==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,r),i=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,r);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=r[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const r=this.getMeasurements();for(const a of r)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:r,behavior:a})=>{this._intendedScrollOffset=s+(r??0),this.options.scrollToFn(s,{behavior:a,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(_r()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&O0(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),f=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,f||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:f?"smooth":"auto"})}this.scheduleScrollReconcile()}}const od=(e,t,s,r)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<r)e=a+1;else if(o>r)t=a-1;else return a}return e>0?e-1:0};function W0(e,t,s){let r=0;for(;r<=t;){const a=(r+t)/2|0,o=e[a*2];if(o<s)r=a+1;else if(o>s)t=a-1;else return a}return r>0?r-1:0}function V0(e,t,s,r,a){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&a!==null){const f=W0(a,o,s);let d=f;const m=s+t;for(;d<o&&a[d*2]+a[d*2+1]<m;)d++;return{startIndex:f,endIndex:d}}let l=od(0,o,f=>e[f].start,s),u=l;if(r===1)for(;u<o&&e[u].end<s+t;)u++;else if(r>1){const f=Array(r).fill(0);for(;u<o&&f.some(m=>m<s+t);){const m=e[u];f[m.lane]=m.end,u++}const d=Array(r).fill(s+t);for(;l>=0&&d.some(m=>m>=s);){const m=e[l];d[m.lane]=m.start,l--}l=Math.max(0,l-l%r),u=Math.min(o,u+(r-1-u%r))}return{startIndex:l,endIndex:u}}const zr=typeof document<"u"?c.useLayoutEffect:c.useEffect;function Q0({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...r}){const a=c.useReducer(f=>f+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=f=>{const d=o.current;if(!d.enabled||!d.container)return;const m=f.getTotalSize();if(m!==d.lastSize){d.lastSize=m;const b=f.options.horizontal?"width":"height";d.container.style[b]=`${m}px`}const h=!!f.options.horizontal,g=d.mode==="transform",v=h?"left":"top",p=f.options.scrollMargin,x=f.getVirtualItems();for(const b of x){const w=b.start-p,j=f.elementsCache.get(b.key);j&&d.lastPositions.get(j)!==w&&(d.lastPositions.set(j,w),g?j.style.transform=h?`translate3d(${w}px, 0, 0)`:`translate3d(0, ${w}px, 0)`:j.style[v]=`${w}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let g=!0;if(h.enabled){i(f);const v=f.range,p=h.prevRange;g=!p||p.isScrolling!==f.isScrolling||p.startIndex!==v?.startIndex||p.endIndex!==v?.endIndex,g&&(h.prevRange=v?{startIndex:v.startIndex,endIndex:v.endIndex,isScrolling:f.isScrolling}:null)}g&&(e&&d?ha.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new H0(l);return Object.assign(f,{containerRef:d=>{const m=o.current;if(m.container=d,m.lastSize=null,d&&m.enabled){const h=f.getTotalSize();m.lastSize=h;const g=f.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),zr(()=>u._didMount(),[]),zr(()=>u._willUpdate()),zr(()=>{i(u)}),u}function Y0(e){return Q0({observeElementRect:F0,observeElementOffset:B0,scrollToFn:q0,...e})}const G0={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},id={delete:"moved to Trash",move:"moved",markRead:"marked as read"},ld={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},X0={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},J0={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},Z0=(e,t,s)=>G0[e](ct(t),ct(s)),Fi=(e,t)=>`${ct(t)} ${id[e]}. Your mail server is still catching up.`,ew=(e,t,s)=>`${ct(t)} ${id[e]}. ${ct(s)} ${ld[e]}.`,tw=(e,t)=>t>0?`Stopped after ${ct(t)} — some messages ${ld[e]}`:X0[e],sw=e=>J0[e],nw=e=>e==="delete"?"danger":"info",cd=100,_n=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),rw=(e,t=cd)=>{if(e.length===0)return[];const s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s},aw=async(e,t,s,r)=>{const a=rw(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(r())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const f=a[u],d=await _n(t(f));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=f.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},ow=async(e,t,s,r,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await _n(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const f=u.value;if(f.ids.length>0){const d=await _n(s(f.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=f.ids.length,r({done:o,total:t})}l=f.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},iw=e=>({done:e.done,total:Math.max(e.total,e.done)}),lw=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await _n(e(a));if(!o.ok)return{total:r,cancelled:!1,error:o.error};const i=o.value;r+=i.ids.length,t(r),a=i.continuationToken}while(a);return{total:r,cancelled:!1}},cw=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},uw=100,dw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],fw=({mailboxId:e,accountId:t,enabled:s,predicateKey:r,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[f,d]=c.useState(void 0),m=c.useRef(!1),h=ye(),{pushError:g}=Ve();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const v=c.useRef(a);v.current=a;const p=c.useCallback(async N=>{const{data:k}=await dl({path:{mailboxId:e},query:{...v.current,continuationToken:N,limit:uw},throwOnError:!0});return{ids:(k.items??[]).map(C=>C.messageId),continuationToken:k.continuationToken}},[e]),x=c.useCallback(N=>async k=>{if(N.kind==="move"){const{data:M}=await Sf({body:{messageIds:k,destinationMailboxId:N.destinationMailboxId},throwOnError:!0});return M}if(N.kind==="markRead"){const{data:M}=await kf({body:{messageIds:k,isRead:!0},throwOnError:!0});return M}const{data:C}=await Cf({body:{messageIds:k},throwOnError:!0});return C},[]),b=c.useCallback(N=>{yt(h,vt(dw(N,e))),t&&h.invalidateQueries({queryKey:Jt({path:{accountId:t}})})},[h,e,t]),w=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),lw(p,N=>i({kind:"counting",countSoFar:N}),()=>m.current).then(N=>{if(N.error){g(Vt("Couldn't count matching messages","The count didn't finish.",N.error)),i({kind:"idle"});return}if(N.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:N.total})})},[p,g]),j=c.useCallback(()=>{m.current=!0},[]),y=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),I=c.useCallback(async(N,k)=>{m.current=!1,u(N);const C=D=>d(iw(D)),M=x(N),P=k!==void 0?await aw(k,M,C,()=>m.current):await ow(p,o.kind==="escalated"?o.total:0,M,C,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),P.error&&g(Vt(tw(N.kind,P.done),sw(N.kind),P.error)),P.done>0&&b(N),P},[x,p,o,g,b]);return{phase:o,escalate:w,stop:j,clear:y,isRunning:l!==void 0,runningAction:l,progress:f,runAction:I}},ud=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",mw=e=>`Select all ${ud(e)}`,hw=(e,t)=>`All ${ct(t)} ${ud(e)} selected`,pw=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",gw=2,xw=(e,t,s=!1)=>e>=gw||t!=="idle"||s,dd=(e,t,s)=>{const r=ve(ll()),{mutate:a,reset:o}=r,[i,l]=c.useState(!1),u=c.useMemo(()=>qf(s),[s]),f=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:qr({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),m=r.data,h=m?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:qr(Hf(u))}))},[h,e,u,a]);const g=i||(m?.semanticUnavailable??!1),v=r.isPending||h,p=i?{matchOperator:"Or",literalClauses:Wf(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:f,reset:d,matchedCount:v?void 0:m?.matchedCount,messageIds:v?void 0:m?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:v,isError:r.isError,error:r.error}},bw=({entry:e,hasSeed:t,previewStatus:s,matchedCount:r})=>{if(e==="something-else"&&!t)return{kind:"something-else"};if(s==="error")return{kind:"error"};if(s!=="success")return{kind:"widening"};const a=r??0;return{kind:"organize",matchedCount:a,fallback:a===0}};function fd({accountId:e,selectedMessageIds:t,seedCount:s,semanticUnavailable:r=!1,senders:a=[],seedMailboxId:o,seedScope:i,onClose:l}){const u=t[0],f=r&&a.length>0,[d]=c.useState(()=>Vf({anchorMessageId:u,semanticUnavailable:r,senders:a,selectionCount:t.length,seedMailboxId:o,seedScope:i})),{rule:m,handlers:h}=Du({initialRule:d,widenAnchorCount:t.length}),{data:g}=ue({..._e({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>Zs(g?.items??[]).map(O=>({id:O.mailboxId,label:Wn(O.fullPath)})),[g?.items]),{labels:p}=kl(e),x=c.useMemo(()=>p.map(O=>({id:O.labelId,name:O.name,color:O.color})),[p]),{createLabel:b}=Jf(e),w=async O=>{const E=await b(O);return{id:E.labelId,name:E.name,color:E.color}},j=pl(e,Ea(m,u),s),y=gl(e),I=xl(e),{createFolder:N}=jl(e),[k,C]=c.useState(),M=c.useRef(!1),P=()=>{const O=bl(m,u);if(m.scope==="once"){y.start(O);return}M.current=!1,C(Qf(O)?O:void 0),I.createFilter(O,m.scope==="standing"?"standing":"temporary",(m.name??"").trim())};c.useEffect(()=>{!k||M.current||!I.isSuccess||(M.current=!0,y.start(k))},[k,I.isSuccess,y.start]);const D=()=>{k&&y.start(k)};return y.isStarting||y.isRunning||y.isDone?n.jsx(Ou,{progress:y.progress,isDone:y.isDone,runningLabel:f?"Organizing mail from these senders…":"Organizing similar mail…",onClose:l}):I.isSuccess&&y.isError?n.jsx(py,{onRetry:D,onClose:l}):I.isPending?n.jsx(ra,{}):I.isSuccess?k?n.jsx(ra,{}):n.jsx(Pu,{onClose:l}):I.isError?n.jsx(Lu,{onRetry:I.reset,onClose:l}):n.jsx(cl,{rule:m,folders:v,labels:x,preview:j,semanticAvailable:!r,clauseFields:Na,...h,onCreateFolder:N,onCreateLabel:w,onCommit:P,onCancel:l})}const _i=(e,t)=>e.find(s=>s.label.toLowerCase()===t),vw=(e,t)=>{const s=[],r=_i(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=_i(e,"archive");a&&s.push({id:"file-archive",label:"File in Archive",seed:{moveMailboxId:a.id}});const o=t?e.find(i=>i.id===t):void 0;return o&&s.push({id:"move-junk",label:`Move to ${o.label}`,seed:{moveMailboxId:o.id}}),s},yw=(e,t)=>{const s=e.toLowerCase(),r=t.find(o=>s.includes(o.label.toLowerCase())),a=/\b(always|keep|future|from now)\b/.test(s);return{moveMailboxId:r?.id,scope:a?"standing":void 0}};function ww({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>vw(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(yw(l,e))};return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"What should Remit do?"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:"Pick a shortcut or say it in your own words."})]}),n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4",children:o.map(l=>n.jsx(Y,{variant:"secondary",onClick:()=>s(l.seed),className:"h-12 w-full justify-start px-4",children:l.label},l.id))}),n.jsxs("div",{className:"flex items-center gap-2 border-t border-line px-5 py-3",children:[n.jsx(Nf,{value:r,onChange:l=>a(l.target.value),onKeyDown:l=>l.key==="Enter"&&i(),placeholder:"Tell Remit what to do…","aria-label":"Tell Remit what to do",className:"flex-1"}),n.jsx(Y,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx($m,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const jw=e=>e?.scope==="standing"?"standing":void 0,Sw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function kw({entry:e,accountId:t,selectedMessageIds:s,selectedSenders:r,junkMailboxId:a,onClose:o}){const i=s[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,senders:h,isPending:g,isError:v,error:p}=dd(t,i,r);c.useEffect(()=>{f()},[f]);const{data:x}=ue({..._e({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),b=c.useMemo(()=>Zs(x?.items??[]).map(j=>({id:j.mailboxId,label:Wn(j.fullPath)})),[x?.items]),w=bw({entry:e,hasSeed:l!==void 0,previewStatus:Sw(v,g,d),matchedCount:d});return n.jsxs(hl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[w.kind==="something-else"&&n.jsx(ww,{folderOptions:b,junkMailboxId:a,onSeed:u}),w.kind==="widening"&&n.jsx(Cw,{}),w.kind==="error"&&n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:p instanceof Error?p.message:"Please try again."}),n.jsx(Y,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),w.kind==="organize"&&n.jsx(fd,{accountId:t,selectedMessageIds:s,seedCount:w.matchedCount,seedScope:jw(l),seedMailboxId:l?.moveMailboxId,semanticUnavailable:m,senders:h,onClose:o})]})}function Cw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function Nw({open:e,accountId:t,selectedMessageIds:s,selectedSenders:r,onClose:a}){const o=s[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,senders:d,isPending:m,isError:h,error:g}=dd(t,o,r);c.useEffect(()=>{e&&i()},[e,i]);const v=()=>{l(),a()};return e?n.jsx(ua,{open:e,onClose:v,title:"Filter rule",children:m||u===void 0?h?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:g instanceof Error?g.message:"Please try again."}),n.jsx(Y,{variant:"ghost",onClick:v,className:"mt-2",children:"Close"})]}):n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(nt,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(fd,{accountId:t,selectedMessageIds:s,seedCount:u,semanticUnavailable:f,senders:d,onClose:v})}):null}const Ew=(e,t)=>({id:e.messageId,accountId:e.accountConfigId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:rr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Iw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,messageCount:d,isMultiSelectMode:m,onLongPress:h,isDesktop:g,density:v})=>n.jsx(to,{thread:Ew(e,d),linkMailboxId:t,inListbox:!0,active:r,focused:a,isTabStop:o,density:v,isDesktop:g,onFocusRow:i,selection:{isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:m,onLongPress:h},badge:e.autoMoved?n.jsx(Vc,{accountId:s,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,size:"sm"}):void 0}),Tw=c.memo(Iw),Rw=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountConfigId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:Lt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:rr(e.category),suspicious:t}},Mw=({thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,onDelete:g,onToggleRead:v,density:p})=>{const[x,b]=c.useState("none"),w=c.useCallback(I=>{navigator.vibrate?.(10),I==="trailing"?g(e.messageId):v(e.messageId,e.isRead),b("none")},[g,v,e.messageId,e.isRead]),j=c.useCallback(()=>{m(e.messageId)},[m,e.messageId]),y=c.useCallback(()=>{u(e.messageId)},[u,e.messageId]);return h||d?n.jsx(Tw,{thread:e,mailboxId:t,accountId:s,isSelected:r,isFocused:a,isTabStop:o,onFocusRow:i,isChecked:l,onToggleCheck:u,onRowSelect:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,density:p}):n.jsx(Jl,{thread:Rw(e),selectionMode:!1,checked:!1,active:r,peek:x,onPeek:b,onToggleCheck:y,onLongPress:j,onOpen:()=>{},onAct:w,linkComponent:({onOpenClick:I,children:N,...k})=>n.jsx(pt,{...k,to:"/mail/$mailboxId",params:{mailboxId:t},search:C=>({...C,selectedMessageId:e.messageId}),"data-message-row":!0,onClick:I,children:N})})},Aw=72,Dw=32,Ow=5,md="remit:list-density",Pw={kind:"delete"},zi={kind:"markRead"},Lw=()=>{try{const e=localStorage.getItem(md);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},$w=({query:e,count:t})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(Vn,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:[t," ",t===1?"result":"results"," for “",e,"”"]})]}),Fw=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:r,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:f,onMoveMessages:d,isDeleting:m=!1,isMoving:h=!1,onLoadMore:g,hasMore:v=!1,isLoadingMore:p=!1,accountId:x,listTitle:b,listMeta:w,onTriageContextChange:j,commandsRef:y,hideHeader:I=!1})=>{const N=c.useRef(null),k=Oe(),C=Ot(),[M,P]=c.useState(!1),[D,O]=c.useState(null),E=!!l?.trim(),[S,A]=c.useState(s),[L,T]=c.useState(Lw),F=c.useCallback(()=>{T(_=>{const se=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(md,se)}catch{}return se})},[]),{toggleReadFor:R}=nr({mailboxId:e}),{junkMailboxId:$}=or(x),{selectedIds:B,selectedCount:K,hasSelection:J,isSelected:ee,toggle:X,select:me,clearSelection:ce,selectRange:te,setAnchor:U,selectAll:q,toggleAll:re,intersectWith:Ie}=_u(),je=zu(K,C);c.useEffect(()=>{K===0&&O(null)},[K]);const[V,G]=c.useState(null),ae=E&&!!u,le=`${e}|${JSON.stringify(u??{})}`,z=fw({mailboxId:e,accountId:x,enabled:ae,predicateKey:le,searchQuery:u??{}}),Fe=z.phase.kind,pe=z.clear,ge=c.useCallback(()=>{Fe==="escalated"&&pe(),ce()},[ce,pe,Fe]),[Se,Qe]=c.useState(null),[ts,ze]=c.useState(null),Ze=c.useRef(null),Be=c.useRef(!1),Ke=c.useRef(null),ft=!r&&t.length>0,Te=V!==null,ss=c.useCallback((_,se)=>{const{exit:St,retryIds:Xe}=cw(se);if(St){ze(Fi(_.kind,se.done)),Qe(null),ge();return}if(Xe.length>0){Qe({action:_,succeeded:se.done}),q(Xe);return}Qe(null)},[ge,q]),Ue=Y0({count:t.length,getScrollElement:()=>N.current,estimateSize:()=>L==="compact"?Dw:Aw,overscan:Ow}),_t=s?t.findIndex(_=>_.messageId===s):-1,Ne=S?t.findIndex(_=>_.messageId===S):-1,qe=c.useCallback(_=>{if(_<0||_>=t.length)return;const se=t[_];if(je){X(se.messageId);return}Ze.current=se.messageId,Be.current=!1,A(se.messageId)},[t,je,X]),mt=c.useCallback(()=>{if(t.length===0)return;const _=Ne<0?0:Math.min(Ne+1,t.length-1);qe(_)},[t.length,Ne,qe]),ns=c.useCallback(()=>{if(t.length===0)return;const _=Ne<=0?0:Ne-1;qe(_)},[t.length,Ne,qe]),zt=c.useCallback(()=>qe(0),[qe]),Z=c.useCallback(()=>qe(t.length-1),[qe,t.length]),ie=c.useCallback(()=>{S&&X(S)},[S,X]),ne=c.useMemo(()=>t.map(_=>_.messageId),[t]),oe=c.useMemo(()=>{const _=[];for(const se of t)B.has(se.messageId)&&se.fromEmail&&_.push(se.fromEmail);return _},[t,B]),he=c.useCallback((_,se)=>se.shiftKey?(te(ne,_,S),!0):se.metaKey||se.ctrlKey?(X(_),!0):(ge(),U(_),!1),[ne,S,te,X,ge,U]),fe=c.useCallback(_=>{!f||_.length===0||(Ke.current=S??null,G({source:"ids",ids:_}))},[f,S]),we=c.useCallback(()=>{z.phase.kind==="escalated"&&(Ke.current=S??null,G({source:"predicate",total:z.phase.total}))},[z.phase,S]),Pe=c.useCallback(_=>{const se=Fu(ne,S,_);se!==void 0&&(te(ne,se),Ze.current=se,Be.current=!1,A(se))},[ne,S,te]),Ae=c.useCallback(()=>Pe(-1),[Pe]),He=c.useCallback(()=>Pe(1),[Pe]),De=c.useCallback(()=>{ne.length>0&&q(ne)},[ne,q]),Re=c.useCallback(()=>V!==null?!0:f?K>0?(fe(Array.from(B)),!0):S?(fe([S]),!0):!1:!1,[V,f,K,B,S,fe]),Ye=c.useCallback(()=>{S&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:S})})},[S,k,e]),Ge=c.useCallback(()=>{K>0&&fe(Array.from(B))},[fe,K,B]),et=c.useCallback(async(_,se)=>{const St=await z.runAction(_,se);ss(_,St)},[z,ss]),Bt=c.useCallback(async _=>{G(null),Ke.current=null,await et(Pw,_)},[et]),fr=c.useCallback(()=>{if(!V)return;if(V.source==="predicate"){Bt(void 0);return}const{ids:_}=V;if(_.length===0){G(null);return}if(_.length>cd){Bt(_);return}const se=new Set(_),St=t.findIndex($e=>se.has($e.messageId));let Xe;for(let $e=St+1;$e<t.length;$e++)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}if(Xe===void 0){for(let $e=St-1;$e>=0;$e--)if(!se.has(t[$e].messageId)){Xe=t[$e].messageId;break}}f?.(_),ge(),Ke.current=null,G(null),Xe!==void 0&&(Ze.current=Xe,Be.current=!1,A(Xe),C&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:$e=>({...$e,selectedMessageId:Xe}),replace:!0})),C||ze(Fi("delete",_.length))},[V,t,f,ge,k,e,C,Bt]),wt=c.useCallback(()=>{const _=Ke.current;Ke.current=null,G(null),_!==null&&(Ze.current=_,Be.current=!1,A(_))},[]),dn=c.useCallback(()=>{if(z.phase.kind==="escalated"){et(zi);return}K!==0&&et(zi,Array.from(B))},[z.phase,et,K,B]),rs=c.useCallback(_=>{if(z.phase.kind==="escalated"){et({kind:"move",destinationMailboxId:_});return}!d||K===0||(d(Array.from(B),_),ge())},[z.phase,et,d,K,B,ge]),mr=c.useCallback(()=>{$&&rs($)},[$,rs]),Kt=c.useMemo(()=>{if(K===0)return;const _=new Set;for(const se of t)B.has(se.messageId)&&_.add(se.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[K,B,t]),hr=c.useCallback(_=>{f?.([_])},[f]),pr=c.useCallback((_,se)=>{R([_],!se)},[R]),gr=c.useCallback(_=>{C||me(_)},[C,me]),jt=c.useCallback(()=>{if(z.phase.kind==="escalated"){we();return}Ge()},[z.phase,we,Ge]),As=c.useCallback(()=>{if(z.isRunning||z.phase.kind==="counting"){z.stop();return}ge()},[z,ge]),fn=c.useCallback(()=>{z.clear()},[z]),xr=c.useCallback(()=>{if(!Se)return;const _=Array.from(B);if(Se.action.kind==="delete"){Bt(_);return}et(Se.action,_)},[Se,Bt,et,B]);c.useEffect(()=>{if(Be.current||!C&&s)return;const _=Ne>=0?Ne:_t;_>=0&&Ue.scrollToIndex(_,{align:"auto"})},[Ne,_t,Ue,C,s]),c.useEffect(()=>{s&&(Be.current=!1,A(s))},[s]),c.useEffect(()=>{S&&(t.some(_=>_.messageId===S)||A(t[0]?.messageId))},[t,S]),c.useEffect(()=>{j?.({focusedMessageId:S,selectedIds:Array.from(B),hasList:ft,blocksKeyboard:Te})},[S,B,ft,Te,j]);const mn=c.useRef(j);mn.current=j,c.useEffect(()=>()=>mn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{z.phase.kind!=="idle"||z.isRunning||Ie(t.map(_=>_.messageId))},[t,Ie,z.phase,z.isRunning]);const hn=c.useRef(e);c.useEffect(()=>{hn.current!==e&&(hn.current=e,ge())},[e,ge]),Ax({shouldBlockFn:({action:_})=>wy(_,J)?(ge(),!0):!1,enableBeforeUnload:!1,disabled:!J}),c.useEffect(()=>{const _=N.current;if(!_||!v||!g)return;const se=()=>{if(p)return;const{scrollTop:St,scrollHeight:Xe,clientHeight:$e}=_;St+$e>=Xe-200&&g()};return _.addEventListener("scroll",se,{passive:!0}),se(),()=>_.removeEventListener("scroll",se)},[v,p,g]),c.useEffect(()=>{const _=Ze.current;if(!_)return;const se=N.current?.querySelector(`[data-message-id="${_}"]`);se&&(Ze.current=null,se.focus({preventScroll:!0}))}),c.useEffect(()=>{if(y){if(!ft){y.current=null;return}return y.current={focusNext:mt,focusPrevious:ns,focusFirst:zt,focusLast:Z,openFocused:Ye,toggleSelect:ie,extendSelectDown:He,extendSelectUp:Ae,selectAll:De,clearSelection:()=>J?(ge(),!0):!1,requestDelete:Re,toggleDensity:F},()=>{y.current=null}}},[y,ft,mt,ns,zt,Z,Ye,ie,He,Ae,De,J,ge,Re,F]);const pn=r?"loading":a?"error":t.length===0?"empty":"ready",br=a?vl(o):void 0,Q=c.useCallback(()=>{const _=va(ba());window.open(_,"_blank","noopener,noreferrer")},[]),tt=[{id:"inbox",threads:[]}],Le=ne.length>0&&ne.every(_=>B.has(_)),kd=ae&&v&&Le&&!m&&!h&&z.phase.kind==="idle"&&!z.isRunning,Cd=m||h||z.isRunning,vr=z.phase.kind==="escalated"?z.phase.total:K,lo=z.runningAction?Z0(z.runningAction.kind,z.progress?.done??0,z.progress?.total??0):z.phase.kind==="counting"?z.phase.countSoFar>=5e3?`Counting… ${ct(z.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${ct(z.phase.countSoFar)} so far`:z.phase.kind==="escalated"?hw(u??{},z.phase.total):void 0,co=z.phase.kind!=="escalated"&&ne.length>0?{checked:Le,indeterminate:K>0&&!Le,onChange:()=>re(ne)}:void 0,uo=z.runningAction&&z.progress?{value:z.progress.done,max:z.progress.total,tone:nw(z.runningAction.kind)}:void 0,fo=z.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:z.stop}}:z.phase.kind==="escalated"&&!z.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:fn}}:kd?{tone:"info",text:"",action:{label:mw(u??{}),onClick:z.escalate}}:Se!==null&&K>0?{tone:"danger",text:ew(Se.action.kind,Se.succeeded,K),action:{label:`Retry ${ct(K)}`,onClick:xr}}:void 0,mo=fo??(Kt?{tone:"warning",text:Kt}:void 0),ho=pw({isRunning:z.isRunning,isCounting:z.phase.kind==="counting",isEscalated:z.phase.kind==="escalated"}),po=!C&&je&&xw(vr,ho,mo!==void 0),Nd=(d||z.phase.kind==="escalated")&&x&&e?n.jsx(un,{accountId:x,currentMailboxId:e,onMove:m||h?()=>{}:rs,disabledHint:Kt,label:"Move selected messages"}):void 0,go=D&&x&&!C&&K>0?n.jsx(kw,{entry:D,accountId:x,selectedMessageIds:Array.from(B),selectedSenders:oe,junkMailboxId:$,onClose:()=>{O(null),ge()}}):void 0,xo=po?n.jsx(Yp,{count:vr,mode:ho,onCancel:As,onDelete:jt,onJunk:$&&$!==e&&!Kt?mr:void 0,onMarkRead:dn,onSelectSimilar:x?()=>O("select-similar"):void 0,onSomethingElse:x?()=>O("something-else"):void 0,moveSlot:Nd,isBusy:Cd,selectAll:co,statusLabel:lo,progress:uo,notice:mo}):void 0,Ed=xo||go?n.jsxs(n.Fragment,{children:[xo,go]}):void 0,Id=J&&C?n.jsx(Ku,{selectedCount:vr,onDelete:jt,onClearSelection:As,onMarkAsRead:dn,onMove:d?rs:void 0,onOrganize:()=>P(!0),isDeleting:m,isMoving:h,accountId:x,currentMailboxId:e,selectedMessageIds:Array.from(B),moveDisabledHint:Kt,selectAll:ae?co:void 0,statusLabel:lo,isCounting:z.phase.kind==="counting",progress:uo,notice:fo}):void 0,Td=Bu(ne,S),Rd=c.useCallback(_=>{Be.current=!0,A(_)},[]),Md=n.jsxs(n.Fragment,{children:[E&&l&&n.jsx($w,{query:l,count:t.length}),n.jsxs("div",{ref:N,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",style:po?{paddingBottom:Ks}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Ue.getTotalSize()}px`},children:Ue.getVirtualItems().map(_=>{const se=t[_.index];return n.jsx("div",{role:"presentation","data-index":_.index,ref:Ue.measureElement,className:be("absolute left-0 top-0 w-full border-b border-line",z.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:n.jsx(Mw,{thread:se,mailboxId:e,accountId:x,isSelected:s===se.messageId,isFocused:S===se.messageId,isTabStop:Td===se.messageId,onFocusRow:Rd,isChecked:ee(se.messageId),onToggleCheck:X,onRowSelect:he,isMultiSelectMode:je,onLongPress:gr,isDesktop:C,onDelete:hr,onToggleRead:pr,density:L})},_.key)})}),p&&n.jsx("div",{className:"flex justify-center py-4",children:n.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-fg-muted border-t-transparent"})})]})]}),Ad=V?V.source==="ids"?V.ids.length:V.total:0,bo=V?.source==="predicate";return n.jsxs(n.Fragment,{children:[ts&&!C&&n.jsx(Xt,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ze(null),children:ts}),n.jsx(Zl,{listTitle:b,listMeta:w,sections:tt,flatList:!0,listState:pn,searchQuery:E?l:void 0,errorMessage:br,onRetry:i,onReportError:Q,density:L,selectedThreadId:s,onSelectThread:_=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:se=>({...se,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:C,hideHeader:I,selectionBar:Id,selectionSheet:Ed,listBody:pn==="ready"?Md:void 0}),n.jsx(Ra,{isOpen:V!==null,title:wl(Ad,bo),description:bo?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:m,onConfirm:fr,onCancel:wt}),M&&x&&n.jsx(Nw,{open:M,accountId:x,selectedMessageIds:Array.from(B),selectedSenders:oe,onClose:()=>P(!1)})]})},_w=e=>Jt({path:{accountId:e}}),zw=e=>{const t=ye(),s=Js(),r=ve({...Ef(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:_w(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Bw=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=zw(e);return n.jsx(Cp,{onRefresh:s,isRefreshing:r,children:t})};function Kw({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=Js(),{t:u}=Kn("mail",{useSuspense:!1}),f=c.useCallback((w,j)=>u(w,{defaultValue:j}),[u]),{inboxMailboxId:d}=Qa(e),m=Wc(e),{data:h}=ue({..._e({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const w=Zs(h?.items??[],m),j=Xs(m);return w.map(y=>({id:y.mailboxId,label:bs(y,j.get(y.mailboxId),f),searchValue:y.fullPath,isCurrent:y.mailboxId===t}))},[h?.items,m,t,f]),v=c.useMemo(()=>d||(g.find(j=>j.label.toLowerCase()==="inbox")?.id??g.find(j=>!j.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,Wy(l,s.length))},[l,s.length]);const x=c.useCallback(()=>{Vy(l,s.length),i(!0)},[l,s.length]),b=c.useCallback((w,j)=>{Qy(l,{selected:w.length,total:s.length,toInbox:j===d}),r(w,j)},[l,s.length,d,r]);return n.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:n.jsx(Ip,{count:s.length,onReview:x})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Fp,{open:o,candidates:s,defaultDestinationId:v,availableFolders:g,onConfirmMove:b,onCancel:()=>i(!1)})]})}const Uw="We can verify this sender";function qw(e){const{data:t}=ue({...If({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(r=>({id:r.messageId,senderName:r.fromName||r.fromEmail||"Unknown sender",senderAddress:r.fromEmail??"",subject:r.subject||"(no subject)",snippet:r.snippet??"",trustReason:Uw,trustSubReason:Hy(r.senderTrust),senderTrust:r.senderTrust}))}}const Hw=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},hd="remit:intelligence-open";function Ww(){try{return localStorage.getItem(hd)!=="closed"}catch{return!0}}function Bi(e){try{localStorage.setItem(hd,e?"open":"closed")}catch{}}const Vw=(e,t)=>e!==t,Qw=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},Yw={unread:e=>!e.isRead,flagged:e=>e.hasStars===!0,attachment:e=>!!e.hasAttachment};function Gw(e,t,s){const r=Array.from(s).map(a=>Yw[a]).filter(a=>a!=null);return t==="all"&&r.length===0?e:e.filter(a=>(t==="all"||a.category===t)&&r.every(o=>o(a)))}const pd=c.createContext(null);function dr(){const e=c.useContext(pd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function Xw({mailboxId:e,selectedMessageId:t,children:s}){const r=Oe(),o=lr()==="desktop",i=Js(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=Ce(),g=Ts(),v=Za(u),p=v.length>0,{freeText:x,tokens:b}=Rs(v,g),w=b.find(Q=>Q.type==="from"),j={order:"desc",...x?{query:x}:{},...w?{from:w.value}:{},...b.some(Q=>Q.type==="hasAttachment")?{attachments:!0}:{},...b.some(Q=>Q.type==="isUnread")?{unread:!0}:{}},y=p?rl({path:{mailboxId:e},query:j}):wa({path:{mailboxId:e},query:{order:"desc"}}),{data:I,isLoading:N,isError:k,error:C,refetch:M,fetchNextPage:P,hasNextPage:D,isFetchingNextPage:O}=Sc({queryKey:y,queryFn:async({pageParam:Q})=>{if(p){const{data:Le}=await dl({path:{mailboxId:e},query:{...j,continuationToken:Q},throwOnError:!0});return Le}const{data:tt}=await Rf({path:{mailboxId:e},query:{order:"desc",continuationToken:Q},throwOnError:!0});return tt},initialPageParam:void 0,getNextPageParam:Q=>Q.continuationToken,enabled:p?v.length>0:!0,placeholderData:Tf}),E=c.useCallback(Q=>{t&&Q.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:tt=>({...tt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:S,isPending:A}=Yt({mailboxId:e,onAfterOptimisticRemove:E}),{accountId:L}=qc(e),T=Oc({accounts:l}),{moveMessages:F,isPending:R}=Qt({mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),$=qb(Hw(I?.pages.flatMap(Q=>Q.items??[])??[])),[B,K]=c.useState("all"),[J,ee]=c.useState(new Set),X=c.useMemo(()=>Gw($,B,J),[$,B,J]),me=c.useCallback(Q=>{K(Q)},[]),ce=c.useCallback(Q=>{ee(tt=>{const Le=new Set(tt);return Le.has(Q)?Le.delete(Q):Le.add(Q),Le})},[]),te=c.useCallback(()=>{K("all"),ee(new Set)},[]),U=Vw(f,u),q=Qw($,t,U),{selectedThreadId:re}=vs({strict:!1}),Ie=c.useMemo(()=>Ju(q,{messageId:t,threadId:U?void 0:re,mailboxId:e}),[q,t,re,U,e]),je=no(),{listCommandsRef:V,onTriageContextChange:G,focusedMessageId:ae,selectedIds:le}=je,z=X.find(Q=>Q.messageId===ae)??q,Fe=c.useRef(null);c.useEffect(()=>{const Q=q?.messageId??null;Q&&Fe.current!==Q&&q?.authenticity?.dkimMismatch&&(Fe.current=Q,d||m())},[q?.messageId,q?.authenticity?.dkimMismatch,d,m]);const pe=c.useRef(!1);c.useEffect(()=>{pe.current||o&&q?.messageId&&(pe.current=!0,Ww()&&!d&&h(!0))},[o,q?.messageId,d,h]);const Se=Hx({accounts:l})??$.filter(Q=>!Q.isRead).length,Qe=ye(),{pushError:ts}=Ve(),ze=Qs({thread:q,mailboxId:e,accountId:L,onAfterOptimisticRemove:E}),{draftsMailboxId:Ze}=Kb(L),Be=Ze!==void 0&&Ze===e,{archiveMailboxId:Ke}=Bb(L),ft=Xu(),{requestCompose:Te}=ze,ss=c.useCallback(()=>{Te("reply")},[Te]),Ue=c.useCallback(()=>{Te("reply_all")},[Te]),_t=c.useCallback(()=>{Te("forward")},[Te]),{state:Ne,openCompose:qe,closeCompose:mt}=Dt(),ns=c.useCallback(()=>{qe({mode:"new"})},[qe]),zt=ve({...qn(),onError:Q=>{ts(Vt("Couldn't discard draft","The draft wasn't deleted.",Q))}}),Z=c.useCallback(()=>{const Q=Ne.outboxMessageId;Q&&(zt.mutate({path:{outboxMessageId:Q}}),Qe.invalidateQueries({queryKey:ka()}),mt())},[Ne.outboxMessageId,zt,Qe,mt]),ie=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Q=>({...Q,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),ne=c.useCallback(Q=>Q?ft(Q):[],[ft]),{toggleStar:oe}=Wa({threadId:z?.threadId??"",mailboxId:e}),{toggleReadFor:he}=nr({mailboxId:e,accountId:L}),{junkMailboxId:fe}=or(L),we=fe!=null&&fe===e,{candidates:Pe}=qw(we?fe:void 0),{moveMessages:Ae}=Qt({mailboxId:e,threadId:z?.threadId,accountId:L,onAfterOptimisticRemove:E}),{deleteMessages:He}=Yt({mailboxId:e,threadId:z?.threadId,onAfterOptimisticRemove:E}),{addressId:De,address:Re}=Vu(z),{updateFlags:Ye}=Qu({addressId:De,senderEmail:z?.fromEmail??void 0}),Ge=c.useCallback(()=>t||!ae?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Q=>({...Q,selectedMessageId:ae})}),!0),[t,ae,e,r]),et=c.useCallback(()=>{Ge()||q&&Te("reply")},[Ge,q,Te]),Bt=c.useCallback(()=>{Ge()||q&&Te("reply_all")},[Ge,q,Te]),fr=c.useCallback(()=>{Ge()||q&&Te("forward")},[Ge,q,Te]),wt=c.useCallback(()=>le.length>0?le:ne(z),[le,ne,z]),dn=c.useCallback(()=>{if(V.current?.requestDelete())return;const Q=wt();Q.length>0&&He(Q)},[V,wt,He]),rs=c.useCallback(()=>{if(!fe)return;const Q=wt();Q.length!==0&&(Gu(i,{count:Q.length,senderTrust:z?.senderTrust??"unknown",wasRescuable:z?Yu(z):!1}),Ae(Q,fe))},[fe,wt,Ae,i,z]),mr=c.useCallback(()=>{if(le.length>0){const Q=!(z?.hasStars??!1),tt=new Set(le);for(const Le of X)tt.has(Le.messageId)&&Le.hasStars!==Q&&oe(Le.messageId,Le.hasStars);return}z&&oe(z.messageId,z.hasStars)},[le,X,z,oe]),Kt=c.useCallback(()=>{const Q=wt();if(Q.length===0)return;const tt=!(z?.isRead??!1);he(Q,tt)},[wt,z,he]),hr=c.useCallback(()=>{if(!De)return;const Q=Re?.flags?.muted?.value!==!0;Ye({muted:{value:Q}})},[De,Re,Ye]),pr=c.useCallback(()=>{if(!De)return;const Q=Re?.flags?.vip?.value!==!0;Ye({vip:{value:Q}})},[De,Re,Ye]),gr=c.useCallback(()=>{d||m()},[d,m]),jt=c.useCallback(Q=>{r({to:Q})},[r]),As=Be?"drafts":Ke===e?"archive":fe===e?"junk":"inbox",fn=c.useRef("");c.useEffect(()=>{const Q=fn.current;fn.current=v,v.length>0&&Q.length===0&&i.recordEvent("search.submitted",{mailboxType:As})},[v,As,i]);const xr=Be&&Ne.isOpen&&!!Ne.outboxMessageId&&!q,{goBack:mn,nextMessageId:hn,previousMessageId:pn}=ro({context:je,orderedIds:X.map(Q=>Q.messageId),selectedMessageId:t,enabled:!Ne.isOpen,onClose:ie,handlers:{reply:et,replyAll:Bt,forward:fr,delete:dn,toggleStar:mr,toggleRead:Kt,muteSender:hr,blockSender:gr,vipSender:pr,markJunk:rs,toggleIntelligence:q?m:void 0,compose:ns,goBrief:()=>jt("/mail"),goInbox:()=>jt("/mail"),goSent:()=>jt("/mail"),goFlagged:()=>jt("/mail/flagged"),goSettings:()=>jt("/settings")}});Ha({enabled:Ne.isOpen,bindings:[{key:"Escape",handler:mt,preventDefault:!0}]});const br={mailboxId:e,selectedMessageId:t,selectedThread:q,conversation:Ie,threads:X,isLoading:N,isError:k,error:C,mailboxAccountId:L,mailboxName:T,unreadCount:Se,isDraftsMailbox:Be,isSpamFolder:we,rescueCandidates:Pe,filterCategory:B,filterAttributes:J,onSelectFilterCategory:me,onToggleFilterAttribute:ce,onClearFilters:te,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p?j:void 0,onDeleteMessages:S,onMoveMessages:F,isDeleting:A,isMoving:R,onLoadMore:P,hasMore:D,isLoadingMore:O,onTriageContextChange:G,listCommandsRef:V,onRetry:()=>M(),toolbarComposeRequest:ze.composeRequest,onToolbarReply:ss,onToolbarReplyAll:Ue,onToolbarForward:_t,onClearComposeRequest:ze.clearComposeRequest,onToolbarDelete:ze.deleteThread,onToolbarStar:ze.toggleStar,onToolbarDiscardDraft:Z,onToolbarMove:ze.moveThread,composeState:Ne,closeCompose:mt,hasRemitDraftOpen:xr,onBack:mn,nextMessageId:hn,previousMessageId:pn};return n.jsx(pd.Provider,{value:br,children:s})}function gd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:r,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,mailboxAccountId:g,mailboxName:v,unreadCount:p,isDraftsMailbox:x,isSpamFolder:b,rescueCandidates:w,onTriageContextChange:j,listCommandsRef:y,onRetry:I,filterCategory:N,filterAttributes:k,onSelectFilterCategory:C,onToggleFilterAttribute:M,onClearFilters:P,searchPredicate:D}=dr(),{searchQuery:O,searchInput:E,accounts:S,resultFolderIndex:A}=Ce(),L=lr(),T=Oe(),F=v??"Inbox",R=c.useMemo(()=>Zp(),[]),$=c.useMemo(()=>s.map(U=>ay(U,A)),[s,A]),{hits:B,isLoading:K}=ku({mailboxId:e,filterCategory:N}),J=c.useMemo(()=>Iu(B,s.map(U=>U.threadId),A),[B,s,A]),ee=c.useCallback(U=>T({to:"/mail/$mailboxId",params:{mailboxId:U.mailboxId??e},search:q=>({...q,q:E||void 0,selectedMessageId:U.id,selectedThreadId:U.threadId})}),[e,T,E]);if(x&&g)return n.jsx(A0,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:v??"Drafts",unreadCount:p??void 0});const X=n.jsx(Fw,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:I,searchQuery:O,searchPredicate:D,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:g,listTitle:F,hideHeader:!0,onTriageContextChange:j,commandsRef:y}),me=S[0]?.accountId,ce=L==="phone"&&me?n.jsx(Bw,{accountId:me,children:X}):X,te=b&&w.length>0&&g?n.jsx(Kw,{accountId:g,currentMailboxId:e,candidates:w,onMove:l,children:ce}):ce;return n.jsx(sd,{title:F,unreadCount:p,preset:R,selectedCategory:N,activeFilters:k,onSelectCategory:C,onToggleFilter:M,onClearFilters:P,searchResults:$,searchLoading:r,relatedResults:J,relatedLoading:K,onSelectSearchResult:ee,searchResultsInBody:!0,children:te})}function Jw(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:r,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:f,onToolbarForward:d,onClearComposeRequest:m,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:v,onToolbarMove:p,composeState:x}=dr(),b=Ss()?.showIntelligencePane??!1,w=!!r,j=b&&w,y=x.isOpen&&!r?n.jsx(ad,{}):r?n.jsx(Is,{threadId:r.threadId,mailboxId:r.mailboxId,subject:r.subject,selectedMessageId:r.messageId,authenticity:r.authenticity,onOpenIntelligence:r.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:m}):n.jsx(Es,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(so,{hasThread:w,intelligenceOpen:j&&o,canToggleIntelligence:j,onToggleIntelligence:i,onReply:w?u:void 0,onReplyAll:w?f:void 0,onForward:w?d:void 0,canDelete:w||a,onDelete:w?h:a?v:void 0,onToggleStar:w?g:void 0,isStarred:s?.hasStars,moveContext:w&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:y})]})}function Zw(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=dr();return n.jsx(Ms,{onClose:r,thread:s,mailboxId:e,accountId:t})}function ej(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=dr(),f=Oe();if(s){const d=m=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:m,selectedThreadId:void 0})});return n.jsxs(n.Fragment,{children:[n.jsx(Is,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:r}),n.jsx(Ua,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(Ms,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(ad,{})}):n.jsx(gd,{})}const Bs=Object.assign(Xw,{List:gd,Reading:Jw,Intelligence:Zw,Phone:ej}),xd=e=>e==="failed"||e==="blocked",bd=e=>e!=="draft"&&e!=="sent",oo="remit.savedSearches",tj=25;function zn(){try{const e=localStorage.getItem(oo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function sj(e){const t=e.trim();if(!t)return zn();const s=[t,...zn().filter(r=>r!==t)].slice(0,tj);try{localStorage.setItem(oo,JSON.stringify(s))}catch{return s}return s}function nj(e){const t=zn().filter(s=>s!==e);try{localStorage.setItem(oo,JSON.stringify(t))}catch{return t}return t}const Ki=e=>/^\d/.test(e),rj=(e,t)=>{const s=Ki(e),r=Ki(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function aj(e,t,s){const r=[],a=[];for(const o of e)t.has(o.mailboxId)?r.push(o):a.push(o);return a.sort((o,i)=>rj(bs(o,void 0,s),bs(i,void 0,s))),{system:r,labels:a}}function oj(e,t,s){const r=Mf(t)&&e.unseenCount>0;return{id:e.mailboxId,name:bs(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function ij(){const e=er(),t=ya({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function Ui({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=ye(),a=Oe(),o=ij(),{searchInput:i,onSearchChange:l}=Ce(),[u,f]=c.useState(zn),{t:d}=Kn("mail",{useSuspense:!1}),m=c.useCallback((C,M)=>d(C,{defaultValue:M}),[d]),h=Ft({queries:e.map(C=>({..._e({path:{accountId:C.accountId}}),staleTime:1/0}))}),{data:g}=ue(Un()),v=c.useMemo(()=>(g?.items??[]).filter(C=>bd(C.status)).length,[g?.items]),p=c.useMemo(()=>e.map((C,M)=>{const P=h[M],D=P?.data?.items??[],O=Xs(C.folderAppointments),{system:E,labels:S}=aj(D,O,m),A=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:C.accountId,label:C.email,email:C.email,muted:!!C.muted,outboxPending:v,status:A,onRetry:()=>P?.refetch(),mailboxes:[...E,...S].map(L=>oj(L,O.get(L.mailboxId),m))}}),[e,h,v,m]),x=C=>{r.invalidateQueries({queryKey:wa({path:{mailboxId:C},query:{order:"desc"}})})},b=({navId:C,className:M,ariaLabel:P,title:D,children:O,onClick:E})=>C==="brief"?n.jsx(pt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="outbox"?n.jsx(pt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="flagged"?n.jsx(pt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):C==="settings"?n.jsx(pt,{to:"/settings/accounts",onClick:()=>E?.(),className:M,"aria-label":P,title:D,children:O}):n.jsx(pt,{to:"/mail/$mailboxId",params:{mailboxId:C},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{x(C),E?.()},className:M,"aria-label":P,title:D,children:O}),w=()=>{l(""),t?.()},j=i.trim(),y=j.length>0&&!u.includes(j)?j:void 0,I=c.useCallback(()=>{y&&f(sj(y))},[y]),N=c.useCallback(C=>{f(nj(C))},[]),k=c.useCallback(C=>{l(C),a({to:"/mail",search:{q:C,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(Zh,{accounts:p,selectedNavId:o,onSelectNav:w,linkComponent:b,variant:s,savedSearches:u,saveableQuery:y,onSaveCurrentSearch:I,onSelectSavedSearch:k,onRemoveSavedSearch:N})}function lj({accounts:e,onMailboxSelect:t}){return Ss()?.showNavPane??!0?n.jsx(Ui,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Ui,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(pt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(Oa,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(Ec,{variant:"drawer"}),n.jsx(Nc,{children:({signOut:a})=>n.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[n.jsx(Bl,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function cj(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const r=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||r.includes(a))}function uj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const vd={queued:{icon:Ta,label:"Queued",className:"text-warning"},sending:{icon:nt,label:"Sending…",className:"text-accent-2"},sent:{icon:$l,label:"Sent",className:"text-positive"},failed:{icon:Gt,label:"Failed",className:"text-danger"},blocked:{icon:fa,label:"Blocked",className:"text-warning"}},dj=e=>Yf(e).toDateString()===new Date().toDateString()?On(e,{hour:"numeric",minute:"2-digit"}):On(e,{month:"short",day:"numeric"}),qi=e=>On(e,{dateStyle:"medium",timeStyle:"short"}),fj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},yd=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",wd=c.createContext(null);function io(){const e=c.useContext(wd);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function mj({children:e}){const t=Oe(),{selectedOutboxMessageId:s}=vs({strict:!1}),{data:r,isLoading:a}=ue(Un()),{searchQuery:o}=Ce(),i=Ts(),l=Za(o),u=Rs(l,i),f=l.length>0,d=uj(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>bd(p.status)).filter(p=>cj(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:x=>({...x,selectedOutboxMessageId:p})})},[t]),v={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return n.jsx(wd.Provider,{value:v,children:e})}function jd({message:e,isSelected:t,onSelect:s}){const r=ye(),{openCompose:a}=Dt(),{pushError:o}=Ve(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:ka()})},[r]),l=ve({...nl(),onSuccess:i,onError:m=>{o(Vt("Couldn't resend message","The message wasn't sent.",m))}}),u=ve({...qn(),onSuccess:i,onError:m=>{o(Vt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!vd[f])return null;const d=xd(e.status);return n.jsx(Sp,{recipients:fj(e),subject:e.subject||"",time:dj(e.sentAt??e.updatedAt),status:f,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:f==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Sd({message:e,onBack:t}){const s=e.status,r=vd[s],a=r?.icon??Gs,o=e.sentAt?qi(e.sentAt):qi(e.updatedAt);return n.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[n.jsxs("div",{className:"border-b border-line p-4",children:[t&&n.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[n.jsx(Pl,{className:"size-4"}),n.jsx("span",{children:"Back"})]}),n.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),n.jsxs("div",{className:"space-y-1 text-sm",children:[n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),n.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),n.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),n.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),n.jsx("span",{className:"text-fg",children:o})]}),r&&n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(a,{className:be("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:be("text-xs font-medium",r.className),children:r.label}),xd(e.status)&&e.lastError&&n.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),n.jsx("div",{className:"p-4",children:n.jsx(yu,{html:e.htmlBody,text:e.textBody})})]})}function hj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=io(),i=c.useRef(null);return Bn({containerRef:i,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:yd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>n.jsx(jd,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function pj(){const{selectedMessage:e}=io();return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Sd,{message:e}):n.jsx(Es,{message:"Select a message to read",showHints:!1})})]})}function gj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=io(),l=c.useRef(null);return Bn({containerRef:l,itemSelector:ia}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?n.jsx(Sd,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Es,{message:yd(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(ao,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>n.jsx(jd,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const En=Object.assign(mj,{List:hj,Reading:pj,Phone:gj}),xj=({isOpen:e,onClose:t})=>{const s=c.useCallback(r=>{r.key==="Escape"&&(r.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:r=>r.key==="Escape"&&t(),children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{className:be("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key!=="Escape"&&r.stopPropagation()},children:[n.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),n.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:n.jsx(We,{className:"size-5"})})]}),n.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:Lc.map(r=>n.jsxs("div",{children:[n.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:r.title}),n.jsx("div",{className:"space-y-2",children:r.hints.map(a=>n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("span",{className:"text-sm",children:a.description}),n.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>n.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),n.jsx(ps,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},r.title))}),n.jsx("div",{className:"mt-6 border-t border-line pt-4",children:n.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",n.jsx(ps,{children:"Esc"})," to close"]})})]})]}):null};function bj(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase(),a=r.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(r)||t.set(r,s.accountId)}return t}function vj(e){const t=new Map;for(const s of e)for(const r of s){const a=r.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,r.mailboxId),o&&!t.has(o)&&t.set(o,r.mailboxId)}return t}function yj(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>vj(t.map(s=>s.data?.items??[])),[t])}const wj=e=>e.map(t=>t.data?.items??[]);function jj(e){const t=Ft({queries:e.map(s=>({..._e({path:{accountId:s.accountId}}),staleTime:1/0})),combine:wj});return c.useMemo(()=>Af(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var In={exports:{}},Hi;function Sj(){if(Hi)return In.exports;Hi=1;const e=(t,s,r)=>new Promise((a,o)=>{if(r=Object.assign({concurrency:1/0},r),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=r;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let f=!1,d=!1,m=0,h=0;const g=()=>{if(f)return;const v=u.next(),p=h;if(h++,v.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(v.value).then(x=>s(x,p)).then(x=>{l[p]=x,m--,g()},x=>{f=!0,o(x)})};for(let v=0;v<i&&(g(),!d);v++);});return In.exports=e,In.exports.default=e,In.exports}var kj=Sj();const Cj=Df(kj),Nj=900*1e3,Ej=300,Ij=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Tj=60*1e3,Rj=e=>Math.max(Ij(e,Ej)*1e3,Tj),Dn=Rj(Lf().mailboxPollIntervalSeconds),Mj=5,aa=new Set,Aj=(e,t,s=Nj)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),Dj=(e,t,s=Dn)=>e-t>=s,Oj=(e,t)=>e.filter(s=>!t.has(s)),Wi=(e,t)=>{if(aa.delete(e),Pf(t,{softError:!0})){ul(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Vi=(e,t)=>Of({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Jt({path:{accountId:e}})})}),Pj=e=>{const t=ye(),s=c.useRef(e);s.current=e;const r=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=Aj(s.current,a).filter(l=>!aa.has(l));if(i.length!==0)for(const l of i)aa.add(l),Vi(l,t).catch(u=>{Wi(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=Oj(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);Cj(d,m=>Vi(m,t).catch(h=>{Wi(m,h)}).finally(()=>{i.delete(m)}),{concurrency:Mj})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Dn);return}},f=()=>{document.visibilityState==="visible"&&Dj(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Dn))};return o=setTimeout(u,Dn),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function Lj(e,t,s){if(e!==t)return s}function $j(e,t){return e===""?"":t}function Fj(e,t,s){return t!==e?!1:t!==s}function _j(){const{q:e=""}=vs({from:"/mail"}),t=Oe(),s=lr(),r=Tu(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(te=>{f(te),Bi(te)},[]),[m,h]=c.useState(e),g=ml(m,200),v=$j(m,g),p=c.useRef(e);p.current=e;const x=gt({select:te=>zx(te.matches)}),[b,w]=c.useState(x);if(b!==x){const te=Lj(b,x,e);w(x),te!==void 0&&h(te)}c.useEffect(()=>{Fj(m,v,p.current)&&t({to:".",search:te=>{const U=te.q===v;return{...te,q:v||void 0,...v&&!U?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,v,t]);const{data:j,isLoading:y,isError:I,error:N,refetch:k}=ue({...xt(),staleTime:1/0}),C=!!(j&&(j.accounts?.length??0)===0);c.useEffect(()=>{C&&t({to:"/onboarding",replace:!0})},[C,t]),Ha({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=c.useCallback(te=>{h(te)},[]),P=c.useCallback(()=>{h("")},[]),D=c.useCallback(()=>{h("")},[]),O=c.useCallback(()=>{f(te=>{const U=!te;return Bi(U),U})},[]),E=j?.accounts??[],S=yj(E),A=jj(E),L=c.useMemo(()=>bj(E),[E]),T=gt({select:te=>te.matches.find(q=>"mailboxId"in q.params)?.params.mailboxId}),{selectedMessageId:F}=vs({strict:!1}),R=gt({select:te=>Ka(te.matches)}),$=gt({select:te=>nn(te.matches)}),B=gt({select:te=>tr(te.matches)});Pj(E);const K=c.useCallback(()=>{l(!1)},[]),J={accounts:E,mailboxNameIndex:S,accountNameIndex:L,resultFolderIndex:A,searchQuery:v,searchInput:m,searchViewKey:x,onSearchChange:M,onSearchClear:P,onSearchClearQuery:D,intelligenceOpen:u,onToggleIntelligence:O,onSetIntelligenceOpen:d},ee=n.jsx(lj,{accounts:E,onMailboxSelect:K}),X=r?n.jsx($x,{accounts:E}):void 0,me=r?void 0:n.jsx(Qx,{accounts:E}),ce={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs($f.Provider,{value:J,children:[I?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(Pt,{title:"Couldn't load your account",error:N,onRetry:()=>{k()}})}):R?n.jsx(Fs,{selectedMessageId:F,children:r?n.jsx(kt,{nav:ee,list:n.jsx(Fs.Phone,{}),intelligenceOpen:u,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce}):n.jsx(kt,{nav:ee,topBar:me,list:n.jsx(Fs.List,{}),reading:n.jsx(Fs.Reading,{}),intelligence:n.jsx(Fs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce})}):$?n.jsx(_s,{selectedMessageId:F,children:r?n.jsx(kt,{nav:ee,list:n.jsx(_s.Phone,{}),intelligenceOpen:u,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce}):n.jsx(kt,{nav:ee,topBar:me,list:n.jsx(_s.List,{}),reading:n.jsx(_s.Reading,{}),intelligence:n.jsx(_s.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce})}):T?n.jsx(Bs,{mailboxId:T,selectedMessageId:F,children:r?n.jsx(kt,{nav:ee,list:n.jsx(Bs.Phone,{}),intelligenceOpen:u,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce}):n.jsx(kt,{nav:ee,topBar:me,list:n.jsx(Bs.List,{}),reading:n.jsx(Bs.Reading,{}),intelligence:n.jsx(Bs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce})}):B?n.jsx(En,{children:r?n.jsx(kt,{nav:ee,list:n.jsx(En.Phone,{}),intelligenceOpen:!1,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce}):n.jsx(kt,{nav:ee,topBar:me,list:n.jsx(En.List,{}),reading:n.jsx(En.Reading,{}),intelligenceOpen:!1,overlay:X,skeleton:n.jsx(ht,{}),isLoading:y||C,...ce})}):n.jsx(ht,{}),n.jsx(xj,{isOpen:a,onClose:()=>o(!1)}),n.jsx(Ff,{})]})}const aS=Object.freeze(Object.defineProperty({__proto__:null,component:_j,useMailContext:Ce},Symbol.toStringTag,{value:"Module"}));export{rS as S,Ym as U,aS as m};